Compare commits

...
Author SHA1 Message Date
Dennis Kobert 663d670492 Name the carried source consistently in the entries emitter 2026-09-09 13:13:53 +00:00
Dennis Kobert d7e9e8fe45 Adopt master's list length name for the element count node 2026-09-09 13:08:40 +00:00
Dennis Kobert 25cc63eb8d Source a record io node's rows from its implementations secondary 2026-09-09 13:08:40 +00:00
Dennis KobertandClaude Fable 5 a46a23e516 Read a named attribute at each value type it can hold
One read node per value type, mirroring master's read family. A name
means one value type, so there is no coercion between them: master's
number read silently widened integers, and these refuse instead, which
is the same rule the write side already enforces.

Each takes any record wire through the opaque reading input and serves
the name's own default where the attribute is absent, so the value
carries the declared type either way.

The gradient enums join the value-type rows now that a family exists to
read them at.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 12:48:58 +00:00
Dennis KobertandClaude Fable 5 840729db04 Accept any record wire on an input read only for its attributes
An element generic declared on a reading input, absent from the output
and from every other input, has nowhere to go and nothing to be: the
node reads its declared attributes and never the element. That is an
attr-to-element map, so it accepts any upstream record wire.

The blessing is inferred rather than marked, since the signature already
says it. The two substrate pieces were both in place: the element rides
as the byte-carried token, so the registry takes one generic row instead
of a row per element type, and the reads resolve against the input's own
layout as they always have. Only the passthrough rule stood in the way,
in the three places that enforced it.

A generic the output carries, or one on an input with no reads, is
unchanged and still owes an implementations list.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 12:47:49 +00:00
Dennis KobertandClaude Fable 5 8501010ece Name the attribute read for the type it reads
The read is a number read, not a read of whatever the name holds: our
model has no coercion, so a name written at another value type is a graph
error rather than a conversion. The name says so.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 12:47:49 +00:00
Dennis KobertandClaude Fable 5 6e5ab01b76 Serve a declared name's census default on an absent read
An absent read of a name the census declares now serves that name's own
default rather than its value type's, which is the rule for a declared
name. The census stages it exactly as it fills any absent field, as the
declared default's bytes, so the read reuses the census's own mechanism
instead of a second one; the compiler takes them when the name folds and
`set_layout` installs them beside the offset.

A name the census does not declare keeps the value type's default, which
is that case's own rule. One name carries one value type, checked when
the name folds, so the row's value type and width agree with the read's.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 12:47:49 +00:00
Dennis KobertandClaude Fable 5 fffcaa6555 Resolve a named read's offset when the graph compiles
The fold already holds the name and the read input's finished layout, so
the offset falls out there rather than at construction: `RecordLayout`
carries the resolved numbers and `set_layout` copies them into the read
slots. Constructors are untouched, and census-marker reads keep their
current installation.

A read meets the value type the name was written at, so a disagreement
between a read here and a write upstream is the same graph error as two
writes disagreeing; the one-name-one-type check now spans reads and
writes together. An absent attribute stays absent and the read serves
the forced default rather than reporting it.

`read_attribute` is the catalog's get half, typed and never `Option` at
the kernel boundary, with the name declared exactly as the write side
declares it.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 12:47:43 +00:00
Dennis KobertandClaude Fable 5 41fa0ba955 Keep the name placeholder out of the kernel entirely
A name input declares where a placeholder's name is wired and nothing
more. The name is spent resolving the layout when the graph compiles, so
the kernel neither declares it nor is passed it; the return type's
`Named<X, V>` is the only tie between the write slot and the folded name.

The wire is untouched: the input keeps its declared position and crosses
as constant text, so a document's input order is unchanged. The
placeholder stays a concrete token, so it adds no generic for the node
to carry and none to go unconstrained.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 12:46:31 +00:00
Dennis KobertandClaude Fable 5 bc7e2232e3 Carry the new layout fields through the hand-built fixtures
The record fixtures spell their metas and resolved layouts out in full,
so the name-from-input fields reach them as empty. `named_value!`'s
example moves to `ignore`: its `for T` arm implements a core-types trait
on the value type, which only core-types itself may do.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 12:45:48 +00:00
Dennis KobertandClaude Fable 5 81d72b159b Write an attribute under a name the graph supplies
`Named<X>` in parameter position declares where a placeholder's name is
wired, and the macro gives that input constant text; `Attr<Named<X, V>>`
in the return writes under it. The kernel is handed the bare placeholder,
since the name is spent resolving the layout and a folded offset is all
the write needs, so the hot path matches a marker node's exactly.

A name-generic write names its value type through the wired generic,
which only an implementations row resolves, so those nodes emit their
layout meta per row rather than sharing one across rows.

`write_attribute` is the catalog's set half, restoring the identifier
master's documents carry with its input positions. Its name input is a
constant, so those documents resolve without migration, and the reset
marker that stood in for the missing node retires with it.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 12:45:42 +00:00
Dennis KobertandClaude Fable 5 db9a59aa7d Fold attribute names out of their constant inputs when the graph compiles
`compute_layouts` resolves every name-from-input write against the text
its name input carries, so a folded meta is indistinguishable from a
marker node's and the layout holds a `&'static str` from there on. That
leaves nowhere for a name to be computed, which is the whole of the
rule: a name input that is not a constant is refused right here, per
node, with the path the editor pins its diagnostic to.

One name carries one value type, checked across the census and the
names a node folds together, so no graph can declare one field at two
widths. `compute_layouts` returns those refusals rather than panicking.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 12:44:42 +00:00
Dennis KobertandClaude Fable 5 4f12de68a7 Carry a name-generic attribute's value type as its own row
An attribute's name and its value type separate: `AttrValue` declares
everything `Attribute` does except the name and its name-specific
default, and `Named<X, V>` pairs one with a name the graph supplies.
The value type stays concrete in the signature while the name varies
per instance, so a computed name has nowhere to come from.

`LayoutMeta` gains the name-from-input variant the fold consumes: a
`FieldWrite` template with every facet minted from the concrete type
and only the name left as a placeholder, plus the input position the
name's constant sits at. `fold_name` resolves one, preferring the
census row's descriptor where the name is declared so a known name
keeps its census default. `RecordLayout` carries the folded names so
`set_layout` can resolve offsets without a marker's `NAME`.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 12:44:36 +00:00
Dennis Kobert 8266a61c52 Pad master era stroke nodes with the trailing paint order input 2026-09-08 19:42:50 +00:00
Dennis Kobert 5faafa1964 Move the paint order input last so master era documents index cleanly 2026-09-08 19:40:15 +00:00
Dennis Kobert 9e6250d0d9 Accept any paint element on the graphic fill and stroke rows 2026-09-08 19:35:27 +00:00
Dennis Kobert 35a34168d7 Accept any paint element on the fill and stroke inputs 2026-09-08 18:54:21 +00:00
Dennis Kobert a593430e38 Adapt the test surface to our wire kind and no-content graphic 2026-09-08 17:41:29 +00:00
Dennis Kobert 33b20d6329 Bring the editor onto the reconciled node catalog and paint carrier 2026-09-08 16:33:52 +00:00
Dennis Kobert 3830ace926 Reach a compiling workspace on the merged tree 2026-09-08 16:11:30 +00:00
Dennis Kobert a854c25eb8 Rebuild the render walk on the new vector and gradient APIs 2026-09-08 15:23:20 +00:00
Dennis Kobert ff45cf9525 Keep the preprocessor and the type defaults on one wire kind 2026-09-08 15:18:12 +00:00
Dennis Kobert 95ce26e36c Drop the stranded ranked wrappers from the node signatures 2026-09-08 15:16:13 +00:00
Dennis Kobert c98570fd8a Read the stroke weight from the paint list in the clip path test 2026-09-08 15:14:43 +00:00
Dennis Kobert 694fd05ea0 Match the render metadata collection arity across the render seam 2026-09-08 15:13:45 +00:00
Dennis Kobert b93b395d2f Speak our record wire kind in the type defaults and artboard exports 2026-09-08 15:11:33 +00:00
Dennis Kobert 8555e6fb79 Drop the superseded rank promotion executor tests and cover brush stroke lists 2026-09-08 15:09:41 +00:00
Dennis Kobert db9b587f41 Route the render metadata attributes through fill and stroke 2026-09-08 15:06:47 +00:00
Dennis Kobert 985f85baec Adapt the merged tree to our rank model and paint attributes 2026-09-08 15:06:05 +00:00
Dennis Kobert f59ceba19f Merge origin/master into the async record refactor
Scaffolding merge for the reconcile; the final series to master is
authored fresh. Rank plumbing resolves to our axis-IR model, the node
macro and the LaneSource render walk stay ours, master's vector
restructure and gradient vocabulary are adopted, and the paint and
appearance adoption is deliberately deferred behind our fill and stroke
markers.
2026-09-08 15:03:57 +00:00
Dennis Kobert b321c094d2 Keep the new assert messages inside the format width 2026-09-08 13:29:09 +00:00
Dennis Kobert d4768d606f Justify the unsafe sites in the arena, record and graphic glue 2026-09-08 13:23:52 +00:00
Dennis Kobert 148008c695 Refuse a wasm threads build where the Send and Sync impls assume one thread 2026-09-08 13:15:18 +00:00
Dennis Kobert 2b5845464c Rederive the shared source pointer through an unwinding set_layout 2026-09-08 13:15:13 +00:00
Dennis Kobert 5e388cb38f Assert the deep element glue is registered before the executor evaluates 2026-09-08 13:15:06 +00:00
Dennis Kobert 49daf2895e Make Attribute an unsafe trait stating its re-park and glue coupling 2026-09-08 13:14:59 +00:00
Dennis Kobert 682d3dafbd Bound attribute value types Send and Sync 2026-09-08 13:14:59 +00:00
Dennis Kobert ad03b5b0bf Check a census row against the field before its writer runs 2026-09-08 13:14:33 +00:00
Dennis Kobert 324925aedb Debit the retained hint before the drop glue that may panic 2026-09-08 13:14:18 +00:00
Dennis Kobert e78a987e3e Bind a park forwarding to the destination arena generation 2026-09-08 13:14:12 +00:00
Dennis Kobert 2c8fa44eb4 Mint arena handles only over bytes the bump reserved 2026-09-08 13:14:12 +00:00
Dennis Kobert 6b22316077 Re-park a cross-arena adopt's payloads into the target arena 2026-09-08 13:11:04 +00:00
Dennis Kobert 98cabee4c6 Rebuild stale rasterize subgraphs at document migration 2026-09-08 12:53:02 +00:00
Dennis Kobert e0848abc59 Scan item attribute values for groups the ownership gates miss 2026-09-08 12:22:04 +00:00
Dennis Kobert f237a5ee50 Claim the carrier's frame before the lazy cursor snapshot 2026-09-08 12:22:04 +00:00
Dennis Kobert df99ab3a72 Guard attribute writes against an uninstalled layout offset 2026-09-07 16:12:01 +00:00
Dennis Kobert 0fc4424a09 State the disjointness a plan's copies require 2026-09-07 16:11:56 +00:00
Dennis Kobert e9a3199456 State what contains the laundered arena borrow in the flatten test 2026-09-07 16:11:32 +00:00
Dennis Kobert ef8312806d Serve the probe record the forwarding test finishes 2026-09-07 16:11:32 +00:00
Dennis Kobert 548cbfbf4e Check the claim's layout when replaying an owned record 2026-09-07 16:11:32 +00:00
Dennis Kobert 313c591f70 State from_resident's borrow-window contract at its call sites 2026-09-07 16:11:32 +00:00
Dennis Kobert f07f708ee8 Back the owned-item tests' lanes with word storage 2026-09-07 16:03:10 +00:00
Dennis Kobert 5f73044b6b Back the repark test's element slot with word storage 2026-09-07 16:03:10 +00:00
Dennis Kobert 11aedd8196 Refuse record layouts wider than the frame tier's alignment 2026-09-07 16:03:10 +00:00
Dennis Kobert f4f266b1ba Refuse a lift that never filled its layout's fields 2026-09-07 15:56:28 +00:00
Dennis Kobert 77e4e8c894 Bound and order the lanes a serve run records as filled 2026-09-07 15:51:08 +00:00
Dennis Kobert c231bd0eb8 Check the serve run's lane capacity arithmetic 2026-09-07 15:50:32 +00:00
Dennis Kobert 095e0bb4ff Require content glue for a group's element 2026-09-07 15:39:00 +00:00
Dennis Kobert 369f7db992 Copy records out untyped instead of through a byte slice 2026-09-07 15:38:53 +00:00
Dennis Kobert 79750fb52d Stage attribute default bytes through zeroed storage 2026-09-07 15:38:11 +00:00
Dennis Kobert f7360688f2 Point the construction docs at the registry that exists 2026-09-06 17:08:03 +00:00
Dennis Kobert 00920823aa Rewrite the node-graph README for the record and serving model 2026-09-06 16:58:45 +00:00
Dennis Kobert 0426a01e82 Rename the DynEdge alias to DynSource 2026-09-06 16:27:32 +00:00
Dennis Kobert 02f9cf3e6b Rename generic_record_edge_type to generic_record_source_type 2026-09-06 16:27:25 +00:00
Dennis Kobert 33f7257e47 Rename record_edge_type to record_source_type 2026-09-06 16:27:11 +00:00
Dennis Kobert 2921f44e5c Rename leveled_record_value_edge to leveled_record_value_source 2026-09-06 16:27:01 +00:00
Dennis Kobert 1e91511f93 Rename record_value_edge to record_value_source 2026-09-06 16:26:49 +00:00
Dennis Kobert daf0231c0c Rename the record_edge accessor to record_source 2026-09-06 16:26:33 +00:00
Dennis Kobert 92adc524ca Rename EdgeHandle to SourceHandle 2026-09-06 16:26:03 +00:00
Dennis Kobert 9f0e0ebc96 Clear the remaining clippy warnings on the diff surface 2026-09-06 16:25:17 +00:00
Dennis Kobert a911bcc165 Justify the three clippy lints that must stand 2026-09-06 16:24:53 +00:00
Dennis Kobert 5bedfa4d11 Name the erased repark and replay function types 2026-09-06 16:24:35 +00:00
Dennis Kobert e52af0cee0 Condense the multi-line safety notes to one line 2026-09-06 16:00:05 +00:00
Dennis Kobert fbdba0e545 Drop narration and internal asides from comments 2026-09-06 15:59:41 +00:00
Dennis Kobert 6cdab6b95d Drop docs naming mechanisms that do not exist 2026-09-06 15:58:40 +00:00
Dennis Kobert e92faf763d Correct docs that misstate what the code does 2026-09-06 15:58:01 +00:00
Dennis Kobert 305c36fb25 Reattach docs to the items they describe 2026-09-06 15:57:05 +00:00
Dennis Kobert fc9e69a7a7 Spell the elided Graphic and Artboard lifetimes in return paths 2026-09-06 15:48:45 +00:00
Dennis Kobert c9525d76c4 Give the split graphic modules their abstraction-level docs 2026-09-06 15:45:57 +00:00
Dennis Kobert 451922c217 Reattach the legacy mapping doc to its function 2026-09-06 15:29:03 +00:00
Dennis Kobert 92ea594a2a Split the graphic module into type, paint, walk, glue, and legacy modules 2026-09-06 15:29:03 +00:00
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
166 changed files with 35959 additions and 15285 deletions

No files matched your search

Generated
+2 -4
View File
@@ -2056,6 +2056,7 @@ dependencies = [
"graphene-hash", "graphene-hash",
"graphic-types", "graphic-types",
"gungraun", "gungraun",
"interpreted-executor",
"js-sys", "js-sys",
"log", "log",
"mmap-io", "mmap-io",
@@ -2990,6 +2991,7 @@ dependencies = [
"graph-craft", "graph-craft",
"graphene-core", "graphene-core",
"graphene-std", "graphene-std",
"graphic-types",
"gungraun", "gungraun",
"log", "log",
"once_cell", "once_cell",
@@ -4917,15 +4919,11 @@ dependencies = [
"core-types", "core-types",
"dyn-any", "dyn-any",
"glam", "glam",
"graphene-core",
"graphic-types", "graphic-types",
"kurbo",
"log", "log",
"node-macro", "node-macro",
"raster-types", "raster-types",
"serde", "serde",
"tokio",
"vector-nodes",
"vector-types", "vector-types",
] ]
+5
View File
@@ -98,6 +98,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 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 { Self {
render_state: None, render_state: None,
wgpu_context, wgpu_context,
+1 -1
View File
@@ -228,7 +228,7 @@ impl RenderState {
return; return;
}; };
let size = glam::UVec2::new(viewport_texture.width(), viewport_texture.height()); 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 { match result {
Ok(texture) => { Ok(texture) => {
self.overlays_texture = Some(texture); self.overlays_texture = Some(texture);
+4
View File
@@ -53,6 +53,10 @@ impl DesktopWrapper {
executor.execute() 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 { pub async fn execute_node_graph() -> NodeGraphExecutionResult {
let result = graphite_editor::node_graph_executor::run_node_graph().await; let result = graphite_editor::node_graph_executor::run_node_graph().await;
match result { match result {
@@ -1,6 +1,5 @@
pub mod node { pub mod node {
pub const CALL_ARGUMENT: &str = "call_argument"; pub const CALL_ARGUMENT: &str = "call_argument";
pub const CONTEXT_FEATURES: &str = "context_features";
pub const VISIBLE: &str = "visible"; pub const VISIBLE: &str = "visible";
pub const SKIP_DEDUPLICATION: &str = "skip_deduplication"; pub const SKIP_DEDUPLICATION: &str = "skip_deduplication";
pub const REFLECTION_METADATA: &str = "reflection_metadata"; pub const REFLECTION_METADATA: &str = "reflection_metadata";
@@ -1,7 +1,6 @@
use std::collections::HashMap; use std::collections::HashMap;
use core_types::Context; use core_types::Context;
use core_types::context::ContextDependencies;
use core_types::uuid::NodeId as RuntimeNodeId; use core_types::uuid::NodeId as RuntimeNodeId;
use graph_craft::concrete; use graph_craft::concrete;
use graph_craft::document::value::TaggedValue; use graph_craft::document::value::TaggedValue;
@@ -390,9 +389,6 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(doc_node: &DocumentNode, locatio
attributes attributes
.set_if_not_default(node::CALL_ARGUMENT, &doc_node.call_argument, &concrete!(Context), timestamp) .set_if_not_default(node::CALL_ARGUMENT, &doc_node.call_argument, &concrete!(Context), timestamp)
.map_err(map_serialization_error(node::CALL_ARGUMENT))?; .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 attributes
.set_if_not_default(node::VISIBLE, &doc_node.visible, &true, timestamp) .set_if_not_default(node::VISIBLE, &doc_node.visible, &true, timestamp)
.map_err(map_serialization_error(node::VISIBLE))?; .map_err(map_serialization_error(node::VISIBLE))?;
@@ -14,7 +14,9 @@ use crate::{NetworkId, NodeMetadataSource, PeerId, Position, Registry};
/// Test networks with Import inputs will fail compilation (which is expected). /// Test networks with Import inputs will fail compilation (which is expected).
fn verify_network_compiles(network: &NodeNetwork) -> Result<(), String> { fn verify_network_compiles(network: &NodeNetwork) -> Result<(), String> {
let compiler = Compiler {}; 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(()) Ok(())
} }
@@ -246,11 +248,6 @@ fn test_nested_network_flattening() {
#[test] #[test]
fn test_metadata_preservation() { fn test_metadata_preservation() {
// Create a network with nodes that have non-default metadata // 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 { let network = NodeNetwork {
exports: vec![NodeInput::node(NodeId(1), 0)], exports: vec![NodeInput::node(NodeId(1), 0)],
nodes: [ nodes: [
@@ -260,7 +257,6 @@ fn test_metadata_preservation() {
inputs: vec![NodeInput::import(concrete!(f64), 0), NodeInput::import(Type::Generic(Cow::Borrowed("T")), 1)], inputs: vec![NodeInput::import(concrete!(f64), 0), NodeInput::import(Type::Generic(Cow::Borrowed("T")), 1)],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("test::NodeWithMetadata")), implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("test::NodeWithMetadata")),
call_argument: concrete!(String), call_argument: concrete!(String),
context_features,
visible: false, // Non-default value visible: false, // Non-default value
skip_deduplication: true, // Non-default value skip_deduplication: true, // Non-default value
..Default::default() ..Default::default()
@@ -294,8 +290,12 @@ fn test_metadata_preservation() {
let conv_node_1 = converted.nodes.get(&NodeId(1)).unwrap(); 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"); 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 // Verify context_features is not stored
assert_eq!(orig_node_0.context_features, conv_node_0.context_features, "context_features should be preserved"); assert_eq!(
conv_node_0.context_features,
ContextDependencies::default(),
"context_features should resolve at compile, not round-trip"
);
// Verify visible is preserved // Verify visible is preserved
assert_eq!(orig_node_0.visible, conv_node_0.visible, "visible should be 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)?, implementation: convert_implementation(context, &node.implementation, metadata_path, runtime_node_id, node_collector, network_collector)?,
visible: node.attributes.get_or(node::VISIBLE, true), visible: node.attributes.get_or(node::VISIBLE, true),
skip_deduplication: node.attributes.get_or(node::SKIP_DEDUPLICATION, false), 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. // Regenerated during compilation; not stored.
context_features: Default::default(),
original_location: Default::default(), original_location: Default::default(),
}) })
} }
@@ -14,7 +14,6 @@ use graphene_std::extract_xy::XY;
use graphene_std::gradient::Gradient; use graphene_std::gradient::Gradient;
use graphene_std::list::{Item, List, NodeIdPath}; use graphene_std::list::{Item, List, NodeIdPath};
use graphene_std::math::float_noise::round_away_float_noise; use graphene_std::math::float_noise::round_away_float_noise;
use graphene_std::memo::IORecord;
use graphene_std::raster::{ use graphene_std::raster::{
CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, LuminanceCalculation, NoiseType, RedGreenBlue, RedGreenBlueAlpha, RelativeAbsolute, SelectiveColorChoice, CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, LuminanceCalculation, NoiseType, RedGreenBlue, RedGreenBlueAlpha, RelativeAbsolute, SelectiveColorChoice,
}; };
@@ -30,7 +29,7 @@ use graphene_std::vector::style::{
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin, DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin,
}; };
use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector}; use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector};
use graphene_std::{Appearance, Artboard, Color, Context, Cover, Coverage, Graphic}; use graphene_std::{Appearance, Artboard, Color, Cover, Coverage, Graphic};
use std::any::Any; use std::any::Any;
use std::sync::Arc; use std::sync::Arc;
@@ -188,8 +187,8 @@ macro_rules! generate_layout_downcast {
($introspected_data:expr, $data:expr, [ $($ty:ty),* $(,)? ]) => { ($introspected_data:expr, $data:expr, [ $($ty:ty),* $(,)? ]) => {
if false { None } if false { None }
$( $(
else if let Some(io) = $introspected_data.downcast_ref::<IORecord<Context, $ty>>() { else if let Some(element) = $introspected_data.downcast_ref::<$ty>() {
Some(io.output.layout_with_breadcrumb($data)) Some(element.layout_with_breadcrumb($data))
} }
)* )*
else { None } else { None }
@@ -197,10 +196,14 @@ macro_rules! generate_layout_downcast {
} }
// TODO: We simply try all these types sequentially. Find a better strategy. // TODO: We simply try all these types sequentially. Find a better strategy.
fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'static>, data: &mut LayoutData) -> Option<Vec<LayoutGroup>> { fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'static>, data: &mut LayoutData) -> Option<Vec<LayoutGroup>> {
// `Item<NodeIdPath>` is interpreted as a path (e.g. the value produced by `path_of_subgraph`), shown as a // `NodeIdPath` is interpreted as a path (e.g. the value produced by `path_of_subgraph`), shown as a
// `List` where each item's NodeId resolves against the prefix made up of the items above it. // `List` where each item's NodeId resolves against the prefix made up of the items above it.
if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, Item<NodeIdPath>>>() { if let Some(path) = introspected_data.downcast_ref::<NodeIdPath>() {
return Some(table_node_id_path_layout_with_breadcrumb(&io.output.element().0, data)); return Some(table_node_id_path_layout_with_breadcrumb(&path.0, data));
}
// The path's bare list form, introspected off a leveled wire.
if let Some(list) = introspected_data.downcast_ref::<List<NodeId>>() {
return Some(table_node_id_path_layout_with_breadcrumb(list, data));
} }
generate_layout_downcast!(introspected_data, data, [ generate_layout_downcast!(introspected_data, data, [
List<Artboard>, List<Artboard>,
@@ -258,61 +261,61 @@ fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'st
List<QRCodeErrorCorrectionLevel>, List<QRCodeErrorCorrectionLevel>,
List<InterpolationDistribution>, List<InterpolationDistribution>,
List<RowsOrColumns>, List<RowsOrColumns>,
Item<Artboard>, Artboard,
Item<Graphic>, Graphic,
Item<Vector>, Vector,
Item<Raster<CPU>>, Raster<CPU>,
Item<Raster<GPU>>, Raster<GPU>,
Item<Color>, Color,
Item<Gradient>, Gradient,
Item<String>, String,
Item<f64>, f64,
Item<f32>, f32,
Item<u32>, u32,
Item<u64>, u64,
Item<i32>, i32,
Item<i64>, i64,
Item<bool>, bool,
Item<DVec2>, DVec2,
Item<DAffine2>, DAffine2,
Item<BlendMode>, BlendMode,
Item<GradientForm>, GradientForm,
Item<GradientSpread>, GradientSpread,
Item<GradientSpace>, GradientSpace,
Item<GradientHueDirection>, GradientHueDirection,
Item<GradientInterpolation>, GradientInterpolation,
Item<DashPattern>, DashPattern,
Item<BoxCorners>, BoxCorners,
Item<StrokeJoin>, StrokeJoin,
Item<StrokeAlign>, StrokeAlign,
Item<StrokeCap>, StrokeCap,
Item<MergeByDistanceAlgorithm>, MergeByDistanceAlgorithm,
Item<ExtrudeJoiningAlgorithm>, ExtrudeJoiningAlgorithm,
Item<PointSpacingType>, PointSpacingType,
Item<StringCapitalization>, StringCapitalization,
Item<LuminanceCalculation>, LuminanceCalculation,
Item<RedGreenBlue>, RedGreenBlue,
Item<RedGreenBlueAlpha>, RedGreenBlueAlpha,
Item<RelativeAbsolute>, RelativeAbsolute,
Item<SelectiveColorChoice>, SelectiveColorChoice,
Item<XY>, XY,
Item<ScaleType>, ScaleType,
Item<ReferencePoint>, ReferencePoint,
Item<CentroidType>, CentroidType,
Item<BooleanOperation>, BooleanOperation,
Item<NoiseType>, NoiseType,
Item<FractalType>, FractalType,
Item<CellularDistanceFunction>, CellularDistanceFunction,
Item<CellularReturnType>, CellularReturnType,
Item<DomainWarpType>, DomainWarpType,
Item<RealTimeMode>, RealTimeMode,
Item<GridType>, GridType,
Item<ArcType>, ArcType,
Item<SpiralType>, SpiralType,
Item<TextAlign>, TextAlign,
Item<QRCodeErrorCorrectionLevel>, QRCodeErrorCorrectionLevel,
Item<InterpolationDistribution>, InterpolationDistribution,
Item<RowsOrColumns>, RowsOrColumns,
]) ])
} }
@@ -478,7 +481,7 @@ impl<T: TableItemLayout> TableItemLayout for List<T> {
} }
} }
impl TableItemLayout for Artboard { impl TableItemLayout for Artboard<'_> {
fn type_name() -> &'static str { fn type_name() -> &'static str {
"Artboard" "Artboard"
} }
@@ -594,29 +597,23 @@ impl TableItemLayout for graphene_std::core_types::none::None {
} }
} }
impl TableItemLayout for Graphic { impl TableItemLayout for Graphic<'_> {
fn type_name() -> &'static str { fn type_name() -> &'static str {
"Graphic" "Graphic"
} }
fn identifier(&self) -> String { fn identifier(&self) -> String {
// Our leaf variants hold the bare element, so they report the element's own identifier
match self { match self {
Self::None(item) => item.identifier(),
Self::Graphic(item) => item.identifier(),
Self::Vector(item) => item.identifier(),
Self::RasterCPU(item) => item.identifier(),
Self::RasterGPU(item) => item.identifier(),
Self::Color(item) => item.identifier(),
Self::Gradient(item) => item.identifier(),
Self::Text(item) => item.identifier(),
Self::NoneList(list) => list.identifier(),
Self::GraphicList(list) => list.identifier(), Self::GraphicList(list) => list.identifier(),
Self::VectorList(list) => list.identifier(), Self::Vector(vector) => vector.identifier(),
Self::RasterCPUList(list) => list.identifier(), Self::RasterCPU(raster) => raster.identifier(),
Self::RasterGPUList(list) => list.identifier(), Self::RasterGPU(raster) => raster.identifier(),
Self::ColorList(list) => list.identifier(), Self::Color(color) => color.identifier(),
Self::GradientList(list) => list.identifier(), Self::Gradient(gradient) => gradient.identifier(),
Self::TextList(list) => list.identifier(), Self::Text(text) => text.identifier(),
Self::Stroke(stroke) => stroke.identifier(),
Self::StrokeList(list) => list.identifier(), Self::StrokeList(list) => list.identifier(),
Self::Group(_) => "Group".to_string(),
} }
} }
// Don't put a breadcrumb for Graphic // Don't put a breadcrumb for Graphic
@@ -625,23 +622,16 @@ impl TableItemLayout for Graphic {
} }
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> { fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
match self { match self {
Self::None(item) => item.layout_with_breadcrumb(data),
Self::Graphic(item) => item.layout_with_breadcrumb(data),
Self::Vector(item) => item.layout_with_breadcrumb(data),
Self::RasterCPU(item) => item.layout_with_breadcrumb(data),
Self::RasterGPU(item) => item.layout_with_breadcrumb(data),
Self::Color(item) => item.layout_with_breadcrumb(data),
Self::Gradient(item) => item.layout_with_breadcrumb(data),
Self::Text(item) => item.layout_with_breadcrumb(data),
Self::NoneList(list) => list.layout_with_breadcrumb(data),
Self::GraphicList(list) => list.layout_with_breadcrumb(data), Self::GraphicList(list) => list.layout_with_breadcrumb(data),
Self::VectorList(list) => list.layout_with_breadcrumb(data), Self::Vector(vector) => vector.layout_with_breadcrumb(data),
Self::RasterCPUList(list) => list.layout_with_breadcrumb(data), Self::RasterCPU(raster) => raster.layout_with_breadcrumb(data),
Self::RasterGPUList(list) => list.layout_with_breadcrumb(data), Self::RasterGPU(raster) => raster.layout_with_breadcrumb(data),
Self::ColorList(list) => list.layout_with_breadcrumb(data), Self::Color(color) => color.layout_with_breadcrumb(data),
Self::GradientList(list) => list.layout_with_breadcrumb(data), Self::Gradient(gradient) => gradient.layout_with_breadcrumb(data),
Self::TextList(list) => list.layout_with_breadcrumb(data), Self::Text(text) => text.layout_with_breadcrumb(data),
Self::Stroke(stroke) => stroke.layout_with_breadcrumb(data),
Self::StrokeList(list) => list.layout_with_breadcrumb(data), Self::StrokeList(list) => list.layout_with_breadcrumb(data),
Self::Group(_) => Vec::new(),
} }
} }
} }
@@ -1364,6 +1354,11 @@ fn drilldown_attribute_layout(any: &dyn Any, data: &mut LayoutData) -> Option<Ve
if let Some(path) = any.downcast_ref::<NodeIdPath>() { if let Some(path) = any.downcast_ref::<NodeIdPath>() {
return Some(table_node_id_path_layout_with_breadcrumb(&path.0, data)); return Some(table_node_id_path_layout_with_breadcrumb(&path.0, data));
} }
// The path's plain value form, the layer-path marker's owned shape.
if let Some(path) = any.downcast_ref::<Vec<NodeId>>() {
let list: List<NodeId> = path.iter().copied().map(graphene_std::list::Item::new_from_element).collect();
return Some(table_node_id_path_layout_with_breadcrumb(&list, data));
}
macro_rules! check { macro_rules! check {
( $($ty:ty),* $(,)? ) => { ( $($ty:ty),* $(,)? ) => {
$( $(
@@ -11,8 +11,9 @@ use crate::messages::portfolio::utility_types::PanelType;
use crate::messages::prelude::*; use crate::messages::prelude::*;
use glam::{DAffine2, IVec2}; use glam::{DAffine2, IVec2};
use graph_craft::document::NodeId; use graph_craft::document::NodeId;
use graphene_std::Appearance;
use graphene_std::Color; use graphene_std::Color;
use graphene_std::Graphic;
use graphene_std::list::List;
use graphene_std::raster::BlendMode; use graphene_std::raster::BlendMode;
use graphene_std::raster::Image; use graphene_std::raster::Image;
use graphene_std::transform::Footprint; use graphene_std::transform::Footprint;
@@ -244,10 +245,14 @@ pub enum DocumentMessage {
vector_data: HashMap<NodeId, Arc<Vector>>, vector_data: HashMap<NodeId, Arc<Vector>>,
}, },
// `Message` is only serialized at `editor_wrapper.rs`, and only inputs from JS pass through it. // `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`/`UpdateStrokeAttributes` are produced inside `editor.handle_message` by `node_graph_executor.rs` and consumed in the same dispatch loop, so they never reach that serialization point.
#[serde(skip)] #[serde(skip)]
UpdateAppearanceAttributes { UpdateFillAttributes {
appearance_attributes: HashMap<NodeId, Arc<Appearance>>, fill_attributes: HashMap<NodeId, Arc<List<Graphic<'static>>>>,
},
#[serde(skip)]
UpdateStrokeAttributes {
stroke_attributes: HashMap<NodeId, Arc<List<Graphic<'static>>>>,
}, },
Undo, Undo,
UngroupSelectedLayers, UngroupSelectedLayers,
@@ -35,9 +35,9 @@ use crate::node_graph_executor::NodeGraphExecutor;
use glam::{DAffine2, DVec2}; use glam::{DAffine2, DVec2};
use graph_craft::application_io::resource::ResourceId; use graph_craft::application_io::resource::ResourceId;
use graph_craft::application_io::wgpu_available; use graph_craft::application_io::wgpu_available;
use graph_craft::concrete;
use graph_craft::document::value::TaggedValue; use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput, NodeNetwork, OldNodeNetwork}; use graph_craft::document::{NodeId, NodeInput, NodeNetwork, OldNodeNetwork};
use graph_craft::list;
use graphene_std::Cover; use graphene_std::Cover;
use graphene_std::math::quad::Quad; use graphene_std::math::quad::Quad;
use graphene_std::path_bool_nodes::boolean_intersect; use graphene_std::path_bool_nodes::boolean_intersect;
@@ -1518,19 +1518,13 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
.collect(); .collect();
self.network_interface.update_vector_data(layer_vector_data); 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_fill_attributes = self.layer_keyed(fill_attributes);
let layer_appearance_attributes = appearance_attributes self.network_interface.update_fill_attributes(layer_fill_attributes);
.into_iter() }
.filter(|(node_id, _)| self.network_interface.document_network().nodes.contains_key(node_id)) DocumentMessage::UpdateStrokeAttributes { stroke_attributes } => {
.filter_map(|(node_id, attrs)| { let layer_stroke_attributes = self.layer_keyed(stroke_attributes);
self.network_interface.is_layer(&node_id, &[]).then(|| { self.network_interface.update_stroke_attributes(layer_stroke_attributes);
let layer = LayerNodeIdentifier::new(node_id, &self.network_interface);
(layer, attrs)
})
})
.collect();
self.network_interface.update_appearance_attributes(layer_appearance_attributes);
} }
DocumentMessage::Undo => { DocumentMessage::Undo => {
if self.network_interface.transaction_status() != TransactionStatus::Finished { if self.network_interface.transaction_status() != TransactionStatus::Finished {
@@ -1806,6 +1800,15 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
} }
impl DocumentMessageHandler { impl DocumentMessageHandler {
/// Rekeys a per-node attribute snapshot by layer, dropping nodes that are not layers.
fn layer_keyed<T>(&self, attributes: HashMap<NodeId, T>) -> HashMap<LayerNodeIdentifier, T> {
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(|| (LayerNodeIdentifier::new(node_id, &self.network_interface), attrs)))
.collect()
}
/// Build a document handler from a `.gdd` working copy. /// Build a document handler from a `.gdd` working copy.
pub fn from_storage(interface: NodeNetworkInterface, storage: document_format::GddV1, name: String, path: Option<std::path::PathBuf>) -> Self { pub fn from_storage(interface: NodeNetworkInterface, storage: document_format::GddV1, name: String, path: Option<std::path::PathBuf>) -> Self {
let mut document = Self { let mut document = Self {
@@ -2764,7 +2767,7 @@ 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 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 item_at_index_definition = document_node_definitions::resolve_proto_node_type(graphene_std::graphic::index_elements::IDENTIFIER).expect("Item at Index node should exist");
let mut resulting_layers: Vec<NodeId> = Vec::new(); let mut resulting_layers: Vec<NodeId> = Vec::new();
@@ -2774,13 +2777,14 @@ impl DocumentMessageHandler {
continue; continue;
} }
let appearance = self.network_interface.document_metadata().layer_appearance_attributes.get(&layer); let metadata = self.network_interface.document_metadata();
let fill_paint = metadata.layer_fill_attributes.get(&layer);
let stroke_paint = metadata.layer_stroke_attributes.get(&layer);
let has_fill = appearance.is_some_and(|appearance| appearance.has_painted_cover(Cover::Fill)); let has_fill = fill_paint.is_some_and(|paint| paint.element(0).is_some_and(|graphic| !graphic.is_guaranteed_fully_transparent()));
// A visible stroke needs both renderable geometry (non-zero weight) and paint that draws something // A visible stroke needs both renderable geometry (non-zero weight) and paint that draws something
let has_stroke = appearance.is_some_and(|appearance| { let has_stroke = stroke_paint.is_some_and(|paint| {
appearance.first_coverage_of(Cover::Stroke).is_some_and(|coverage| coverage.stroke_params().has_renderable_stroke()) graphene_std::renderer::stroke_params(paint).has_renderable_stroke() && paint.element(0).is_some_and(|graphic| !graphic.is_guaranteed_fully_transparent())
&& appearance.first_paint_of(Cover::Stroke).is_some_and(|paint| !paint.is_guaranteed_fully_transparent())
}); });
// No stroke means there's nothing to solidify. Fill-only layers are already in the desired form, so skip. // No stroke means there's nothing to solidify. Fill-only layers are already in the desired form, so skip.
@@ -3800,7 +3804,7 @@ impl DocumentMessageHandler {
/// Create a network interface with a single export /// Create a network interface with a single export
fn default_document_network_interface() -> NodeNetworkInterface { fn default_document_network_interface() -> NodeNetworkInterface {
let mut network_interface = NodeNetworkInterface::default(); let mut network_interface = NodeNetworkInterface::default();
network_interface.add_export(TaggedValue::TypeDefault(list!(graphene_std::Artboard)), -1, "", &[]); network_interface.add_export(TaggedValue::TypeDefault(graph_craft::descriptor!(graphene_std::list::List<graphene_std::Artboard>)), -1, "", &[]);
network_interface network_interface
} }
@@ -4350,8 +4354,9 @@ mod document_message_handler_tests {
let phantom_count = news let phantom_count = news
.iter() .iter()
.flat_map(|new| new.iter_element_values()) .flat_map(|new| new.iter_element_values())
.filter(|graphic| matches!(graphic, graphene_std::Graphic::None(_))) // Our no-content graphic is an empty list rather than master's dedicated None variant
.filter(|graphic| graphic.is_empty())
.count(); .count();
assert_eq!(phantom_count, 0, "No stacked element should be a phantom None graphic"); assert_eq!(phantom_count, 0, "No stacked element should be a phantom empty graphic");
} }
} }
@@ -9,9 +9,9 @@ use crate::messages::portfolio::document::utility_types::nodes::CollapsedLayers;
use crate::messages::prelude::*; use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::graph_modification_utils::get_clip_mode; use crate::messages::tool::common_functionality::graph_modification_utils::get_clip_mode;
use glam::{DAffine2, DVec2, IVec2}; use glam::{DAffine2, DVec2, IVec2};
use graph_craft::concrete;
use graph_craft::document::value::TaggedValue; use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput}; use graph_craft::document::{NodeId, NodeInput};
use graph_craft::list;
use graphene_std::renderer::convert_usvg_path::convert_usvg_path; use graphene_std::renderer::convert_usvg_path::convert_usvg_path;
use graphene_std::text::{Font, TypesettingConfig}; 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::{Gradient, GradientForm, GradientSettings, GradientSpace, GradientSpread, GradientStop, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
@@ -252,7 +252,7 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
} }
// Set the bottom input of the artboard back to artboard // Set the bottom input of the artboard back to artboard
let bottom_input = NodeInput::type_default(list!(Artboard), true); let bottom_input = NodeInput::type_default(graph_craft::descriptor!(graphene_std::list::List<Artboard>), true);
network_interface.set_input(&InputConnector::primary_input(artboard_layer.to_node()), bottom_input, &[]); network_interface.set_input(&InputConnector::primary_input(artboard_layer.to_node()), bottom_input, &[]);
} else { } else {
// We have some non layers (e.g. just a rectangle node). We disconnect the bottom input and connect it to the left input. // We have some non layers (e.g. just a rectangle node). We disconnect the bottom input and connect it to the left input.
@@ -260,7 +260,7 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
network_interface.set_input(&InputConnector::layer_secondary_input(artboard_layer.to_node()), primary_input, &[]); network_interface.set_input(&InputConnector::layer_secondary_input(artboard_layer.to_node()), primary_input, &[]);
// Set the bottom input of the artboard back to artboard // Set the bottom input of the artboard back to artboard
let bottom_input = NodeInput::type_default(list!(Artboard), true); let bottom_input = NodeInput::type_default(graph_craft::descriptor!(graphene_std::list::List<Artboard>), true);
network_interface.set_input(&InputConnector::primary_input(artboard_layer.to_node()), bottom_input, &[]); network_interface.set_input(&InputConnector::primary_input(artboard_layer.to_node()), bottom_input, &[]);
} }
} }
@@ -3,7 +3,7 @@ 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, 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::utility_types::document_metadata::LayerNodeIdentifier; 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::portfolio::document::utility_types::network_interface::{self, FlowType, InputConnector, NodeNetworkInterface};
use crate::messages::prelude::*; use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::graph_modification_utils::{ 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, ReplaceablePaintChain, get_fill_input_node_id, get_upstream_gradient_value_node_id, gradient_chain_target_input, replaceable_paint_chain,
@@ -12,7 +12,8 @@ use glam::{DAffine2, DVec2, IVec2};
use graph_craft::application_io::resource::ResourceId; use graph_craft::application_io::resource::ResourceId;
use graph_craft::document::value::TaggedValue; use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput}; use graph_craft::document::{NodeId, NodeInput};
use graph_craft::{ProtoNodeIdentifier, list}; use graph_craft::{ProtoNodeIdentifier, concrete, descriptor};
use graphene_std::list::List;
use graphene_std::raster::BlendMode; use graphene_std::raster::BlendMode;
use graphene_std::raster_types::Image; use graphene_std::raster_types::Image;
use graphene_std::text::{Font, TypesettingConfig}; use graphene_std::text::{Font, TypesettingConfig};
@@ -70,8 +71,8 @@ impl<'a> ModifyInputsContext<'a> {
/// Creates an artboard as the primary export for the document network. /// 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 { 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([ 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(descriptor!(List<Artboard>), true)),
Some(NodeInput::type_default(list!(Graphic), true)), Some(NodeInput::type_default(descriptor!(List<Graphic>), true)),
Some(NodeInput::value(TaggedValue::DVec2(location), false)), Some(NodeInput::value(TaggedValue::DVec2(location), false)),
Some(NodeInput::value(TaggedValue::DVec2(dimensions), false)), Some(NodeInput::value(TaggedValue::DVec2(dimensions), false)),
Some(NodeInput::value(TaggedValue::Color(background), false)), Some(NodeInput::value(TaggedValue::Color(background), false)),
@@ -85,7 +86,7 @@ impl<'a> ModifyInputsContext<'a> {
let boolean = resolve_proto_node_type(graphene_std::path_bool_nodes::boolean_operation::IDENTIFIER) let boolean = resolve_proto_node_type(graphene_std::path_bool_nodes::boolean_operation::IDENTIFIER)
.expect("Boolean node does not exist") .expect("Boolean node does not exist")
.node_template_input_override([ .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)), Some(NodeInput::value(TaggedValue::BooleanOperation(operation), false)),
]); ]);
@@ -97,7 +98,7 @@ impl<'a> ModifyInputsContext<'a> {
pub fn insert_blend_data(&mut self, layer: LayerNodeIdentifier, count: f64) -> NodeId { pub fn insert_blend_data(&mut self, layer: LayerNodeIdentifier, count: f64) -> NodeId {
let blend = resolve_network_node_type("Blend") let blend = resolve_network_node_type("Blend")
.expect("Blend node does not exist") .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(); let blend_id = NodeId::new();
self.network_interface.insert_node(blend_id, blend, &[]); self.network_interface.insert_node(blend_id, blend, &[]);
@@ -109,7 +110,7 @@ impl<'a> ModifyInputsContext<'a> {
pub fn insert_morph_data(&mut self, layer: LayerNodeIdentifier) -> NodeId { pub fn insert_morph_data(&mut self, layer: LayerNodeIdentifier) -> NodeId {
let morph = resolve_proto_node_type(graphene_std::vector::morph::IDENTIFIER) let morph = resolve_proto_node_type(graphene_std::vector::morph::IDENTIFIER)
.expect("Morph node does not exist") .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(); let morph_id = NodeId::new();
self.network_interface.insert_node(morph_id, morph, &[]); self.network_interface.insert_node(morph_id, morph, &[]);
@@ -443,10 +444,6 @@ impl<'a> ModifyInputsContext<'a> {
} }
let fill_value = color.map_or_else(TaggedValue::no_paint, TaggedValue::Color); 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); 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();
}
} }
pub fn fill_gradient_set(&mut self, gradient: Gradient, gradient_form: GradientForm, settings: GradientSettings, transform: DAffine2) { pub fn fill_gradient_set(&mut self, gradient: Gradient, gradient_form: GradientForm, settings: GradientSettings, transform: DAffine2) {
@@ -492,21 +489,6 @@ impl<'a> ModifyInputsContext<'a> {
NodeInput::value(TaggedValue::GradientForm(gradient_form), false), NodeInput::value(TaggedValue::GradientForm(gradient_form), false),
false, false,
); );
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);
} }
pub fn blend_mode_set(&mut self, blend_mode: BlendMode) { pub fn blend_mode_set(&mut self, blend_mode: BlendMode) {
@@ -877,6 +859,9 @@ impl<'a> ModifyInputsContext<'a> {
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::StrokeJoin(stroke.join), false), true); 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);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.join_miter_limit), false), false); self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.join_miter_limit), false), false);
// Our stroke node keeps a paint order input rather than encoding the order by Fill/Stroke node adjacency, and master's `Stroke` no longer carries one to copy
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintOrderInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::PaintOrder(Default::default()), false), false);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashPatternInput); 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); 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::DashOffsetInput);
@@ -1014,59 +999,15 @@ impl<'a> ModifyInputsContext<'a> {
} }
} }
/// The wires feeding off a node's primary output. /// Sets the Stroke node's paint order input, which decides whether the stroke paints above or below the fill.
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. /// 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 { 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 connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintOrderInput);
let is_fill = |network_interface: &NodeNetworkInterface, node_id: &NodeId| network_interface.reference(node_id, network_path).as_ref() == Some(&fill_reference); if let Some(NodeInput::Value { tagged_value, .. }) = network_interface.input_from_connector(&connector, network_path)
&& **tagged_value == TaggedValue::PaintOrder(paint_order)
// 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; return false;
} }
network_interface.set_input(&connector, NodeInput::value(TaggedValue::PaintOrder(paint_order), false), network_path);
// 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 true
} }
@@ -13,8 +13,10 @@ use glam::DVec2;
use graph_craft::ProtoNodeIdentifier; use graph_craft::ProtoNodeIdentifier;
use graph_craft::document::value::*; use graph_craft::document::value::*;
use graph_craft::document::*; use graph_craft::document::*;
use graph_craft::{concrete, list}; use graph_craft::concrete;
use graph_craft::descriptor;
use graphene_std::extract_xy::XY; use graphene_std::extract_xy::XY;
use graphene_std::list::List;
use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, Color, DomainWarpType, FractalType, NoiseType, RedGreenBlueAlpha}; use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, Color, DomainWarpType, FractalType, NoiseType, RedGreenBlueAlpha};
use graphene_std::raster_types::{CPU, Raster}; use graphene_std::raster_types::{CPU, Raster};
#[allow(unused_imports)] #[allow(unused_imports)]
@@ -154,11 +156,11 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
// Primary (bottom) input type coercion // Primary (bottom) input type coercion
NodeTemplate { NodeTemplate {
inputs: vec![NodeInput::import(generic!(T), 0)], inputs: vec![NodeInput::import(generic!(T), 0)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::as_graphic::IDENTIFIER), implementation: NodeTemplateImplementation::ProtoNode(graphic::to_graphic::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-21, -2)), node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-21, -3)),
..Default::default() ..Default::default()
}, },
// Secondary (left) input type coercion // Collection of the content into the layer's group; the wrap keeps the content level's element type for the legacy boundary
NodeTemplate { NodeTemplate {
inputs: vec![NodeInput::import(generic!(T), 1)], inputs: vec![NodeInput::import(generic!(T), 1)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::into_group::IDENTIFIER), implementation: NodeTemplateImplementation::ProtoNode(graphic::into_group::IDENTIFIER),
@@ -169,18 +171,14 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
NodeTemplate { NodeTemplate {
inputs: vec![NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::DocumentNodePath)], inputs: vec![NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::DocumentNodePath)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::path_of_subgraph::IDENTIFIER), implementation: NodeTemplateImplementation::ProtoNode(graphic::path_of_subgraph::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-21, 0)), node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-21, 1)),
..Default::default() ..Default::default()
}, },
// Stamp each item of the content with the parent layer's NodeId via the `editor:layer_path` attribute, // Stamp each item of the content with the parent layer's NodeId via the `editor:layer_path` attribute,
// so editor tools (e.g. selection, click target routing) can trace data back to its owning layer. // so editor tools (e.g. selection, click target routing) can trace data back to its owning layer.
NodeTemplate { NodeTemplate {
inputs: vec![ inputs: vec![NodeInput::node(NodeId(1), 0), NodeInput::node(NodeId(2), 0)],
NodeInput::node(NodeId(1), 0), implementation: NodeTemplateImplementation::ProtoNode(graphic::stamp_layer_path::IDENTIFIER),
NodeInput::value(TaggedValue::String(graphene_std::ATTR_EDITOR_LAYER_PATH.to_string()), false),
NodeInput::node(NodeId(2), 0),
],
implementation: NodeTemplateImplementation::ProtoNode(graphic::write_attribute::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-14, -1)), node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-14, -1)),
..Default::default() ..Default::default()
}, },
@@ -196,7 +194,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
call_argument: generic!(T), call_argument: generic!(T),
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::node(NodeId(4), 0)], inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::node(NodeId(4), 0)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::extend::IDENTIFIER), implementation: NodeTemplateImplementation::ProtoNode(graphic::extend::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -2)), node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -3)),
..Default::default() ..Default::default()
}, },
] ]
@@ -206,7 +204,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
.collect(), .collect(),
..Default::default() ..Default::default()
}), }),
inputs: vec![NodeInput::type_default(list!(Graphic), true), NodeInput::type_default(list!(Graphic), true)], inputs: vec![NodeInput::type_default(descriptor!(List<Graphic>), true), NodeInput::type_default(descriptor!(List<Graphic>), true)],
input_metadata: vec![("Base", "TODO").into(), ("Content", "TODO").into()], input_metadata: vec![("Base", "TODO").into(), ("Content", "TODO").into()],
output_names: vec!["Out".to_string()], output_names: vec!["Out".to_string()],
node_type_metadata: NodeTypePersistentMetadata::layer(IVec2::new(0, 0)), node_type_metadata: NodeTypePersistentMetadata::layer(IVec2::new(0, 0)),
@@ -226,11 +224,11 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
call_argument: generic!(T), call_argument: generic!(T),
implementation: NodeTemplateImplementation::ProtoNode(artboard::create_artboard::IDENTIFIER), implementation: NodeTemplateImplementation::ProtoNode(artboard::create_artboard::IDENTIFIER),
inputs: vec![ inputs: vec![
NodeInput::import(Type::Fn(concrete!(Context).into(), generic!(T).into()), 1), NodeInput::node(NodeId(6), 0),
NodeInput::import(item!(TaggedValue), 2), NodeInput::import(concrete!(TaggedValue), 2),
NodeInput::import(item!(TaggedValue), 3), NodeInput::import(concrete!(TaggedValue), 3),
NodeInput::import(item!(TaggedValue), 4), NodeInput::import(concrete!(TaggedValue), 4),
NodeInput::import(item!(TaggedValue), 5), NodeInput::import(concrete!(TaggedValue), 5),
], ],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-21, -3)), node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-21, -3)),
..Default::default() ..Default::default()
@@ -245,18 +243,14 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
// Stamp each item of the content with the parent layer's NodeId via the `editor:layer_path` attribute, // Stamp each item of the content with the parent layer's NodeId via the `editor:layer_path` attribute,
// so editor tools (e.g. selection, click target routing) can trace data back to its owning layer. // so editor tools (e.g. selection, click target routing) can trace data back to its owning layer.
NodeTemplate { NodeTemplate {
inputs: vec![ inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::node(NodeId(1), 0)],
NodeInput::node(NodeId(0), 0), implementation: NodeTemplateImplementation::ProtoNode(graphic::stamp_layer_path::IDENTIFIER),
NodeInput::value(TaggedValue::String(graphene_std::ATTR_EDITOR_LAYER_PATH.to_string()), false),
NodeInput::node(NodeId(1), 0),
],
implementation: NodeTemplateImplementation::ProtoNode(graphic::write_attribute::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-14, -3)), node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-14, -3)),
..Default::default() ..Default::default()
}, },
// The monitor node is used to display a thumbnail in the UI. // The monitor node is used to display a thumbnail in the UI.
NodeTemplate { NodeTemplate {
inputs: vec![NodeInput::node(NodeId(2), 0)], inputs: vec![NodeInput::node(NodeId(7), 0)],
implementation: NodeTemplateImplementation::ProtoNode(memo::monitor::IDENTIFIER), implementation: NodeTemplateImplementation::ProtoNode(memo::monitor::IDENTIFIER),
call_argument: generic!(T), call_argument: generic!(T),
skip_deduplication: true, skip_deduplication: true,
@@ -265,13 +259,37 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
}, },
NodeTemplate { NodeTemplate {
inputs: vec![ inputs: vec![
NodeInput::import(graphene_std::Type::Fn(Box::new(concrete!(Context)), Box::new(list!(Artboard))), 0), NodeInput::import(graphene_std::Type::Fn(Box::new(concrete!(Context)), Box::new(concrete!(List<Artboard>))), 0),
NodeInput::node(NodeId(3), 0), NodeInput::node(NodeId(3), 0),
], ],
implementation: NodeTemplateImplementation::ProtoNode(graphic::extend::IDENTIFIER), implementation: NodeTemplateImplementation::ProtoNode(graphic::extend::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -4)), node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -4)),
..Default::default() ..Default::default()
}, },
// Content coercion into a graphic level, evaluated within the artboard's footprint
NodeTemplate {
inputs: vec![NodeInput::import(generic!(T), 1)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::to_graphic::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-35, -3)),
..Default::default()
},
NodeTemplate {
inputs: vec![NodeInput::node(NodeId(5), 0), NodeInput::import(concrete!(TaggedValue), 2)],
implementation: NodeTemplateImplementation::ProtoNode(artboard::translate_footprint::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-28, -3)),
..Default::default()
},
// Lifts the artboard element onto a one-lane level so it concatenates with the base stack
NodeTemplate {
inputs: vec![
NodeInput::node(NodeId(2), 0),
NodeInput::value(TaggedValue::U32(1), false),
NodeInput::value(TaggedValue::Bool(false), false),
],
implementation: NodeTemplateImplementation::ProtoNode(repeat_nodes::repeat::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-10, -3)),
..Default::default()
},
] ]
.into_iter() .into_iter()
.enumerate() .enumerate()
@@ -280,8 +298,8 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
..Default::default() ..Default::default()
}), }),
inputs: vec![ inputs: vec![
NodeInput::type_default(list!(Artboard), true), NodeInput::type_default(descriptor!(List<Artboard>), true),
NodeInput::type_default(list!(Graphic), true), NodeInput::type_default(descriptor!(List<Graphic>), true),
NodeInput::value(TaggedValue::DVec2(DVec2::ZERO), false), NodeInput::value(TaggedValue::DVec2(DVec2::ZERO), false),
NodeInput::value(TaggedValue::DVec2(DVec2::new(1920., 1080.)), false), NodeInput::value(TaggedValue::DVec2(DVec2::new(1920., 1080.)), false),
NodeInput::value(TaggedValue::Color(Color::WHITE), false), NodeInput::value(TaggedValue::Color(Color::WHITE), false),
@@ -353,7 +371,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
// 3: Floor (integer count per subpath) // 3: Floor (integer count per subpath)
NodeTemplate { NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::floor::IDENTIFIER), implementation: NodeTemplateImplementation::ProtoNode(math_nodes::floor::IDENTIFIER),
inputs: vec![NodeInput::import(item!(f64), 1)], inputs: vec![NodeInput::import(concrete!(f64), 1)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 13)), node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 13)),
..Default::default() ..Default::default()
}, },
@@ -441,8 +459,8 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
NodeInput::import(generic!(T), 0), NodeInput::import(generic!(T), 0),
NodeInput::node(NodeId(14), 0), NodeInput::node(NodeId(14), 0),
NodeInput::value(TaggedValue::Bool(false), false), NodeInput::value(TaggedValue::Bool(false), false),
NodeInput::import(item!(vector::misc::InterpolationDistribution), 3), NodeInput::import(concrete!(vector::misc::InterpolationDistribution), 3),
NodeInput::import(item!(Vector), 4), NodeInput::import(concrete!(Vector), 4),
], ],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(44, 3)), node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(44, 3)),
..Default::default() ..Default::default()
@@ -476,11 +494,11 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
..Default::default() ..Default::default()
}), }),
inputs: vec![ inputs: vec![
NodeInput::type_default(list!(Vector), true), NodeInput::type_default(descriptor!(List<Vector>), true),
NodeInput::value(TaggedValue::F64(10.), false), NodeInput::value(TaggedValue::F64(10.), false),
NodeInput::value(TaggedValue::Bool(Default::default()), false), NodeInput::value(TaggedValue::Bool(Default::default()), false),
NodeInput::value(TaggedValue::InterpolationDistribution(Default::default()), false), NodeInput::value(TaggedValue::InterpolationDistribution(Default::default()), false),
NodeInput::type_default(list!(Vector), false), NodeInput::type_default(descriptor!(List<Vector>), false),
], ],
input_metadata: vec![ input_metadata: vec![
("Content", "TODO").into(), ("Content", "TODO").into(),
@@ -566,7 +584,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
.collect(), .collect(),
..Default::default() ..Default::default()
}), }),
inputs: vec![NodeInput::type_default(list!(Vector), true)], inputs: vec![NodeInput::type_default(descriptor!(List<Vector>), true)],
input_metadata: vec![("Vector", "TODO").into()], input_metadata: vec![("Vector", "TODO").into()],
output_names: vec!["Vector".to_string()], output_names: vec!["Vector".to_string()],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)), node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
@@ -583,7 +601,12 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
exports: vec![NodeInput::node(NodeId(1), 0)], exports: vec![NodeInput::node(NodeId(1), 0)],
nodes: [ nodes: [
NodeTemplate { NodeTemplate {
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::import(item!(String), 1)], inputs: vec![
NodeInput::value(TaggedValue::None, false),
NodeInput::import(concrete!(String), 1),
NodeInput::scope("graphene_std::runtime::RuntimeNode"),
NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::SourceId),
],
implementation: NodeTemplateImplementation::ProtoNode(platform_application_io::load_resource::IDENTIFIER), implementation: NodeTemplateImplementation::ProtoNode(platform_application_io::load_resource::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)), node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
..Default::default() ..Default::default()
@@ -631,7 +654,14 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
..Default::default() ..Default::default()
}, },
NodeTemplate { NodeTemplate {
inputs: vec![NodeInput::import(generic!(T), 0), NodeInput::import(item!(Footprint), 1), NodeInput::node(NodeId(1), 0)], inputs: vec![
NodeInput::value(TaggedValue::None, false),
NodeInput::import(generic!(T), 0),
NodeInput::import(concrete!(Footprint), 1),
NodeInput::node(NodeId(1), 0),
NodeInput::scope("graphene_std::runtime::RuntimeNode"),
NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::SourceId),
],
implementation: NodeTemplateImplementation::ProtoNode(platform_application_io::rasterize::IDENTIFIER), implementation: NodeTemplateImplementation::ProtoNode(platform_application_io::rasterize::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(14, 0)), node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(14, 0)),
..Default::default() ..Default::default()
@@ -644,7 +674,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
..Default::default() ..Default::default()
}), }),
inputs: vec![ inputs: vec![
NodeInput::type_default(list!(Vector), true), NodeInput::type_default(descriptor!(List<Vector>), true),
NodeInput::value( NodeInput::value(
TaggedValue::Footprint(Footprint { TaggedValue::Footprint(Footprint {
transform: DAffine2::from_scale_angle_translation(DVec2::new(1000., 1000.), 0., DVec2::new(0., 0.)), transform: DAffine2::from_scale_angle_translation(DVec2::new(1000., 1000.), 0., DVec2::new(0., 0.)),
@@ -676,7 +706,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
nodes: [ nodes: [
NodeTemplate { NodeTemplate {
inputs: vec![ inputs: vec![
NodeInput::import(list!(Raster<CPU>), 0), NodeInput::import(concrete!(List<Raster<CPU>>), 0),
NodeInput::value(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Red), false), NodeInput::value(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Red), false),
], ],
implementation: NodeTemplateImplementation::ProtoNode(raster_nodes::adjustments::extract_channel::IDENTIFIER), implementation: NodeTemplateImplementation::ProtoNode(raster_nodes::adjustments::extract_channel::IDENTIFIER),
@@ -686,7 +716,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
}, },
NodeTemplate { NodeTemplate {
inputs: vec![ inputs: vec![
NodeInput::import(list!(Raster<CPU>), 0), NodeInput::import(concrete!(List<Raster<CPU>>), 0),
NodeInput::value(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Green), false), NodeInput::value(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Green), false),
], ],
implementation: NodeTemplateImplementation::ProtoNode(raster_nodes::adjustments::extract_channel::IDENTIFIER), implementation: NodeTemplateImplementation::ProtoNode(raster_nodes::adjustments::extract_channel::IDENTIFIER),
@@ -696,7 +726,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
}, },
NodeTemplate { NodeTemplate {
inputs: vec![ inputs: vec![
NodeInput::import(list!(Raster<CPU>), 0), NodeInput::import(concrete!(List<Raster<CPU>>), 0),
NodeInput::value(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Blue), false), NodeInput::value(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Blue), false),
], ],
implementation: NodeTemplateImplementation::ProtoNode(raster_nodes::adjustments::extract_channel::IDENTIFIER), implementation: NodeTemplateImplementation::ProtoNode(raster_nodes::adjustments::extract_channel::IDENTIFIER),
@@ -706,7 +736,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
}, },
NodeTemplate { NodeTemplate {
inputs: vec![ inputs: vec![
NodeInput::import(list!(Raster<CPU>), 0), NodeInput::import(concrete!(List<Raster<CPU>>), 0),
NodeInput::value(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Alpha), false), NodeInput::value(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Alpha), false),
], ],
implementation: NodeTemplateImplementation::ProtoNode(raster_nodes::adjustments::extract_channel::IDENTIFIER), implementation: NodeTemplateImplementation::ProtoNode(raster_nodes::adjustments::extract_channel::IDENTIFIER),
@@ -721,7 +751,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
.collect(), .collect(),
..Default::default() ..Default::default()
}), }),
inputs: vec![NodeInput::type_default(list!(Raster<CPU>), true)], inputs: vec![NodeInput::type_default(descriptor!(List<Raster<CPU>>), true)],
input_metadata: vec![("Image", "TODO").into()], input_metadata: vec![("Image", "TODO").into()],
output_names: vec!["".to_string(), "Red".to_string(), "Green".to_string(), "Blue".to_string(), "Alpha".to_string()], output_names: vec!["".to_string(), "Red".to_string(), "Green".to_string(), "Blue".to_string(), "Alpha".to_string()],
..Default::default() ..Default::default()
@@ -737,14 +767,14 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
exports: vec![NodeInput::value(TaggedValue::None, false), NodeInput::node(NodeId(0), 0), NodeInput::node(NodeId(1), 0)], exports: vec![NodeInput::value(TaggedValue::None, false), NodeInput::node(NodeId(0), 0), NodeInput::node(NodeId(1), 0)],
nodes: [ nodes: [
NodeTemplate { NodeTemplate {
inputs: vec![NodeInput::import(item!(DVec2), 0), NodeInput::value(TaggedValue::XY(XY::X), false)], inputs: vec![NodeInput::import(concrete!(DVec2), 0), NodeInput::value(TaggedValue::XY(XY::X), false)],
implementation: NodeTemplateImplementation::ProtoNode(extract_xy::extract_xy::IDENTIFIER), implementation: NodeTemplateImplementation::ProtoNode(extract_xy::extract_xy::IDENTIFIER),
call_argument: generic!(T), call_argument: generic!(T),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)), node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
..Default::default() ..Default::default()
}, },
NodeTemplate { NodeTemplate {
inputs: vec![NodeInput::import(item!(DVec2), 0), NodeInput::value(TaggedValue::XY(XY::Y), false)], inputs: vec![NodeInput::import(concrete!(DVec2), 0), NodeInput::value(TaggedValue::XY(XY::Y), false)],
implementation: NodeTemplateImplementation::ProtoNode(extract_xy::extract_xy::IDENTIFIER), implementation: NodeTemplateImplementation::ProtoNode(extract_xy::extract_xy::IDENTIFIER),
call_argument: generic!(T), call_argument: generic!(T),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 2)), node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 2)),
@@ -774,7 +804,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
category: "", category: "",
node_template: NodeTemplate { node_template: NodeTemplate {
implementation: NodeTemplateImplementation::Extract, implementation: NodeTemplateImplementation::Extract,
inputs: vec![NodeInput::type_default(concrete!(DocumentNode), true)], inputs: vec![NodeInput::type_default(descriptor!(DocumentNode), true)],
input_metadata: vec![("Node", "TODO").into()], input_metadata: vec![("Node", "TODO").into()],
output_names: vec!["Document Node".to_string()], output_names: vec!["Document Node".to_string()],
..Default::default() ..Default::default()
@@ -797,27 +827,27 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
// Node 0: regex_find proto node — returns List<String> of [whole_match, ...capture_groups] // Node 0: regex_find proto node — returns List<String> of [whole_match, ...capture_groups]
NodeTemplate { NodeTemplate {
inputs: vec![ inputs: vec![
NodeInput::import(item!(String), 0), NodeInput::import(concrete!(String), 0),
NodeInput::import(item!(String), 1), NodeInput::import(concrete!(String), 1),
NodeInput::import(item!(f64), 2), NodeInput::import(concrete!(f64), 2),
NodeInput::import(item!(bool), 3), NodeInput::import(concrete!(bool), 3),
NodeInput::import(item!(bool), 4), NodeInput::import(concrete!(bool), 4),
], ],
implementation: NodeTemplateImplementation::ProtoNode(text_nodes::regex::regex_find::IDENTIFIER), implementation: NodeTemplateImplementation::ProtoNode(text_nodes::regex::regex_find::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)), node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
..Default::default() ..Default::default()
}, },
// Node 1: item_at_index at index 0, extracts the whole match as a bare String (drops the item's start/end/name attributes since the unwrapped String can't carry them) // Node 1: extract_element at index 0, extracts the whole match as a bare String (drops the item's start/end/name attributes since the unwrapped String can't carry them)
NodeTemplate { NodeTemplate {
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::F64(0.), false)], inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::F64(0.), false)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::item_at_index::IDENTIFIER), implementation: NodeTemplateImplementation::ProtoNode(graphic::extract_element::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 0)), node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 0)),
..Default::default() ..Default::default()
}, },
// Node 2: remove_at_index at index 0, returns the capture group items as a List<String>, preserving each item's start/end/name attributes // Node 2: omit_element at index 0, returns the capture group items as a List<String>, preserving each item's start/end/name attributes
NodeTemplate { NodeTemplate {
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::F64(0.), false)], inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::F64(0.), false)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::remove_at_index::IDENTIFIER), implementation: NodeTemplateImplementation::ProtoNode(graphic::omit_element::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 2)), node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 2)),
..Default::default() ..Default::default()
}, },
@@ -888,7 +918,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
..Default::default() ..Default::default()
}), }),
inputs: vec![ inputs: vec![
NodeInput::type_default(item!(Vector), true), NodeInput::type_default(descriptor!(Vector), true),
NodeInput::value(TaggedValue::VectorModification(Default::default()), false), NodeInput::value(TaggedValue::VectorModification(Default::default()), false),
], ],
input_metadata: vec![("Content", "TODO").into(), ("Modification", "TODO").into()], input_metadata: vec![("Content", "TODO").into(), ("Modification", "TODO").into()],
@@ -1556,7 +1586,7 @@ impl InputTypeConstraint {
// Find the union of all the possible types from the dynamic executor implementations // Find the union of all the possible types from the dynamic executor implementations
let mut result_accepted = Self::empty(); let mut result_accepted = Self::empty();
for node_io in implementations.keys() { for node_io in implementations.iter().map(|entry| &entry.io) {
if let Some(input_type) = node_io.inputs.get(input_index) { if let Some(input_type) = node_io.inputs.get(input_index) {
result_accepted.insert(input_type); result_accepted.insert(input_type);
} }
@@ -28,7 +28,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`. // 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 extended_node_registry = &*interpreted_executor::node_registry::NODE_REGISTRY;
let node_registry = NODE_REGISTRY.lock().unwrap(); 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); let context_type = concrete!(Context);
for (id, metadata) in NODE_METADATA.lock().unwrap().iter() { for (id, metadata) in NODE_METADATA.lock().unwrap().iter() {
let identifier = DefinitionIdentifier::ProtoNode(id.clone()); let identifier = DefinitionIdentifier::ProtoNode(id.clone());
@@ -41,18 +41,17 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
fields, fields,
description, description,
properties, properties,
context_features,
.. ..
} = metadata; } = metadata;
let implementations = node_registry.get(id).unwrap_or(&empty_implementations); 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() { 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) { } 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 { } else {
Vec::new() Vec::new()
}; };
@@ -74,7 +73,8 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
inputs, inputs,
call_argument: input_type.clone(), call_argument: input_type.clone(),
implementation: NodeTemplateImplementation::ProtoNode(id.clone()), implementation: NodeTemplateImplementation::ProtoNode(id.clone()),
context_features: ContextDependencies::from(context_features.as_slice()), // Context features are resolved from the registry at compile time, not persisted on the node
context_features: ContextDependencies::default(),
// TODO: Store information for input overrides in the node macro // TODO: Store information for input overrides in the node macro
input_metadata: fields input_metadata: fields
.iter() .iter()
@@ -19,6 +19,7 @@ use graph_craft::{Type, concrete};
use graphene_std::animation::RealTimeMode; use graphene_std::animation::RealTimeMode;
use graphene_std::color::SRGBA8; use graphene_std::color::SRGBA8;
use graphene_std::extract_xy::XY; use graphene_std::extract_xy::XY;
use graphene_std::list::List;
use graphene_std::raster::{ use graphene_std::raster::{
BlendMode, CellularDistanceFunction, CellularReturnType, Color, DomainWarpType, FractalType, LuminanceCalculation, NoiseType, RedGreenBlue, RedGreenBlueAlpha, RelativeAbsolute, BlendMode, CellularDistanceFunction, CellularReturnType, Color, DomainWarpType, FractalType, LuminanceCalculation, NoiseType, RedGreenBlue, RedGreenBlueAlpha, RelativeAbsolute,
SelectiveColorChoice, SelectiveColorChoice,
@@ -32,8 +33,8 @@ use graphene_std::vector::misc::{
ArcType, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridType, InterpolationDistribution, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns, SpiralType, ArcType, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridType, InterpolationDistribution, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns, SpiralType,
}; };
use graphene_std::vector::style::{ use graphene_std::vector::style::{
FillChoice, Gradient, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStops, StrokeAlign, StrokeCap, StrokeJoin, FillChoice, Gradient, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStops, PaintOrder, StrokeAlign, StrokeCap,
build_transform_with_y_preservation, StrokeJoin, build_transform_with_y_preservation,
}; };
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification}; use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
use graphene_std::{NodeParameter, ParameterRef}; use graphene_std::{NodeParameter, ParameterRef};
@@ -283,6 +284,8 @@ pub(crate) fn property_from_type(
Some(x) if id_is::<String>(x) => text_widget(default_info).into(), Some(x) if id_is::<String>(x) => text_widget(default_info).into(),
Some(x) if id_is::<DVec2>(x) => vec2_widget(default_info, "X", "Y", "", None, false), Some(x) if id_is::<DVec2>(x) => vec2_widget(default_info, "X", "Y", "", None, false),
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &mut extra_widgets), Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &mut extra_widgets),
// A leveled f64 arrives peeled to its element, so only a genuinely list-typed input reaches this arm
Some(x) if id_is::<List<f64>>(x) => array_of_number_widget(default_info, TextInput::default()).into(),
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)), Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)), Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
// ============ // ============
@@ -340,14 +343,10 @@ pub(crate) fn property_from_type(
} }
} }
} }
Type::Item(element) => return property_from_type(node_id, index, element, number_options, unit, display_decimal_places, step, context),
Type::List(element) => match element.as_ref() {
Type::Concrete(element_type) if element_type.name == std::any::type_name::<f64>() => array_of_number_widget(default_info, TextInput::default()).into(),
_ => return Err(unsupported_widgets(default_info, ty.to_string())),
},
Type::Generic(_) => vec![TextLabel::new("Generic Type (Not Supported)").widget_instance()].into(), Type::Generic(_) => vec![TextLabel::new("Generic Type (Not Supported)").widget_instance()].into(),
Type::Fn(_, out) => return property_from_type(node_id, index, out, number_options, unit, display_decimal_places, step, context), Type::Fn(_, out) => return property_from_type(node_id, index, out, number_options, unit, display_decimal_places, step, context),
Type::Future(out) => return property_from_type(node_id, index, out, number_options, unit, display_decimal_places, step, context), Type::Future(out) => return property_from_type(node_id, index, out, number_options, unit, display_decimal_places, step, context),
Type::Record(inner) => return property_from_type(node_id, index, inner, number_options, unit, display_decimal_places, step, context),
}; };
extra_widgets.push(widgets); extra_widgets.push(widgets);
@@ -2292,7 +2291,7 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
return Vec::new(); return Vec::new();
}; };
let mut input_types = implementations.keys().filter_map(|item| item.inputs.get(input_index)).collect::<Vec<_>>(); let mut input_types = implementations.iter().filter_map(|entry| entry.io.inputs.get(input_index)).collect::<Vec<_>>();
input_types.sort_by_key(|ty| ty.type_name()); input_types.sort_by_key(|ty| ty.type_name());
let input_type = input_types.first().cloned(); let input_type = input_types.first().cloned();
@@ -2648,6 +2647,8 @@ pub fn stroke_properties(node_id: NodeId, context: &mut NodePropertiesContext) -
ParameterWidgetsInfo::new(node_id, MiterLimitInput, true, context), ParameterWidgetsInfo::new(node_id, MiterLimitInput, true, context),
NumberInput::default().min(0.).disabled(miter_limit_disabled), NumberInput::default().min(0.).disabled(miter_limit_disabled),
); );
// Our stroke node keeps a paint order input rather than encoding the order by Fill/Stroke node adjacency
let paint_order = enum_choice::<PaintOrder>().for_socket(ParameterWidgetsInfo::new(node_id, PaintOrderInput, true, context)).property_row();
let disabled_number_input = NumberInput::default().unit(" px").disabled(has_dash_lengths); let disabled_number_input = NumberInput::default().unit(" px").disabled(has_dash_lengths);
let dash_lengths = dash_pattern_widget(ParameterWidgetsInfo::new(node_id, DashPatternInput, true, context), TextInput::default().centered(true)); let dash_lengths = dash_pattern_widget(ParameterWidgetsInfo::new(node_id, DashPatternInput, true, context), TextInput::default().centered(true));
let number_input = disabled_number_input; let number_input = disabled_number_input;
@@ -2660,6 +2661,7 @@ pub fn stroke_properties(node_id: NodeId, context: &mut NodePropertiesContext) -
cap, cap,
join, join,
LayoutGroup::row(miter_limit), LayoutGroup::row(miter_limit),
paint_order,
LayoutGroup::row(dash_lengths), LayoutGroup::row(dash_lengths),
LayoutGroup::row(dash_offset), LayoutGroup::row(dash_offset),
] ]
@@ -1,5 +1,10 @@
use graph_craft::document::NodeId; 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))] #[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)] #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
@@ -19,22 +24,20 @@ pub enum FrontendGraphDataType {
impl FrontendGraphDataType { impl FrontendGraphDataType {
pub fn from_type(input: &Type) -> Self { 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 match TaggedValue::from_type_or_none(input) {
let nested_type = input.nested_type(); TaggedValue::U32(_) | TaggedValue::U64(_) | TaggedValue::F32(_) | TaggedValue::F64(_) | TaggedValue::DVec2(_) | TaggedValue::F64Array(_) | TaggedValue::DAffine2(_) => Self::Number,
let element = match nested_type.bundle_element_name() { TaggedValue::Color(_) => Self::Color,
Some(bundle_element) => simplify_identifier_name(bundle_element), TaggedValue::LegacyGradient(_) | TaggedValue::GradientRamp(_) => Self::Gradient,
None => nested_type.list_element().unwrap_or(nested_type).identifier_name(), 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() {
match element.as_str() { n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Graphic>>()) => Self::Graphic,
"Vector" => Self::Vector, n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Artboard>>()) => Self::Artboard,
"Graphic" => Self::Graphic, n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Raster<CPU>>>()) => Self::Raster,
"Artboard" => Self::Artboard, n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Vector>>()) => Self::Vector,
"Color" => Self::Color, n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<String>>()) => Self::Typography,
"Gradient" => Self::Gradient, _ => Self::General,
"String" => Self::Typography, },
"f64" | "f32" | "u32" | "u64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
raster if raster.starts_with("Raster") => Self::Raster,
_ => Self::General, _ => Self::General,
} }
} }
@@ -20,6 +20,27 @@ pub fn load_demo(file_name: &str) -> DocumentMessageHandler {
DocumentMessageHandler::deserialize_document(&content).unwrap_or_else(|e| panic!("Failed to deserialize {path}: {e:?}")) DocumentMessageHandler::deserialize_document(&content).unwrap_or_else(|e| panic!("Failed to deserialize {path}: {e:?}"))
} }
/// Dev tool: writes each demo's migrated re-save into the directory named by `DEMO_OUT`, leaving the checked-in originals untouched.
#[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 /// 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. /// iterate every node addressable from the metadata side.
pub fn node_paths(interface: &NodeNetworkInterface) -> Vec<(Vec<NodeId>, NodeId)> { 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 crate::messages::tool::common_functionality::graph_modification_utils;
use glam::{DAffine2, DVec2}; use glam::{DAffine2, DVec2};
use graph_craft::document::NodeId; 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::math::quad::Quad;
use graphene_std::transform::Footprint; use graphene_std::transform::Footprint;
use graphene_std::vector::Vector; use graphene_std::vector::Vector;
@@ -40,8 +41,12 @@ pub struct DocumentMetadata {
/// Vector data keyed by layer ID, used as fallback when no Path node exists. /// Vector data keyed by layer ID, used as fallback when no Path node exists.
/// This provides accurate SegmentIds for layers without explicit Path nodes. /// This provides accurate SegmentIds for layers without explicit Path nodes.
pub layer_vector_data: HashMap<LayerNodeIdentifier, Arc<Vector>>, 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. /// Per-layer `ATTR_FILL` attribute, exposed so message handlers can read paint
pub layer_appearance_attributes: HashMap<LayerNodeIdentifier, Arc<Appearance>>, /// 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. /// Transform from document space to viewport space.
pub document_to_viewport: DAffine2, pub document_to_viewport: DAffine2,
} }
@@ -231,11 +236,8 @@ impl DocumentMetadata {
/// bounds for non-vector layers (groups, raster, text, color, gradient). /// bounds for non-vector layers (groups, raster, text, color, gradient).
pub fn bounding_box_document_with_stroke(&self, layer: LayerNodeIdentifier) -> Option<[DVec2; 2]> { pub fn bounding_box_document_with_stroke(&self, layer: LayerNodeIdentifier) -> Option<[DVec2; 2]> {
if let Some(vector) = self.layer_vector_data.get(&layer) { if let Some(vector) = self.layer_vector_data.get(&layer) {
let stroke = self // The stroke geometry rides the stroke paint list's own attribute columns, the carrier that replaced the deleted `Vector::stroke`.
.layer_appearance_attributes let stroke = self.layer_stroke_attributes.get(&layer).map(|paint| graphene_std::renderer::stroke_params(paint));
.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()) { if let Some(bounds) = vector.stroke_inclusive_bounding_box_with_transform(self.transform_to_document(layer), stroke.as_ref()) {
return Some(bounds); return Some(bounds);
} }
@@ -40,7 +40,8 @@ use graph_craft::Type;
use graph_craft::application_io::resource::ResourceId; use graph_craft::application_io::resource::ResourceId;
use graph_craft::document::value::TaggedValue; use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork, OldDocumentNodeImplementation, OldNodeNetwork}; use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork, OldDocumentNodeImplementation, OldNodeNetwork};
use graphene_std::Appearance; use graphene_std::Graphic;
use graphene_std::list::List;
use graphene_std::ContextDependencies; use graphene_std::ContextDependencies;
use graphene_std::math::quad::Quad; use graphene_std::math::quad::Quad;
use graphene_std::transform::Footprint; use graphene_std::transform::Footprint;
@@ -650,17 +650,6 @@ impl NodeNetworkInterface {
node.call_argument = call_argument; node.call_argument = call_argument;
} }
pub fn set_context_features(&mut self, node_id: &NodeId, network_path: &[NodeId], context_features: ContextDependencies) {
let Some(network) = self.network_mut(network_path) else {
log::error!("Could not get nested network in set_context_features");
return;
};
let Some(node) = network.nodes.get_mut(node_id) else {
log::error!("Could not get node in set_context_features");
return;
};
node.context_features = context_features;
}
/// Lightweight version of `set_input` for bulk import operations. /// Lightweight version of `set_input` for bulk import operations.
/// Directly sets the input without `is_acyclic` checks, `load_structure`, position conversions, /// Directly sets the input without `is_acyclic` checks, `load_structure`, position conversions,
@@ -57,15 +57,26 @@ impl TypeSource {
} }
} }
/// Whether the compiled type is a rank-1 `List<T>`, as opposed to a rank-0 `Item<T>` or a bare value. /// Whether the compiled type is a packed `Record` lane, as opposed to a bare rank-0 value.
/// A bundled cell carrying a whole list displays as the list it carries.
pub fn is_list(&self) -> bool { pub fn is_list(&self) -> bool {
self.compiled_nested_type().is_some_and(|ty| matches!(ty, Type::List(_)) || ty.bundle_element_name().is_some()) // `nested_type` peels `Record`, so the rank has to be read off the unpeeled type
fn is_record(ty: &Type) -> bool {
match ty {
Type::Fn(_, output) | Type::Future(output) => is_record(output),
Type::Record(_) => true,
_ => false,
}
}
match self {
TypeSource::Compiled(compiled_type) => is_record(compiled_type),
TypeSource::TaggedValue(value_type) => is_record(value_type),
_ => false,
}
} }
/// The element type with any rank-0 `Item` or rank-1 `List` wrapper peeled, so semantic type checks can be rank-agnostic. /// The element type, so semantic type checks can be rank-agnostic.
pub fn compiled_element_type(&self) -> Option<&Type> { pub fn compiled_element_type(&self) -> Option<&Type> {
Some(element_of(self.compiled_nested_type()?)) self.compiled_nested_type()
} }
/// The identifier name of [`Self::compiled_element_type`]. /// The identifier name of [`Self::compiled_element_type`].
@@ -109,14 +120,6 @@ 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 { impl NodeNetworkInterface {
fn input_has_error(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> bool { fn input_has_error(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> bool {
match input_connector { match input_connector {
@@ -191,7 +194,7 @@ impl NodeNetworkInterface {
log::error!("Proto node {node:?} not found in the node registry, in layer_chain_hosts_node"); log::error!("Proto node {node:?} not found in the node registry, in layer_chain_hosts_node");
return false; return false;
}; };
implementations.keys().any(|node_io| node_io.inputs.first().is_some_and(|content| element_of(content) == element)) implementations.iter().map(|entry| &entry.io).any(|node_io| node_io.inputs.first().is_some_and(|content| content.nested_type() == element))
} }
None => !matches!(chain_type, TypeSource::Invalid), None => !matches!(chain_type, TypeSource::Invalid),
} }
@@ -243,18 +246,7 @@ impl NodeNetworkInterface {
} }
}; };
// A List-typed default drops to its Item counterpart (when that has a default value and the connector accepts rank 0), // `TaggedValue::from_type` recurses through `Record` to the element, so a record default already drops to 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) TaggedValue::from_type_or_none(&guaranteed_type)
} }
@@ -300,8 +292,9 @@ impl NodeNetworkInterface {
}; };
let number_of_inputs = self.number_of_inputs(node_id, network_path); let number_of_inputs = self.number_of_inputs(node_id, network_path);
implementations implementations
.keys() .iter()
.filter_map(|node_io| { .filter_map(|entry| {
let node_io = &entry.io;
// Check if this NodeIOTypes implementation is valid for the other inputs // 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 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_at_index(*node_id, iterator_index), network_path);
@@ -340,8 +333,9 @@ impl NodeNetworkInterface {
let valid_output_types = self.valid_output_types(&OutputConnector::primary_output(*node_id), network_path); let valid_output_types = self.valid_output_types(&OutputConnector::primary_output(*node_id), network_path);
implementations implementations
.keys() .iter()
.filter_map(|node_io| { .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()) { if !valid_output_types.iter().any(|output_type| output_type.nested_type() == node_io.return_value.nested_type()) {
return None; return None;
} }
@@ -370,7 +364,7 @@ impl NodeNetworkInterface {
log::error!("Protonode {render_node:?} not found in registry"); log::error!("Protonode {render_node:?} not found in registry");
return Vec::new(); return Vec::new();
}; };
implementations.keys().map(|types| types.inputs[1].clone()).collect() implementations.iter().map(|entry| entry.io.inputs[1].clone()).collect()
} }
} }
} }
@@ -186,8 +186,13 @@ impl NodeNetworkInterface {
self.document_metadata.layer_vector_data = new_layer_vector_data; self.document_metadata.layer_vector_data = new_layer_vector_data;
} }
/// Update the per-layer `ATTR_APPEARANCE` snapshot. /// Update the per-layer `ATTR_FILL` snapshot.
pub fn update_appearance_attributes(&mut self, new_layer_appearance_attributes: HashMap<LayerNodeIdentifier, Arc<Appearance>>) { pub fn update_fill_attributes(&mut self, new_layer_fill_attributes: HashMap<LayerNodeIdentifier, Arc<List<Graphic<'static>>>>) {
self.document_metadata.layer_appearance_attributes = new_layer_appearance_attributes; self.document_metadata.layer_fill_attributes = new_layer_fill_attributes;
}
/// Update the per-layer `ATTR_STROKE` snapshot.
pub fn update_stroke_attributes(&mut self, new_layer_stroke_attributes: HashMap<LayerNodeIdentifier, Arc<List<Graphic<'static>>>>) {
self.document_metadata.layer_stroke_attributes = new_layer_stroke_attributes;
} }
} }
@@ -1,7 +1,6 @@
// TODO: Eventually remove this document upgrade code // TODO: Eventually remove this document upgrade code
// This file contains lots of hacky code for upgrading old documents to the new format // This file contains lots of hacky code for upgrading old documents to the new format
use crate::messages::portfolio::document::graph_operation::utility_types::set_stroke_paint_order;
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::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::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeTemplate, NodeTemplateImplementation, OutputConnector}; use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeTemplate, NodeTemplateImplementation, OutputConnector};
@@ -10,10 +9,11 @@ use glam::{DVec2, IVec2};
use graph_craft::application_io::resource::{DataSource, Resource, ResourceHash, ResourceId}; use graph_craft::application_io::resource::{DataSource, Resource, ResourceHash, ResourceId};
use graph_craft::document::DocumentNode; use graph_craft::document::DocumentNode;
use graph_craft::document::{DocumentNodeImplementation, NodeInput, value::TaggedValue}; use graph_craft::document::{DocumentNodeImplementation, NodeInput, value::TaggedValue};
use graph_craft::{Type, item, list}; use graph_craft::{Type, concrete, descriptor};
use graphene_std::Color; use graphene_std::Color;
use graphene_std::ParameterRef; use graphene_std::ParameterRef;
use graphene_std::ProtoNodeIdentifier; use graphene_std::ProtoNodeIdentifier;
use graphene_std::list::List;
use graphene_std::text::{TextAlign, TypesettingConfig}; use graphene_std::text::{TextAlign, TypesettingConfig};
use graphene_std::transform::ScaleType; use graphene_std::transform::ScaleType;
use graphene_std::uuid::NodeId; use graphene_std::uuid::NodeId;
@@ -148,7 +148,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
aliases: &["graphene_core::graphic::FlattenVectorNode", "graphene_core::graphic_element::FlattenVectorNode"], aliases: &["graphene_core::graphic::FlattenVectorNode", "graphene_core::graphic_element::FlattenVectorNode"],
}, },
NodeReplacement { NodeReplacement {
node: graphene_std::graphic::item_at_index::IDENTIFIER, node: graphene_std::graphic::index_elements::IDENTIFIER,
aliases: &[ aliases: &[
"graphene_core::graphic_element::IndexNode", "graphene_core::graphic_element::IndexNode",
"graphene_core::graphic::IndexNode", "graphene_core::graphic::IndexNode",
@@ -158,15 +158,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
], ],
}, },
NodeReplacement { NodeReplacement {
node: graphene_std::graphic::read_attribute_gradient_form::IDENTIFIER, node: graphene_std::graphic::omit_element::IDENTIFIER,
aliases: &["graphic_nodes::graphic::ReadAttributeGradientTypeNode"],
},
NodeReplacement {
node: graphene_std::graphic::read_attribute_gradient_spread::IDENTIFIER,
aliases: &["graphic_nodes::graphic::ReadAttributeSpreadMethodNode"],
},
NodeReplacement {
node: graphene_std::graphic::remove_at_index::IDENTIFIER,
aliases: &["graphic_nodes::graphic::OmitElementNode"], aliases: &["graphic_nodes::graphic::OmitElementNode"],
}, },
NodeReplacement { NodeReplacement {
@@ -1064,6 +1056,7 @@ pub fn document_migration_reset_node_definition(document_serialized_content: &st
return true; return true;
} }
false false
} }
@@ -1408,6 +1401,34 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
if reset_node_definitions_on_open && let Some(reference) = document.network_interface.reference(node_id, network_path) { if reset_node_definitions_on_open && let Some(reference) = document.network_interface.reference(node_id, network_path) {
let node_definition = resolve_document_node_type(&reference)?; let node_definition = resolve_document_node_type(&reference)?;
document.network_interface.replace_implementation(node_id, network_path, &mut node_definition.default_node_template()); document.network_interface.replace_implementation(node_id, network_path, &mut node_definition.default_node_template());
// The leveled-records flip moved the Copy to Points content wire ahead of the points wire.
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::copy_to_points::IDENTIFIER) {
let mut node_template = node_definition.default_node_template();
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[1].clone(), network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), old_inputs[0].clone(), network_path);
for (index, input) in old_inputs.into_iter().enumerate().skip(2) {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input, network_path);
}
}
// The leveled-records flip moved the Repeat on Points content wire ahead of the points wire.
if reference == DefinitionIdentifier::ProtoNode(graphene_std::repeat::repeat_on_points::IDENTIFIER) {
let mut node_template = node_definition.default_node_template();
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[1].clone(), network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), old_inputs[0].clone(), network_path);
for (index, input) in old_inputs.into_iter().enumerate().skip(2) {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input, network_path);
}
}
// The leveled-records flip gave Mandelbrot a unit primary input.
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER) {
let mut node_template = node_definition.default_node_template();
document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
}
} }
// Rebuild stale Merge/Artboard subgraphs that still use the removed LegacyLayerExtendNode internally // Rebuild stale Merge/Artboard subgraphs that still use the removed LegacyLayerExtendNode internally
@@ -1422,6 +1443,18 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
document.network_interface.replace_implementation(node_id, network_path, &mut node_definition.default_node_template()); document.network_interface.replace_implementation(node_id, network_path, &mut node_definition.default_node_template());
} }
// Rebuild stale Rasterize subgraphs from before the async-source conversion gave the inner proto node a unit primary input (5 inputs, now 6).
if let DocumentNodeImplementation::Network(inner) = &node.implementation
&& inner
.nodes
.values()
.any(|n| n.inputs.len() == 5 && matches!(&n.implementation, DocumentNodeImplementation::ProtoNode(id) if id.as_str().contains("rasterize")))
&& document.network_interface.reference(node_id, network_path) == Some(DefinitionIdentifier::Network("Rasterize".into()))
&& let Some(node_definition) = resolve_document_node_type(&DefinitionIdentifier::Network("Rasterize".into()))
{
document.network_interface.replace_implementation(node_id, network_path, &mut node_definition.default_node_template());
}
// Upgrade old nodes to use `Context` instead of `()` or `Footprint` as their call argument // Upgrade old nodes to use `Context` instead of `()` or `Footprint` as their call argument
if node.call_argument == graph_craft::concrete!(()) || node.call_argument == graph_craft::concrete!(graphene_std::transform::Footprint) { if node.call_argument == graph_craft::concrete!(()) || node.call_argument == graph_craft::concrete!(graphene_std::transform::Footprint) {
document.network_interface.set_call_argument(node_id, network_path, graph_craft::concrete!(graphene_std::Context)); document.network_interface.set_call_argument(node_id, network_path, graph_craft::concrete!(graphene_std::Context));
@@ -1706,6 +1739,19 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
inputs_count = 7; inputs_count = 7;
} }
// Master retired the stroke paint order input, encoding the order as coverage list position instead. Ours keeps the
// input and carries it LAST, so a master-era stroke node arrives one input short and is padded with the default order.
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER) && inputs_count == 9 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
for (index, input) in old_inputs.into_iter().enumerate() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input, network_path);
}
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 9), NodeInput::value(TaggedValue::PaintOrder(Default::default()), false), network_path);
}
// Fill split its `Option<DAffine2>` placement into a `_has_transform` bool immediately before the `_transform` matrix. The modern // Fill split its `Option<DAffine2>` placement into a `_has_transform` bool immediately before the `_transform` matrix. The modern
// shape is also 7 inputs, so this era is identified by its `_spread_method` input at 5 or its optional transform at 6. // shape is also 7 inputs, so this era is identified by its `_spread_method` input at 5 or its optional transform at 6.
let is_pre_transform_split_fill = inputs_count == 7 let is_pre_transform_split_fill = inputs_count == 7
@@ -1777,12 +1823,13 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
inputs_count = 7; inputs_count = 7;
} }
// Upgrade Stroke node to reorder parameters and add "Align" (#2644) // Upgrade Stroke node to reorder parameters and add "Align" and "Paint Order" (#2644)
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER) && inputs_count == 8 { if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER) && inputs_count == 8 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template(); let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?; let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
let align_input = NodeInput::value(TaggedValue::StrokeAlign(StrokeAlign::Center), false); let align_input = NodeInput::value(TaggedValue::StrokeAlign(StrokeAlign::Center), false);
let paint_order_input = NodeInput::value(TaggedValue::PaintOrder(PaintOrder::StrokeAbove), false);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path); document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), old_inputs[1].clone(), network_path); document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), old_inputs[1].clone(), network_path);
@@ -1791,34 +1838,13 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 4), old_inputs[5].clone(), network_path); document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 4), old_inputs[5].clone(), network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 5), old_inputs[6].clone(), network_path); document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 5), old_inputs[6].clone(), network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 6), old_inputs[7].clone(), network_path); document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 6), old_inputs[7].clone(), network_path);
// Our stroke node keeps the paint order input, so the dash pair lands at 8 and 9
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 7), paint_order_input, network_path);
let dash_input = migrate_dash_input(&old_inputs[3]).unwrap_or_else(|| old_inputs[3].clone()); let dash_input = migrate_dash_input(&old_inputs[3]).unwrap_or_else(|| old_inputs[3].clone());
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 7), dash_input, network_path); document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 8), dash_input, network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 8), old_inputs[4].clone(), network_path); document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 9), old_inputs[4].clone(), network_path);
inputs_count = 9; inputs_count = 10;
}
// The Stroke node's "Paint Order" input was retired in favor of the relative order of the Fill and Stroke
// nodes in the chain, so the stored value becomes a topology rewrite that reorders the two nodes.
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER) && inputs_count == 10 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
// A wired paint order input cannot be evaluated statically, so it degrades to the default and leaves its source disconnected
let paint_order = match old_inputs.get(7).and_then(|input| input.as_value()) {
Some(&TaggedValue::PaintOrder(value)) => value,
_ => PaintOrder::StrokeAbove,
};
for (index, input) in old_inputs.iter().enumerate().take(7) {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input.clone(), network_path);
}
let dash_input = migrate_dash_input(&old_inputs[8]).unwrap_or_else(|| old_inputs[8].clone());
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 7), dash_input, network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 8), old_inputs[9].clone(), network_path);
inputs_count = 9;
set_stroke_paint_order(&mut document.network_interface, network_path, *node_id, paint_order);
} }
// A legacy "no color" on a plain color connector (`TaggedValue::no_paint()` restored by the deserializer) becomes a color, // A legacy "no color" on a plain color connector (`TaggedValue::no_paint()` restored by the deserializer) becomes a color,
@@ -1866,7 +1892,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
// The stored no-paint sentinel was the `List<Graphic>` type default before the paint connectors ranked down to `Item<Graphic>`. // The stored no-paint sentinel was the `List<Graphic>` type default before the paint connectors ranked down to `Item<Graphic>`.
// This must run before the stale-List-default cleanup below, which would otherwise adopt the definition's default paint. // This must run before the stale-List-default cleanup below, which would otherwise adopt the definition's default paint.
{ {
let legacy_no_paint = TaggedValue::TypeDefault(list!(graphene_std::Graphic)); let legacy_no_paint = TaggedValue::TypeDefault(descriptor!(List<graphene_std::Graphic>));
let paint_parameters: &[ParameterRef] = &[graphene_std::vector::fill::PaintInput.into(), graphene_std::vector::stroke::PaintInput.into()]; let paint_parameters: &[ParameterRef] = &[graphene_std::vector::fill::PaintInput.into(), graphene_std::vector::stroke::PaintInput.into()];
for parameter in paint_parameters { for parameter in paint_parameters {
if reference != DefinitionIdentifier::ProtoNode(parameter.node_identifier.clone()) { if reference != DefinitionIdentifier::ProtoNode(parameter.node_identifier.clone()) {
@@ -2647,15 +2673,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
} }
} }
// Add context features to nodes that don't have them (fine-grained context caching migration)
if node.context_features == graphene_std::ContextDependencies::default()
&& let Some(reference) = document.network_interface.reference(node_id, network_path).clone()
&& let Some(node_definition) = resolve_document_node_type(&reference)
{
let context_features = node_definition.node_template.context_features;
document.network_interface.set_context_features(node_id, network_path, context_features);
}
// Add the "Scale Type" parameter to the "Decompose Scale" node // Add the "Scale Type" parameter to the "Decompose Scale" node
if reference == DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::decompose_scale::IDENTIFIER) && inputs_count == 1 { if reference == DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::decompose_scale::IDENTIFIER) && inputs_count == 1 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template(); let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
@@ -2694,7 +2711,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
document.network_interface.set_input( document.network_interface.set_input(
&InputConnector::node_at_index(*node_id, 0), &InputConnector::node_at_index(*node_id, 0),
NodeInput::type_default(item!(graphene_std::vector::Vector), true), NodeInput::type_default(descriptor!(graphene_std::vector::Vector), true),
network_path, network_path,
); );
@@ -2744,7 +2761,8 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
.input_from_connector(&InputConnector::node_at_index(*node_id, index), network_path) .input_from_connector(&InputConnector::node_at_index(*node_id, index), network_path)
.is_some_and(|stored_input| match stored_input { .is_some_and(|stored_input| match stored_input {
NodeInput::Value { tagged_value, .. } => match &**tagged_value { NodeInput::Value { tagged_value, .. } => match &**tagged_value {
TaggedValue::TypeDefault(stored_type) if matches!(stored_type, Type::List(_)) && !tagged_value.is_no_paint() => { // Our type defaults name their type rather than carrying a structural rank, so a list-carrying wire is recognized by its name.
TaggedValue::TypeDefault(stored_type) if stored_type.name.contains("list::List<") && !tagged_value.is_no_paint() => {
!matches!(definition_input, NodeInput::Value { tagged_value, .. } if matches!(&**tagged_value, TaggedValue::TypeDefault(definition_type) if definition_type == stored_type)) !matches!(definition_input, NodeInput::Value { tagged_value, .. } if matches!(&**tagged_value, TaggedValue::TypeDefault(definition_type) if definition_type == stored_type))
} }
_ => false, _ => false,
@@ -2882,11 +2900,15 @@ fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, ne
if let Some(DefinitionIdentifier::Network(name)) = document.network_interface.reference(node_id, network_path) if let Some(DefinitionIdentifier::Network(name)) = document.network_interface.reference(node_id, network_path)
&& name == "Upload Texture" && name == "Upload Texture"
{ {
let mut node_template = resolve_proto_node_type(graphene_std::platform_application_io::upload_texture::IDENTIFIER)?.default_node_template(); // Our `upload_texture` node belongs to the optional wgpu-executor crate rather than to platform_application_io, so the conversion only exists in a GPU build.
document.network_interface.replace_implementation(node_id, network_path, &mut node_template); #[cfg(feature = "gpu")]
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?; {
if let Some(content) = old_inputs.first() { let mut node_template = resolve_proto_node_type(wgpu_executor::texture_conversion::upload_texture::IDENTIFIER)?.default_node_template();
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), content.clone(), network_path); document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
if let Some(content) = old_inputs.first() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), content.clone(), network_path);
}
} }
} }
@@ -2901,7 +2923,8 @@ mod tests {
#[test] #[test]
fn removed_definition_swap_targets_resolve() { fn removed_definition_swap_targets_resolve() {
assert!(resolve_proto_node_type(graphene_std::ops::passthrough::IDENTIFIER).is_some()); assert!(resolve_proto_node_type(graphene_std::ops::passthrough::IDENTIFIER).is_some());
assert!(resolve_proto_node_type(graphene_std::platform_application_io::upload_texture::IDENTIFIER).is_some()); #[cfg(feature = "gpu")]
assert!(resolve_proto_node_type(wgpu_executor::texture_conversion::upload_texture::IDENTIFIER).is_some());
} }
// Migrating a Merge network's coercion nodes by alias would leave a reducer in the primary slot, so every alias must reset instead // Migrating a Merge network's coercion nodes by alias would leave a reducer in the primary slot, so every alias must reset instead
@@ -3005,6 +3028,15 @@ mod tests {
} }
} }
#[test]
fn a_written_attribute_no_longer_resets_the_layer_definitions() {
// The node resolves natively again, so a document carrying it keeps
// its own layer internals instead of rebuilding them.
assert!(!document_migration_reset_node_definition(
r#"{"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}}}"#
));
}
#[test] #[test]
fn test_no_duplicate_node_replacements() { fn test_no_duplicate_node_replacements() {
let mut hashmap = HashMap::<ProtoNodeIdentifier, u32>::new(); let mut hashmap = HashMap::<ProtoNodeIdentifier, u32>::new();
@@ -682,7 +682,10 @@ pub fn get_stroke_options(layer: LayerNodeIdentifier, network_interface: &NodeNe
Some(TaggedValue::F64(value)) => *value, Some(TaggedValue::F64(value)) => *value,
_ => 4., _ => 4.,
}; };
let paint_order = get_stroke_paint_order(layer, network_interface); let paint_order = match parameters.value(stroke::PaintOrderInput) {
Some(TaggedValue::PaintOrder(value)) => *value,
_ => PaintOrder::default(),
};
let dash_lengths = match parameters.value(stroke::DashPatternInput) { let dash_lengths = match parameters.value(stroke::DashPatternInput) {
Some(TaggedValue::DashPattern(lengths)) => lengths.clone(), Some(TaggedValue::DashPattern(lengths)) => lengths.clone(),
_ => Vec::new(), _ => Vec::new(),
@@ -708,64 +711,16 @@ 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)) 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, /// Whether the paint order can act on the layer: it rides the Stroke node's paint order input, so any layer with a Stroke node qualifies.
/// 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 { pub fn stroke_paint_order_applicable(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> bool {
let stroke_reference = DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER); get_stroke_id(layer, network_interface).is_some()
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 /// The paint order of a layer's stroke, read from the Stroke node's paint order input rather than from the chain topology.
/// 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 { pub fn get_stroke_paint_order(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> PaintOrder {
let stroke_reference = DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER); match NodeGraphLayer::new(layer, network_interface).parameter_value(graphene_std::vector::stroke::PaintOrderInput) {
let fill_reference = DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER); Some(TaggedValue::PaintOrder(paint_order)) => *paint_order,
_ => PaintOrder::default(),
// 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,
} }
} }
@@ -574,15 +574,22 @@ mod test_artboard {
use graphene_std::Artboard; use graphene_std::Artboard;
use graphene_std::list::List; use graphene_std::list::List;
async fn get_artboards(editor: &mut EditorTestUtils) -> List<Artboard> { /// 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 { let instrumented = match editor.eval_graph().await {
Ok(instrumented) => instrumented, Ok(instrumented) => instrumented,
Err(e) => panic!("Failed to evaluate graph: {e}"), Err(e) => panic!("Failed to evaluate graph: {e}"),
}; };
instrumented let mut artboards = List::new();
.grab_all_input::<graphene_std::graphic::extend::NewInput, List<Artboard>>(&editor.runtime) for list in instrumented.grab_all_input::<graphene_std::graphic::extend::NewInput, List<Artboard>>(&editor.runtime) {
.flatten() for index in 0..list.len() {
.collect() if let Some(item) = list.clone_item(index) {
artboards.push(item);
}
}
}
artboards
} }
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
@@ -264,17 +264,20 @@ fn whole_expanse_rect(layer: LayerNodeIdentifier, document: &DocumentMessageHand
mod test_fill { mod test_fill {
pub use crate::test_utils::test_prelude::*; pub use crate::test_utils::test_prelude::*;
use graphene_std::color::SRGBA8; use graphene_std::color::SRGBA8;
use graphene_std::list::Item; use graphene_std::list::List;
use graphene_std::vector::fill; use graphene_std::vector::fill;
// The Fill tool writes solid colors, whose stored values the input monitor records as `Item<Color>` wires /// The monitored fill wire carries `Color`; the `Graphic` conversion sits downstream of the monitor.
async fn get_fills(editor: &mut EditorTestUtils) -> Vec<Item<Color>> { async fn get_fills(editor: &mut EditorTestUtils) -> Vec<Color> {
let instrumented = match editor.eval_graph().await { let instrumented = match editor.eval_graph().await {
Ok(instrumented) => instrumented, Ok(instrumented) => instrumented,
Err(e) => panic!("Failed to evaluate graph: {e}"), Err(e) => panic!("Failed to evaluate graph: {e}"),
}; };
instrumented.grab_all_input::<fill::PaintInput, Item<Color>>(&editor.runtime).collect() instrumented
.grab_all_input::<fill::PaintInput, List<Color>>(&editor.runtime)
.flat_map(|list| list.iter_element_values().cloned().collect::<Vec<_>>())
.collect()
} }
#[tokio::test] #[tokio::test]
@@ -304,8 +307,7 @@ mod test_fill {
editor.click_tool(ToolType::Fill, MouseKeys::LEFT, DVec2::new(2., 2.), ModifierKeys::empty()).await; editor.click_tool(ToolType::Fill, MouseKeys::LEFT, DVec2::new(2., 2.), ModifierKeys::empty()).await;
let fills = get_fills(&mut editor).await; let fills = get_fills(&mut editor).await;
assert_eq!(fills.len(), 1); assert_eq!(fills.len(), 1);
let color = fills.first().unwrap().element(); assert_eq!(SRGBA8::from(fills[0]), SRGBA8::from(Color::GREEN));
assert_eq!(SRGBA8::from(*color), SRGBA8::from(Color::GREEN));
} }
#[tokio::test] #[tokio::test]
@@ -317,8 +319,7 @@ mod test_fill {
editor.click_tool(ToolType::Fill, MouseKeys::LEFT, DVec2::new(2., 2.), ModifierKeys::SHIFT).await; editor.click_tool(ToolType::Fill, MouseKeys::LEFT, DVec2::new(2., 2.), ModifierKeys::SHIFT).await;
let fills = get_fills(&mut editor).await; let fills = get_fills(&mut editor).await;
assert_eq!(fills.len(), 1); assert_eq!(fills.len(), 1);
let color = fills.first().unwrap().element(); assert_eq!(SRGBA8::from(fills[0]), SRGBA8::from(Color::YELLOW));
assert_eq!(SRGBA8::from(*color), SRGBA8::from(Color::YELLOW));
} }
#[tokio::test] #[tokio::test]
+34 -38
View File
@@ -10,12 +10,11 @@ use graphene_std::application_io::{ExportFormat, NodeGraphUpdateMessage, RenderC
use graphene_std::bounds::RenderBoundingBox; use graphene_std::bounds::RenderBoundingBox;
use graphene_std::color::SRGBA8; use graphene_std::color::SRGBA8;
use graphene_std::list::List; use graphene_std::list::List;
use graphene_std::memo::IORecord;
use graphene_std::raster::{CPU, Raster}; use graphene_std::raster::{CPU, Raster};
use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box}; use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box};
use graphene_std::transform::Footprint; use graphene_std::transform::Footprint;
use graphene_std::vector::{Vector, graphic_types}; use graphene_std::vector::{Vector, graphic_types};
use graphene_std::{ATTR_TRANSFORM, Context, Graphic}; use graphene_std::{ATTR_TRANSFORM, Graphic};
use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta; use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta;
use std::any::Any; use std::any::Any;
use std::sync::Arc; use std::sync::Arc;
@@ -26,7 +25,7 @@ pub use runtime_io::NodeRuntimeIO;
mod runtime; mod runtime;
pub use runtime::*; pub use runtime::*;
#[derive(Debug, serde::Serialize, serde::Deserialize)] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ExecutionRequest { pub struct ExecutionRequest {
execution_id: u64, execution_id: u64,
render_config: RenderConfig, render_config: RenderConfig,
@@ -59,6 +58,9 @@ pub struct NodeGraphExecutor {
runtime_io: NodeRuntimeIO, runtime_io: NodeRuntimeIO,
current_execution_id: u64, current_execution_id: u64,
futures: VecDeque<(u64, ExecutionContext)>, futures: VecDeque<(u64, ExecutionContext)>,
/// The most recently consumed plain render execution, kept so a runtime-replayed response with the same id
/// (sent after an async source completion) finds its context again.
last_execution_context: Option<(u64, ExecutionContext)>,
node_graph_hash: u64, node_graph_hash: u64,
/// Full path from the root document network to the node currently being inspected by the Data panel, or empty if nothing is selected. /// Full path from the root document network to the node currently being inspected by the Data panel, or empty if nothing is selected.
/// The last element is the inspect target itself; preceding elements identify the nested subnetwork the node lives in, /// The last element is the inspect target itself; preceding elements identify the nested subnetwork the node lives in,
@@ -108,6 +110,7 @@ impl NodeGraphExecutor {
let node_executor = Self { let node_executor = Self {
futures: Default::default(), futures: Default::default(),
runtime_io: NodeRuntimeIO::with_channels(request_sender, response_receiver), runtime_io: NodeRuntimeIO::with_channels(request_sender, response_receiver),
last_execution_context: None,
node_graph_hash: 0, node_graph_hash: 0,
current_execution_id: 0, current_execution_id: 0,
previous_node_to_inspect: Vec::new(), previous_node_to_inspect: Vec::new(),
@@ -375,10 +378,22 @@ impl NodeGraphExecutor {
} }
} }
let Some((queued_execution_id, execution_context)) = self.futures.pop_front() else { let execution_context = if self.futures.front().is_some_and(|&(queued_execution_id, _)| queued_execution_id == execution_id) {
panic!("InvalidGenerationId") let (_, execution_context) = self.futures.pop_front().expect("front was just matched");
self.last_execution_context = Some((execution_id, execution_context.clone()));
execution_context
} else {
// A runtime-replayed response re-uses an already consumed id; only plain renders may re-apply.
match &self.last_execution_context {
Some((last_execution_id, execution_context)) if *last_execution_id == execution_id => {
if execution_context.export_config.is_some() || execution_context.measure_fill.is_some() {
continue;
}
execution_context.clone()
}
_ => panic!("InvalidGenerationId"),
}
}; };
assert_eq!(queued_execution_id, execution_id, "Missmatch in execution id");
// TODO: Eventually remove this document upgrade code // TODO: Eventually remove this document upgrade code
// Gradient-migration measurement runs only read back the fill's evaluated geometry; they never render to the artwork. // Gradient-migration measurement runs only read back the fill's evaluated geometry; they never render to the artwork.
@@ -697,7 +712,8 @@ impl NodeGraphExecutor {
text_frames, text_frames,
clip_targets, clip_targets,
vector_data, vector_data,
appearance_attributes, fill_attributes,
stroke_attributes,
backgrounds: _, backgrounds: _,
} = render_output.metadata; } = render_output.metadata;
@@ -712,7 +728,8 @@ impl NodeGraphExecutor {
responses.add(DocumentMessage::UpdateTextFrames { text_frames }); responses.add(DocumentMessage::UpdateTextFrames { text_frames });
responses.add(DocumentMessage::UpdateClipTargets { clip_targets }); responses.add(DocumentMessage::UpdateClipTargets { clip_targets });
responses.add(DocumentMessage::UpdateVectorData { vector_data }); responses.add(DocumentMessage::UpdateVectorData { vector_data });
responses.add(DocumentMessage::UpdateAppearanceAttributes { appearance_attributes }); responses.add(DocumentMessage::UpdateFillAttributes { fill_attributes });
responses.add(DocumentMessage::UpdateStrokeAttributes { stroke_attributes });
responses.add(DocumentMessage::RenderScrollbars); responses.add(DocumentMessage::RenderScrollbars);
responses.add(DocumentMessage::RenderRulers); responses.add(DocumentMessage::RenderRulers);
responses.add(OverlaysMessage::Draw); responses.add(OverlaysMessage::Draw);
@@ -882,18 +899,9 @@ fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2,
} }
// TODO: Eventually remove this document upgrade code // TODO: Eventually remove this document upgrade code
/// Extract a monitor node's recorded output, trying each context type the runtime may have evaluated it under. /// Extract a monitor node's captured output element.
fn introspected_output<T: Clone + Send + Sync + 'static>(data: &Arc<dyn Any + Send + Sync>) -> Option<T> { fn introspected_output<T: Clone + Send + Sync + 'static>(data: &Arc<dyn Any + Send + Sync>) -> Option<T> {
if let Some(io) = data.downcast_ref::<IORecord<(), T>>() { data.downcast_ref::<T>().cloned()
return Some(io.output.clone());
}
if let Some(io) = data.downcast_ref::<IORecord<Footprint, T>>() {
return Some(io.output.clone());
}
if let Some(io) = data.downcast_ref::<IORecord<Context, T>>() {
return Some(io.output.clone());
}
None
} }
// Re-export for usage by tests in other modules // Re-export for usage by tests in other modules
@@ -909,10 +917,7 @@ mod test {
use crate::test_utils::test_prelude::{self, NodeGraphLayer}; use crate::test_utils::test_prelude::{self, NodeGraphLayer};
use graph_craft::ProtoNodeIdentifier; use graph_craft::ProtoNodeIdentifier;
use graph_craft::document::NodeNetwork; use graph_craft::document::NodeNetwork;
use graphene_std::Context;
use graphene_std::NodeParameter; use graphene_std::NodeParameter;
use graphene_std::list::Item;
use graphene_std::memo::IORecord;
use test_prelude::LayerNodeIdentifier; use test_prelude::LayerNodeIdentifier;
/// Stores all of the monitor nodes that have been attached to a graph /// Stores all of the monitor nodes that have been attached to a graph
@@ -975,24 +980,17 @@ mod test {
instrumented instrumented
} }
/// Pulls a concrete output type out of a monitor record, tolerating the three context shapes the executor records against. /// Pulls a concrete output type out of what the monitor introspects as.
/// Our monitor stores only the context snapshot, so `introspect` recreates the value itself rather than an `IORecord`.
fn downcast_record<Output: Send + Sync + Clone + 'static>(dynamic: Arc<dyn std::any::Any + Send + Sync>) -> Option<Output> { fn downcast_record<Output: Send + Sync + Clone + 'static>(dynamic: Arc<dyn std::any::Any + Send + Sync>) -> Option<Output> {
if let Some(x) = dynamic.downcast_ref::<IORecord<(), Output>>() { dynamic.downcast_ref::<Output>().cloned()
Some(x.output.clone())
} else if let Some(x) = dynamic.downcast_ref::<IORecord<Footprint, Output>>() {
Some(x.output.clone())
} else if let Some(x) = dynamic.downcast_ref::<IORecord<Context, Output>>() {
Some(x.output.clone())
} else {
None
}
} }
/// Grab all of the values of the input every time it occurs in the graph, downcast to the recorded `Output` type. /// Grab all of the values of the input every time it occurs in the graph, downcast to the recorded `Output` type.
/// A record whose type does not match `Output` is skipped, so a wrong `Output` yields an empty iterator rather than an error. /// A record whose type does not match `Output` is skipped, so a wrong `Output` yields an empty iterator rather than an error.
pub fn grab_all_input<'a, Input: NodeParameter + 'a, Output: Send + Sync + Clone + 'static>(&'a self, runtime: &'a NodeRuntime) -> impl Iterator<Item = Output> + 'a { pub fn grab_all_input<'a, Input: NodeParameter + 'a, Output: Send + Sync + Clone + 'static>(&'a self, runtime: &'a NodeRuntime) -> impl Iterator<Item = Output> + 'a {
self.protonodes_by_name self.protonodes_by_name
.get(&Input::NODE_IDENTIFIER) .get(&Input::identifier())
.map_or([].as_slice(), |x| x.as_slice()) .map_or([].as_slice(), |x| x.as_slice())
.iter() .iter()
.filter_map(|inputs| inputs.get(Input::INDEX)) .filter_map(|inputs| inputs.get(Input::INDEX))
@@ -1009,11 +1007,9 @@ mod test {
} }
/// Grabs a ranked input's recorded value as its bare element `Element`. /// Grabs a ranked input's recorded value as its bare element `Element`.
/// A stored value materializes as an `Item<Element>` wire, so the monitor records the whole cell and this unwraps its element. /// `introspect` serves a rank-0 input as its element, so no cell unwrapping is needed here.
pub fn grab_ranked_input<Input: NodeParameter, Element: Send + Sync + Clone + 'static>(&self, path: &Vec<NodeId>, runtime: &NodeRuntime) -> Option<Element> { pub fn grab_ranked_input<Input: NodeParameter, Element: Send + Sync + Clone + 'static>(&self, path: &Vec<NodeId>, runtime: &NodeRuntime) -> Option<Element> {
let input_monitor_node = self.protonodes_by_path.get(path)?.get(Input::INDEX)?; self.grab_protonode_input::<Input, Element>(path, runtime)
let dynamic = runtime.executor.introspect(input_monitor_node).ok()?;
Self::downcast_record::<Item<Element>>(dynamic).map(|item| item.into_element())
} }
pub fn grab_input_from_layer<Input: NodeParameter, Output: Send + Sync + Clone + 'static>( pub fn grab_input_from_layer<Input: NodeParameter, Output: Send + Sync + Clone + 'static>(
@@ -1023,7 +1019,7 @@ mod test {
runtime: &NodeRuntime, runtime: &NodeRuntime,
) -> Option<Output> { ) -> Option<Output> {
let node_graph_layer = NodeGraphLayer::new(layer, network_interface); let node_graph_layer = NodeGraphLayer::new(layer, network_interface);
let node = node_graph_layer.upstream_node_id_from_protonode(Input::NODE_IDENTIFIER)?; let node = node_graph_layer.upstream_node_id_from_protonode(Input::identifier())?;
self.grab_protonode_input::<Input, Output>(&vec![node], runtime) self.grab_protonode_input::<Input, Output>(&vec![node], runtime)
} }
} }
+186 -93
View File
@@ -3,25 +3,24 @@ use crate::messages::frontend::utility_types::{ExportBounds, FileType};
use glam::{DAffine2, DVec2, UVec2}; use glam::{DAffine2, DVec2, UVec2};
use graph_craft::application_io::resource::ResourceRegistry; use graph_craft::application_io::resource::ResourceRegistry;
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi}; use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
use graph_craft::concrete;
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue}; use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
use graph_craft::document::{NodeId, NodeNetwork}; use graph_craft::document::{NodeId, NodeNetwork};
use graph_craft::graphene_compiler::Compiler; use graph_craft::graphene_compiler::Compiler;
use graph_craft::proto::GraphErrors; use graph_craft::proto::GraphErrors;
use graphene_std::application_io::{ApplicationIo, ExportFormat, NodeGraphUpdateMessage, NodeGraphUpdateSender, RenderConfig, Texture}; use graphene_std::application_io::{ApplicationIo, ExportFormat, NodeGraphUpdateMessage, NodeGraphUpdateSender, RenderConfig, Texture};
use graphene_std::bounds::RenderBoundingBox; use graphene_std::bounds::RenderBoundingBox;
use graphene_std::list::{Item, List}; use graphene_std::core_types::gpoll::GPoll;
use graphene_std::memo::IORecord; use graphene_std::ops::ConvertAsync;
use graphene_std::ops::Convert;
#[cfg(all(target_family = "wasm", feature = "gpu", feature = "wasm"))] #[cfg(all(target_family = "wasm", feature = "gpu", feature = "wasm"))]
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasSurface, CanvasSurfaceHandle}; use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasSurface, CanvasSurfaceHandle};
use graphene_std::raster_types::Raster; use graphene_std::raster_types::Raster;
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender, SvgSegment}; use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender, SvgSegment};
use graphene_std::runtime::{DynGraphRuntime, DynNotifier, DynSpawner, GraphRuntime, RuntimeHandle, SourceFuture, Spawner, poll_once};
use graphene_std::transform::RenderQuality; use graphene_std::transform::RenderQuality;
use graphene_std::vector::Vector; use graphene_std::vector::Vector;
use graphene_std::vector::style::RenderMode; use graphene_std::vector::style::RenderMode;
use graphene_std::{Artboard, Context, Graphic}; use graphene_std::{Artboard, Graphic};
use interpreted_executor::dynamic_executor::{DynamicExecutor, IntrospectError, ResolvedDocumentNodeTypesDelta}; use interpreted_executor::dynamic_executor::{DynamicExecutor, ResolvedDocumentNodeTypesDelta};
use interpreted_executor::util::wrap_network_in_scope; use interpreted_executor::util::wrap_network_in_scope;
use spin::Mutex; use spin::Mutex;
use std::sync::Arc; use std::sync::Arc;
@@ -40,6 +39,9 @@ pub struct NodeRuntime {
editor_preferences: EditorPreferences, editor_preferences: EditorPreferences,
old_graph: Option<NodeNetwork>, old_graph: Option<NodeNetwork>,
update_thumbnails: bool, update_thumbnails: bool,
graph_runtime: Arc<DynGraphRuntime>,
/// The last plain render request, replayed when an async source completion marks the graph dirty.
last_render: Option<ExecutionRequest>,
editor_api: Arc<PlatformEditorApi>, editor_api: Arc<PlatformEditorApi>,
resources: ResourceRegistry, resources: ResourceRegistry,
@@ -119,20 +121,88 @@ impl NodeGraphUpdateSender for InternalNodeGraphUpdateSender {
// TODO: Replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>) or similar // TODO: Replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>) or similar
pub static NODE_RUNTIME: once_cell::sync::Lazy<Mutex<Option<NodeRuntime>>> = once_cell::sync::Lazy::new(|| Mutex::new(None)); pub static NODE_RUNTIME: once_cell::sync::Lazy<Mutex<Option<NodeRuntime>>> = once_cell::sync::Lazy::new(|| Mutex::new(None));
#[cfg(not(target_family = "wasm"))]
pub struct TokioSpawner(Option<tokio::runtime::Runtime>);
#[cfg(not(target_family = "wasm"))]
impl TokioSpawner {
pub fn new() -> Self {
Self(Some(tokio::runtime::Runtime::new().expect("Failed to start the async source runtime")))
}
}
#[cfg(not(target_family = "wasm"))]
impl Default for TokioSpawner {
fn default() -> Self {
Self::new()
}
}
#[cfg(not(target_family = "wasm"))]
impl Spawner for TokioSpawner {
fn spawn(&self, mut task: SourceFuture) -> bool {
let runtime = self.0.as_ref().expect("runtime lives until drop");
let _guard = runtime.enter();
if poll_once(&mut task) {
return true;
}
runtime.spawn(task);
false
}
}
/// Dropping a tokio runtime blocks on its tasks, which panics inside an async context; the tests drop
/// [`NodeRuntime`] from one, so shut down in the background instead.
#[cfg(not(target_family = "wasm"))]
impl Drop for TokioSpawner {
fn drop(&mut self) {
if let Some(runtime) = self.0.take() {
runtime.shutdown_background();
}
}
}
#[cfg(target_family = "wasm")]
pub struct WasmSpawner;
#[cfg(target_family = "wasm")]
impl Spawner for WasmSpawner {
fn spawn(&self, mut task: SourceFuture) -> bool {
if poll_once(&mut task) {
return true;
}
wasm_bindgen_futures::spawn_local(task);
false
}
}
impl NodeRuntime { impl NodeRuntime {
pub fn new(receiver: Receiver<GraphRuntimeRequest>, sender: Sender<NodeGraphUpdate>) -> Self { pub fn new(receiver: Receiver<GraphRuntimeRequest>, sender: Sender<NodeGraphUpdate>) -> Self {
#[cfg(not(target_family = "wasm"))]
// The box is a trait object, so `Box::default()` cannot name the concrete spawner.
#[allow(clippy::box_default)]
let spawner: Box<DynSpawner> = Box::new(TokioSpawner::new());
#[cfg(target_family = "wasm")]
let spawner: Box<DynSpawner> = Box::new(WasmSpawner);
let graph_runtime: Arc<DynGraphRuntime> = Arc::new(GraphRuntime::new(spawner));
let mut executor = DynamicExecutor::default();
executor.set_runtime(Arc::clone(&graph_runtime));
Self { Self {
executor: DynamicExecutor::default(), executor,
receiver, receiver,
sender: InternalNodeGraphUpdateSender(sender.clone()), sender: InternalNodeGraphUpdateSender(sender.clone()),
editor_preferences: EditorPreferences::default(), editor_preferences: EditorPreferences::default(),
old_graph: None, old_graph: None,
resources: ResourceRegistry::default(), resources: ResourceRegistry::default(),
update_thumbnails: true, update_thumbnails: true,
graph_runtime: Arc::clone(&graph_runtime),
last_render: None,
editor_api: PlatformEditorApi { editor_api: PlatformEditorApi {
editor_preferences: Box::new(EditorPreferences::default()), editor_preferences: Box::new(EditorPreferences::default()),
node_graph_message_sender: Box::new(InternalNodeGraphUpdateSender(sender)), node_graph_message_sender: Box::new(InternalNodeGraphUpdateSender(sender)),
runtime: RuntimeHandle(graph_runtime),
#[cfg(not(test))] #[cfg(not(test))]
application_io: None, application_io: None,
@@ -157,6 +227,11 @@ impl NodeRuntime {
} }
} }
#[cfg(test)]
pub fn take_dirty(&self) -> bool {
self.executor.take_dirty()
}
pub async fn run(&mut self) -> Option<Texture> { pub async fn run(&mut self) -> Option<Texture> {
let mut preferences = None; let mut preferences = None;
let mut graph = None; let mut graph = None;
@@ -173,6 +248,9 @@ impl NodeRuntime {
} }
let for_export = execution_request.render_config.for_export; let for_export = execution_request.render_config.for_export;
if !for_export {
self.last_render = Some(execution_request.clone());
}
execution = Some(request); execution = Some(request);
@@ -193,6 +271,10 @@ impl NodeRuntime {
eyedropper.render_config.pointer = execution.render_config.pointer; eyedropper.render_config.pointer = execution.render_config.pointer;
} }
if self.executor.take_dirty() && execution.is_none() {
execution = self.last_render.clone().map(GraphRuntimeRequest::ExecutionRequest);
}
let requests = [preferences, graph, eyedropper, execution].into_iter().flatten(); let requests = [preferences, graph, eyedropper, execution].into_iter().flatten();
for request in requests { for request in requests {
@@ -203,11 +285,12 @@ impl NodeRuntime {
application_io: self.editor_api.application_io.clone(), application_io: self.editor_api.application_io.clone(),
node_graph_message_sender: Box::new(self.sender.clone()), node_graph_message_sender: Box::new(self.sender.clone()),
editor_preferences: Box::new(preferences), editor_preferences: Box::new(preferences),
runtime: self.editor_api.runtime.clone(),
} }
.into(); .into();
if let Some(graph) = self.old_graph.clone() { if let Some(graph) = self.old_graph.clone() {
// We ignore this result as compilation errors should have been reported in an earlier iteration // We ignore this result as compilation errors should have been reported in an earlier iteration
let _ = self.update_network(graph).await; let _ = self.update_network(graph);
} }
} }
GraphRuntimeRequest::GraphUpdate(GraphUpdate { GraphRuntimeRequest::GraphUpdate(GraphUpdate {
@@ -222,7 +305,7 @@ impl NodeRuntime {
self.resources = resources; self.resources = resources;
self.node_graph_errors.clear(); self.node_graph_errors.clear();
let result = self.update_network(network).await; let result = self.update_network(network);
let node_graph_errors = self.node_graph_errors.clone(); let node_graph_errors = self.node_graph_errors.clone();
self.update_thumbnails = true; self.update_thumbnails = true;
@@ -237,7 +320,7 @@ impl NodeRuntime {
render_config.export_format = ExportFormat::Svg; render_config.export_format = ExportFormat::Svg;
} }
let result = self.execute_network(render_config).await; let result = self.execute_network(render_config);
let mut responses = VecDeque::new(); let mut responses = VecDeque::new();
// TODO: Only process monitor nodes if the graph has changed, not when only the Footprint changes // TODO: Only process monitor nodes if the graph has changed, not when only the Footprint changes
if !render_config.for_eyedropper { if !render_config.for_eyedropper {
@@ -258,10 +341,10 @@ impl NodeRuntime {
.application_io .application_io
.as_ref() .as_ref()
.unwrap() .unwrap()
.gpu_executor() .gpu_executor_arc()
.expect("GPU executor should be available when we receive a texture"); .expect("GPU executor should be available when we receive a texture");
let raster_cpu = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor).await; let raster_cpu = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, wgpu_executor::WgpuExecutorHandle(executor)).await;
let (data, width, height) = raster_cpu.to_flat_u8(); let (data, width, height) = raster_cpu.to_flat_u8();
@@ -282,10 +365,10 @@ impl NodeRuntime {
.application_io .application_io
.as_ref() .as_ref()
.unwrap() .unwrap()
.gpu_executor() .gpu_executor_arc()
.expect("GPU executor should be available when we receive a texture"); .expect("GPU executor should be available when we receive a texture");
let raster_cpu = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor).await; let raster_cpu = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, wgpu_executor::WgpuExecutorHandle(executor)).await;
self.sender.send_eyedropper_preview(raster_cpu); self.sender.send_eyedropper_preview(raster_cpu);
continue; continue;
@@ -345,7 +428,7 @@ impl NodeRuntime {
None None
} }
async fn update_network(&mut self, graph: NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> { fn update_network(&mut self, graph: NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
let mut scoped_network = wrap_network_in_scope(graph, self.editor_api.clone()); let mut scoped_network = wrap_network_in_scope(graph, self.editor_api.clone());
if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| self.resources.hash(&resource_id)) { if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| self.resources.hash(&resource_id)) {
@@ -356,7 +439,7 @@ impl NodeRuntime {
assert_eq!(scoped_network.exports.len(), 1, "Graph with multiple outputs not yet handled"); assert_eq!(scoped_network.exports.len(), 1, "Graph with multiple outputs not yet handled");
let c = Compiler {}; let c = Compiler {};
let proto_network = match c.compile_single(scoped_network) { let proto_network = match c.compile_single(scoped_network, &interpreted_executor::node_registry::NODE_REGISTRY) {
Ok(network) => network, Ok(network) => network,
Err(e) => return Err((ResolvedDocumentNodeTypesDelta::default(), e)), Err(e) => return Err((ResolvedDocumentNodeTypesDelta::default(), e)),
}; };
@@ -368,20 +451,24 @@ impl NodeRuntime {
.collect::<Vec<_>>(); .collect::<Vec<_>>();
assert_ne!(proto_network.nodes.len(), 0, "No proto nodes exist?"); assert_ne!(proto_network.nodes.len(), 0, "No proto nodes exist?");
self.executor.update(proto_network).await.map_err(|(types, e)| { self.executor.update(proto_network).map_err(|(types, e)| {
self.node_graph_errors.clone_from(&e); self.node_graph_errors.clone_from(&e);
(types, format!("{e:?}")) (types, format!("{e:?}"))
}) })
} }
async fn execute_network(&mut self, render_config: RenderConfig) -> Result<TaggedValue, String> { fn execute_network(&mut self, render_config: RenderConfig) -> Result<TaggedValue, String> {
use graph_craft::graphene_compiler::Executor; use graph_craft::graphene_compiler::Executor;
match self.executor.input_type() { match (&self.executor).execute(render_config).map_err(|e| e.to_string())? {
Some(t) if t == concrete!(Context) => (&self.executor).execute(render_config.into_context()).await.map_err(|e| e.to_string()), GPoll::Final(value) | GPoll::Partial(value) => Ok(value),
Some(t) if t == concrete!(()) => (&self.executor).execute(()).await.map_err(|e| e.to_string()), GPoll::Fallback(boxed) => {
Some(t) => Err(format!("Invalid input type {t:?}")), let (value, error) = *boxed;
_ => Err(format!("No input type:\n{:?}", self.node_graph_errors)), error!("Node graph evaluation reported an error alongside its fallback output: {error:?}");
Ok(value)
}
GPoll::Pending => Err("Node graph evaluation is pending".to_string()),
GPoll::Error(error) => Err(format!("Node graph evaluation failed: {error:?}")),
} }
} }
@@ -406,66 +493,71 @@ impl NodeRuntime {
continue; continue;
}; };
// Extract the monitor node's stored `Graphic` data // Read the monitored run directly, inside the introspection window
let Ok(introspected_data) = self.executor.introspect(monitor_node_path) else { let thumbnail_renders = &mut self.thumbnail_renders;
let vector_modify = &mut self.vector_modify;
let result = self.executor.introspect_with(monitor_node_path, |layout, batch, _arena| {
use graphene_std::core_types::record::{Group, GroupItem, RunView};
let type_id = layout.element.type_id;
// Graphic run: thumbnail (text-aware bounds, since the `BoundingBox` trait can't lay out `Graphic::Text` content)
if type_id == std::any::TypeId::of::<Graphic>() {
if update_thumbnails {
// SAFETY: `introspect_with`'s closure is higher-ranked over the batch's
// lifetime, so the item cannot escape this read window, which the
// frames outlive.
let item = unsafe { GroupItem::from_resident(batch) };
let bounds = graphene_std::renderer::graphic_list_bounding_box(&RunView::<Graphic>::new(&item)?, DAffine2::IDENTITY);
let group = Graphic::Group(Group { row: None, content: item });
Self::render_thumbnail(thumbnail_renders, parent_network_node_id, &group, bounds, responses)
}
Some(())
}
// Artboard thumbnail bounds come from the clipping rectangles, not the content union, since the renderer
// clips content to those rectangles so anything outside isn't visible
else if type_id == std::any::TypeId::of::<Artboard>() {
if update_thumbnails {
// SAFETY: `introspect_with`'s closure is higher-ranked over the batch's
// lifetime, so the item cannot escape this read window, which the
// frames outlive.
let item = unsafe { GroupItem::from_resident(batch) };
let run = RunView::<Artboard>::new(&item)?;
let bounds = artboard_clip_bounds(&run);
Self::render_thumbnail(thumbnail_renders, parent_network_node_id, &run, bounds, responses)
}
Some(())
}
// Vector run: vector modifications
else if type_id == std::any::TypeId::of::<Vector>() {
// SAFETY: `introspect_with`'s closure is higher-ranked over the batch's
// lifetime, so the item cannot escape this read window, which the
// frames outlive.
let item = unsafe { GroupItem::from_resident(batch) };
let run = RunView::<Vector>::new(&item)?;
use graphene_std::core_types::lane::LaneSource;
vector_modify.insert(parent_network_node_id, run.element(0).cloned().unwrap_or_default());
Some(())
}
// String run: thumbnail (bounds need text layout, which the `BoundingBox` trait can't do for a bare `String`)
else if type_id == std::any::TypeId::of::<String>() {
if update_thumbnails {
// SAFETY: `introspect_with`'s closure is higher-ranked over the batch's
// lifetime, so the item cannot escape this read window, which the
// frames outlive.
let item = unsafe { GroupItem::from_resident(batch) };
let run = RunView::<String>::new(&item)?;
let bounds = graphene_std::renderer::text_list_bounding_box(&run, DAffine2::IDENTITY);
Self::render_thumbnail(thumbnail_renders, parent_network_node_id, &run, bounds, responses)
}
Some(())
} else {
log::warn!("Failed to read monitor node output {parent_network_node_id:?}");
Some(())
}
});
if let Err(_error) = result {
// TODO: Fix the root of the issue causing the spam of this warning (this at least temporarily disables it in release builds) // TODO: Fix the root of the issue causing the spam of this warning (this at least temporarily disables it in release builds)
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
warn!("Failed to introspect monitor node {}", self.executor.introspect(monitor_node_path).unwrap_err()); warn!("Failed to introspect monitor node {}", _error);
continue;
};
// Graphic list: thumbnail (text-aware bounds, since the `BoundingBox` trait can't lay out `Graphic::TextList` content)
if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, List<Graphic>>>() {
if update_thumbnails {
let bounds = graphene_std::renderer::graphic_list_bounding_box(&io.output, DAffine2::IDENTITY);
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &io.output, bounds, responses)
}
}
// Artboard thumbnail bounds come from the clipping rectangles, not the content union, since the renderer
// clips content to those rectangles so anything outside isn't visible
else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, List<Artboard>>>() {
if update_thumbnails {
let bounds = artboard_clip_bounds(&io.output);
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &io.output, bounds, responses)
}
}
// Vector list: vector modifications
else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, List<Vector>>>() {
// Insert the vector modify
self.vector_modify.insert(parent_network_node_id, io.output.element(0).cloned().unwrap_or_default());
}
// String list: thumbnail (bounds need text layout, which the `BoundingBox` trait can't do for a bare `String`)
else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, List<String>>>() {
if update_thumbnails {
let bounds = graphene_std::renderer::text_list_bounding_box(&io.output, DAffine2::IDENTITY);
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &io.output, bounds, responses)
}
}
// Rank-0 wires record single items; each arm mirrors its list counterpart through a singleton raise
else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, Item<Graphic>>>() {
if update_thumbnails {
let singleton = List::new_from_item(io.output.clone());
let bounds = graphene_std::renderer::graphic_list_bounding_box(&singleton, DAffine2::IDENTITY);
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &singleton, bounds, responses)
}
} else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, Item<Artboard>>>() {
if update_thumbnails {
let singleton = List::new_from_item(io.output.clone());
let bounds = artboard_clip_bounds(&singleton);
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &singleton, bounds, responses)
}
} else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, Item<Vector>>>() {
self.vector_modify.insert(parent_network_node_id, io.output.element().clone());
} else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, Item<String>>>() {
if update_thumbnails {
let singleton = List::new_from_item(io.output.clone());
let bounds = graphene_std::renderer::text_list_bounding_box(&singleton, DAffine2::IDENTITY);
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &singleton, bounds, responses)
}
}
// Other
else {
log::warn!("Failed to downcast monitor node output {parent_network_node_id:?}");
} }
} }
} }
@@ -533,11 +625,12 @@ impl NodeRuntime {
/// Returns the union of the artboards' clipping rectangles, used as the thumbnail bounds for an artboard layer so the /// Returns the union of the artboards' clipping rectangles, used as the thumbnail bounds for an artboard layer so the
/// framing matches what's actually visible after clipping rather than the unclipped content extents. /// framing matches what's actually visible after clipping rather than the unclipped content extents.
fn artboard_clip_bounds(artboards: &List<Artboard>) -> RenderBoundingBox { fn artboard_clip_bounds<'a, S: graphene_std::core_types::lane::LaneSource<Element = Artboard<'a>>>(artboards: &S) -> RenderBoundingBox {
use graphene_std::core_types::attribute::{Dimensions, Location};
let mut combined: Option<[DVec2; 2]> = None; let mut combined: Option<[DVec2; 2]> = None;
for index in 0..artboards.len() { for index in 0..artboards.lane_count() {
let location: DVec2 = artboards.attribute_cloned_or_default(graphene_std::ATTR_LOCATION, index); let location: DVec2 = artboards.attr::<Location>(index);
let dimensions: DVec2 = artboards.attribute_cloned_or_default(graphene_std::ATTR_DIMENSIONS, index); let dimensions: DVec2 = artboards.attr::<Dimensions>(index);
let bounds = [location, location + dimensions]; let bounds = [location, location + dimensions];
combined = Some(match combined { combined = Some(match combined {
Some(existing) => [existing[0].min(bounds[0]), existing[1].max(bounds[1])], Some(existing) => [existing[0].min(bounds[0]), existing[1].max(bounds[1])],
@@ -566,14 +659,6 @@ fn expand_to_thumbnail_aspect(bounds: [DVec2; 2]) -> [DVec2; 2] {
[center - half, center + half] [center - half, center + half]
} }
pub async fn introspect_node(path: &[NodeId]) -> Result<Arc<dyn std::any::Any + Send + Sync + 'static>, IntrospectError> {
let runtime = NODE_RUNTIME.lock();
if let Some(ref mut runtime) = runtime.as_ref() {
return runtime.executor.introspect(path);
}
Err(IntrospectError::RuntimeNotReady)
}
pub async fn run_node_graph() -> (bool, Option<Texture>) { pub async fn run_node_graph() -> (bool, Option<Texture>) {
let Some(mut runtime) = NODE_RUNTIME.try_lock() else { return (false, None) }; let Some(mut runtime) = NODE_RUNTIME.try_lock() else { return (false, None) };
if let Some(ref mut runtime) = runtime.as_mut() { if let Some(ref mut runtime) = runtime.as_mut() {
@@ -593,12 +678,20 @@ pub(crate) fn replace_application_io(application_io: PlatformApplicationIo) {
} }
} }
pub fn set_completion_notifier(notifier: Arc<DynNotifier>) {
let node_runtime = NODE_RUNTIME.lock();
if let Some(node_runtime) = &*node_runtime {
node_runtime.graph_runtime.set_notifier(notifier);
}
}
impl NodeRuntime { impl NodeRuntime {
pub(crate) fn replace_application_io(&mut self, application_io: PlatformApplicationIo) { pub(crate) fn replace_application_io(&mut self, application_io: PlatformApplicationIo) {
self.editor_api = PlatformEditorApi { self.editor_api = PlatformEditorApi {
application_io: Some(application_io.into()), application_io: Some(application_io.into()),
node_graph_message_sender: Box::new(self.sender.clone()), node_graph_message_sender: Box::new(self.sender.clone()),
editor_preferences: Box::new(self.editor_preferences.clone()), editor_preferences: Box::new(self.editor_preferences.clone()),
runtime: self.editor_api.runtime.clone(),
} }
.into(); .into();
} }
+21
View File
@@ -51,6 +51,27 @@ impl EditorTestUtils {
} }
runtime.run().await; runtime.run().await;
// An async source reports `Pending` on the evaluation that starts it and marks the runtime dirty once
// it completes, so the value only reaches the render on a follow-up evaluation. The superseded response's
// `Pending` error is ignored, but its messages carry the incremental resolved-types delta and must be
// dispatched, or the editor's type map desyncs permanently.
while runtime.take_dirty() {
let mut superseded_messages = VecDeque::new();
let _ = editor.poll_node_graph_evaluation(&mut superseded_messages);
for message in superseded_messages {
editor.handle_message(message);
}
let portfolio = &mut editor.dispatcher.message_handlers.portfolio_message_handler;
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
let document = documents.get_mut(&document_id).unwrap();
if let Err(e) = executor.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO) {
return Err(format!("submit_current_node_graph_evaluation failed\n\n{e}"));
}
runtime.run().await;
}
let mut messages = VecDeque::new(); let mut messages = VecDeque::new();
if let Err(e) = editor.poll_node_graph_evaluation(&mut messages) { if let Err(e) = editor.poll_node_graph_evaluation(&mut messages) {
return Err(format!("Graph should render\n\n{e}")); return Err(format!("Graph should render\n\n{e}"));
+29 -21
View File
@@ -5,7 +5,7 @@ extern crate proc_macro;
use proc_macro::TokenStream; use proc_macro::TokenStream;
use proc_macro2::Span; use proc_macro2::Span;
use quote::quote; use quote::quote;
use syn::{DeriveInput, GenericParam, Lifetime, LifetimeParam, TypeParamBound, parse_macro_input}; use syn::{DeriveInput, GenericParam, Lifetime, TypeParamBound, parse_macro_input};
/// Derives an implementation for the [`DynAny`] trait. /// Derives an implementation for the [`DynAny`] trait.
/// ///
@@ -40,37 +40,45 @@ pub fn system_desc_derive(input: TokenStream) -> TokenStream {
let struct_name = &ast.ident; let struct_name = &ast.ident;
let generics = &ast.generics; let generics = &ast.generics;
let static_params = replace_lifetimes(generics, "'static"); let static_params = generic_arguments(generics, "'static");
let dyn_params = replace_lifetimes(generics, "'dyn_any"); let dyn_params = generic_arguments(generics, "'dyn_any");
let old_params = &generics.params.iter().collect::<Vec<_>>(); let impl_params = generics.params.iter().map(|param| match param {
GenericParam::Type(t) => {
let mut t = t.clone();
t.bounds.push(TypeParamBound::Lifetime(Lifetime::new("'static", Span::call_site())));
quote! {#t}
}
param => quote! {#param},
});
quote! { quote! {
unsafe impl<'dyn_any, #(#old_params,)*> dyn_any::StaticType for #struct_name <#(#dyn_params,)*> { unsafe impl<'dyn_any, #(#impl_params,)*> dyn_any::StaticType for #struct_name <#(#dyn_params,)*> {
type Static = #struct_name <#(#static_params,)*>; type Static = #struct_name <#(#static_params,)*>;
} }
} }
.into() .into()
} }
fn replace_lifetimes(generics: &syn::Generics, replacement: &str) -> Vec<proc_macro2::TokenStream> { /// The struct's generic parameters as argument tokens: bare idents for type
/// and const parameters (bounds are illegal in argument position), the
/// replacement for lifetimes.
fn generic_arguments(generics: &syn::Generics, replacement: &str) -> Vec<proc_macro2::TokenStream> {
generics generics
.params .params
.iter() .iter()
.map(|param| { .map(|param| match param {
let param = match param { GenericParam::Lifetime(_) => {
GenericParam::Lifetime(_) => GenericParam::Lifetime(LifetimeParam::new(Lifetime::new(replacement, Span::call_site()))), let lifetime = Lifetime::new(replacement, Span::call_site());
GenericParam::Type(t) => { quote! {#lifetime}
let mut t = t.clone(); }
t.bounds.iter_mut().for_each(|bond| { GenericParam::Type(t) => {
if let TypeParamBound::Lifetime(t) = bond { let ident = &t.ident;
*t = Lifetime::new(replacement, Span::call_site()) quote! {#ident}
} }
}); GenericParam::Const(c) => {
GenericParam::Type(t.clone()) let ident = &c.ident;
} quote! {#ident}
c => c.clone(), }
};
quote! {#param}
}) })
.collect::<Vec<_>>() .collect::<Vec<_>>()
} }
+119 -131
View File
@@ -1,173 +1,161 @@
# Creating Nodes In Graphite # The Graphite Node Graph
## Purpose of Nodes Graphite is a node based image editor. Everything it renders comes from evaluating a graph of nodes, and this directory holds that system: the types nodes are built on, the node library, the macro that turns a plain Rust function into a node, and the compiler and executor that turn a saved document into a running graph.
Graphite is an image editor which is centered around a node based editing workflow, which allows operations to be visually connected in a graph. This is flexible as it allows all operations to be viewed or modified at any time without losing original data. The node system has been designed to be as general as possible with all data types being representable and a broad selection of nodes for a variety of use cases being planned. This is an orientation document, not a specification. It says what lives where and what the vocabulary means. The code is the ground truth, and the module level `//!` headers under `libraries/core-types/src/` carry the real design detail.
## The Document Graph ## Crate map
The graph that is presented to users in the editor is known as the document graph, and is defined in the `NodeNetwork` struct. Each node that has been placed in this graph has the following properties: Foundations, in `libraries/`:
```rs | Crate | Directory | What it is |
pub struct DocumentNode { | --- | --- | --- |
pub inputs: Vec<NodeInput>, | `core-types` | `libraries/core-types` | The `Node` trait, records, attributes, the arena, contexts, and the node registry. Everything else sits on it. |
pub call_argument: Type, | `no-std-types` | `libraries/no-std-types` | `no_std` primitives shared with the GPU shader crates: color, blending, choice types. |
pub implementation: DocumentNodeImplementation, | `graphene-hash` | `libraries/graphene-hash` | `CacheHash`, which hashes floats by bit pattern so cache keys stay stable. |
pub skip_deduplication: bool, | `graphic-types` | `libraries/graphic-types` | Document element types: `Graphic`, `Vector`, `Artboard`, and their attribute markers. |
pub visible: bool, | `raster-types` | `libraries/raster-types` | `Image`, `Raster<CPU>` and `Raster<GPU>`, `Texture`, and the pixel traits. |
pub original_location: OriginalLocation, | `vector-types` | `libraries/vector-types` | Vector geometry: `Vector`, subpaths, point and segment domains, gradients, styles. |
} | `rendering` | `libraries/rendering` | The `Render` trait and the SVG and Vello backends. |
``` | `graphene-application-io` | `libraries/application-io` | Traits for reaching the host: GPU access, resource loading, `EditorApi`. |
(Explanatory comments omitted; the actual definition is currently found in [`node-graph/graph-craft/src/document.rs`](https://github.com/GraphiteEditor/Graphite/blob/master/node-graph/graph-craft/src/document.rs)) | `graphene-resource` | `libraries/resources` | Content addressed binary blobs and their async loading. |
| `graphene-canvas-utils` | `libraries/canvas-utils` | HTML canvas helpers, and nothing at all off wasm. |
| `wgpu-executor` | `libraries/wgpu-executor` | The GPU backend: wgpu context, pipeline and texture caches, the Vello renderer. |
Each `DocumentNode` is of a particular type, for example the "Opacity" node type. You can define your own type of document node in `editor/src/messages/portfolio/document/node_graph/node_graph_message_handler/document_node_types.rs`. A sample document node type definition for the opacity node is shown: The node library, in `nodes/`:
```rs | Crate | Directory | What it is |
DocumentNodeDefinition { | --- | --- | --- |
name: "Opacity", | `graphene-core` | `nodes/gcore` | Core nodes: arithmetic, context modification, memoization, animation, and the pilot record nodes. |
category: "Image Adjustments", | `graphene-std` | `nodes/gstd` | The standard library. Re-exports every other node crate and adds the render pipeline, text, and platform IO nodes. |
implementation: DocumentNodeImplementation::proto("graphene_core::raster::OpacityNode"), | `blending-nodes` | `nodes/blending` | Blend mode, opacity, and fill. |
inputs: vec![ | `brush-nodes` | `nodes/brush` | Brush strokes, stamping, and brush rendering. |
DocumentInputType::value("Image", TaggedValue::ImageFrame(ImageFrame::empty()), true), | `graphic-nodes` | `nodes/graphic` | Grouping and artboard construction over `Graphic`. |
DocumentInputType::value("Factor", TaggedValue::F32(100.), false), | `math-nodes` | `nodes/math` | The expression parser node plus arithmetic, random, and vector math. |
], | `path-bool-nodes` | `nodes/path-bool` | Boolean path operations on vector geometry. |
outputs: vec![DocumentOutputType::new("Image", FrontendGraphDataType::Raster)], | `raster-nodes` | `nodes/raster` | Color adjustments, blending, and filters. Written `no_std` capable so the kernels double as GPU shaders. |
properties: node_properties::multiply_opacity, | `repeat-nodes` | `nodes/repeat` | Grid, linear, and circular repeats. |
..Default::default() | `text-nodes` | `nodes/text` | Font loading, glyph shaping, text to path, and string operations. |
}, | `transform-nodes` | `nodes/transform` | Translation, rotation, scale, skew, and footprint aware transforms. |
``` | `vector-nodes` | `nodes/vector` | Shape generators, path operations, and vector modification. |
The identifier here must be the same as that of the proto-node which will be discussed soon (usually the path to the node implementation). Compiler and runtime:
> [!NOTE] | Crate | Directory | What it is |
> Nodes defined in `graphene_core` are re-exported by `graphene_std`. However if the strings for the type names do not match exactly then you will encounter an error. | --- | --- | --- |
| `graph-craft` | `graph-craft` | The document graph and its lowering: `NodeNetwork` and `DocumentNode` down to `ProtoNetwork`, plus type inference. |
| `preprocessor` | `preprocessor` | The pass over a freshly loaded document: expands proto nodes into their definitions, injects scopes, resolves resource inputs. |
| `interpreted-executor` | `interpreted-executor` | The dynamic executor. Instantiates a `ProtoNetwork` into a tree of boxed nodes and evaluates it. |
| `node-macro` | `node-macro` | `#[node]` and friends. Generates the node struct, its `Node` impl, the registry entries, and the editor metadata. |
| `graphene-cli` | `graphene-cli` | Headless CLI: load a document, compile it, run it, export the result. |
## Properties panel ## Core concepts
The input names are shown in the graph when an input is exposed (with a dot in the properties panel). The default input is used when a node is first created or when a link is disconnected. An input is comprised from a `TaggedValue` (allowing serialization of a dynamic type with serde) in addition to an exposed boolean, which defines if the input is shown as a dot in the node graph UI by default. In the opacity node, the "Color" input is shown but the "Factor" input is hidden from the graph by default, allowing for a less cluttered graph. ### Nodes
The properties field is a function that defines a number input, which can be seen by selecting the opacity node in the graph. The code for this property is shown below: `Node` lives in `libraries/core-types/src/node.rs` and has exactly one required method, `serve`. A node serves its output record through a frame claim its caller hands it, and returns a proof that only the claim's own closing methods can mint, so a served record is of the claimed layout by construction rather than by convention. Each node claims its frame out of the free space its caller left, so the frame space divides without bookkeeping.
```rs Everything else on the trait has a default. `extent_at` and `extent` report how many items the node produces at a nesting level, `layout` reports the record layout, and `eval_batch` serves a whole range at once. The default `eval_batch` advertises no support and drivers fall back to per lane serves with copy out, so an override exists to beat that loop and never for correctness.
pub fn multiply_opacity(document_node: &DocumentNode, node_id: NodeId, _context: &mut NodePropertiesContext) -> Vec<LayoutGroup> {
let factor = number_widget(document_node, node_id, 1, "Factor", NumberInput::default().min(0.).max(100.).unit("%"), true);
vec![LayoutGroup::Row { widgets: factor }] Kernels written with the macro do not see `serve`. They receive typed inputs and call `eval` on them, and the generated code handles the claim, the protocol, and status folding.
### Records
A record is what flows between nodes: the element at offset 0 plus one field per attribute written upstream. Its `Layout` is computed at wiring time from the upstream write set and is never serialized. Records of inline layouts live in the `RecordValue` itself, and larger ones live as per lane views on the evaluation's `Frames`, which the root owns and every node claims its own frame out of. Only generated and wiring code touches offsets, so a safe kernel cannot misalign a field.
`libraries/core-types/src/record/` is split by abstraction level, and each module's `//!` header states its job:
| Module | Concern |
| --- | --- |
| `layout` | Wiring time shape facts: the layout a record takes and the writes it folds from. |
| `access` | Raw typed access to a record at a wiring proven layout. |
| `frames` | The evaluation's record frame storage. |
| `serve` | The serving protocol: a node's own frame claim and the proof it closes with. |
| `input` | Consumer side bindings onto a record input, and the drivers they run. |
| `route` | Producer side routing: a source's translation into the union layout. |
| `promote` | Transient to persistent promotion of records and their parked payloads. |
| `owned` | The owned crossing: deep copies that outlive the evaluation their content borrowed. |
| `run` | Runs and groups: many records of one layout, resident or owned. |
| `testkit` | Law test scaffolding over the record tier. |
Two words are used precisely throughout. An input is the consumer side of a connection, and a source is the producer side. Neither is called a wire; that word belongs to the editor UI.
### Attributes
An attribute is a named, typed channel that rides along with an element. A marker declares the name once, fixing its value type and its name specific default, and a census collects every declaration so name resolution, defaults, and diagnostics all happen at graph compile time. One name belongs to one marker, so a name can never mean two types. Declare markers with `core_types::attribute!`:
```rust
core_types::attribute! {
/// The measured length of an element.
pub Length("length"): f64;
/// A label parked in the arena by whoever writes it.
pub Label("label"): &str;
} }
``` ```
## Graphene (proto node executor) Values are `Copy` and pack directly into record fields. Anything with drop glue rides the arena instead: the marker declares a reference value such as `&str`, the writing kernel parks the payload in the arena, and the record field carries a reference good for the evaluation.
The graphene crate (found in `gcore/`) and the graphene standard library (found in `gstd/`) is where actual implementation for nodes are located. In a kernel, `Attr<A>` as a parameter is a read, yielding the declared default where nothing upstream wrote it. `Attr<A>` in the return tuple is a write, and the same marker on both sides is a modify. `OwnedAttr<A>` carries a value across the evaluation boundary, and `RemoveAttr<A>` subtracts the attribute from the layout. See `libraries/core-types/src/attribute.rs`, and `nodes/gcore/src/record.rs` for worked examples of every form.
Implementing a node is done by defining a `struct` implementing the `Node` trait. The `Node` trait has a required function named `eval` that takes one generic input. A sample implementation for an opacity node acting on a color is seen below: ### The arena
```rs Two regions, both in `libraries/core-types/src/arena.rs`. The transient arena is reset at the top of every evaluation, so anything parked in it lives exactly as long as the evaluation that parked it. The persistent region backs promoted memo levels; it is flushed whole between evaluations and never during one, so no flush can land while a promoted value is still readable.
use crate::{Color, Node};
#[derive(Debug, Clone, Copy)] `Arena::move_park` is the promotion. It copies a payload's header into the receiving region, hands over the drop obligation, and tombstones the source entry in place. The heap the payload owns is neither copied nor freed, since ownership travels with the obligation, and a payload two records share moves once. Region sizes and the flush policy live in `interpreted-executor/src/dynamic_executor.rs`.
pub struct OpacityNode<OpacityMultiplierInput> {
opacity_multiplier: OpacityMultiplierInput,
}
impl<'i, OpacityMultiplierInput: Node<'i, (), Output = f64> + 'i> Node<'i, Color> for OpacityNode<OpacityMultiplierInput> { ### Serving
type Output = Color;
fn eval(&'i self, color: Color) -> Color {
let opacity_multiplier = self.opacity_multiplier.eval(()) as f32 / 100.;
Color::from_rgbaf32_unchecked(color.r(), color.g(), color.b(), color.a() * opacity_multiplier)
}
}
```
The `eval` function can only take one input. To support more than one input, the node struct can store references to other nodes. This can be seen here, as the `opacity_multiplier` field, which is generic and is constrained to the trait `Node<'i, (), Output = f64>`. This means that it is a node with the input of `()` (no input is required to compute the opacity) and an output of an `f64`. Evaluating a graph is a walk of `serve` calls down from the root. The root claims the frame buffer, each node claims its own frame out of what its caller left, and status rides the `GPoll` return: `Final`, `Partial` for a result that is correct but incomplete, `Pending` for work not yet ready, `Error`, and `Fallback` for a usable value paired with the error that degraded it. `StatusCell` folds each input's status into the serving node's own, which is what lets a kernel be written as though its inputs simply returned values.
To compute the value when executing the `OpacityNode`, we need to call `self.opacity_multiplier.eval(())`. This evaluates the node that provides the `opacity_multiplier` input, with the input value of `()`— nothing. This occurs each time the opacity node is run. ## Adding a node
To test this: Write a function and put `#[node_macro::node]` on it. The macro generates the node struct, the `Node` implementation, the registry entries, and the metadata the editor builds its catalog and properties panel from.
```rs
#[test]
fn test_opacity_node() {
let opacity_node = OpacityNode {
opacity_multiplier: crate::value::CopiedNode(10_f64), // set opacity to 10%
};
assert_eq!(opacity_node.eval(Color::WHITE), Color::from_rgbaf32_unchecked(1., 1., 1., 0.1));
}
```
The `graphene_core::value::CopiedNode` is a node that, when evaluated, copies `10_f32` and returns it. ```rust
use core_types::Ctx;
use core_types::attribute::{Attr, Opacity};
## Creating a new node /// Scales the opacity attribute of every element passing through.
Instead of manually implementing the `Node` trait with complex generics, one can use the `node` macro, which can be applied to a function like `opacity`. This will generate the struct, implementation, node_registry entry, document node definition and properties panel entries:
```rs
#[node_macro::node(category("Raster: Adjustments"))] #[node_macro::node(category("Raster: Adjustments"))]
fn opacity(_input: (), #[default(424242)] color: Color, #[range] #[soft(0..100)] opacity_multiplier: f64) -> Color { fn multiply_opacity(
let opacity_multiplier = opacity_multiplier as f32 / 100.; _: impl Ctx,
Color::from_rgbaf32_unchecked(color.r(), color.g(), color.b(), color.a() * opacity_multiplier) /// The element and its current opacity.
(element, opacity): (f64, Attr<Opacity>),
/// The factor to scale the opacity by.
#[default(1.)]
#[range]
#[soft(0..2)]
factor: f64,
) -> (f64, Attr<Opacity>) {
(element, Attr(*opacity * factor))
} }
``` ```
## Additional Macro Options Reading that back: the first parameter is the evaluation context. A tuple parameter is a record input, binding the element alongside the attributes this kernel reads, while a plain parameter is an ordinary value input the user can set. The return tuple is the write set, and returning `Attr<Opacity>` after reading it makes this a modify rather than a fresh write.
The macro invocation can be extended with additional attributes. The currently supported attributes are (`name`, `path`, `skip_impl`, `category`). When using generics the `#[implementations()]` attribute can be used to automatically populate the node_registry for you. You can also use the `default`, `expose`, `soft`, `hard`, and `range` attributes to influence how the properties are generated. The `#[soft(a..b)]` and `#[hard(a..b)]` attributes set the slider's suggested extent and its enforced clamp, respectively (either endpoint may be omitted, e.g. `0..` or `..100`; both endpoints are inclusive, so there is no `..=` form), and `#[range]` renders the input as a draggable slider. Values typed into the input may exceed the soft extent but are clamped to the hard bounds, so `#[soft]` is only meaningful together with `#[range]`. Doc comments are not decoration. The one on the function becomes the node's description in the editor's catalog, and the one on each parameter becomes that input's description.
## Executing a document `NodeNetwork` Options on the invocation are `category`, `name`, `path`, `properties` (naming a function in `editor/src/messages/portfolio/document/node_graph/node_properties.rs` for a custom panel), `extent` (naming a function that computes the node's extent, for nodes that change the item count), and `skip_impl`.
When the document graph is executed, the following steps occur: Per parameter there are `#[default(..)]`, `#[expose]`, `#[name(..)]`, `#[widget(..)]`, and `#[implementations(..)]`, which enumerates the concrete type rows a generic node registers. For numbers, `#[range]` renders a draggable slider, `#[soft(a..b)]` sets its suggested extent, and `#[hard(a..b)]` sets the enforced clamp. Either endpoint may be omitted and both are inclusive, so there is no `..=` form. Typed values may exceed the soft extent but are clamped to the hard bounds, so `#[soft]` only means anything together with `#[range]`. The macro checks these and will reject a `#[range]` missing an end, or a `#[soft]` bound equal to its `#[hard]` counterpart.
- The `NodeNetwork` is flattened using `NodeNetwork::flatten`. This involves removing any `DocumentNodeImplementation::Network` - which allow for nested document node networks. Instead, all of the inner nodes are moved into a single node graph.
- The `NodeNetwork` is converted into a proto-graph. Each node's inputs are stored as a list of node IDs in the `ConstructionArgs` struct in the `ProtoNode`. Converting a document graph into a proto graph is done with `NodeNetwork::into_proto_networks`.
- The newly created `ProtoNode`s are then converted into the corresponding constructor functions using the mapping defined in `node-graph/interpreted-executor/src/node_registry.rs`. This is done by `BorrowTree::push_node`.
- The constructor functions are run with the `ConstructionArgs` enum. Constructors generally evaluate the result of these inputs, e.g. if you have a `Pi` node that is used as the second input to an `Add` node, the `Add` node's constructor will evaluate the `Pi` node. This is visible if you place a log statement in the `Pi` node's implementation.
- The resolved functions are stored in a `BorrowTree`, which allows previous proto-nodes to be referenced as inputs by later nodes. The `BorrowTree` ensures nodes can't be removed while being referenced by other nodes.
The definition for the constructor of a node that applies the opacity transformation to each pixel of an image: Registration is automatic. The macro emits a `ctor` constructor that inserts into `NODE_REGISTRY` and `NODE_METADATA` in `libraries/core-types/src/registry.rs` at process start, and `interpreted-executor/src/node_registry.rs` takes that table and adds a hand written set of conversion nodes to build the registry the compiler consumes. There is no separate definition table to edit; writing the function is the whole job. On wasm the `ctor` attribute is skipped and registration is driven explicitly instead.
```rs
(
// Matches against the string defined in the document node.
ProtoNodeIdentifier::new("graphene_core::raster::OpacityNode"),
// This function is run when converting the `ProtoNode` struct into the desired struct.
|args| {
Box::pin(async move {
// Creates an instance of the struct that defines the node.
let node = construct_node!(args, graphene_core::raster::OpacityNode<_>, [f64]).await;
// Create a new map image node, that calls the `node` for each pixel.
let map_node = graphene_std::raster::MapImageNode::new(graphene_core::value::ValueNode::new(node));
// Wraps this in a type erased future `Box<Pin<dyn core::future::Future<Output = T> + 'n>>` - this allows it to work with async.
let map_node = graphene_std::any::FutureWrapperNode::new(map_node);
// The `DynAnyNode` downcasts its input from a `Box<dyn DynAny>` i.e. dynamically typed, to the desired statically typed input value. It then runs the wrapped node and converts the result back into a dynamically typed `Box<dyn DynAny>`.
let any: DynAnyNode<Image<Color>, _, _> = graphene_std::any::DynAnyNode::new(graphene_core::value::ValueNode::new(map_node));
// Nodes are stored as type erased, which means they are `Box<dyn NodeIo + Node>`. This allows us to create dynamic graphs, using dynamic dispatch so we do not have to know all node combinations at compile time.
any.into_type_erased()
})
},
// Defines the call argument, return value, and inputs.
NodeIOTypes::new(concrete!(Image<Color>), concrete!(Image<Color>), vec![fn_type!((), f64)]),
),
```
Nodes in the borrow stack take a `Box<dyn DynAny>` as input and output another `Box<dyn DynAny>`, to allow for any type. To use a specific type, we must downcast the values that have been passed in. ## From a document to a result
However the `OpacityNode` only works on one pixel at a time, so we first insert a `MapImageNode` to call the `OpacityNode` for every pixel in the image.
Finally we call `.into_type_erased()` on the result and that is inserted into the borrow stack.
We also need to add an implementation so that the user can change the opacity of just a single color. To simplify this process for raster nodes, a `raster_node!` macro is available which can simplify the definition of the opacity node to: A saved document arrives as a `NodeNetwork`. The preprocessor expands each proto node reference into the `DocumentNode` template built from its registry metadata, reconciling saved inputs against what the current definition expects, which is what lets old documents load against new node definitions. `NodeNetwork::flatten` then dissolves nested networks into one graph, `into_proto_networks` lowers it to a `ProtoNetwork`, and `TypingContext` resolves types against the registry. The executor pushes each `ProtoNode` into its `BorrowTree`, which keeps a node alive as long as anything references it, and `eval_root` resets the transient arena, sizes the frame buffer to the graph's need, and serves the output.
```rs
raster_node!(graphene_core::raster::OpacityNode<_>, params: [f64]),
```
There is also the more general `register_node!` for nodes that do not need to run per pixel. ## Deeper reading
```rs
register_node!(graphene_core::transform_nodes::SetTransformNode<_>, input: Vector, params: [DAffine2]), The design documentation for the record tier is the `//!` headers in the source. Read `libraries/core-types/src/record/mod.rs` first, then the submodule headers in the table above, then `node.rs`, `attribute.rs`, and `arena.rs`.
```
Two RFCs cover work adjacent to this system:
- [`rfcs/document-format.md`](rfcs/document-format.md), the `.gdd` on disk format and its CRDT delta model.
- [`rfcs/fine-grained-context-caching.md`](rfcs/fine-grained-context-caching.md), a compilation pass that nullifies unused parts of the context to avoid needless cache invalidation.
## Debugging ## Debugging
Debugging inside your node can be done with the `log::debug!()` macro, for example `log::debug!("The opacity is {opacity_multiplier}");`. `log::debug!()` works inside a node body. For running a graph without the editor in the way, `graphene-cli` loads a document, compiles it, evaluates it, and can list every registered node.
We need a utility to easily view a graph as the various steps are applied. We also need a way to transparently see which constructors are being run, which nodes are being evaluated, and in what order. If any of this is wrong or unclear, please ask in the Graphite Discord. We are happy to help.
## Conclusion
While we simplify the writing of nodes using the macro by hiding some of the details, creating nodes involves many files and concepts. We will work to continue making this system easier to use.
Any contributions you might have would be greatly appreciated. If any parts of this guide are outdated or difficult to understand, please feel free to ask for help in the Graphite Discord. We are very happy to answer any questions :)
+1
View File
@@ -74,6 +74,7 @@ mmap-io = { workspace = true }
[dev-dependencies] [dev-dependencies]
# Workspace dependencies # Workspace dependencies
graph-craft = { workspace = true, features = ["loading"] } graph-craft = { workspace = true, features = ["loading"] }
interpreted-executor = { workspace = true }
pretty_assertions = { workspace = true } pretty_assertions = { workspace = true }
criterion = { workspace = true } criterion = { workspace = true }
gungraun = { workspace = true } gungraun = { workspace = true }
@@ -6,10 +6,13 @@ use graph_craft::util::DEMO_ART;
fn compile_to_proto(c: &mut Criterion) { fn compile_to_proto(c: &mut Criterion) {
use graph_craft::util::{compile, load_from_name}; use graph_craft::util::{compile, load_from_name};
let mut c = c.benchmark_group("Compile Network cold"); let mut c = c.benchmark_group("Compile Network cold");
let registry = &interpreted_executor::node_registry::NODE_REGISTRY;
for name in DEMO_ART { for name in DEMO_ART {
let network = load_from_name(name); let network = load_from_name(name);
c.bench_function(name, |b| b.iter_batched(|| network.clone(), |network| compile(black_box(network)), criterion::BatchSize::SmallInput)); c.bench_function(name, |b| {
b.iter_batched(|| network.clone(), |network| compile(black_box(network), registry), criterion::BatchSize::SmallInput)
});
} }
} }
@@ -5,7 +5,7 @@ use gungraun::prelude::*;
#[library_benchmark] #[library_benchmark]
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = load_from_name)] #[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = load_from_name)]
pub fn compile_to_proto(_input: NodeNetwork) { pub fn compile_to_proto(_input: NodeNetwork) {
std::hint::black_box(compile(_input)); std::hint::black_box(compile(_input, &interpreted_executor::node_registry::NODE_REGISTRY));
} }
library_benchmark_group!(name = compile_group; benchmarks = compile_to_proto); library_benchmark_group!(name = compile_group; benchmarks = compile_to_proto);
+9 -4
View File
@@ -9,7 +9,7 @@ pub use graphene_application_io::ApplicationIo;
#[derive(Default)] #[derive(Default)]
pub struct PlatformApplicationIo { pub struct PlatformApplicationIo {
#[cfg(feature = "wgpu")] #[cfg(feature = "wgpu")]
gpu_executor: Option<WgpuExecutor>, gpu_executor: Option<std::sync::Arc<WgpuExecutor>>,
resources: Option<Box<dyn resource::LoadResource>>, resources: Option<Box<dyn resource::LoadResource>>,
} }
@@ -26,7 +26,7 @@ impl PlatformApplicationIo {
Self { Self {
#[cfg(feature = "wgpu")] #[cfg(feature = "wgpu")]
gpu_executor: executor, gpu_executor: executor.map(std::sync::Arc::new),
resources: None, resources: None,
} }
} }
@@ -39,7 +39,7 @@ impl PlatformApplicationIo {
set_wgpu_available(wgpu_available); set_wgpu_available(wgpu_available);
Self { Self {
gpu_executor: executor, gpu_executor: executor.map(std::sync::Arc::new),
resources: None, resources: None,
} }
} }
@@ -57,7 +57,12 @@ impl ApplicationIo for PlatformApplicationIo {
#[cfg(feature = "wgpu")] #[cfg(feature = "wgpu")]
fn gpu_executor(&self) -> Option<&Self::Executor> { fn gpu_executor(&self) -> Option<&Self::Executor> {
self.gpu_executor.as_ref() self.gpu_executor.as_deref()
}
#[cfg(feature = "wgpu")]
fn gpu_executor_arc(&self) -> Option<std::sync::Arc<Self::Executor>> {
self.gpu_executor.clone()
} }
fn load_resource(&self, hash: resource::ResourceHash) -> resource::ResourceFuture<'_> { fn load_resource(&self, hash: resource::ResourceHash) -> resource::ResourceFuture<'_> {
+35 -12
View File
@@ -8,7 +8,6 @@ pub use core_types::uuid::generate_uuid;
use core_types::{Context, ContextDependencies, Cow, MemoHash, NodeParameter, ProtoNodeIdentifier, Type}; use core_types::{Context, ContextDependencies, Cow, MemoHash, NodeParameter, ProtoNodeIdentifier, Type};
use dyn_any::DynAny; use dyn_any::DynAny;
use glam::IVec2; use glam::IVec2;
use log::Metadata;
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use std::collections::HashMap; use std::collections::HashMap;
use std::collections::hash_map::DefaultHasher; use std::collections::hash_map::DefaultHasher;
@@ -58,7 +57,8 @@ pub struct DocumentNode {
#[serde(default)] #[serde(default)]
pub skip_deduplication: bool, pub skip_deduplication: bool,
/// List of Extract and Inject annotations for the Context. /// List of Extract and Inject annotations for the Context.
#[serde(default)] /// Resolved from the registry at compile time; only code-built wrapper nodes carry a declaration here.
#[serde(skip)]
pub context_features: ContextDependencies, pub context_features: ContextDependencies,
/// The path to this node and its inputs and outputs as of when [`NodeNetwork::generate_node_paths`] was called. /// The path to this node and its inputs and outputs as of when [`NodeNetwork::generate_node_paths`] was called.
#[serde(skip)] #[serde(skip)]
@@ -139,7 +139,6 @@ impl DocumentNode {
/// Normalizes this node's stored types (call argument, `Import` input types, `TypeDefault` value payloads, and any nested network) to their structural form. /// Normalizes this node's stored types (call argument, `Import` input types, `TypeDefault` value payloads, and any nested network) to their structural form.
/// Applied once at ingestion (document migration and clipboard paste) so no name-encoded ranked type enters a live document. /// Applied once at ingestion (document migration and clipboard paste) so no name-encoded ranked type enters a live document.
pub fn normalize_stored_types(&mut self) { pub fn normalize_stored_types(&mut self) {
self.call_argument = self.call_argument.clone().normalize_rank();
for input in &mut self.inputs { for input in &mut self.inputs {
normalize_input_stored_type(input); normalize_input_stored_type(input);
} }
@@ -194,6 +193,8 @@ impl DocumentNode {
original_location: self.original_location, original_location: self.original_location,
skip_deduplication: self.skip_deduplication, skip_deduplication: self.skip_deduplication,
context_features: self.context_features, context_features: self.context_features,
lane_invariant_inputs: 0,
resolved: Default::default(),
} }
} }
} }
@@ -242,12 +243,14 @@ impl InlineRust {
#[derive(Debug, Clone, PartialEq, Hash, core_types::CacheHash, DynAny, serde::Serialize, serde::Deserialize)] #[derive(Debug, Clone, PartialEq, Hash, core_types::CacheHash, DynAny, serde::Serialize, serde::Deserialize)]
pub enum DocumentNodeMetadata { pub enum DocumentNodeMetadata {
DocumentNodePath, DocumentNodePath,
SourceId,
} }
impl DocumentNodeMetadata { impl DocumentNodeMetadata {
pub fn ty(&self) -> Type { pub fn ty(&self) -> Type {
match self { match self {
DocumentNodeMetadata::DocumentNodePath => item!(core_types::list::NodeIdPath), DocumentNodeMetadata::DocumentNodePath => concrete!(Vec<NodeId>),
DocumentNodeMetadata::SourceId => concrete!(u64),
} }
} }
} }
@@ -264,8 +267,8 @@ impl NodeInput {
/// Constructs a `NodeInput::Value` whose tagged value is `TaggedValue::TypeDefault(ty)`, recording only the /// Constructs a `NodeInput::Value` whose tagged value is `TaggedValue::TypeDefault(ty)`, recording only the
/// type so the runtime materializes its default rather than baking a placeholder value into the saved document. /// type so the runtime materializes its default rather than baking a placeholder value into the saved document.
pub fn type_default(ty: Type, exposed: bool) -> Self { pub fn type_default(td: core_types::TypeDescriptor, exposed: bool) -> Self {
Self::value(TaggedValue::TypeDefault(ty.normalize_rank()), exposed) Self::value(TaggedValue::TypeDefault(td), exposed)
} }
pub const fn import(import_type: Type, import_index: usize) -> Self { pub const fn import(import_type: Type, import_index: usize) -> Self {
@@ -301,7 +304,7 @@ impl NodeInput {
NodeInput::Import { import_type, .. } => import_type.clone(), NodeInput::Import { import_type, .. } => import_type.clone(),
NodeInput::Inline(_) => panic!("ty() called on NodeInput::Inline"), NodeInput::Inline(_) => panic!("ty() called on NodeInput::Inline"),
NodeInput::Scope(_) => panic!("ty() called on NodeInput::Scope"), NodeInput::Scope(_) => panic!("ty() called on NodeInput::Scope"),
NodeInput::Reflection(_) => concrete!(Metadata), NodeInput::Reflection(metadata) => metadata.ty(),
} }
} }
@@ -339,7 +342,7 @@ pub enum DocumentNodeImplementation {
Network(NodeNetwork), Network(NodeNetwork),
/// This describes a (document) node implemented as a proto node. /// This describes a (document) node implemented as a proto node.
/// ///
/// A proto node identifier which can be found in `node_registry.rs`. /// A proto node identifier, resolved against `NODE_REGISTRY` in `core-types/src/registry.rs`.
#[serde(alias = "Unresolved")] // TODO: Eventually remove this alias document upgrade code #[serde(alias = "Unresolved")] // TODO: Eventually remove this alias document upgrade code
ProtoNode(ProtoNodeIdentifier), ProtoNode(ProtoNodeIdentifier),
/// The Extract variant is a tag which tells the compilation process to do something special: it invokes language-level functionality built for use by the ExtractNode to enable metaprogramming. /// The Extract variant is a tag which tells the compilation process to do something special: it invokes language-level functionality built for use by the ExtractNode to enable metaprogramming.
@@ -754,10 +757,10 @@ impl ScopeChain<'_> {
/// Normalizes the ranked types an input can store: an `Import`'s type or a value's `TypeDefault` payload. /// Normalizes the ranked types an input can store: an `Import`'s type or a value's `TypeDefault` payload.
fn normalize_input_stored_type(input: &mut NodeInput) { fn normalize_input_stored_type(input: &mut NodeInput) {
match input { match input {
NodeInput::Import { import_type, .. } => *import_type = import_type.clone().normalize_rank(), NodeInput::Import { .. } => {}
NodeInput::Value { tagged_value, .. } => { NodeInput::Value { tagged_value, .. } => {
if let TaggedValue::TypeDefault(ty) = &**tagged_value { if let TaggedValue::TypeDefault(ty) = &**tagged_value {
let normalized = ty.clone().normalize_rank(); let normalized = ty.clone();
if normalized != *ty { if normalized != *ty {
*tagged_value = TaggedValue::TypeDefault(normalized).into(); *tagged_value = TaggedValue::TypeDefault(normalized).into();
} }
@@ -933,7 +936,7 @@ impl NodeNetwork {
// Replace value inputs with dedicated value nodes // Replace value inputs with dedicated value nodes
if node.implementation != DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::value::ClonedNode")) { if node.implementation != DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::value::ClonedNode")) {
Self::replace_value_inputs_with_nodes(&mut node.inputs, &mut self.nodes, &path, gen_id, map_ids, id); Self::replace_value_inputs_with_nodes(&mut node.inputs, &mut self.nodes, &path, gen_id, map_ids, id, Some(&mut node.context_features));
} }
let DocumentNodeImplementation::Network(mut inner_network) = node.implementation else { let DocumentNodeImplementation::Network(mut inner_network) = node.implementation else {
@@ -952,6 +955,7 @@ impl NodeNetwork {
gen_id, gen_id,
map_ids, map_ids,
id, id,
None,
); );
// Connect all network inputs to either the parent network nodes, or newly created value nodes for the parent node. // Connect all network inputs to either the parent network nodes, or newly created value nodes for the parent node.
@@ -1032,6 +1036,12 @@ impl NodeNetwork {
} }
} }
fn source_id_for_path(path: &[NodeId]) -> u64 {
let mut hasher = graphene_hash::FxHasher64::new();
path.hash(&mut hasher);
hasher.finish()
}
#[inline(never)] #[inline(never)]
fn replace_value_inputs_with_nodes( fn replace_value_inputs_with_nodes(
inputs: &mut [NodeInput], inputs: &mut [NodeInput],
@@ -1040,6 +1050,7 @@ impl NodeNetwork {
gen_id: impl Fn() -> NodeId + Copy, gen_id: impl Fn() -> NodeId + Copy,
map_ids: impl Fn(NodeId, NodeId) -> NodeId + Copy, map_ids: impl Fn(NodeId, NodeId) -> NodeId + Copy,
id: NodeId, id: NodeId,
mut context_features: Option<&mut ContextDependencies>,
) { ) {
// Replace value exports and imports with value nodes, added inside the nested network // Replace value exports and imports with value nodes, added inside the nested network
for export in inputs { for export in inputs {
@@ -1049,7 +1060,14 @@ impl NodeNetwork {
let (tagged_value, exposed) = match previous_export { let (tagged_value, exposed) = match previous_export {
NodeInput::Value { tagged_value, exposed } => (tagged_value, exposed), NodeInput::Value { tagged_value, exposed } => (tagged_value, exposed),
NodeInput::Reflection(reflect) => match reflect { NodeInput::Reflection(reflect) => match reflect {
DocumentNodeMetadata::DocumentNodePath => (TaggedValue::NodeIdPath(core_types::list::NodeIdPath::from(path.to_vec())).into(), false), DocumentNodeMetadata::DocumentNodePath => (TaggedValue::NodeIdPath(path.to_vec()).into(), false),
DocumentNodeMetadata::SourceId => {
let source_id = Self::source_id_for_path(path);
if let Some(context_features) = context_features.as_deref_mut() {
context_features.add_sources(&[source_id]);
}
(TaggedValue::U64(source_id).into(), false)
}
}, },
previous_export => { previous_export => {
*export = previous_export; *export = previous_export;
@@ -1200,6 +1218,7 @@ impl NodeNetwork {
inputs: Vec::new(), inputs: Vec::new(),
output: node_id, output: node_id,
nodes, nodes,
..Default::default()
}] }]
.into_iter(); .into_iter();
} }
@@ -1216,6 +1235,7 @@ impl NodeNetwork {
// inputs: self.imports.clone(), // inputs: self.imports.clone(),
output: node_id, output: node_id,
nodes: nodes.clone(), nodes: nodes.clone(),
..Default::default()
}) })
} else { } else {
None None
@@ -1262,7 +1282,9 @@ fn migrate_call_argument<'de, D: serde::Deserializer<'de>>(deserializer: D) -> R
Old(Option<Type>), Old(Option<Type>),
} }
// TODO: Eventually remove this migration document upgrade code
Ok(match CallArg::deserialize(deserializer)? { Ok(match CallArg::deserialize(deserializer)? {
CallArg::New(Type::Concrete(descriptor)) if descriptor.name.ends_with("OwnedContextImpl>>") => concrete!(Context),
CallArg::New(ty) => ty, CallArg::New(ty) => ty,
CallArg::Old(ty) => ty.unwrap_or_default(), CallArg::Old(ty) => ty.unwrap_or_default(),
}) })
@@ -1478,6 +1500,7 @@ mod test {
] ]
.into_iter() .into_iter()
.collect(), .collect(),
..Default::default()
}; };
let network = flat_network(); let network = flat_network();
let mut resolved_network = network.into_proto_networks().collect::<Vec<_>>(); let mut resolved_network = network.into_proto_networks().collect::<Vec<_>>();
+358 -182
View File
@@ -1,12 +1,17 @@
use super::DocumentNode; use super::DocumentNode;
use crate::application_io::PlatformEditorApi; use crate::application_io::PlatformEditorApi;
use crate::application_io::resource::Resource; use crate::application_io::resource::Resource;
use crate::proto::{Any as DAny, FutureAny}; use crate::proto::Any as DAny;
use brush_nodes::{BrushCache, Stroke}; use brush_nodes::{BrushCache, Stroke};
use core_types::color::SRGBA8; use core_types::color::SRGBA8;
use core_types::list::{Item, List, NodeIdPath}; use core_types::context::Context;
use core_types::gpoll::GPoll;
use core_types::list::{Item, List};
use core_types::registry::SourceHandle;
use core_types::transform::Footprint; use core_types::transform::Footprint;
use core_types::{CacheHash, Color, ContextFeatures, MemoHash, Node, Type, TypeDescriptor}; use core_types::uuid::NodeId;
use core_types::value::{leveled_record_value_source, record_value_source};
use core_types::{CacheHash, Color, ContextModification, MemoHash, Type, TypeDescriptor};
use dyn_any::DynAny; use dyn_any::DynAny;
pub use dyn_any::StaticType; pub use dyn_any::StaticType;
pub use glam::{DAffine2, DVec2, IVec2, UVec2}; pub use glam::{DAffine2, DVec2, IVec2, UVec2};
@@ -21,7 +26,6 @@ use graphic_types::{Artboard, Graphic, Vector};
use rendering::RenderMetadata; use rendering::RenderMetadata;
use std::fmt::Display; use std::fmt::Display;
use std::hash::Hash; use std::hash::Hash;
use std::marker::PhantomData;
use std::str::FromStr; use std::str::FromStr;
pub use std::sync::Arc; pub use std::sync::Arc;
use text_nodes::Font; use text_nodes::Font;
@@ -80,7 +84,7 @@ macro_rules! tagged_value {
/// Stores a type, from which its `Default::default()` value can be obtained, rather than storing an actual type's value. /// Stores a type, from which its `Default::default()` value can be obtained, rather than storing an actual type's value.
/// Example: `TaggedValue::TypeDefault(concrete!(String))` stores the type `String` but no specific string value. /// Example: `TaggedValue::TypeDefault(concrete!(String))` stores the type `String` but no specific string value.
/// (Old documents stored a bare `TypeDescriptor` payload, routed to this shape by `deserialize_tagged_value_with_legacy_migration`.) /// (Old documents stored a bare `TypeDescriptor` payload, routed to this shape by `deserialize_tagged_value_with_legacy_migration`.)
TypeDefault(Type), TypeDefault(TypeDescriptor),
/// Stored compactly as a `Vec<f64>`, materializes as `List<f64>` at runtime via `to_dynany`/`to_any`. Aliases recover legacy on-disk shapes. /// Stored compactly as a `Vec<f64>`, materializes as `List<f64>` at runtime via `to_dynany`/`to_any`. Aliases recover legacy on-disk shapes.
#[serde(deserialize_with = "core_types::misc::migrate_to_f64_array")] // TODO: Eventually remove this document upgrade code #[serde(deserialize_with = "core_types::misc::migrate_to_f64_array")] // TODO: Eventually remove this document upgrade code
#[serde(alias = "F64Table", alias = "VecF64", alias = "VecF32", alias = "F64Array4")] #[serde(alias = "F64Table", alias = "VecF64", alias = "VecF32", alias = "F64Array4")]
@@ -91,7 +95,7 @@ macro_rules! tagged_value {
BoxCorners(Vec<f64>), BoxCorners(Vec<f64>),
/// Stored as the `GradientRamp` exchange struct (nested `{ stops: { color, position?, midpoint? } }`), materializing as an `Item<Gradient>` at runtime. Aliases recover legacy on-disk shapes. /// Stored as the `GradientRamp` exchange struct (nested `{ stops: { color, position?, midpoint? } }`), materializing as an `Item<Gradient>` at runtime. Aliases recover legacy on-disk shapes.
/// (Old documents stored flat stops, a tuple list, or the ancient full `Gradient` struct under the legacy `"Gradient"` tag, all routed by `deserialize_tagged_value_with_legacy_migration`.) /// (Old documents stored flat stops, a tuple list, or the ancient full `Gradient` struct under the legacy `"Gradient"` tag, all routed by `deserialize_tagged_value_with_legacy_migration`.)
#[serde(alias = "Gradient", alias = "GradientTable", alias = "GradientPositions", alias = "GradientStops")] #[serde(alias = "Gradient", alias = "GradientTable", alias = "GradientPositions", alias = "Gradient")]
GradientRamp(GradientRamp), GradientRamp(GradientRamp),
Strokes(Vec<Stroke>), Strokes(Vec<Stroke>),
BrushCache(BrushCache), BrushCache(BrushCache),
@@ -104,15 +108,15 @@ macro_rules! tagged_value {
// ======================= // =======================
#[serde(skip)] #[serde(skip)]
RenderOutput(RenderOutput), RenderOutput(RenderOutput),
/// Path to the consumer of a `NodeInput::Reflection(DocumentNodePath)`. Materializes an `Item<NodeIdPath>` at runtime via `to_dynany`/`to_any` during graph flattening, matching the ranked connectors it feeds. /// Path to the consumer of a `NodeInput::Reflection(DocumentNodePath)`, in the `Vec<NodeId>` form our node catalog consumes.
#[serde(skip)] #[serde(skip)]
NodeIdPath(NodeIdPath), NodeIdPath(Vec<NodeId>),
/// The `DocumentNode` value carried by an `Extract` proto node, populated at flatten time by `resolve_extract_nodes`. The on-disk placeholder uses `TypeDefault(concrete!(DocumentNode))`. /// The `DocumentNode` value carried by an `Extract` proto node, populated at flatten time by `resolve_extract_nodes`. The on-disk placeholder uses `TypeDefault(concrete!(DocumentNode))`.
#[serde(skip)] #[serde(skip)]
DocumentNode(DocumentNode), DocumentNode(DocumentNode),
/// Carried by context nullification proto nodes constructed at proto node compilation time in `insert_context_nullification_nodes`. /// Carried by context nullification proto nodes constructed at proto node compilation time in `insert_context_nullification_nodes`.
#[serde(skip)] #[serde(skip)]
ContextFeatures(ContextFeatures), ContextModification(ContextModification),
#[serde(skip)] #[serde(skip)]
EditorApi(Arc<PlatformEditorApi>), EditorApi(Arc<PlatformEditorApi>),
/// Only used by the `resource` node, should never be serialized /// Only used by the `resource` node, should never be serialized
@@ -144,7 +148,7 @@ macro_rules! tagged_value {
// ======================= // =======================
Self::NodeIdPath(path) => path.cache_hash(state), Self::NodeIdPath(path) => path.cache_hash(state),
Self::DocumentNode(node) => node.cache_hash(state), Self::DocumentNode(node) => node.cache_hash(state),
Self::ContextFeatures(features) => features.cache_hash(state), Self::ContextModification(modification) => modification.cache_hash(state),
Self::RenderOutput(x) => x.cache_hash(state), Self::RenderOutput(x) => x.cache_hash(state),
Self::EditorApi(x) => x.cache_hash(state), Self::EditorApi(x) => x.cache_hash(state),
Self::ResourceHash(x) => x.cache_hash(state), Self::ResourceHash(x) => x.cache_hash(state),
@@ -162,37 +166,23 @@ macro_rules! tagged_value {
Self::None => Box::new(()), Self::None => Box::new(()),
Self::TypeDefault(td) => { Self::TypeDefault(td) => {
// Construct the actual default for types without a `TaggedValue` variant directly. // Construct the actual default for types without a `TaggedValue` variant directly.
// Recursion through `from_type_or_none` below is safe only because the type-default lists // Recursion through `from_type_or_none` below is safe only because `for_each_type_default!`
// exhaustively cover every type that `from_type` would route back to `TypeDefault`. // exhaustively handles every type that `from_type` would route back to `TypeDefault`.
match &td { let name = td.name.as_ref();
Type::List(element) => { macro_rules! check {
macro_rules! check { ($type_default:ty) => {
($type_default:ty) => { if name == core_types::normalize_type_name(std::any::type_name::<$type_default>()) { return Box::new(<$type_default>::default()); }
if **element == concrete!($type_default) { return Box::new(List::<$type_default>::default()); } };
};
}
for_each_list_type_default!(check);
}
Type::Item(element) => {
macro_rules! check {
($type_default:ty) => {
if **element == concrete!($type_default) { return Box::new(Item::<$type_default>::default()); }
};
}
for_each_item_type_default!(check);
}
Type::Concrete(descriptor) => {
let name = descriptor.name.as_ref();
macro_rules! check_bare {
($type_default:ty) => {
if name == std::any::type_name::<$type_default>() { return Box::new(<$type_default>::default()); }
};
}
for_each_bare_type_default!(check_bare);
}
_ => {}
} }
Self::from_type_or_none(&td).to_dynany() macro_rules! check_list {
($element:ty) => {
if name == core_types::normalize_type_name(std::any::type_name::<List<$element>>()) { return Box::new(List::<$element>::default()); }
};
}
for_each_list_type_default!(check_list);
for_each_item_type_default!(check);
for_each_bare_type_default!(check);
Self::from_type_or_none(&Type::Concrete(td.clone())).to_dynany()
} }
Self::F64Array(values) => { Self::F64Array(values) => {
let list: List<f64> = values.into_iter().map(core_types::list::Item::new_from_element).collect(); let list: List<f64> = values.into_iter().map(core_types::list::Item::new_from_element).collect();
@@ -213,10 +203,10 @@ macro_rules! tagged_value {
// ======================= // =======================
// NON-SERIALIZED VARIANTS // NON-SERIALIZED VARIANTS
// ======================= // =======================
Self::RenderOutput(x) => Box::new(Item::new_from_element(x)), Self::RenderOutput(x) => Box::new(x),
Self::NodeIdPath(path) => Box::new(Item::new_from_element(path)), Self::NodeIdPath(path) => Box::new(path),
Self::DocumentNode(node) => Box::new(node), Self::DocumentNode(node) => Box::new(node),
Self::ContextFeatures(features) => Box::new(Item::new_from_element(features)), Self::ContextModification(modification) => Box::new(modification),
Self::EditorApi(x) => Box::new(x), Self::EditorApi(x) => Box::new(x),
Self::ResourceHash(x) => Box::new(Item::new_from_element(x)), Self::ResourceHash(x) => Box::new(Item::new_from_element(x)),
} }
@@ -231,35 +221,21 @@ macro_rules! tagged_value {
Self::None => Arc::new(()), Self::None => Arc::new(()),
Self::TypeDefault(td) => { Self::TypeDefault(td) => {
// Same direct-construction path as `to_dynany` for the same reason as in `to_dynany`. // Same direct-construction path as `to_dynany` for the same reason as in `to_dynany`.
match &td { let name = td.name.as_ref();
Type::List(element) => { macro_rules! check {
macro_rules! check { ($type_default:ty) => {
($type_default:ty) => { if name == core_types::normalize_type_name(std::any::type_name::<$type_default>()) { return Arc::new(<$type_default>::default()); }
if **element == concrete!($type_default) { return Arc::new(List::<$type_default>::default()); } };
};
}
for_each_list_type_default!(check);
}
Type::Item(element) => {
macro_rules! check {
($type_default:ty) => {
if **element == concrete!($type_default) { return Arc::new(Item::<$type_default>::default()); }
};
}
for_each_item_type_default!(check);
}
Type::Concrete(descriptor) => {
let name = descriptor.name.as_ref();
macro_rules! check_bare {
($type_default:ty) => {
if name == std::any::type_name::<$type_default>() { return Arc::new(<$type_default>::default()); }
};
}
for_each_bare_type_default!(check_bare);
}
_ => {}
} }
Self::from_type_or_none(&td).to_any() macro_rules! check_list {
($element:ty) => {
if name == core_types::normalize_type_name(std::any::type_name::<List<$element>>()) { return Arc::new(List::<$element>::default()); }
};
}
for_each_list_type_default!(check_list);
for_each_item_type_default!(check);
for_each_bare_type_default!(check);
Self::from_type_or_none(&Type::Concrete(td.clone())).to_any()
} }
Self::F64Array(values) => { Self::F64Array(values) => {
let list: List<f64> = values.into_iter().map(core_types::list::Item::new_from_element).collect(); let list: List<f64> = values.into_iter().map(core_types::list::Item::new_from_element).collect();
@@ -280,46 +256,179 @@ macro_rules! tagged_value {
// ======================= // =======================
// NON-SERIALIZED VARIANTS // NON-SERIALIZED VARIANTS
// ======================= // =======================
Self::RenderOutput(x) => Arc::new(Item::new_from_element(x)), Self::RenderOutput(x) => Arc::new(x),
Self::NodeIdPath(path) => Arc::new(Item::new_from_element(path)), Self::NodeIdPath(path) => Arc::new(path),
Self::DocumentNode(node) => Arc::new(node), Self::DocumentNode(node) => Arc::new(node),
Self::ContextFeatures(features) => Arc::new(Item::new_from_element(features)), Self::ContextModification(modification) => Arc::new(modification),
Self::EditorApi(x) => Arc::new(x), Self::EditorApi(x) => Arc::new(x),
Self::ResourceHash(x) => Arc::new(Item::new_from_element(x)), Self::ResourceHash(x) => Arc::new(x),
} }
} }
/// Creates the wire [`Type`] of the value inside the tagged value, with ranked types in their structural form. /// Creates the wire [`Type`] of the value inside the tagged value, with ranked types in their structural form.
pub fn ty(&self) -> Type { pub fn ty(&self) -> Type {
let ty = match self { match self {
// =============== // ===============
// MANUAL VARIANTS // MANUAL VARIANTS
// =============== // ===============
Self::None => concrete!(()), Self::None => concrete!(()),
Self::TypeDefault(td) => td.clone(), // The list-typed defaults type by their element: depth is not a
Self::F64Array(_) => list!(f64), // `Type` axis, it rides the layout proven at wiring.
Self::DashPattern(_) => item!(DashPattern), Self::TypeDefault(td) => {
Self::BoxCorners(_) => item!(BoxCorners), let name = td.name.as_ref();
Self::GradientRamp(_) => item!(Gradient), if name == core_types::normalize_type_name(std::any::type_name::<List<Graphic>>()) { return concrete!(Graphic); }
Self::Strokes(_) => list!(Stroke), if name == core_types::normalize_type_name(std::any::type_name::<List<Artboard>>()) { return concrete!(Artboard); }
Self::BrushCache(_) => item!(BrushCache), if name == core_types::normalize_type_name(std::any::type_name::<List<Raster<CPU>>>()) { return concrete!(Raster<CPU>); }
if name == core_types::normalize_type_name(std::any::type_name::<List<Vector>>()) { return concrete!(Vector); }
if name == core_types::normalize_type_name(std::any::type_name::<List<String>>()) { return concrete!(String); }
Type::Concrete(td.clone())
}
Self::F64Array(_) => concrete!(f64),
Self::Color(_) => concrete!(Color),
Self::GradientRamp(_) => concrete!(Gradient),
Self::Strokes(_) => concrete!(Stroke),
Self::DashPattern(_) => concrete!(DashPattern),
Self::BoxCorners(_) => concrete!(BoxCorners),
Self::BrushCache(_) => concrete!(BrushCache),
// ======================= // =======================
// AUTO-GENERATED VARIANTS // AUTO-GENERATED VARIANTS
// ======================= // =======================
$( Self::$identifier(_) => item!($ty), )* $( Self::$identifier(_) => concrete!($ty), )*
// ======================= // =======================
// NON-SERIALIZED VARIANTS // NON-SERIALIZED VARIANTS
// ======================= // =======================
Self::RenderOutput(_) => item!(RenderOutput), Self::RenderOutput(_) => concrete!(RenderOutput),
Self::NodeIdPath(_) => item!(NodeIdPath), Self::NodeIdPath(_) => concrete!(Vec<NodeId>),
Self::DocumentNode(_) => concrete!(DocumentNode), Self::DocumentNode(_) => concrete!(DocumentNode),
Self::ContextFeatures(_) => item!(ContextFeatures), Self::ContextModification(_) => concrete!(ContextModification),
Self::EditorApi(_) => item!(&PlatformEditorApi), Self::EditorApi(_) => concrete!(Arc<PlatformEditorApi>),
Self::ResourceHash(_) => item!(ResourceHash), Self::ResourceHash(_) => concrete!(ResourceHash),
}; }
}
// Defensively converges any remaining name-encoded ranked type (e.g. an opaque macro capture) to the structural form /// The record layout of this value's source: leveled for the list-carrying
ty.normalize_rank() /// variants, element-only at rank 0 otherwise. `None` for a
/// [`Self::TypeDefault`] whose named type is outside `for_each_type_default!`.
pub fn value_layout(&self) -> Option<core_types::record::Layout> {
fn leveled<T: Clone + Send + Sync + CacheHash + PartialEq + dyn_any::StaticTypeSized>() -> Option<core_types::record::Layout>
where
T::Static: Clone + Send + Sync,
{
Some(core_types::record::Layout::default().with_writes(1, core_types::record::element_write_hashed::<T>(), &[]))
}
fn scalar<T: Clone + Send + Sync + dyn_any::StaticTypeSized>() -> Option<core_types::record::Layout>
where
T::Static: Clone + Send + Sync,
{
Some(core_types::record::Layout::default().with_writes(0, core_types::record::element_write::<T>(), &[]))
}
match self {
Self::None => scalar::<()>(),
Self::TypeDefault(td) => {
let name = td.name.as_ref();
if name == core_types::normalize_type_name(std::any::type_name::<List<Graphic>>()) { return leveled::<Graphic>(); }
if name == core_types::normalize_type_name(std::any::type_name::<List<Artboard>>()) { return leveled::<Artboard>(); }
if name == core_types::normalize_type_name(std::any::type_name::<List<Raster<CPU>>>()) { return leveled::<Raster<CPU>>(); }
if name == core_types::normalize_type_name(std::any::type_name::<List<Vector>>()) { return leveled::<Vector>(); }
if name == core_types::normalize_type_name(std::any::type_name::<List<String>>()) { return leveled::<String>(); }
if name == core_types::normalize_type_name(std::any::type_name::<DocumentNode>()) { return scalar::<DocumentNode>(); }
if name == core_types::normalize_type_name(std::any::type_name::<Resource>()) { return scalar::<Resource>(); }
None
}
Self::F64Array(_) => leveled::<f64>(),
Self::Color(_) => leveled::<Color>(),
Self::GradientRamp(_) => leveled::<Gradient>(),
Self::Strokes(_) => leveled::<Stroke>(),
Self::DashPattern(_) => scalar::<DashPattern>(),
Self::BoxCorners(_) => scalar::<BoxCorners>(),
Self::BrushCache(_) => scalar::<BrushCache>(),
$( Self::$identifier(_) => scalar::<$ty>(), )*
Self::RenderOutput(_) => scalar::<RenderOutput>(),
Self::NodeIdPath(_) => scalar::<Vec<NodeId>>(),
Self::DocumentNode(_) => scalar::<DocumentNode>(),
Self::ContextModification(_) => scalar::<ContextModification>(),
Self::EditorApi(_) => scalar::<Arc<PlatformEditorApi>>(),
Self::ResourceHash(_) => scalar::<ResourceHash>(),
}
}
/// Materializes the value as [`Self::to_dynany`] does, wrapped in a value source typed by [`Self::ty`].
pub fn to_edge(self) -> Result<SourceHandle, String> {
match self {
// ===============
// MANUAL VARIANTS
// ===============
Self::None => Ok(record_value_source(())),
Self::TypeDefault(td) => {
let name = td.name.as_ref();
// The list-typed defaults serve an empty level; the rest construct
// their default directly, mirroring `to_dynany`'s recursion guard.
macro_rules! check_level {
($list:ty, $element:ty) => {
if name == core_types::normalize_type_name(std::any::type_name::<$list>()) {
return Ok(leveled_record_value_source(Vec::<$element>::new()));
}
};
}
check_level!(List<Graphic>, Graphic);
check_level!(List<Artboard>, Artboard);
check_level!(List<Raster<CPU>>, Raster<CPU>);
// One default lane rather than an empty level: an unwired path input
// starts from a blank vector, as the legacy path modify synthesized itself.
if name == core_types::normalize_type_name(std::any::type_name::<List<Vector>>()) { return Ok(leveled_record_value_source(vec![Vector::default()])); }
check_level!(List<String>, String);
if name == core_types::normalize_type_name(std::any::type_name::<DocumentNode>()) { return Ok(record_value_source(DocumentNode::default())); }
if name == core_types::normalize_type_name(std::any::type_name::<Resource>()) { return Ok(record_value_source(Resource::default())); }
Self::from_type_or_none(&Type::Concrete(td)).to_edge()
}
Self::F64Array(values) => Ok(leveled_record_value_source(values)),
Self::Color(color) => Ok(leveled_record_value_source(vec![color])),
Self::GradientRamp(ramp) => Ok(leveled_record_value_source(vec![Gradient::from(ramp)])),
Self::Strokes(strokes) => Ok(leveled_record_value_source(strokes)),
Self::DashPattern(lengths) => Ok(record_value_source(DashPattern(lengths.into_iter().map(core_types::list::Item::new_from_element).collect()))),
Self::BoxCorners(values) => Ok(record_value_source(BoxCorners(values.into_iter().map(core_types::list::Item::new_from_element).collect()))),
Self::BrushCache(cache) => Ok(record_value_source(cache)),
// =======================
// AUTO-GENERATED VARIANTS
// =======================
$( Self::$identifier(x) => Ok(record_value_source(x)), )*
// =======================
// NON-SERIALIZED VARIANTS
// =======================
Self::RenderOutput(x) => Ok(record_value_source(x)),
Self::NodeIdPath(path) => Ok(record_value_source(path)),
Self::DocumentNode(node) => Ok(record_value_source(node)),
Self::ContextModification(modification) => Ok(record_value_source(modification)),
Self::EditorApi(x) => Ok(record_value_source(x)),
Self::ResourceHash(x) => Ok(record_value_source(x)),
}
}
/// Evaluates a typed source and converts the landed value into a tagged value, with the coverage of [`Self::try_from_any`].
pub fn from_edge<'f>(handle: SourceHandle, ctx: &Context<'f>, frames: &core_types::record::Frames<'f>) -> Result<GPoll<Self>, String> {
let ty = handle.ty().clone();
// =======================
// RECORD WIRES, WHICH LAND AS THEIR ELEMENT
// =======================
if ty == core_types::registry::record_source_type::<()>() {
let edge = handle.downcast_record::<()>().map_err(|e| format!("{e:?}"))?;
return Ok(core_types::record::serve_input(&edge, ctx, frames).map(|_| TaggedValue::None));
}
$(
if ty == core_types::registry::record_source_type::<$ty>() {
let layout = handle.layout().clone();
let edge = handle.downcast_record::<$ty>().map_err(|e| format!("{e:?}"))?;
return Ok(core_types::record::serve_input(&edge, ctx, frames)
.map(|value| TaggedValue::$identifier(unsafe { core_types::record::read_element::<$ty>(layout.rec(&value)) })));
}
)*
if ty == core_types::registry::record_source_type::<RenderOutput>() {
let layout = handle.layout().clone();
let edge = handle.downcast_record::<RenderOutput>().map_err(|e| format!("{e:?}"))?;
return Ok(core_types::record::serve_input(&edge, ctx, frames)
.map(|value| TaggedValue::RenderOutput(unsafe { core_types::record::read_element::<RenderOutput>(layout.rec(&value)) })));
}
Err(format!("Cannot convert edge of type {ty} to TaggedValue"))
} }
/// Attempts to downcast the dynamic type to a tagged value /// Attempts to downcast the dynamic type to a tagged value
@@ -399,36 +508,49 @@ macro_rules! tagged_value {
Type::Concrete(concrete_type) => { Type::Concrete(concrete_type) => {
let name = concrete_type.name.as_ref(); let name = concrete_type.name.as_ref();
// Tries using the default for the tagged value type. If it not implemented, then uses the default used in document_node_types. If it is not used there, then TaggedValue::None is returned. // Tries using the default for the tagged value type. If it not implemented, then uses the default used in document_node_types. If it is not used there, then TaggedValue::None is returned.
if name == std::any::type_name::<()>() { return Some(TaggedValue::None) } if name == core_types::normalize_type_name(std::any::type_name::<()>()) { return Some(TaggedValue::None) }
if name == std::any::type_name::<Gradient>() { return Some(TaggedValue::GradientRamp(GradientRamp::default())) } // List-wrapped types need a single-item default with the element's default, not an empty list
if name == std::any::type_name::<DashPattern>() { return Some(TaggedValue::DashPattern(Vec::new())) } if name == core_types::normalize_type_name(std::any::type_name::<List<Color>>()) { return Some(TaggedValue::Color(Color::default())) }
if name == std::any::type_name::<BoxCorners>() { return Some(TaggedValue::BoxCorners(Vec::new())) } if name == core_types::normalize_type_name(std::any::type_name::<List<Gradient>>()) { return Some(TaggedValue::GradientRamp(GradientRamp::default())) }
$( if name == std::any::type_name::<$ty>() { return Some(TaggedValue::$identifier(Default::default())) } )* $( if name == core_types::normalize_type_name(std::any::type_name::<$ty>()) { return Some(TaggedValue::$identifier(Default::default())) } )*
if name == std::any::type_name::<List<Stroke>>() { return Some(TaggedValue::Strokes(Vec::new())) } if name == core_types::normalize_type_name(std::any::type_name::<List<f64>>()) { return Some(TaggedValue::F64Array(Vec::new())) }
if name == std::any::type_name::<BrushCache>() { return Some(TaggedValue::BrushCache(Default::default())) } if name == core_types::normalize_type_name(std::any::type_name::<List<Stroke>>()) { return Some(TaggedValue::Strokes(Vec::new())) }
// Unranked types without a variant route through `TypeDefault`, with `to_dynany`/`to_any` constructing the actual default at execution time // The manual variants are not in the generated `$ty` list, so their defaults are named here
macro_rules! check_bare { if name == core_types::normalize_type_name(std::any::type_name::<BoxCorners>()) { return Some(TaggedValue::BoxCorners(Vec::new())) }
if name == core_types::normalize_type_name(std::any::type_name::<DashPattern>()) { return Some(TaggedValue::DashPattern(Vec::new())) }
if name == core_types::normalize_type_name(std::any::type_name::<List<BoxCorners>>()) { return Some(TaggedValue::BoxCorners(Vec::new())) }
if name == core_types::normalize_type_name(std::any::type_name::<List<DashPattern>>()) { return Some(TaggedValue::DashPattern(Vec::new())) }
if name == core_types::normalize_type_name(std::any::type_name::<BrushCache>()) { return Some(TaggedValue::BrushCache(Default::default())) }
if name == core_types::normalize_type_name(std::any::type_name::<GradientRamp>()) { return Some(TaggedValue::GradientRamp(GradientRamp::default())) }
// Leveled inputs type by their element; each element name maps to the
// same tagged default as its legacy list form.
if name == core_types::normalize_type_name(std::any::type_name::<Color>()) { return Some(TaggedValue::Color(Color::default())) }
if name == core_types::normalize_type_name(std::any::type_name::<Gradient>()) { return Some(TaggedValue::GradientRamp(GradientRamp::default())) }
if name == core_types::normalize_type_name(std::any::type_name::<Stroke>()) { return Some(TaggedValue::Strokes(Vec::new())) }
if name == core_types::normalize_type_name(std::any::type_name::<Graphic>()) { return Some(TaggedValue::TypeDefault(core_types::descriptor!(List<Graphic>))) }
if name == core_types::normalize_type_name(std::any::type_name::<Artboard>()) { return Some(TaggedValue::TypeDefault(core_types::descriptor!(List<Artboard>))) }
if name == core_types::normalize_type_name(std::any::type_name::<Raster<CPU>>()) { return Some(TaggedValue::TypeDefault(core_types::descriptor!(List<Raster<CPU>>))) }
if name == core_types::normalize_type_name(std::any::type_name::<Vector>()) { return Some(TaggedValue::TypeDefault(core_types::descriptor!(List<Vector>))) }
// Types whose `TaggedValue` variant has been removed. They route through `TypeDefault` instead, with `to_dynany`/`to_any` constructing the actual default at execution time.
macro_rules! check {
($type_default:ty) => { ($type_default:ty) => {
if name == std::any::type_name::<$type_default>() { return Some(TaggedValue::TypeDefault(input.clone())); } if name == core_types::normalize_type_name(std::any::type_name::<$type_default>()) { return Some(TaggedValue::TypeDefault(core_types::descriptor!($type_default))); }
}; };
} }
for_each_bare_type_default!(check_bare); for_each_bare_type_default!(check);
macro_rules! check_list {
($element:ty) => {
if name == core_types::normalize_type_name(std::any::type_name::<List<$element>>()) { return Some(TaggedValue::TypeDefault(core_types::descriptor!(List<$element>))); }
};
}
for_each_list_type_default!(check_list);
None None
} }
Type::Fn(_, output) => TaggedValue::from_type(output), Type::Fn(_, output) => TaggedValue::from_type(output),
Type::Future(output) => TaggedValue::from_type(output), Type::Future(output) => TaggedValue::from_type(output),
// Element types with a dedicated variant use it directly (the variant's value is a rank-0 cell); the rest store the structural type // One wire kind: a record input types by its element, so the element's own
Type::Item(element) => TaggedValue::from_type(element).or_else(|| { // dedicated variant is used where there is one and the structural type otherwise.
macro_rules! check { Type::Record(element) => TaggedValue::from_type(element).or_else(|| {
($type_default:ty) => {
if **element == concrete!($type_default) { return Some(TaggedValue::TypeDefault(input.clone())); }
};
}
for_each_item_type_default!(check);
None
}),
// Structural lists match by element; `List<f64>` stays the dedicated `F64Array` variant
Type::List(element) => {
if **element == concrete!(f64) { if **element == concrete!(f64) {
return Some(TaggedValue::F64Array(Vec::new())); return Some(TaggedValue::F64Array(Vec::new()));
} }
@@ -437,12 +559,13 @@ macro_rules! tagged_value {
} }
macro_rules! check { macro_rules! check {
($type_default:ty) => { ($type_default:ty) => {
if **element == concrete!($type_default) { return Some(TaggedValue::TypeDefault(input.clone())); } if **element == concrete!($type_default) { return Some(TaggedValue::TypeDefault(core_types::descriptor!($type_default))); }
}; };
} }
for_each_item_type_default!(check);
for_each_list_type_default!(check); for_each_list_type_default!(check);
None None
} })
} }
} }
@@ -473,7 +596,7 @@ macro_rules! tagged_value {
Self::RenderOutput(_) => "RenderOutput".to_string(), Self::RenderOutput(_) => "RenderOutput".to_string(),
Self::NodeIdPath(path) => format!("NodeIdPath({path:?})"), Self::NodeIdPath(path) => format!("NodeIdPath({path:?})"),
Self::DocumentNode(node) => format!("DocumentNode({node:?})"), Self::DocumentNode(node) => format!("DocumentNode({node:?})"),
Self::ContextFeatures(features) => format!("ContextFeatures({features:?})"), Self::ContextModification(modification) => format!("ContextModification({modification:?})"),
Self::EditorApi(_) => "PlatformEditorApi".to_string(), Self::EditorApi(_) => "PlatformEditorApi".to_string(),
Self::ResourceHash(hash) => format!("ResourceHash({hash:?})"), Self::ResourceHash(hash) => format!("ResourceHash({hash:?})"),
} }
@@ -680,6 +803,8 @@ impl TaggedValue {
match ty { match ty {
Type::Generic(_) => None, Type::Generic(_) => None,
// A leveled input's default is its element's default, as in `from_type`.
Type::Record(inner) => TaggedValue::from_primitive_string(string, inner),
Type::Concrete(concrete_type) => { Type::Concrete(concrete_type) => {
let ty = concrete_type.id?; let ty = concrete_type.id?;
use std::any::TypeId; use std::any::TypeId;
@@ -696,6 +821,10 @@ impl TaggedValue {
() if ty == TypeId::of::<Color>() => to_color(string).map(TaggedValue::Color)?, () if ty == TypeId::of::<Color>() => to_color(string).map(TaggedValue::Color)?,
// The Fill/Stroke paint wires carry `Graphic` or `Gradient` elements, so a paint default parses through the element recursion as a color or gradient literal // The Fill/Stroke paint wires carry `Graphic` or `Gradient` elements, so a paint default parses through the element recursion as a color or gradient literal
() if ty == TypeId::of::<Graphic>() => to_color(string).map(TaggedValue::Color)?, () if ty == TypeId::of::<Graphic>() => to_color(string).map(TaggedValue::Color)?,
// A rank-1 paint wire names its list type, so it parses the same literal as its element does
() if ty == TypeId::of::<List<Graphic>>() => to_color(string).map(TaggedValue::Color)?,
() if ty == TypeId::of::<List<Color>>() => to_color(string).map(TaggedValue::Color)?,
() if ty == TypeId::of::<List<Gradient>>() => to_gradient(string).map(|gradient| TaggedValue::GradientRamp(gradient.into()))?,
() if ty == TypeId::of::<Gradient>() => to_gradient(string).map(|gradient| TaggedValue::GradientRamp(gradient.into()))?, () if ty == TypeId::of::<Gradient>() => to_gradient(string).map(|gradient| TaggedValue::GradientRamp(gradient.into()))?,
() if ty == TypeId::of::<ReferencePoint>() => to_reference_point(string).map(TaggedValue::ReferencePoint)?, () if ty == TypeId::of::<ReferencePoint>() => to_reference_point(string).map(TaggedValue::ReferencePoint)?,
() if ty == TypeId::of::<DashPattern>() => TaggedValue::DashPattern(core_types::misc::parse_f64_list(string)), () if ty == TypeId::of::<DashPattern>() => TaggedValue::DashPattern(core_types::misc::parse_f64_list(string)),
@@ -706,8 +835,6 @@ impl TaggedValue {
} }
Type::Fn(_, output) => TaggedValue::from_primitive_string(string, output), Type::Fn(_, output) => TaggedValue::from_primitive_string(string, output),
Type::Future(fut) => TaggedValue::from_primitive_string(string, fut), Type::Future(fut) => TaggedValue::from_primitive_string(string, fut),
Type::Item(element) => TaggedValue::from_primitive_string(string, element),
Type::List(element) => TaggedValue::from_primitive_string(string, element),
} }
} }
@@ -720,12 +847,12 @@ impl TaggedValue {
/// The stored form of a paint input's red-slash "no paint" choice: the `Item<Graphic>` type default, materializing as a `Graphic::None` paint. /// The stored form of a paint input's red-slash "no paint" choice: the `Item<Graphic>` type default, materializing as a `Graphic::None` paint.
pub fn no_paint() -> Self { pub fn no_paint() -> Self {
TaggedValue::TypeDefault(item!(Graphic)) TaggedValue::TypeDefault(core_types::descriptor!(Graphic))
} }
/// Whether this is the `Item<Graphic>` type default created by [`Self::no_paint`] (and by disconnecting a paint wire). /// Whether this is the `Item<Graphic>` type default created by [`Self::no_paint`] (and by disconnecting a paint wire).
pub fn is_no_paint(&self) -> bool { pub fn is_no_paint(&self) -> bool {
matches!(self, TaggedValue::TypeDefault(td) if *td == item!(Graphic)) matches!(self, TaggedValue::TypeDefault(td) if *td == core_types::descriptor!(Graphic))
} }
} }
@@ -733,16 +860,16 @@ impl TaggedValue {
/// ///
/// Routes legacy variant names into modern variants, in typed Rust. Each legacy name is also matched against the historical `#[serde(alias = "...")]` spellings the deleted variant accepted, so old-shape inner payloads are caught: /// Routes legacy variant names into modern variants, in typed Rust. Each legacy name is also matched against the historical `#[serde(alias = "...")]` spellings the deleted variant accepted, so old-shape inner payloads are caught:
/// ///
/// - `Graphic` (or alias `GraphicGroup`/`Group`) → `TaggedValue::TypeDefault(list!(Graphic))` /// - `Graphic` (or alias `GraphicGroup`/`Group`) → `TaggedValue::TypeDefault(core_types::descriptor!(List<Graphic>))`
/// - `Artboard` (or alias `ArtboardGroup`) → `TaggedValue::TypeDefault(list!(Artboard))` /// - `Artboard` (or alias `ArtboardGroup`) → `TaggedValue::TypeDefault(core_types::descriptor!(List<Artboard>))`
/// - `Raster` (or alias `ImageFrame`/`RasterData`/`Image`): /// - `Raster` (or alias `ImageFrame`/`RasterData`/`Image`):
/// - non-empty (the legacy `image` proto's input 1, where the inner `Raster<CPU>` serializes as the embedded `Image<Color>`) → `TaggedValue::ImageData(<inner Image<Color>>)` /// - non-empty (the legacy `image` proto's input 1, where the inner `Raster<CPU>` serializes as the embedded `Image<Color>`) → `TaggedValue::ImageData(<inner Image<Color>>)`
/// - empty → `TaggedValue::TypeDefault(list!(Raster<CPU>))` /// - empty → `TaggedValue::TypeDefault(core_types::descriptor!(List<Raster<CPU>>))`
/// - `Vector` (or alias `VectorData`): /// - `Vector` (or alias `VectorData`):
/// - non-empty → `TaggedValue::VectorModification(<built from first element>)` (the document_migration's Path pass disambiguates this between SVG-import legacy and a discardable modern baked value via the input's `exposed` flag) /// - non-empty → `TaggedValue::VectorModification(<built from first element>)` (the document_migration's Path pass disambiguates this between SVG-import legacy and a discardable modern baked value via the input's `exposed` flag)
/// - empty → `TaggedValue::TypeDefault(list!(Vector))` /// - empty → `TaggedValue::TypeDefault(core_types::descriptor!(List<Vector>))`
/// - `FillChoice` → `TaggedValue::Color` (solid), `TaggedValue::GradientRamp` (gradient), or `TaggedValue::no_paint()` (none) /// - `FillChoice` → `TaggedValue::Color` (solid), `TaggedValue::GradientRamp` (gradient), or `TaggedValue::no_paint()` (none)
/// - `Gradient` (or alias `GradientTable`/`GradientPositions`/`GradientStops`) → `TaggedValue::LegacyGradient` (ancient full struct) or `TaggedValue::GradientRamp` (ramp and legacy stops shapes, unwrapped from the legacy table form) /// - `Gradient` (or alias `GradientTable`/`GradientPositions`/`Gradient`) → `TaggedValue::LegacyGradient` (ancient full struct) or `TaggedValue::GradientRamp` (ramp and legacy stops shapes, unwrapped from the legacy table form)
/// - `TypeDefault` with the old bare-`TypeDescriptor` payload → the same variant wrapping a `Type` (name-encoded `List` normalized to structural) /// - `TypeDefault` with the old bare-`TypeDescriptor` payload → the same variant wrapping a `Type` (name-encoded `List` normalized to structural)
/// ///
/// All other tags (including ones with the modern shape) fall through to the standard derived `Deserialize` for `TaggedValue`. /// All other tags (including ones with the modern shape) fall through to the standard derived `Deserialize` for `TaggedValue`.
@@ -757,8 +884,8 @@ pub fn deserialize_tagged_value_with_legacy_migration<'de, D: serde::Deserialize
&& let Some((tag, content)) = map.iter().next() && let Some((tag, content)) = map.iter().next()
{ {
match tag.as_str() { match tag.as_str() {
"Graphic" | "GraphicGroup" | "Group" => return Ok(MemoHash::new(TaggedValue::TypeDefault(list!(Graphic)))), "Graphic" | "GraphicGroup" | "Group" => return Ok(MemoHash::new(TaggedValue::TypeDefault(core_types::descriptor!(List<Graphic>)))),
"Artboard" | "ArtboardGroup" => return Ok(MemoHash::new(TaggedValue::TypeDefault(list!(Artboard)))), "Artboard" | "ArtboardGroup" => return Ok(MemoHash::new(TaggedValue::TypeDefault(core_types::descriptor!(List<Artboard>)))),
"Raster" | "ImageFrame" | "RasterData" | "Image" => { "Raster" | "ImageFrame" | "RasterData" | "Image" => {
let first_element = content let first_element = content
.as_object() .as_object()
@@ -769,7 +896,7 @@ pub fn deserialize_tagged_value_with_legacy_migration<'de, D: serde::Deserialize
let image: Image<Color> = serde_json::from_value(image_value.clone()).map_err(serde::de::Error::custom)?; let image: Image<Color> = serde_json::from_value(image_value.clone()).map_err(serde::de::Error::custom)?;
return Ok(MemoHash::new(TaggedValue::ImageData(image))); return Ok(MemoHash::new(TaggedValue::ImageData(image)));
} }
return Ok(MemoHash::new(TaggedValue::TypeDefault(list!(Raster<CPU>)))); return Ok(MemoHash::new(TaggedValue::TypeDefault(core_types::descriptor!(List<Raster<CPU>>))));
} }
"Vector" | "VectorData" => { "Vector" | "VectorData" => {
let vector = graphic_types::migrations::migrate_to_optional_vector(content.clone()).map_err(serde::de::Error::custom)?; let vector = graphic_types::migrations::migrate_to_optional_vector(content.clone()).map_err(serde::de::Error::custom)?;
@@ -777,12 +904,41 @@ pub fn deserialize_tagged_value_with_legacy_migration<'de, D: serde::Deserialize
let modification = Box::new(VectorModification::create_from_vector(&vector)); let modification = Box::new(VectorModification::create_from_vector(&vector));
return Ok(MemoHash::new(TaggedValue::VectorModification(modification))); return Ok(MemoHash::new(TaggedValue::VectorModification(modification)));
} }
return Ok(MemoHash::new(TaggedValue::TypeDefault(list!(Vector)))); return Ok(MemoHash::new(TaggedValue::TypeDefault(core_types::descriptor!(List<Vector>))));
} }
// The `TypeDefault` payload used to be a bare `TypeDescriptor`; it now carries a `Type` // Documents written against the structural rank model store the payload as a `Type`
// (`{"List": {"Concrete": {..}}}`). Our one wire kind reduces that to the element it names,
// keeping the `List<..>` spelling for a rank-1 wire so the existing name lookups still match.
"TypeDefault" if content.as_object().is_some_and(|c| c.contains_key("Concrete") || c.contains_key("Item") || c.contains_key("List")) => {
fn structural_type_name(value: &serde_json::Value) -> Option<String> {
let object = value.as_object()?;
if let Some(concrete) = object.get("Concrete") {
return Some(concrete.as_object()?.get("name")?.as_str()?.to_string());
}
if let Some(item) = object.get("Item") {
return structural_type_name(item);
}
if let Some(list) = object.get("List") {
return Some(format!("core_types::list::List<{}>", structural_type_name(list)?));
}
object.get("Generic")?.as_str().map(str::to_string)
}
let Some(name) = structural_type_name(&content) else {
return Err(serde::de::Error::custom("a structural TypeDefault payload named no type"));
};
let descriptor = TypeDescriptor {
id: None,
name: std::borrow::Cow::Owned(name),
alias: None,
size: 0,
align: 0,
};
return Ok(MemoHash::new(TaggedValue::TypeDefault(descriptor)));
}
// The `TypeDefault` payload is a bare `TypeDescriptor`: our one wire kind needs no structural rank in it
"TypeDefault" if content.as_object().is_some_and(|c| c.contains_key("name")) => { "TypeDefault" if content.as_object().is_some_and(|c| c.contains_key("name")) => {
let descriptor: TypeDescriptor = serde_json::from_value(content.clone()).map_err(serde::de::Error::custom)?; let descriptor: TypeDescriptor = serde_json::from_value(content.clone()).map_err(serde::de::Error::custom)?;
return Ok(MemoHash::new(TaggedValue::TypeDefault(Type::Concrete(descriptor).normalize_rank()))); return Ok(MemoHash::new(TaggedValue::TypeDefault(descriptor)));
} }
// The `Color` tag used to carry `Option<Color>`, where a `null` payload (or an empty legacy color table) was the red-slash "no paint" choice // The `Color` tag used to carry `Option<Color>`, where a `null` payload (or an empty legacy color table) was the red-slash "no paint" choice
"Color" | "ColorTable" | "OptionalColor" | "ColorNotInTable" "Color" | "ColorTable" | "OptionalColor" | "ColorNotInTable"
@@ -811,7 +967,7 @@ pub fn deserialize_tagged_value_with_legacy_migration<'de, D: serde::Deserialize
} }
// The gradient tags carried several shapes over time, disambiguated here: the ancient full struct (`start`/`end` keys) becomes `LegacyGradient`, // The gradient tags carried several shapes over time, disambiguated here: the ancient full struct (`start`/`end` keys) becomes `LegacyGradient`,
// while the current ramp, the flat stops struct, the old tuple list, and the legacy one-element table wrapper all parse as the ramp value directly // while the current ramp, the flat stops struct, the old tuple list, and the legacy one-element table wrapper all parse as the ramp value directly
"Gradient" | "GradientTable" | "GradientPositions" | "GradientStops" => { "Gradient" | "GradientTable" | "GradientPositions" | "Gradient" => {
let table_element = content let table_element = content
.as_object() .as_object()
.and_then(|c| c.get("element").or_else(|| c.get("instance")).or_else(|| c.get("instances"))) .and_then(|c| c.get("element").or_else(|| c.get("instance")).or_else(|| c.get("instances")))
@@ -860,39 +1016,6 @@ impl Display for TaggedValue {
} }
} }
pub struct UpcastNode {
value: MemoHash<TaggedValue>,
}
impl<'input> Node<'input, DAny<'input>> for UpcastNode {
type Output = FutureAny<'input>;
fn eval(&'input self, _: DAny<'input>) -> Self::Output {
let memo_clone = MemoHash::clone(&self.value);
Box::pin(async move { memo_clone.into_inner().as_ref().clone().to_dynany() })
}
}
impl UpcastNode {
pub fn new(value: MemoHash<TaggedValue>) -> Self {
Self { value }
}
}
#[derive(Default, Debug, Clone, Copy)]
pub struct UpcastAsRefNode<T: AsRef<U> + Sync + Send, U: Sync + Send>(pub T, PhantomData<U>);
impl<'i, T: 'i + AsRef<U> + Sync + Send, U: 'i + StaticType + Sync + Send> Node<'i, DAny<'i>> for UpcastAsRefNode<T, U> {
type Output = FutureAny<'i>;
#[inline(always)]
fn eval(&'i self, _: DAny<'i>) -> Self::Output {
Box::pin(async move { Box::new(Item::new_from_element(self.0.as_ref())) as DAny<'i> })
}
}
impl<T: AsRef<U> + Sync + Send, U: Sync + Send> UpcastAsRefNode<T, U> {
pub const fn new(value: T) -> UpcastAsRefNode<T, U> {
UpcastAsRefNode(value, PhantomData)
}
}
#[derive(Debug, Clone, PartialEq, dyn_any::DynAny, serde::Serialize, serde::Deserialize)] #[derive(Debug, Clone, PartialEq, dyn_any::DynAny, serde::Serialize, serde::Deserialize)]
pub struct RenderOutput { pub struct RenderOutput {
pub data: RenderOutputType, pub data: RenderOutputType,
@@ -963,14 +1086,14 @@ mod typedefault_dispatch {
fn typedefault_dispatch_terminates() { fn typedefault_dispatch_terminates() {
macro_rules! check { macro_rules! check {
($type_default:ty, $stored:expr) => {{ ($type_default:ty, $stored:expr) => {{
let ty: Type = $stored; let ty: TypeDescriptor = $stored;
let expected_type_id = std::any::TypeId::of::<$type_default>(); let expected_type_id = std::any::TypeId::of::<$type_default>();
let dyn_value = TaggedValue::TypeDefault(ty.clone()).to_dynany(); let dyn_value = TaggedValue::TypeDefault(ty.clone()).to_dynany();
assert_eq!( assert_eq!(
DynAny::type_id(&*dyn_value), DynAny::type_id(&*dyn_value),
expected_type_id, expected_type_id,
"`to_dynany(TypeDefault({0}))` did not produce a `{0}` — the type-default lists cover this type but the unwrap site doesn't handle it. Without a match, `to_dynany` falls back to `from_type_or_none`, which returns `TypeDefault({0})` again and recurses forever.", "`to_dynany(TypeDefault({0}))` did not produce a `{0}` — `for_each_type_default!` lists this type but the unwrap site doesn't handle it. Without a match, `to_dynany` falls back to `from_type_or_none`, which returns `TypeDefault({0})` again and recurses forever.",
std::any::type_name::<$type_default>(), core_types::normalize_type_name(std::any::type_name::<$type_default>()),
); );
let arc_value = TaggedValue::TypeDefault(ty).to_any(); let arc_value = TaggedValue::TypeDefault(ty).to_any();
@@ -978,26 +1101,21 @@ mod typedefault_dispatch {
(*arc_value).type_id(), (*arc_value).type_id(),
expected_type_id, expected_type_id,
"`to_any(TypeDefault({0}))` did not produce a `{0}` — same recursion hazard as above for the `to_any` path.", "`to_any(TypeDefault({0}))` did not produce a `{0}` — same recursion hazard as above for the `to_any` path.",
std::any::type_name::<$type_default>(), core_types::normalize_type_name(std::any::type_name::<$type_default>()),
); );
}}; }};
} }
macro_rules! check_item { // One wire kind: a type default names its type, so the item and list lists both check their list form.
($element:ty) => {
check!(Item<$element>, item!($element));
};
}
macro_rules! check_list { macro_rules! check_list {
($element:ty) => { ($element:ty) => {
check!(List<$element>, list!($element)); check!(List<$element>, core_types::descriptor!(List<$element>));
}; };
} }
macro_rules! check_bare { macro_rules! check_bare {
($type_default:ty) => { ($type_default:ty) => {
check!($type_default, concrete!($type_default)); check!($type_default, core_types::descriptor!($type_default));
}; };
} }
for_each_item_type_default!(check_item);
for_each_list_type_default!(check_list); for_each_list_type_default!(check_list);
for_each_bare_type_default!(check_bare); for_each_bare_type_default!(check_bare);
} }
@@ -1006,7 +1124,6 @@ mod typedefault_dispatch {
#[cfg(test)] #[cfg(test)]
mod paint_default_parsing { mod paint_default_parsing {
use super::*; use super::*;
use core_types::{item, list};
/// A Fill/Stroke paint wire carries `Graphic` elements, so its `Color::BLACK` default must parse through the /// A Fill/Stroke paint wire carries `Graphic` elements, so its `Color::BLACK` default must parse through the
/// element recursion into a `Color` for a fresh Fill node's paint to resolve. /// element recursion into a `Color` for a fresh Fill node's paint to resolve.
@@ -1014,12 +1131,12 @@ mod paint_default_parsing {
fn paint_wire_parses_color_default_through_its_element() { fn paint_wire_parses_color_default_through_its_element() {
let black = Some(TaggedValue::Color(Color::BLACK)); let black = Some(TaggedValue::Color(Color::BLACK));
assert_eq!( assert_eq!(
TaggedValue::from_primitive_string("Color::BLACK", &list!(Graphic)), TaggedValue::from_primitive_string("Color::BLACK", &concrete!(List<Graphic>)),
black, black,
"a `List<Graphic>` paint wire should resolve its color default" "a `List<Graphic>` paint wire should resolve its color default"
); );
assert_eq!( assert_eq!(
TaggedValue::from_primitive_string("Color::BLACK", &item!(Graphic)), TaggedValue::from_primitive_string("Color::BLACK", &concrete!(Graphic)),
black, black,
"an `Item<Graphic>` paint wire should resolve its color default" "an `Item<Graphic>` paint wire should resolve its color default"
); );
@@ -1138,3 +1255,62 @@ mod gradient_shape_migration {
); );
} }
} }
#[cfg(test)]
mod leveled_edges {
use super::*;
use core_types::descriptor;
use core_types::registry::record_source_type;
#[test]
fn list_variants_produce_leveled_edges_typed_by_element() {
let edge = TaggedValue::F64Array(vec![1., 2., 3.]).to_edge().unwrap();
assert_eq!(edge.ty(), &record_source_type::<f64>());
assert_eq!(edge.layout().depth, 1);
let edge = TaggedValue::Color(Color::default()).to_edge().unwrap();
assert_eq!(edge.ty(), &record_source_type::<Color>());
assert_eq!(edge.layout().depth, 1);
let edge = TaggedValue::TypeDefault(descriptor!(List<Graphic>)).to_edge().unwrap();
assert_eq!(edge.ty(), &record_source_type::<Graphic>());
assert_eq!(edge.layout().depth, 1);
}
#[test]
fn scalar_variants_keep_their_rank_zero_edges() {
let edge = TaggedValue::Bool(true).to_edge().unwrap();
assert_eq!(edge.ty(), &record_source_type::<bool>());
assert_eq!(edge.layout().depth, 0);
}
#[test]
fn the_value_layout_matches_the_edge_layout() {
for value in [
TaggedValue::F64Array(vec![1.]),
TaggedValue::Bool(true),
TaggedValue::TypeDefault(descriptor!(List<Vector>)),
TaggedValue::GradientRamp(Default::default()),
] {
let layout = value.value_layout().unwrap();
let edge = value.to_edge().unwrap();
assert_eq!(&layout, edge.layout());
}
}
}
#[cfg(test)]
mod record_defaults {
use super::*;
use core_types::registry::record_source_type;
// The registry can present a record row first (wasm registration order),
// so primitive defaults must parse through the record wrapping.
#[test]
fn primitive_defaults_parse_through_record_wires() {
let leveled = core_types::registry::record_type::<f64>();
assert_eq!(TaggedValue::from_primitive_string("2.", &leveled), Some(TaggedValue::F64(2.)));
assert_eq!(TaggedValue::from_primitive_string("5", &record_source_type::<u32>()), Some(TaggedValue::U32(5)));
assert_eq!(TaggedValue::from_primitive_string("true", &record_source_type::<bool>()), Some(TaggedValue::Bool(true)));
}
}
@@ -1,11 +1,11 @@
use crate::document::NodeNetwork; use crate::document::NodeNetwork;
use crate::proto::{LocalFuture, ProtoNetwork}; use crate::proto::{ProtoNetwork, Registry};
use std::error::Error; use std::error::Error;
pub struct Compiler {} pub struct Compiler {}
impl Compiler { impl Compiler {
pub fn compile(&self, mut network: NodeNetwork) -> impl Iterator<Item = Result<ProtoNetwork, String>> { pub fn compile<'r>(&self, mut network: NodeNetwork, registry: &'r Registry) -> impl Iterator<Item = Result<ProtoNetwork, String>> + 'r {
network.resolve_scope_inputs(); network.resolve_scope_inputs();
network.generate_node_paths(&[]); network.generate_node_paths(&[]);
let node_ids = network.nodes.keys().copied().collect::<Vec<_>>(); let node_ids = network.nodes.keys().copied().collect::<Vec<_>>();
@@ -19,13 +19,17 @@ impl Compiler {
proto_networks.map(move |mut proto_network| { proto_networks.map(move |mut proto_network| {
proto_network.insert_context_nullification_nodes()?; proto_network.insert_context_nullification_nodes()?;
let _ = proto_network.resolve_types(registry);
proto_network
.compute_layouts()
.map_err(|errors| errors.iter().map(|error| format!("{:?}", error.error)).collect::<Vec<_>>().join("\n"))?;
proto_network.generate_stable_node_ids(); proto_network.generate_stable_node_ids();
Ok(proto_network) Ok(proto_network)
}) })
} }
pub fn compile_single(&self, network: NodeNetwork) -> Result<ProtoNetwork, String> { pub fn compile_single(&self, network: NodeNetwork, registry: &Registry) -> Result<ProtoNetwork, String> {
assert_eq!(network.exports.len(), 1, "Graph with multiple outputs not yet handled"); assert_eq!(network.exports.len(), 1, "Graph with multiple outputs not yet handled");
let Some(proto_network) = self.compile(network).next() else { let Some(proto_network) = self.compile(network, registry).next() else {
return Err("Failed to convert graph into proto graph".to_string()); return Err("Failed to convert graph into proto graph".to_string());
}; };
proto_network proto_network
@@ -33,5 +37,5 @@ impl Compiler {
} }
pub trait Executor<I, O> { pub trait Executor<I, O> {
fn execute(&self, input: I) -> LocalFuture<'_, Result<O, Box<dyn Error>>>; fn execute(&self, input: I) -> Result<O, Box<dyn Error>>;
} }
File diff suppressed because it is too large. Load diff
+3 -3
View File
@@ -1,6 +1,6 @@
use crate::document::NodeNetwork; use crate::document::NodeNetwork;
use crate::graphene_compiler::Compiler; use crate::graphene_compiler::Compiler;
use crate::proto::ProtoNetwork; use crate::proto::{ProtoNetwork, Registry};
pub fn load_network(document_string: &str) -> NodeNetwork { pub fn load_network(document_string: &str) -> NodeNetwork {
let document: serde_json::Value = serde_json::from_str(document_string).expect("Failed to parse document"); let document: serde_json::Value = serde_json::from_str(document_string).expect("Failed to parse document");
@@ -8,9 +8,9 @@ pub fn load_network(document_string: &str) -> NodeNetwork {
serde_json::from_str::<NodeNetwork>(&document).expect("Failed to parse document") serde_json::from_str::<NodeNetwork>(&document).expect("Failed to parse document")
} }
pub fn compile(network: NodeNetwork) -> ProtoNetwork { pub fn compile(network: NodeNetwork, registry: &Registry) -> ProtoNetwork {
let compiler = Compiler {}; let compiler = Compiler {};
compiler.compile_single(network).unwrap() compiler.compile_single(network, registry).unwrap()
} }
pub fn load_from_name(name: &str) -> NodeNetwork { pub fn load_from_name(name: &str) -> NodeNetwork {
+37 -9
View File
@@ -1,15 +1,40 @@
use futures::executor::block_on;
use graph_craft::document::value::{RenderOutputType, TaggedValue, UVec2}; use graph_craft::document::value::{RenderOutputType, TaggedValue, UVec2};
use graph_craft::graphene_compiler::Executor; use graph_craft::graphene_compiler::Executor;
use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation}; use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation};
use graphene_std::core_types::ops::Convert; use graphene_std::core_types::gpoll::GPoll;
use graphene_std::core_types::ops::ConvertAsync;
use graphene_std::core_types::transform::Footprint; use graphene_std::core_types::transform::Footprint;
use graphene_std::raster_types::{CPU, GPU, Raster}; use graphene_std::raster_types::{CPU, GPU, Raster};
use interpreted_executor::dynamic_executor::DynamicExecutor; use interpreted_executor::dynamic_executor::DynamicExecutor;
use std::error::Error; use std::error::Error;
use std::io::Cursor; use std::io::Cursor;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::mpsc::Receiver;
use std::time::Duration; use std::time::Duration;
const SOURCE_COMPLETION_TIMEOUT: Duration = Duration::from_secs(30);
fn execute_until_final(executor: &DynamicExecutor, render_config: RenderConfig, completion: &Receiver<()>) -> Result<TaggedValue, Box<dyn Error>> {
loop {
while completion.try_recv().is_ok() {}
match executor.execute(render_config)? {
GPoll::Final(value) => return Ok(value),
GPoll::Fallback(boxed) => {
let (value, error) = *boxed;
log::warn!("Node graph evaluation reported an error alongside its fallback output: {error:?}");
return Ok(value);
}
GPoll::Partial(_) | GPoll::Pending => {
completion
.recv_timeout(SOURCE_COMPLETION_TIMEOUT)
.map_err(|_| format!("Timed out after {}s waiting for async sources to complete", SOURCE_COMPLETION_TIMEOUT.as_secs()))?;
}
GPoll::Error(error) => return Err(format!("Node graph evaluation failed: {error:?}").into()),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FileType { pub enum FileType {
Svg, Svg,
@@ -28,14 +53,16 @@ pub fn detect_file_type(path: &Path) -> Result<FileType, String> {
} }
} }
pub async fn export_document( #[allow(clippy::too_many_arguments)]
pub fn export_document(
executor: &DynamicExecutor, executor: &DynamicExecutor,
wgpu_executor: &wgpu_executor::WgpuExecutor, wgpu_executor: wgpu_executor::WgpuExecutorHandle,
output_path: PathBuf, output_path: PathBuf,
file_type: FileType, file_type: FileType,
scale: f64, scale: f64,
(width, height): (Option<u32>, Option<u32>), (width, height): (Option<u32>, Option<u32>),
transparent: bool, transparent: bool,
completion: &Receiver<()>,
) -> Result<(), Box<dyn Error>> { ) -> Result<(), Box<dyn Error>> {
// Determine export format based on file type // Determine export format based on file type
let export_format = match file_type { let export_format = match file_type {
@@ -57,7 +84,7 @@ pub async fn export_document(
} }
// Execute the graph // Execute the graph
let result = executor.execute(render_config.into_context()).await?; let result = execute_until_final(executor, render_config, completion)?;
// Handle the result based on output type // Handle the result based on output type
match result { match result {
@@ -70,7 +97,7 @@ pub async fn export_document(
RenderOutputType::Texture(texture) => { RenderOutputType::Texture(texture) => {
// Convert GPU texture to CPU buffer // Convert GPU texture to CPU buffer
let gpu_raster = Raster::<GPU>::new_gpu(texture); let gpu_raster = Raster::<GPU>::new_gpu(texture);
let cpu_raster: Raster<CPU> = gpu_raster.convert(Footprint::BOUNDLESS, wgpu_executor).await; let cpu_raster: Raster<CPU> = block_on(gpu_raster.convert(Footprint::BOUNDLESS, wgpu_executor.clone()));
let (data, width, height) = cpu_raster.to_flat_u8(); let (data, width, height) = cpu_raster.to_flat_u8();
// Encode and write raster image // Encode and write raster image
@@ -149,13 +176,14 @@ impl AnimationParams {
} }
/// Export an animated GIF by rendering multiple frames at different animation times /// Export an animated GIF by rendering multiple frames at different animation times
pub async fn export_gif( pub fn export_gif(
executor: &DynamicExecutor, executor: &DynamicExecutor,
wgpu_executor: &wgpu_executor::WgpuExecutor, wgpu_executor: wgpu_executor::WgpuExecutorHandle,
output_path: PathBuf, output_path: PathBuf,
scale: f64, scale: f64,
(width, height): (Option<u32>, Option<u32>), (width, height): (Option<u32>, Option<u32>),
animation: AnimationParams, animation: AnimationParams,
completion: &Receiver<()>,
) -> Result<(), Box<dyn Error>> { ) -> Result<(), Box<dyn Error>> {
use image::codecs::gif::{GifEncoder, Repeat}; use image::codecs::gif::{GifEncoder, Repeat};
use image::{Frame, RgbaImage}; use image::{Frame, RgbaImage};
@@ -195,14 +223,14 @@ pub async fn export_gif(
} }
// Execute the graph for this frame // Execute the graph for this frame
let result = executor.execute(render_config.into_context()).await?; let result = execute_until_final(executor, render_config, completion)?;
// Extract RGBA data from result // Extract RGBA data from result
let (data, img_width, img_height) = match result { let (data, img_width, img_height) = match result {
TaggedValue::RenderOutput(output) => match output.data { TaggedValue::RenderOutput(output) => match output.data {
RenderOutputType::Texture(texture) => { RenderOutputType::Texture(texture) => {
let gpu_raster = Raster::<GPU>::new_gpu(texture); let gpu_raster = Raster::<GPU>::new_gpu(texture);
let cpu_raster: Raster<CPU> = gpu_raster.convert(Footprint::BOUNDLESS, wgpu_executor).await; let cpu_raster: Raster<CPU> = block_on(gpu_raster.convert(Footprint::BOUNDLESS, wgpu_executor.clone()));
cpu_raster.to_flat_u8() cpu_raster.to_flat_u8()
} }
RenderOutputType::Buffer { data, width, height } => (data, width, height), RenderOutputType::Buffer { data, width, height } => (data, width, height),
+49 -16
View File
@@ -7,13 +7,13 @@ use document_format::{GddV1, GddV1Layout};
use fern::colors::{Color, ColoredLevelConfig}; use fern::colors::{Color, ColoredLevelConfig};
use futures::executor::block_on; use futures::executor::block_on;
use graph_craft::application_io::EditorPreferences; use graph_craft::application_io::EditorPreferences;
use graph_craft::application_io::resource::ResourceRegistry;
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi}; use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
use graph_craft::document::*; use graph_craft::document::*;
use graph_craft::graphene_compiler::Compiler; use graph_craft::graphene_compiler::Compiler;
use graph_craft::proto::ProtoNetwork; use graph_craft::proto::ProtoNetwork;
use graph_craft::util::load_network; use graph_craft::util::load_network;
use graphene_std::application_io::{ApplicationIo, NodeGraphUpdateMessage, NodeGraphUpdateSender}; use graphene_std::application_io::{ApplicationIo, NodeGraphUpdateMessage, NodeGraphUpdateSender};
use graphene_std::runtime::{DynGraphRuntime, DynSpawner, GraphRuntime, RuntimeHandle, SourceFuture, Spawner, poll_once};
use interpreted_executor::dynamic_executor::DynamicExecutor; use interpreted_executor::dynamic_executor::DynamicExecutor;
use interpreted_executor::util::wrap_network_in_scope; use interpreted_executor::util::wrap_network_in_scope;
use std::error::Error; use std::error::Error;
@@ -28,6 +28,35 @@ impl NodeGraphUpdateSender for UpdateLogger {
} }
} }
struct TokioSpawner(Option<tokio::runtime::Runtime>);
impl TokioSpawner {
fn new() -> Result<Self, std::io::Error> {
Ok(Self(Some(tokio::runtime::Runtime::new()?)))
}
}
impl Spawner for TokioSpawner {
fn spawn(&self, mut task: SourceFuture) -> bool {
let runtime = self.0.as_ref().expect("runtime lives until drop");
let _guard = runtime.enter();
if poll_once(&mut task) {
return true;
}
runtime.spawn(task);
false
}
}
/// Dropping a tokio runtime blocks on its tasks, which panics inside the async main; shut down in the background instead.
impl Drop for TokioSpawner {
fn drop(&mut self) {
if let Some(runtime) = self.0.take() {
runtime.shutdown_background();
}
}
}
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
#[clap(name = "graphene-cli", version)] #[clap(name = "graphene-cli", version)]
pub struct App { pub struct App {
@@ -101,8 +130,7 @@ struct GlobalOpts {
verbose: u8, verbose: u8,
} }
#[tokio::main] fn main() -> Result<(), Box<dyn Error>> {
async fn main() -> Result<(), Box<dyn Error>> {
let app = App::parse(); let app = App::parse();
let log_level = app.global_opts.verbose; let log_level = app.global_opts.verbose;
@@ -130,9 +158,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
let gdd = if is_gdd { let gdd = if is_gdd {
let archive = std::fs::read(document_path).map_err(|error| format!("Failed to read document {}: {error}", document_path.display()))?; let archive = std::fs::read(document_path).map_err(|error| format!("Failed to read document {}: {error}", document_path.display()))?;
let container = AnyContainer::Memory(MemoryBackend::new()); let container = AnyContainer::Memory(MemoryBackend::new());
let gdd = document_format::Gdd::open_from_archive(archive.as_ref(), container, GddV1Layout) let gdd = block_on(document_format::Gdd::open_from_archive(archive.as_ref(), container, GddV1Layout)).map_err(|error| format!("Failed to open document: {error}"))?;
.await
.map_err(|error| format!("Failed to open document: {error}"))?;
Some(gdd) Some(gdd)
} else { } else {
None None
@@ -140,7 +166,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
if let Command::ExtractLegacyDoc { ref document } = app.command { if let Command::ExtractLegacyDoc { ref document } = app.command {
let Some(gdd) = &gdd else { return Err("ExtractLegacyDoc requires a .gdd document".into()) }; let Some(gdd) = &gdd else { return Err("ExtractLegacyDoc requires a .gdd document".into()) };
let Some(legacy_doc) = gdd.read_legacy_document().await else { let Some(legacy_doc) = block_on(gdd.read_legacy_document()) else {
return Err("gdd file did not contain a legacy .graphite document".into()); return Err("gdd file did not contain a legacy .graphite document".into());
}; };
let mut new_path = document.clone(); let mut new_path = document.clone();
@@ -153,7 +179,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
// Build the runtime network: from the `.gdd` registry, or by loading a legacy `.graphite` document. // Build the runtime network: from the `.gdd` registry, or by loading a legacy `.graphite` document.
let node_network = match &gdd { let node_network = match &gdd {
Some(gdd) => { Some(gdd) => {
let declarations = gdd.declarations(gdd).await; let declarations = block_on(gdd.declarations(gdd));
let (node_network, _metadata) = gdd.registry().to_runtime_with_metadata(&declarations)?; let (node_network, _metadata) = gdd.registry().to_runtime_with_metadata(&declarations)?;
node_network node_network
} }
@@ -164,7 +190,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
}; };
log::info!("Creating GPU context"); log::info!("Creating GPU context");
let mut application_io = PlatformApplicationIo::new().await; let mut application_io = block_on(PlatformApplicationIo::new());
if let Some(gdd) = &gdd { if let Some(gdd) = &gdd {
application_io.inject_resource_proxy(Box::new(gdd.resource_proxy())); application_io.inject_resource_proxy(Box::new(gdd.resource_proxy()));
} }
@@ -176,16 +202,22 @@ async fn main() -> Result<(), Box<dyn Error>> {
let application_io_for_api = application_io_arc.clone(); let application_io_for_api = application_io_arc.clone();
// Get reference to wgpu executor and clone device handle // Get reference to wgpu executor and clone device handle
let wgpu_executor_ref = application_io_arc.gpu_executor().unwrap(); let wgpu_executor_ref = wgpu_executor::WgpuExecutorHandle(application_io_arc.gpu_executor_arc().unwrap());
let device = wgpu_executor_ref.context().device.clone(); let device = wgpu_executor_ref.context().device.clone();
let preferences = EditorPreferences { let preferences = EditorPreferences {
max_render_region_size: EditorPreferences::default().max_render_region_size, max_render_region_size: EditorPreferences::default().max_render_region_size,
}; };
let graph_runtime: Arc<DynGraphRuntime> = Arc::new(GraphRuntime::new(Box::new(TokioSpawner::new()?) as Box<DynSpawner>));
let (completion_sender, completion_receiver) = std::sync::mpsc::channel();
graph_runtime.set_notifier(Arc::new(move || {
let _ = completion_sender.send(());
}));
let editor_api = Arc::new(PlatformEditorApi { let editor_api = Arc::new(PlatformEditorApi {
application_io: Some(application_io_for_api), application_io: Some(application_io_for_api),
node_graph_message_sender: Box::new(UpdateLogger {}), node_graph_message_sender: Box::new(UpdateLogger {}),
editor_preferences: Box::new(preferences), editor_preferences: Box::new(preferences),
runtime: RuntimeHandle(graph_runtime.clone()),
}); });
let proto_graph = compile_graph(node_network, editor_api, gdd.as_ref())?; let proto_graph = compile_graph(node_network, editor_api, gdd.as_ref())?;
@@ -218,7 +250,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
let file_type = export::detect_file_type(&output)?; let file_type = export::detect_file_type(&output)?;
// Create executor // Create executor
let executor = create_executor(proto_graph)?; let executor = create_executor(proto_graph, graph_runtime)?;
if fps <= 0. { if fps <= 0. {
return Err("Fps number must be positive".into()); return Err("Fps number must be positive".into());
@@ -227,9 +259,9 @@ async fn main() -> Result<(), Box<dyn Error>> {
// Perform export based on file type // Perform export based on file type
if file_type == export::FileType::Gif { if file_type == export::FileType::Gif {
let animation = export::AnimationParams::new(fps, frames, duration); let animation = export::AnimationParams::new(fps, frames, duration);
export::export_gif(&executor, wgpu_executor_ref, output, scale, (width, height), animation).await?; export::export_gif(&executor, wgpu_executor_ref.clone(), output, scale, (width, height), animation, &completion_receiver)?;
} else { } else {
export::export_document(&executor, wgpu_executor_ref, output, file_type, scale, (width, height), transparent).await?; export::export_document(&executor, wgpu_executor_ref.clone(), output, file_type, scale, (width, height), transparent, &completion_receiver)?;
} }
} }
_ => unreachable!("All other commands should be handled before this match statement is run"), _ => unreachable!("All other commands should be handled before this match statement is run"),
@@ -282,10 +314,11 @@ fn compile_graph(network: NodeNetwork, editor_api: Arc<PlatformEditorApi>, gdd:
} }
let compiler = Compiler {}; let compiler = Compiler {};
compiler.compile_single(network).map_err(|x| x.into()) compiler.compile_single(network, &interpreted_executor::node_registry::NODE_REGISTRY).map_err(|x| x.into())
} }
fn create_executor(proto_network: ProtoNetwork) -> Result<DynamicExecutor, Box<dyn Error>> { fn create_executor(proto_network: ProtoNetwork, runtime: Arc<DynGraphRuntime>) -> Result<DynamicExecutor, Box<dyn Error>> {
let executor = block_on(DynamicExecutor::new(proto_network)).map_err(|errors| errors.iter().map(|e| format!("{e:?}")).reduce(|acc, e| format!("{acc}\n{e}")).unwrap_or_default())?; let mut executor = DynamicExecutor::new(proto_network).map_err(|errors| errors.iter().map(|e| format!("{e:?}")).reduce(|acc, e| format!("{acc}\n{e}")).unwrap_or_default())?;
executor.set_runtime(runtime);
Ok(executor) Ok(executor)
} }
@@ -15,6 +15,7 @@ wasm = ["graphene-std/wasm"]
graphene-std = { workspace = true } graphene-std = { workspace = true }
graph-craft = { workspace = true } graph-craft = { workspace = true }
graphene-core = { workspace = true } graphene-core = { workspace = true }
graphic-types = { workspace = true }
wgpu-executor = { workspace = true } wgpu-executor = { workspace = true }
core-types = { workspace = true } core-types = { workspace = true }
dyn-any = { workspace = true } dyn-any = { workspace = true }
@@ -1,6 +1,5 @@
use criterion::BenchmarkGroup; use criterion::BenchmarkGroup;
use criterion::measurement::Measurement; use criterion::measurement::Measurement;
use futures::executor::block_on;
use graph_craft::proto::ProtoNetwork; use graph_craft::proto::ProtoNetwork;
use graph_craft::util::{DEMO_ART, compile, load_from_name}; use graph_craft::util::{DEMO_ART, compile, load_from_name};
use graphene_std::application_io::EditorApi; use graphene_std::application_io::EditorApi;
@@ -13,11 +12,13 @@ pub fn setup_network(name: &str) -> (DynamicExecutor, ProtoNetwork) {
let mut network = wrap_network_in_scope(network, editor_api); let mut network = wrap_network_in_scope(network, editor_api);
let preprocessor = preprocessor::Preprocessor::new(); let preprocessor = preprocessor::Preprocessor::new();
preprocessor.preprocess(&mut network, &|_| None).unwrap(); preprocessor.preprocess(&mut network, &|_| None).unwrap();
let proto_network = compile(network); let proto_network = compile(network, &interpreted_executor::node_registry::NODE_REGISTRY);
let executor = block_on(DynamicExecutor::new(proto_network.clone())).unwrap(); let executor = DynamicExecutor::new(proto_network.clone()).unwrap();
(executor, proto_network) (executor, proto_network)
} }
// Some benches in this module's include set drive the demos themselves.
#[allow(dead_code)]
pub fn bench_for_each_demo<M: Measurement, F>(group: &mut BenchmarkGroup<M>, f: F) pub fn bench_for_each_demo<M: Measurement, F>(group: &mut BenchmarkGroup<M>, f: F)
where where
F: Fn(&str, &mut BenchmarkGroup<M>), F: Fn(&str, &mut BenchmarkGroup<M>),
@@ -2,17 +2,15 @@ mod benchmark_util;
use benchmark_util::{bench_for_each_demo, setup_network}; use benchmark_util::{bench_for_each_demo, setup_network};
use criterion::{Criterion, criterion_group, criterion_main}; use criterion::{Criterion, criterion_group, criterion_main};
use graph_craft::graphene_compiler::Executor;
use graphene_std::application_io::RenderConfig; use graphene_std::application_io::RenderConfig;
fn subsequent_evaluations(c: &mut Criterion) { fn subsequent_evaluations(c: &mut Criterion) {
let mut group = c.benchmark_group("Subsequent Evaluations"); let mut group = c.benchmark_group("Subsequent Evaluations");
let context = RenderConfig::default().into_context(); let context = RenderConfig::default();
bench_for_each_demo(&mut group, |name, g| { bench_for_each_demo(&mut group, |name, g| {
let (executor, _) = setup_network(name); let (executor, _) = setup_network(name);
let context = context.clone(); g.bench_function(name, |b| b.iter(|| Executor::execute(&&executor, std::hint::black_box(context)).unwrap()));
g.bench_function(name, |b| {
b.iter(|| futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), std::hint::black_box(context.clone()))).unwrap())
});
}); });
group.finish(); group.finish();
} }
@@ -1,6 +1,7 @@
mod benchmark_util; mod benchmark_util;
use benchmark_util::setup_network; use benchmark_util::setup_network;
use graph_craft::graphene_compiler::Executor;
use graphene_std::application_io::RenderConfig; use graphene_std::application_io::RenderConfig;
use gungraun::prelude::*; use gungraun::prelude::*;
use interpreted_executor::dynamic_executor::DynamicExecutor; use interpreted_executor::dynamic_executor::DynamicExecutor;
@@ -10,17 +11,17 @@ fn setup_run_cached(name: &str) -> DynamicExecutor {
let (executor, _) = setup_network(name); let (executor, _) = setup_network(name);
// Warm up the cache by running once // Warm up the cache by running once
let context = RenderConfig::default().into_context(); let context = RenderConfig::default();
let _ = futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), context)); let _ = Executor::execute(&&executor, context);
executor executor
} }
#[library_benchmark] #[library_benchmark]
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_run_cached)] #[benches::with_setup(args = ["changing-seasons", "isometric-fountain", "painted-dreams", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_run_cached)]
pub fn run_cached(executor: DynamicExecutor) -> DynamicExecutor { pub fn run_cached(executor: DynamicExecutor) -> DynamicExecutor {
let context = RenderConfig::default().into_context(); let context = RenderConfig::default();
black_box(futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), black_box(context))).unwrap()); black_box(Executor::execute(&&executor, black_box(context)).unwrap());
// Return the executor so its teardown happens outside the measured section // Return the executor so its teardown happens outside the measured section
executor executor
@@ -8,15 +8,12 @@ use interpreted_executor::dynamic_executor::DynamicExecutor;
fn update_executor<M: Measurement>(name: &str, c: &mut BenchmarkGroup<M>) { fn update_executor<M: Measurement>(name: &str, c: &mut BenchmarkGroup<M>) {
let network = load_from_name(name); let network = load_from_name(name);
let proto_network = compile(network); let proto_network = compile(network, &interpreted_executor::node_registry::NODE_REGISTRY);
let empty = ProtoNetwork::default();
let executor = futures::executor::block_on(DynamicExecutor::new(empty)).unwrap();
c.bench_function(name, |b| { c.bench_function(name, |b| {
b.iter_batched( b.iter_batched(
|| (executor.clone(), proto_network.clone()), || (DynamicExecutor::new(ProtoNetwork::default()).unwrap(), proto_network.clone()),
|(mut executor, network)| futures::executor::block_on(executor.update(std::hint::black_box(network))), |(mut executor, network)| executor.update(std::hint::black_box(network)),
criterion::BatchSize::SmallInput, criterion::BatchSize::SmallInput,
) )
}); });
@@ -31,12 +28,12 @@ fn update_executor_demo(c: &mut Criterion) {
fn run_once<M: Measurement>(name: &str, c: &mut BenchmarkGroup<M>) { fn run_once<M: Measurement>(name: &str, c: &mut BenchmarkGroup<M>) {
let network = load_from_name(name); let network = load_from_name(name);
let proto_network = compile(network); let proto_network = compile(network, &interpreted_executor::node_registry::NODE_REGISTRY);
let executor = futures::executor::block_on(DynamicExecutor::new(proto_network)).unwrap(); let executor = DynamicExecutor::new(proto_network).unwrap();
let footprint = Footprint::default(); let footprint = Footprint::default();
c.bench_function(name, |b| b.iter(|| futures::executor::block_on((&executor).execute(footprint)))); c.bench_function(name, |b| b.iter(|| (&executor).execute(footprint)));
} }
fn run_once_demo(c: &mut Criterion) { fn run_once_demo(c: &mut Criterion) {
let mut g = c.benchmark_group("Run Once no render"); let mut g = c.benchmark_group("Run Once no render");
@@ -2,18 +2,20 @@ mod benchmark_util;
use benchmark_util::{bench_for_each_demo, setup_network}; use benchmark_util::{bench_for_each_demo, setup_network};
use criterion::{Criterion, criterion_group, criterion_main}; use criterion::{Criterion, criterion_group, criterion_main};
use graph_craft::graphene_compiler::Executor;
use graphene_std::application_io::RenderConfig; use graphene_std::application_io::RenderConfig;
use interpreted_executor::dynamic_executor::DynamicExecutor;
fn run_once(c: &mut Criterion) { fn run_once(c: &mut Criterion) {
let mut group = c.benchmark_group("Run Once"); let mut group = c.benchmark_group("Run Once");
let context = RenderConfig::default().into_context(); let context = RenderConfig::default();
bench_for_each_demo(&mut group, |name, g| { bench_for_each_demo(&mut group, |name, g| {
let context = context.clone(); let (_, network) = setup_network(name);
g.bench_function(name, |b| { g.bench_function(name, |b| {
b.iter_batched( b.iter_batched_ref(
|| setup_network(name), || DynamicExecutor::new(network.clone()).unwrap(),
|(executor, _)| futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), std::hint::black_box(context.clone()))).unwrap(), |executor| Executor::execute(&&*executor, std::hint::black_box(context)).unwrap(),
criterion::BatchSize::SmallInput, criterion::BatchSize::LargeInput,
) )
}); });
}); });
@@ -1,6 +1,7 @@
mod benchmark_util; mod benchmark_util;
use benchmark_util::setup_network; use benchmark_util::setup_network;
use graph_craft::graphene_compiler::Executor;
use graphene_std::application_io; use graphene_std::application_io;
use gungraun::prelude::*; use gungraun::prelude::*;
use interpreted_executor::dynamic_executor::DynamicExecutor; use interpreted_executor::dynamic_executor::DynamicExecutor;
@@ -12,13 +13,13 @@ fn setup_run_once(name: &str) -> DynamicExecutor {
} }
#[library_benchmark] #[library_benchmark]
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_run_once)] #[benches::with_setup(args = ["changing-seasons", "isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_run_once)]
pub fn run_once(executor: DynamicExecutor) -> DynamicExecutor { pub fn run_once(executor: DynamicExecutor) -> (DynamicExecutor, core_types::gpoll::GPoll<graph_craft::document::value::TaggedValue>) {
let context = application_io::RenderConfig::default().into_context(); let context = application_io::RenderConfig::default();
black_box(futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), black_box(context))).unwrap()); let result = black_box(Executor::execute(&&executor, black_box(context)).unwrap());
// Return the executor so its teardown happens outside the measured section // Return the executor and result so their teardown happens outside the measured section
executor (executor, result)
} }
library_benchmark_group!(name = run_once_group; benchmarks = run_once); library_benchmark_group!(name = run_once_group; benchmarks = run_once);
@@ -9,14 +9,14 @@ fn update_executor(c: &mut Criterion) {
let mut group = c.benchmark_group("Update Executor"); let mut group = c.benchmark_group("Update Executor");
bench_for_each_demo(&mut group, |name, g| { bench_for_each_demo(&mut group, |name, g| {
g.bench_function(name, |b| { g.bench_function(name, |b| {
b.iter_batched( b.iter_batched_ref(
|| { || {
let (_, proto_network) = setup_network(name); let (_, proto_network) = setup_network(name);
let empty = ProtoNetwork::default(); let empty = ProtoNetwork::default();
let executor = futures::executor::block_on(DynamicExecutor::new(empty)).unwrap(); let executor = DynamicExecutor::new(empty).unwrap();
(executor, proto_network) (executor, proto_network)
}, },
|(mut executor, network)| futures::executor::block_on(executor.update(std::hint::black_box(network))), |(executor, network)| executor.update(std::hint::black_box(std::mem::take(network))),
criterion::BatchSize::SmallInput, criterion::BatchSize::SmallInput,
) )
}); });
@@ -9,7 +9,7 @@ use std::hint::black_box;
fn setup_update_executor(name: &str) -> (DynamicExecutor, ProtoNetwork) { fn setup_update_executor(name: &str) -> (DynamicExecutor, ProtoNetwork) {
let (_, proto_network) = setup_network(name); let (_, proto_network) = setup_network(name);
let empty = ProtoNetwork::default(); let empty = ProtoNetwork::default();
let executor = futures::executor::block_on(DynamicExecutor::new(empty)).unwrap(); let executor = DynamicExecutor::new(empty).unwrap();
(executor, proto_network) (executor, proto_network)
} }
@@ -17,7 +17,7 @@ fn setup_update_executor(name: &str) -> (DynamicExecutor, ProtoNetwork) {
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_update_executor)] #[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_update_executor)]
pub fn update_executor(setup: (DynamicExecutor, ProtoNetwork)) -> DynamicExecutor { pub fn update_executor(setup: (DynamicExecutor, ProtoNetwork)) -> DynamicExecutor {
let (mut executor, network) = setup; let (mut executor, network) = setup;
let _ = black_box(futures::executor::block_on(executor.update(black_box(network)))); let _ = black_box(executor.update(black_box(network)));
// Return the executor so its teardown happens outside the measured section // Return the executor so its teardown happens outside the measured section
executor executor
@@ -1,17 +1,60 @@
use crate::node_registry; use crate::node_registry;
use dyn_any::StaticType; use core_types::arena::Arena;
use core_types::context::{ContextImpl, DynSlot, EvalScope, ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime, VarArg, VarArgLink, VarArgSlots};
use core_types::gpoll::GPoll;
use core_types::registry::SourceHandle;
use core_types::runtime::{DynGraphRuntime, DynSpawner, GraphRuntime, NoopSpawner};
use graph_craft::Type; use graph_craft::Type;
use graph_craft::document::NodeId; use graph_craft::document::NodeId;
use graph_craft::document::value::{TaggedValue, UpcastAsRefNode, UpcastNode}; use graph_craft::document::value::TaggedValue;
use graph_craft::graphene_compiler::Executor; use graph_craft::graphene_compiler::Executor;
use graph_craft::proto::{ConstructionArgs, GraphError, LocalFuture, NodeContainer, ProtoNetwork, ProtoNode, SharedNodeContainer, TypeErasedBox, TypingContext}; use graph_craft::proto::{ConstructionArgs, GraphError, ProtoNetwork, ProtoNode, TypingContext};
use graph_craft::proto::{GraphErrorType, GraphErrors}; use graph_craft::proto::{GraphErrorType, GraphErrors};
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use std::error::Error; use std::error::Error;
use std::sync::Arc; use std::sync::{Arc, Mutex, PoisonError};
const ARENA_CAPACITY: usize = 1 << 27;
const PERSISTENT_CAPACITY: usize = 1 << 26;
/// The heap the persistent region's parked payloads may own before a flush.
/// Occupancy cannot stand in for it: a park costs one pointer in the region
/// and owns its content outside it, so the two diverge by orders of magnitude.
#[cfg(not(target_family = "wasm"))]
const PERSISTENT_HEAP_BUDGET: usize = 1 << 29;
#[cfg(target_family = "wasm")]
const PERSISTENT_HEAP_BUDGET: usize = 1 << 28;
/// The share of a budget that triggers a flush at the next boundary, chosen so
/// the region is emptied before a promote is refused mid-evaluation.
fn over_budget(used: usize, budget: usize) -> bool {
used >= budget / 8 * 7
}
/// The deep element glue is filled by runtime registration: ctors at load
/// natively, host-invoked exports on wasm. A lifetime-carrying element whose
/// glue never registered takes the shallow clone-out path, which brands its
/// arena borrows `'static` for a memo to hold across a reset, so a missed
/// registration is caught here rather than at the first capture.
fn assert_deep_element_glue() {
for (name, registered) in [
("graphic", core_types::record::has_deep_element_glue(std::any::TypeId::of::<graphic_types::Graphic<'static>>())),
("artboard", core_types::record::has_deep_element_glue(std::any::TypeId::of::<graphic_types::Artboard<'static>>())),
] {
assert!(registered, "deep element glue for `{name}` is missing; run `__node_registry_deep_element_{name}` first");
}
}
fn new_arena(capacity: usize) -> Arena {
Arena::new(capacity).unwrap_or_else(|| {
log::error!("arena generations exhausted; continuing without frame caching");
Arena::parked()
})
}
/// An executor of a node graph that does not require an online compilation server, and instead uses `Box<dyn ...>`. /// An executor of a node graph that does not require an online compilation server, and instead uses `Box<dyn ...>`.
#[derive(Clone)]
pub struct DynamicExecutor { pub struct DynamicExecutor {
output: NodeId, output: NodeId,
/// Stores all of the dynamic node structs. /// Stores all of the dynamic node structs.
@@ -20,15 +63,34 @@ pub struct DynamicExecutor {
typing_context: TypingContext, typing_context: TypingContext,
// This allows us to keep the nodes around for one more frame which is used for introspection // This allows us to keep the nodes around for one more frame which is used for introspection
orphaned_nodes: HashSet<NodeId>, orphaned_nodes: HashSet<NodeId>,
arena: Mutex<Arena>,
/// The region memo levels are promoted into: reset only between
/// evaluations, and only once a promote has been refused.
persistent: Mutex<Arena>,
/// The record frame space, grow-only across evaluations and lent to the
/// root by `&mut`.
frames: Mutex<core_types::record::FrameArena>,
runtime: Arc<DynGraphRuntime>,
live_sources: Vec<core_types::SourceId>,
}
fn noop_runtime() -> Arc<DynGraphRuntime> {
Arc::new(GraphRuntime::new(Box::new(NoopSpawner) as Box<DynSpawner>))
} }
impl Default for DynamicExecutor { impl Default for DynamicExecutor {
fn default() -> Self { fn default() -> Self {
assert_deep_element_glue();
Self { Self {
output: Default::default(), output: Default::default(),
tree: Default::default(), tree: Default::default(),
typing_context: TypingContext::new(&node_registry::NODE_REGISTRY), typing_context: TypingContext::new(&node_registry::NODE_REGISTRY),
orphaned_nodes: HashSet::new(), orphaned_nodes: HashSet::new(),
arena: Mutex::new(new_arena(ARENA_CAPACITY)),
persistent: Mutex::new(new_arena(PERSISTENT_CAPACITY)),
frames: Mutex::new(core_types::record::FrameArena::new()),
runtime: noop_runtime(),
live_sources: Vec::new(),
} }
} }
} }
@@ -48,25 +110,43 @@ pub struct ResolvedDocumentNodeTypesDelta {
} }
impl DynamicExecutor { impl DynamicExecutor {
pub async fn new(proto_network: ProtoNetwork) -> Result<Self, GraphErrors> { pub fn new(mut proto_network: ProtoNetwork) -> Result<Self, GraphErrors> {
assert_deep_element_glue();
let mut typing_context = TypingContext::new(&node_registry::NODE_REGISTRY); let mut typing_context = TypingContext::new(&node_registry::NODE_REGISTRY);
typing_context.update(&proto_network)?; typing_context.update(&mut proto_network)?;
let output = proto_network.output; let output = proto_network.output;
let tree = BorrowTree::new(proto_network, &typing_context).await?; let sources = proto_network.source_ids();
let tree = BorrowTree::new(proto_network, &typing_context)?;
let runtime = noop_runtime();
runtime.retain_sources(&sources);
Ok(Self { Ok(Self {
tree, tree,
output, output,
typing_context, typing_context,
orphaned_nodes: HashSet::new(), orphaned_nodes: HashSet::new(),
arena: Mutex::new(new_arena(ARENA_CAPACITY)),
persistent: Mutex::new(new_arena(PERSISTENT_CAPACITY)),
frames: Mutex::new(core_types::record::FrameArena::new()),
runtime,
live_sources: sources,
}) })
} }
pub fn set_runtime(&mut self, runtime: Arc<DynGraphRuntime>) {
runtime.retain_sources(&self.live_sources);
self.runtime = runtime;
}
pub fn take_dirty(&self) -> bool {
self.runtime.take_dirty()
}
/// Updates the existing [`BorrowTree`] to reflect the new [`ProtoNetwork`], reusing nodes where possible. /// Updates the existing [`BorrowTree`] to reflect the new [`ProtoNetwork`], reusing nodes where possible.
#[cfg_attr(debug_assertions, inline(never))] #[cfg_attr(debug_assertions, inline(never))]
pub async fn update(&mut self, proto_network: ProtoNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, GraphErrors)> { pub fn update(&mut self, mut proto_network: ProtoNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
self.output = proto_network.output; self.output = proto_network.output;
self.typing_context.update(&proto_network).map_err(|e| { self.typing_context.update(&mut proto_network).map_err(|e| {
// If there is an error then get types that have been resolved before the error // If there is an error then get types that have been resolved before the error
let add = proto_network let add = proto_network
.nodes .nodes
@@ -87,11 +167,10 @@ impl DynamicExecutor {
(ResolvedDocumentNodeTypesDelta { add, remove: Vec::new() }, e) (ResolvedDocumentNodeTypesDelta { add, remove: Vec::new() }, e)
})?; })?;
let (add, orphaned) = self let sources = proto_network.source_ids();
.tree let (add, orphaned) = self.tree.update(proto_network, &self.typing_context).map_err(|e| (ResolvedDocumentNodeTypesDelta::default(), e))?;
.update(proto_network, &self.typing_context) self.runtime.retain_sources(&sources);
.await self.live_sources = sources;
.map_err(|e| (ResolvedDocumentNodeTypesDelta::default(), e))?;
let old_to_remove = core::mem::replace(&mut self.orphaned_nodes, orphaned); let old_to_remove = core::mem::replace(&mut self.orphaned_nodes, orphaned);
let mut remove = Vec::with_capacity(old_to_remove.len() - self.orphaned_nodes.len().min(old_to_remove.len())); let mut remove = Vec::with_capacity(old_to_remove.len() - self.orphaned_nodes.len().min(old_to_remove.len()));
for node_id in old_to_remove { for node_id in old_to_remove {
@@ -107,9 +186,71 @@ impl DynamicExecutor {
Ok(ResolvedDocumentNodeTypesDelta { add, remove }) Ok(ResolvedDocumentNodeTypesDelta { add, remove })
} }
/// Calls the `Node::serialize` for that specific node, returning for example the cached value for a monitor node. The node path must match the document node path. /// Calls the `Node::serialize` for that specific node. A monitor serializes
/// its stored context snapshot, and this entry recreates the monitored
/// value from it as the legacy value the editor's downcasts expect: a
/// rank-0 input yields its element and a leveled input its legacy list.
pub fn introspect(&self, node_path: &[NodeId]) -> Result<Arc<dyn std::any::Any + Send + Sync + 'static>, IntrospectError> { pub fn introspect(&self, node_path: &[NodeId]) -> Result<Arc<dyn std::any::Any + Send + Sync + 'static>, IntrospectError> {
self.tree.introspect(node_path) let result = self.tree.introspect(node_path)?;
if result.downcast_ref::<core_types::context::CtxSnapshot>().is_some() {
return self.introspect_with(node_path, graphic_types::boundary::batch_to_legacy).map(Arc::from);
}
Ok(result)
}
/// Re-evaluates the monitored input at `node_path` with its stored context
/// snapshot and hands the resulting resident batch to `read`, inside the
/// introspection window. The monitor stores only the context; the value is
/// recreated against current source data, so a read right after an
/// execution serves out of the warm memo entries.
pub fn introspect_with<R>(&self, node_path: &[NodeId], read: impl FnOnce(&core_types::record::Layout, core_types::node::RecordBatch<'_>, &Arena) -> Option<R>) -> Result<R, IntrospectError> {
let serialized = self.tree.introspect(node_path)?;
let Some(snapshot) = serialized.downcast_ref::<core_types::context::CtxSnapshot>() else {
return Err(IntrospectError::NoData);
};
let edge = self
.tree
.get_by_path(node_path)
.and_then(SourceHandle::record_source)
.ok_or_else(|| IntrospectError::PathNotFound(node_path.to_vec()))?;
let arena = self.arena.lock().unwrap_or_else(PoisonError::into_inner);
let persistent = self.persistent.lock().unwrap_or_else(PoisonError::into_inner);
let mut buffer = self.frames.lock().unwrap_or_else(PoisonError::into_inner);
buffer.reserve(self.tree.stack_need());
let frames = buffer.frames();
let generations = self.runtime.snapshot();
let scope = EvalScope::new(snapshot.try_real_time(), snapshot.try_animation_time(), snapshot.try_pointer_position(), &generations, &arena).with_persistent(&persistent);
let Some(ctx) = snapshot.rehydrate(&scope) else {
return Err(IntrospectError::NoData);
};
let layout = core_types::node::Node::<ContextImpl>::layout(&edge);
// The batch borrows the frames the read closure is handed, so the read
// cannot outlive the scope that owns them.
let frames = frames.scope();
let result = if layout.depth > 0 {
match core_types::record::materialize_level(&edge, &ctx, &arena, &frames) {
core_types::record::LevelStatus::Batch(batch, _) => read(layout, batch, &arena),
_ => None,
}
} else {
match core_types::record::serve_input(&edge, &ctx, &frames) {
GPoll::Final(value) | GPoll::Partial(value) => {
let rec = layout.rec(&value);
// SAFETY: the serve produced one live record of the input's layout.
let batch = unsafe { core_types::node::RecordBatch::new(rec.ptr(), 1, layout) };
read(layout, batch, &arena)
}
GPoll::Fallback(boxed) => {
let (value, _) = *boxed;
let rec = layout.rec(&value);
// SAFETY: as for the final arm.
let batch = unsafe { core_types::node::RecordBatch::new(rec.ptr(), 1, layout) };
read(layout, batch, &arena)
}
_ => None,
}
};
result.ok_or(IntrospectError::NoData)
} }
pub fn input_type(&self) -> Option<Type> { pub fn input_type(&self) -> Option<Type> {
@@ -135,27 +276,75 @@ impl DynamicExecutor {
} }
} }
impl<I> Executor<I, TaggedValue> for &DynamicExecutor impl<I> Executor<I, GPoll<TaggedValue>> for &DynamicExecutor
where where
I: StaticType + 'static + Send + Sync, I: VarArg + Send + Sync + std::panic::RefUnwindSafe,
{ {
fn execute(&self, input: I) -> LocalFuture<'_, Result<TaggedValue, Box<dyn Error>>> { fn execute(&self, input: I) -> Result<GPoll<TaggedValue>, Box<dyn Error>> {
Box::pin(async move { let Some(handle) = self.tree.get(self.output) else {
use futures::FutureExt; return Err("Output node not found in executor".into());
};
let result = self.tree.eval_tagged_value(self.output, input); let mut arena = self.arena.lock().unwrap_or_else(PoisonError::into_inner);
let wrapped_result = std::panic::AssertUnwindSafe(result).catch_unwind().await; let mut persistent = self.persistent.lock().unwrap_or_else(PoisonError::into_inner);
// The region is flushed whole between evaluations and the memos
match wrapped_result { // re-promote: on a refusal, which leaves no room for the next promote,
Ok(result) => result.map_err(|e| e.into()), // and ahead of one where either the region itself or the heap its
Err(e) => { // parked payloads own is close to full.
Box::leak(e); if persistent.exhausted() || over_budget(persistent.occupancy(), persistent.capacity()) || over_budget(persistent.retained_heap(), PERSISTENT_HEAP_BUDGET) {
Err("Node graph execution panicked".into()) persistent.reset();
} }
let mut buffer = self.frames.lock().unwrap_or_else(PoisonError::into_inner);
buffer.reserve(self.tree.stack_need());
let result = eval_root(&mut arena, &persistent, &mut buffer, &self.runtime, &input, |ctx, frames| {
match TaggedValue::from_edge(handle.duplicate(), ctx, frames) {
Ok(poll) => poll.map(Ok),
Err(error) => GPoll::Final(Err(error)),
} }
}) });
match result {
GPoll::Final(value) => Ok(GPoll::Final(value?)),
GPoll::Partial(value) => Ok(GPoll::Partial(value?)),
GPoll::Fallback(boxed) => {
let (value, error) = *boxed;
Ok(GPoll::Fallback(Box::new((value?, error))))
}
GPoll::Pending => Ok(GPoll::Pending),
GPoll::Error(error) => Ok(GPoll::Error(error)),
}
} }
} }
/// One evaluation over the arena and the frame buffer, which the caller sized
/// to the graph's frame need: both are the evaluation's lifetime, so a record
/// served anywhere in the cone lives exactly as long as the arena it may
/// reference. The persistent region is borrowed shared for the same span, so
/// no flush can land while a value promoted into it is readable.
pub fn eval_root<S, T>(
arena: &mut Arena,
persistent: &Arena,
buffer: &mut core_types::record::FrameArena,
runtime: &GraphRuntime<S>,
call_argument: DynSlot,
eval: impl for<'e> FnOnce(&ContextImpl<'e>, &core_types::record::Frames<'e>) -> GPoll<T>,
) -> GPoll<T> {
arena.reset();
let generations = runtime.snapshot();
let scope = EvalScope::new(None, None, None, &generations, arena).with_persistent(persistent);
let root = ContextImpl::root(&scope);
let link = VarArgLink {
args: VarArgSlots::Single(call_argument),
outer: None,
};
let ctx = root.with_varargs(&link);
let frames = buffer.frames();
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| eval(&ctx, &frames))) {
Ok(result) => result,
Err(_) => {
arena.reset();
GPoll::panicked()
}
}
}
pub struct InputMapping {} pub struct InputMapping {}
#[derive(Debug, Clone, PartialEq, Eq, Hash)] #[derive(Debug, Clone, PartialEq, Eq, Hash)]
@@ -188,85 +377,76 @@ impl std::fmt::Display for IntrospectError {
/// ///
/// # Fields /// # Fields
/// ///
/// * `nodes`: A [`HashMap`] of [`NodeId`]s to tuples of [`SharedNodeContainer`] and [`Path`]. /// * `nodes`: A [`HashMap`] of [`NodeId`]s to tuples of [`SourceHandle`] and [`Path`].
/// This stores the actual node instances and their associated paths. /// This stores the actual node instances and their associated paths.
/// ///
/// * `source_map`: A [`HashMap`] from [`Path`] to tuples of [`NodeId`] and [`NodeTypes`]. /// * `source_map`: A [`HashMap`] from [`Path`] to tuples of [`NodeId`] and [`NodeTypes`].
/// This maps document paths to node IDs and their associated type information. /// This maps document paths to node IDs and their associated type information.
/// ///
/// A store of the dynamically typed nodes and also the source map. /// A store of the dynamically typed nodes and also the source map.
#[derive(Default, Clone)] #[derive(Default)]
pub struct BorrowTree { pub struct BorrowTree {
/// A hashmap of node IDs and dynamically typed nodes. /// A hashmap of node IDs and dynamically typed nodes.
nodes: HashMap<NodeId, (SharedNodeContainer, Path)>, nodes: HashMap<NodeId, (SourceHandle, Path)>,
/// A hashmap from the document path to the proto node ID. /// A hashmap from the document path to the proto node ID.
source_map: HashMap<Path, (NodeId, NodeTypes)>, source_map: HashMap<Path, (NodeId, NodeTypes)>,
/// The record-stack reserve, folded from the graph at construction.
stack_need: usize,
} }
impl BorrowTree { impl BorrowTree {
pub async fn new(proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<BorrowTree, GraphErrors> { pub fn new(proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<BorrowTree, GraphErrors> {
let mut nodes = BorrowTree::default(); let mut nodes = BorrowTree::default();
let stack_need = proto_network.stack_need;
for (id, node) in proto_network.nodes { for (id, node) in proto_network.nodes {
nodes.push_node(id, node, typing_context).await? nodes.push_node(id, node, typing_context)?
} }
nodes.stack_need = stack_need;
Ok(nodes) Ok(nodes)
} }
/// Pushes new nodes into the tree and return orphaned nodes /// Pushes new nodes into the tree and return orphaned nodes
pub async fn update(&mut self, proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<(Vec<Path>, HashSet<NodeId>), GraphErrors> { pub fn update(&mut self, proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<(Vec<Path>, HashSet<NodeId>), GraphErrors> {
let stack_need = proto_network.stack_need;
let mut old_nodes: HashSet<_> = self.nodes.keys().copied().collect(); let mut old_nodes: HashSet<_> = self.nodes.keys().copied().collect();
let mut new_nodes: Vec<_> = Vec::new(); let mut new_nodes: Vec<_> = Vec::new();
// TODO: Problem: When a passthrough node is connected directly to an export the first input to the passthrough node is not added to the proto network, while the second input is. This means the primary input does not have a type. // TODO: Problem: When a passthrough node is connected directly to an export the first input to the passthrough node is not added to the proto network, while the second input is. This means the primary input does not have a type.
for (id, node) in proto_network.nodes { for (id, node) in proto_network.nodes {
if !self.nodes.contains_key(&id) { if !self.nodes.contains_key(&id) {
new_nodes.push(node.original_location.path.clone().unwrap_or_default().into()); new_nodes.push(node.original_location.path.clone().unwrap_or_default().into());
self.push_node(id, node, typing_context).await?; self.push_node(id, node, typing_context)?;
} else if self.update_source_map(id, typing_context, &node) { } else if self.update_source_map(id, typing_context, &node) {
new_nodes.push(node.original_location.path.clone().unwrap_or_default().into()); new_nodes.push(node.original_location.path.clone().unwrap_or_default().into());
} }
old_nodes.remove(&id); old_nodes.remove(&id);
} }
self.stack_need = stack_need;
Ok((new_nodes, old_nodes)) Ok((new_nodes, old_nodes))
} }
fn node_deps(&self, nodes: &[NodeId]) -> Vec<SharedNodeContainer> { fn node_deps(&self, nodes: &[NodeId]) -> Vec<SourceHandle> {
nodes.iter().map(|node| self.nodes.get(node).unwrap().0.clone()).collect() nodes.iter().map(|node| self.nodes.get(node).unwrap().0.duplicate()).collect()
} }
fn store_node(&mut self, node: SharedNodeContainer, id: NodeId, path: Path) { fn store_node(&mut self, node: SourceHandle, id: NodeId, path: Path) {
self.nodes.insert(id, (node, path)); self.nodes.insert(id, (node, path));
} }
/// Calls the `Node::serialize` for that specific node, returning for example the cached value for a monitor node. The node path must match the document node path. /// Calls the `Node::serialize` for that specific node, returning for example the captured context snapshot for a monitor node. The node path must match the document node path.
pub fn introspect(&self, node_path: &[NodeId]) -> Result<Arc<dyn std::any::Any + Send + Sync + 'static>, IntrospectError> { pub fn introspect(&self, node_path: &[NodeId]) -> Result<Arc<dyn std::any::Any + Send + Sync + 'static>, IntrospectError> {
let (id, _) = self.source_map.get(node_path).ok_or_else(|| IntrospectError::PathNotFound(node_path.to_vec()))?; let (id, _) = self.source_map.get(node_path).ok_or_else(|| IntrospectError::PathNotFound(node_path.to_vec()))?;
let (node, _path) = self.nodes.get(id).ok_or(IntrospectError::ProtoNodeNotFound(*id))?; let (node, _path) = self.nodes.get(id).ok_or(IntrospectError::ProtoNodeNotFound(*id))?;
node.serialize().ok_or(IntrospectError::NoData) node.serialize().ok_or(IntrospectError::NoData)
} }
pub fn get(&self, id: NodeId) -> Option<SharedNodeContainer> { pub fn get(&self, id: NodeId) -> Option<SourceHandle> {
self.nodes.get(&id).map(|(node, _)| node.clone()) self.nodes.get(&id).map(|(node, _)| node.duplicate())
} }
/// Evaluate the output node of the [`BorrowTree`]. /// The edge handle for the node at a document path.
pub async fn eval<'i, I, O>(&'i self, id: NodeId, input: I) -> Option<O> pub fn get_by_path(&self, node_path: &[NodeId]) -> Option<SourceHandle> {
where let (id, _) = self.source_map.get(node_path)?;
I: StaticType + 'i + Send + Sync, self.get(*id)
O: StaticType + 'i,
{
let (node, _path) = self.nodes.get(&id).cloned()?;
let output = node.eval(Box::new(input));
dyn_any::downcast::<O>(output.await).ok().map(|o| *o)
}
/// Evaluate the output node of the [`BorrowTree`] and cast it to a tagged value.
/// This ensures that no borrowed data can escape the node graph.
pub async fn eval_tagged_value<I>(&self, id: NodeId, input: I) -> Result<TaggedValue, String>
where
I: StaticType + 'static + Send + Sync,
{
let (node, _path) = self.nodes.get(&id).cloned().ok_or("Output node not found in executor")?;
let output = node.eval(Box::new(input));
TaggedValue::try_from_any(output.await)
} }
/// Removes a node from the [`BorrowTree`] and returns its associated path. /// Removes a node from the [`BorrowTree`] and returns its associated path.
@@ -293,10 +473,10 @@ impl BorrowTree {
/// use interpreted_executor::node_registry; /// use interpreted_executor::node_registry;
/// ///
/// ///
/// async fn example() -> Result<(), GraphErrors> { /// fn example() -> Result<(), GraphErrors> {
/// let (proto_network, node_id, proto_node) = ProtoNetwork::example(); /// let (proto_network, node_id, proto_node) = ProtoNetwork::example();
/// let typing_context = TypingContext::new(&node_registry::NODE_REGISTRY); /// let typing_context = TypingContext::default();
/// let mut borrow_tree = BorrowTree::new(proto_network, &typing_context).await?; /// let mut borrow_tree = BorrowTree::new(proto_network, &typing_context)?;
/// ///
/// // Assert that the node exists in the BorrowTree /// // Assert that the node exists in the BorrowTree
/// assert!(borrow_tree.get(node_id).is_some(), "Node should exist before removal"); /// assert!(borrow_tree.get(node_id).is_some(), "Node should exist before removal");
@@ -393,42 +573,26 @@ impl BorrowTree {
/// - `Nodes`: Constructs a node using other nodes as dependencies. /// - `Nodes`: Constructs a node using other nodes as dependencies.
/// - Uses the constructor function from the `typing_context` for `Nodes` construction arguments. /// - Uses the constructor function from the `typing_context` for `Nodes` construction arguments.
/// - Returns an error if no constructor is found for the given node ID. /// - Returns an error if no constructor is found for the given node ID.
async fn push_node(&mut self, id: NodeId, proto_node: ProtoNode, typing_context: &TypingContext) -> Result<(), GraphErrors> { fn push_node(&mut self, id: NodeId, proto_node: ProtoNode, typing_context: &TypingContext) -> Result<(), GraphErrors> {
self.update_source_map(id, typing_context, &proto_node); self.update_source_map(id, typing_context, &proto_node);
let path = proto_node.original_location.path.clone().unwrap_or_default(); let path = proto_node.original_location.path.clone().unwrap_or_default();
match &proto_node.construction_args { match &proto_node.construction_args {
ConstructionArgs::Value(value) => { ConstructionArgs::Value(value) => {
let node = if let TaggedValue::EditorApi(api) = &**value { let node = (**value)
let editor_api = UpcastAsRefNode::new(api.clone()); .clone()
let node = Box::new(editor_api) as TypeErasedBox<'_>; .to_edge()
NodeContainer::new(node) .map_err(|error| vec![GraphError::new(&proto_node, GraphErrorType::ConstructionFailed(error))])?;
} else {
let upcasted = UpcastNode::new(value.to_owned());
let node = Box::new(upcasted) as TypeErasedBox<'_>;
NodeContainer::new(node)
};
self.store_node(node, id, path.into()); self.store_node(node, id, path.into());
} }
ConstructionArgs::Inline(_) => unimplemented!("Inline nodes are not supported yet"), ConstructionArgs::Inline(_) => unimplemented!("Inline nodes are not supported yet"),
ConstructionArgs::Nodes(ids) => { ConstructionArgs::Nodes(ids) => {
let ids = ids.to_vec(); let construction_nodes = self.node_deps(ids);
let mut construction_nodes = self.node_deps(&ids);
// Wrap arguments the typing pass marked for rank promotion with their adapter node
if let Some(promotions) = typing_context.promotions(id) {
for (argument_index, promotion) in promotions {
let adapter_constructor = typing_context
.adapter_constructor(&promotion.adapter_identifier())
.ok_or_else(|| vec![GraphError::new(&proto_node, GraphErrorType::NoConstructor)])?;
let adapter = adapter_constructor(vec![construction_nodes[*argument_index].clone()]).await;
construction_nodes[*argument_index] = NodeContainer::new(adapter);
}
}
let constructor = typing_context.constructor(id).ok_or_else(|| vec![GraphError::new(&proto_node, GraphErrorType::NoConstructor)])?; let constructor = typing_context.constructor(id).ok_or_else(|| vec![GraphError::new(&proto_node, GraphErrorType::NoConstructor)])?;
let node = constructor(construction_nodes).await; let mut node = constructor(construction_nodes).map_err(|error| vec![GraphError::new(&proto_node, GraphErrorType::ConstructionFailed(format!("{error:?}")))])?;
let node = NodeContainer::new(node); if let Some(layout) = proto_node.resolved_layout() {
node.set_layout(layout.clone());
}
self.store_node(node, id, path.into()); self.store_node(node, id, path.into());
} }
}; };
@@ -439,7 +603,496 @@ impl BorrowTree {
pub fn source_map(&self) -> &HashMap<Path, (NodeId, NodeTypes)> { pub fn source_map(&self) -> &HashMap<Path, (NodeId, NodeTypes)> {
&self.source_map &self.source_map
} }
/// The record-stack reserve of an evaluation, folded from the resolved layouts by the layout pass.
pub fn stack_need(&self) -> usize {
self.stack_need
}
} }
#[cfg(test)] #[cfg(test)]
mod test; mod test {
use super::*;
use core_types::arena::ArenaCell;
use core_types::context::{ExtractFootprint, ExtractVarArgs};
use core_types::runtime::{SourceFuture, Spawner};
use graph_craft::document::value::TaggedValue;
struct InertSpawner;
impl Spawner for InertSpawner {
fn spawn(&self, _task: SourceFuture) -> bool {
false
}
}
#[test]
fn the_flush_trigger_fires_on_occupancy_and_on_retained_heap() {
assert!(!over_budget(0, 1 << 10));
assert!(!over_budget(1 << 10 >> 1, 1 << 10), "half full stays");
assert!(over_budget(1 << 10 >> 3 << 3, 1 << 10), "a full region flushes");
assert!(over_budget((1 << 10) / 8 * 7, 1 << 10), "seven eighths is the trigger");
let arena = Arena::new(1024).unwrap();
assert!(!over_budget(arena.retained_heap(), PERSISTENT_HEAP_BUDGET), "an empty region is under every budget");
let owned = vec![0u8; 4096];
let length = owned.len();
arena.alloc_sized(owned, length).unwrap();
assert_eq!(arena.retained_heap(), length);
assert!(over_budget(arena.retained_heap(), 4096), "the heap hint alone can trigger a flush");
assert!(
!over_budget(arena.occupancy(), arena.capacity()),
"occupancy stays low while the retained heap is large, which is why the trigger reads both"
);
}
#[test]
fn eval_root_builds_the_bare_root_with_the_call_argument_as_vararg_0() {
let mut arena = Arena::new(64).unwrap();
let persistent = Arena::new(64).unwrap();
let mut buffer = core_types::record::FrameArena::new();
let runtime = GraphRuntime::new(InertSpawner);
let argument = 21.5f64;
let result = eval_root(&mut arena, &persistent, &mut buffer, &runtime, &argument, |ctx, _frames| {
assert!(ctx.try_footprint().is_none(), "the bare root carries no axes");
GPoll::Final(ctx.vararg(0).ok().and_then(|slot| slot.downcast_ref::<f64>()).copied().unwrap_or(0.))
});
assert_eq!(result, GPoll::Final(21.5));
}
#[test]
fn eval_root_resets_the_arena_at_eval_start() {
let mut arena = Arena::new(64).unwrap();
let persistent = Arena::new(64).unwrap();
let mut buffer = core_types::record::FrameArena::new();
let runtime = GraphRuntime::new(InertSpawner);
let cell = ArenaCell::new();
eval_root(&mut arena, &persistent, &mut buffer, &runtime, &(), |ctx, _frames| {
let (_, weak) = ctx.scope().arena().alloc(5u32).unwrap();
cell.store(weak);
GPoll::Final(())
});
assert!(cell.load(&arena).is_some(), "the introspection window spans until the next eval");
eval_root(&mut arena, &persistent, &mut buffer, &runtime, &(), |ctx, _frames| {
assert!(cell.load(ctx.scope().arena()).is_none(), "the reset at eval start reclaims the previous frame");
GPoll::Final(())
});
}
#[test]
fn a_panicking_eval_reports_the_error_and_resets_the_arena() {
let mut arena = Arena::new(64).unwrap();
let persistent = Arena::new(64).unwrap();
let mut buffer = core_types::record::FrameArena::new();
let runtime = GraphRuntime::new(InertSpawner);
let cell = ArenaCell::new();
let result: GPoll<()> = eval_root(&mut arena, &persistent, &mut buffer, &runtime, &(), |ctx, _frames| {
let (_, weak) = ctx.scope().arena().alloc(5u32).unwrap();
cell.store(weak);
panic!("mid-eval");
});
assert_eq!(result, GPoll::panicked());
assert!(cell.load(&arena).is_none(), "reset-on-panic leaves no stale records");
assert_eq!(eval_root(&mut arena, &persistent, &mut buffer, &runtime, &(), |_, _| GPoll::Final(7u32)), GPoll::Final(7));
}
#[test]
fn push_node_sync() {
let mut tree = BorrowTree::default();
let val_1_protonode = ProtoNode::value(ConstructionArgs::Value(TaggedValue::U32(2u32).into()), vec![]);
let context = TypingContext::default();
tree.push_node(NodeId(0), val_1_protonode, &context).unwrap();
let handle = tree.get(NodeId(0)).unwrap();
let layout = handle.layout().clone();
let edge = handle.duplicate().downcast_record::<u32>().unwrap();
let arena = Arena::new(64).unwrap();
let generations = [];
let scope = EvalScope::new(None, None, None, &generations, &arena);
let ctx = ContextImpl::root(&scope);
let frames = core_types::record::test_frames(layout.frame_bytes());
let GPoll::Final(value) = core_types::record::serve_input(&edge, &ctx, &frames) else {
panic!("expected a final record");
};
assert_eq!(unsafe { core_types::record::read_element::<u32>(layout.rec(&value)) }, 2);
}
fn build_executor(mut network: ProtoNetwork) -> DynamicExecutor {
network.resolve_types(&node_registry::NODE_REGISTRY).unwrap();
network.compute_layouts().unwrap();
DynamicExecutor::new(network).unwrap()
}
fn proto_node(identifier: &'static str, args: Vec<NodeId>) -> ProtoNode {
let mut node = ProtoNode::default();
node.identifier = graph_craft::ProtoNodeIdentifier::new(identifier);
node.call_argument = core_types::concrete!(core_types::context::Context);
node.construction_args = ConstructionArgs::Nodes(args);
node
}
fn string_value(value: &str) -> ProtoNode {
ProtoNode::value(ConstructionArgs::Value(TaggedValue::String(value.to_string()).into()), vec![])
}
/// A record source, a constant name, and a value wired into the write node.
fn write_attribute_network(name: &str, value: TaggedValue) -> ProtoNetwork {
ProtoNetwork {
stack_need: 0,
inputs: vec![],
output: NodeId(3),
nodes: vec![
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(7.).into()), vec![])),
(NodeId(1), string_value(name)),
(NodeId(2), ProtoNode::value(ConstructionArgs::Value(value.into()), vec![])),
(NodeId(3), proto_node("graphic_nodes::graphic::WriteAttributeNode", vec![NodeId(0), NodeId(1), NodeId(2)])),
],
}
}
#[test]
fn a_constant_name_folds_into_the_written_layout() {
let executor = build_executor(write_attribute_network("novel:count", TaggedValue::F64(2.5)));
let arena = Arena::new(1 << 12).unwrap();
let generations = [];
let scope = EvalScope::new(None, None, None, &generations, &arena);
let ctx = ContextImpl::root(&scope);
let handle = executor.tree().get(NodeId(3)).unwrap();
let layout = handle.layout().clone();
let offset = layout.offset_of("novel:count", 0).expect("the folded name names a field of the output layout");
let edge = handle.duplicate().downcast_record::<f64>().unwrap();
let frames = core_types::record::test_frames(executor.tree().stack_need());
let GPoll::Final(value) = core_types::record::serve_input(&edge, &ctx, &frames) else {
panic!("expected a final record");
};
let rec = layout.rec(&value);
assert_eq!(unsafe { rec.element::<f64>() }, 7., "the element passes through the write");
assert_eq!(unsafe { rec.read::<f64>(offset) }, 2.5, "the value lands under the folded name");
}
#[test]
fn a_census_name_writes_at_its_declared_value_type() {
let path = vec![NodeId(7), NodeId(8)];
let executor = build_executor(write_attribute_network("editor:layer_path", TaggedValue::NodeIdPath(path.clone())));
let arena = Arena::new(1 << 12).unwrap();
let generations = [];
let scope = EvalScope::new(None, None, None, &generations, &arena);
let ctx = ContextImpl::root(&scope);
let handle = executor.tree().get(NodeId(3)).unwrap();
let layout = handle.layout().clone();
let offset = layout.offset_of("editor:layer_path", 0).expect("a census name folds onto its census field");
let edge = handle.duplicate().downcast_record::<f64>().unwrap();
let frames = core_types::record::test_frames(executor.tree().stack_need());
let GPoll::Final(value) = core_types::record::serve_input(&edge, &ctx, &frames) else {
panic!("expected a final record");
};
assert_eq!(unsafe { layout.rec(&value).read::<&[NodeId]>(offset) }, path.as_slice());
}
/// Reads `read_name` off a record that a write of `write_name` produced.
fn read_attribute_network(write_name: &str, read_name: &str, value: TaggedValue) -> ProtoNetwork {
read_attribute_network_over(TaggedValue::F64(7.), write_name, read_name, value)
}
/// The same graph over any content element, which the read never looks at.
fn read_attribute_network_over(content: TaggedValue, write_name: &str, read_name: &str, value: TaggedValue) -> ProtoNetwork {
ProtoNetwork {
stack_need: 0,
inputs: vec![],
output: NodeId(5),
nodes: vec![
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(content.into()), vec![])),
(NodeId(1), string_value(write_name)),
(NodeId(2), ProtoNode::value(ConstructionArgs::Value(value.into()), vec![])),
(NodeId(3), proto_node("graphic_nodes::graphic::WriteAttributeNode", vec![NodeId(0), NodeId(1), NodeId(2)])),
(NodeId(4), string_value(read_name)),
(NodeId(5), proto_node("graphic_nodes::graphic::ReadNumberAttributeNode", vec![NodeId(3), NodeId(4)])),
],
}
}
fn read_back(network: ProtoNetwork) -> f64 {
let executor = build_executor(network);
let arena = Arena::new(1 << 12).unwrap();
let generations = [];
let scope = EvalScope::new(None, None, None, &generations, &arena);
let ctx = ContextImpl::root(&scope);
let handle = executor.tree().get(NodeId(5)).unwrap();
let layout = handle.layout().clone();
let edge = handle.duplicate().downcast_record::<f64>().unwrap();
let frames = core_types::record::test_frames(executor.tree().stack_need());
let GPoll::Final(value) = core_types::record::serve_input(&edge, &ctx, &frames) else {
panic!("expected a final record");
};
unsafe { core_types::record::read_element::<f64>(layout.rec(&value)) }
}
#[test]
fn a_named_read_serves_the_written_value() {
assert_eq!(read_back(read_attribute_network("novel:count", "novel:count", TaggedValue::F64(2.5))), 2.5);
}
#[test]
fn an_absent_named_read_serves_the_forced_default() {
// Nothing upstream writes `novel:absent`, so the read collapses to the
// value type's default rather than reporting absence.
assert_eq!(read_back(read_attribute_network("novel:count", "novel:absent", TaggedValue::F64(2.5))), 0.);
}
#[test]
fn one_read_node_serves_every_content_element() {
// The read never looks at the element, so one registry row covers any
// upstream record wire rather than a row per element type.
assert_eq!(read_back(read_attribute_network_over(TaggedValue::F64(7.), "novel:count", "novel:count", TaggedValue::F64(2.5))), 2.5);
assert_eq!(
read_back(read_attribute_network_over(TaggedValue::Bool(true), "novel:count", "novel:count", TaggedValue::F64(2.5))),
2.5
);
assert_eq!(
read_back(read_attribute_network_over(TaggedValue::DVec2(glam::DVec2::ONE), "novel:count", "novel:count", TaggedValue::F64(2.5))),
2.5
);
}
#[test]
fn a_census_named_read_round_trips_its_written_value() {
// A declared name folds onto its census field, so the read resolves
// against the same offset the write installed.
assert_eq!(read_back(read_attribute_network("opacity", "opacity", TaggedValue::F64(0.5))), 0.5);
}
#[test]
fn an_absent_census_named_read_serves_the_census_default() {
// `opacity` is declared `f64` defaulting to 1, so its absence reads as
// the census default rather than the value type's.
assert_eq!(read_back(read_attribute_network("novel:count", "opacity", TaggedValue::F64(2.5))), 1.);
}
#[test]
fn a_named_read_disagreeing_with_its_write_is_refused() {
// The name is written at a path upstream and read at `f64` here, which
// is the one-name-one-type rule spanning a write and a read.
let mut network = read_attribute_network("novel:count", "novel:count", TaggedValue::NodeIdPath(vec![NodeId(1)]));
network.resolve_types(&node_registry::NODE_REGISTRY).unwrap();
let errors = network.compute_layouts().expect_err("a name at two value types must be refused");
assert!(
errors.iter().any(|error| format!("{:?}", error.error).contains("one name carries one value type")),
"the refusal names the one-name-one-type rule, got {errors:?}"
);
}
#[test]
fn a_runtime_attribute_name_is_refused_when_the_graph_compiles() {
// The outer node's name comes off another node rather than sitting on
// the wire as text. It still types as a string, so only the fold can
// reject it, which is the case the design rules out entirely.
let mut network = ProtoNetwork {
stack_need: 0,
inputs: vec![],
output: NodeId(6),
nodes: vec![
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(7.).into()), vec![])),
(NodeId(1), string_value("novel:count")),
(NodeId(2), string_value("inner:name")),
(NodeId(3), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(1.).into()), vec![])),
// Carries a string element, so its output types as a name.
(NodeId(4), proto_node("graphic_nodes::graphic::WriteAttributeNode", vec![NodeId(1), NodeId(2), NodeId(3)])),
(NodeId(5), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(2.5).into()), vec![])),
(NodeId(6), proto_node("graphic_nodes::graphic::WriteAttributeNode", vec![NodeId(0), NodeId(4), NodeId(5)])),
],
};
network.resolve_types(&node_registry::NODE_REGISTRY).unwrap();
let errors = network.compute_layouts().expect_err("a non-constant name must be refused");
assert!(
errors.iter().any(|error| format!("{:?}", error.error).contains("must be a constant")),
"the refusal names the constant requirement, got {errors:?}"
);
}
#[test]
fn one_name_carries_one_value_type() {
// `opacity` is declared `f64` in the census, so writing a path there is
// a graph error rather than a second field of the same name.
let mut network = write_attribute_network("opacity", TaggedValue::NodeIdPath(vec![NodeId(1)]));
network.resolve_types(&node_registry::NODE_REGISTRY).unwrap();
let errors = network.compute_layouts().expect_err("a name at two value types must be refused");
assert!(
errors.iter().any(|error| format!("{:?}", error.error).contains("one name carries one value type")),
"the refusal names the one-name-one-type rule, got {errors:?}"
);
}
#[test]
fn the_clone_node_clones_the_element_out_of_its_record_wire() {
let network = ProtoNetwork {
stack_need: 0,
inputs: vec![],
output: NodeId(1),
nodes: vec![
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64Array(vec![7.]).into()), vec![])),
(NodeId(1), proto_node("graphene_core::debug::CloneNode", vec![NodeId(0)])),
],
};
let executor = build_executor(network);
let arena = Arena::new(1 << 20).unwrap();
let generations = [];
let scope = EvalScope::new(None, None, None, &generations, &arena);
let ctx = ContextImpl::root(&scope);
let handle = executor.tree().get(NodeId(1)).unwrap();
let layout = handle.layout().clone();
let edge = handle.duplicate().downcast_record::<f64>().unwrap();
let frames = core_types::record::test_frames(executor.tree().stack_need());
let GPoll::Final(value) = core_types::record::serve_input(&edge, &ctx, &frames) else {
panic!("the flipped clone must evaluate over record wires, got a non-final poll");
};
assert_eq!(unsafe { core_types::record::read_element::<f64>(layout.rec(&value)) }, 7.);
}
#[test]
fn the_palette_folds_its_record_wire_to_a_color_level() {
let raster_list = TaggedValue::from_type(&core_types::concrete!(graphene_std::list::List<graphene_std::raster_types::Raster<graphene_std::raster_types::CPU>>)).unwrap();
let network = ProtoNetwork {
stack_need: 0,
inputs: vec![],
output: NodeId(2),
nodes: vec![
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(raster_list.into()), vec![])),
(NodeId(1), ProtoNode::value(ConstructionArgs::Value(TaggedValue::U32(4).into()), vec![])),
(NodeId(2), proto_node("raster_nodes::image_color_palette::ImageColorPaletteNode", vec![NodeId(0), NodeId(1)])),
],
};
let executor = build_executor(network);
let arena = Arena::new(1 << 12).unwrap();
let generations = [];
let scope = EvalScope::new(None, None, None, &generations, &arena);
let ctx = ContextImpl::root(&scope);
let edge = executor.tree().get(NodeId(2)).unwrap().downcast_record::<graphene_std::raster::color::Color>().unwrap();
let frames = core_types::record::test_frames(executor.tree().stack_need());
let result = core_types::record::serve_input(&edge, &ctx, &frames);
// The empty raster level folds to an empty palette: past-end at lane 0.
assert!(
matches!(&result, GPoll::Error(error) if error.kind == core_types::gpoll::ErrorKind::PastEnd),
"the empty palette level must serve the past-end signal at lane 0"
);
}
#[test]
fn a_value_edge_is_a_record_wire_end_to_end() {
let network = ProtoNetwork {
stack_need: 0,
inputs: vec![],
output: NodeId(0),
nodes: vec![(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(7.).into()), vec![]))],
};
let executor = build_executor(network);
let value = executor.tree().get(NodeId(0)).unwrap();
assert_eq!(value.ty(), &core_types::registry::record_source_type::<f64>());
assert_eq!(value.layout().depth, 0);
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::F64(7.)));
}
#[test]
fn a_record_monitor_row_forwards_and_introspects_through_the_executor() {
let mut monitor = proto_node("graphene_core::memo::MonitorNode", vec![NodeId(0)]);
monitor.original_location.path = Some(vec![NodeId(9)]);
let network = ProtoNetwork {
stack_need: 0,
inputs: vec![],
output: NodeId(1),
nodes: vec![(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(7.).into()), vec![])), (NodeId(1), monitor)],
};
let executor = build_executor(network);
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::F64(7.)));
let element = executor.introspect(&[NodeId(9)]).unwrap();
let element = element.downcast_ref::<f64>().expect("a record capture materializes to its element");
assert_eq!(*element, 7.);
}
#[test]
fn a_memoize_row_wires_generically_and_replays_over_record_wires() {
let network = ProtoNetwork {
stack_need: 0,
inputs: vec![],
output: NodeId(1),
nodes: vec![
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::String(String::from("cached")).into()), vec![])),
(NodeId(1), proto_node("graphene_core::memo::MemoizeNode", vec![NodeId(0)])),
],
};
let executor = build_executor(network);
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::String(String::from("cached"))));
assert_eq!(
(&executor).execute(()).unwrap(),
GPoll::Final(TaggedValue::String(String::from("cached"))),
"the second execution replays the deep copy against a reset arena"
);
}
fn modification_value() -> ProtoNode {
let modification = core_types::ContextModification::from_sources(core_types::context::ContextFeatures::all(), &[]);
ProtoNode::value(ConstructionArgs::Value(TaggedValue::ContextModification(modification).into()), vec![])
}
#[test]
fn a_context_modification_row_wires_over_a_value_wire() {
let network = ProtoNetwork {
stack_need: 0,
inputs: vec![],
output: NodeId(2),
nodes: vec![
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(7.).into()), vec![])),
(NodeId(1), modification_value()),
(NodeId(2), proto_node("graphene_core::context_modification::ContextModificationNode", vec![NodeId(0), NodeId(1)])),
],
};
let executor = build_executor(network);
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::F64(7.)));
}
#[test]
fn nested_context_modifications_forward_the_layout() {
let network = ProtoNetwork {
stack_need: 0,
inputs: vec![],
output: NodeId(4),
nodes: vec![
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(7.).into()), vec![])),
(NodeId(1), modification_value()),
(NodeId(2), proto_node("graphene_core::context_modification::ContextModificationNode", vec![NodeId(0), NodeId(1)])),
(NodeId(3), modification_value()),
(NodeId(4), proto_node("graphene_core::context_modification::ContextModificationNode", vec![NodeId(2), NodeId(3)])),
],
};
let executor = build_executor(network);
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::F64(7.)));
}
#[test]
fn stacked_frame_memos_replay_over_record_wires() {
let network = ProtoNetwork {
stack_need: 0,
inputs: vec![],
output: NodeId(2),
nodes: vec![
(NodeId(0), string_value("memoized")),
(NodeId(1), proto_node("graphene_core::memo::FrameMemoNode", vec![NodeId(0)])),
(NodeId(2), proto_node("graphene_core::memo::FrameMemoNode", vec![NodeId(1)])),
],
};
let executor = build_executor(network);
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::String("memoized".to_string())));
assert_eq!(
(&executor).execute(()).unwrap(),
GPoll::Final(TaggedValue::String("memoized".to_string())),
"the frame memo must replay across evaluations"
);
}
}
@@ -1,816 +0,0 @@
use super::*;
use core_types::Context;
use core_types::list::{Item, List};
use core_types::{item, list};
use graph_craft::ProtoNodeIdentifier;
use graph_craft::document::value::TaggedValue;
use graphene_std::vector::Vector;
#[test]
fn push_node_sync() {
let mut tree = BorrowTree::default();
let val_1_protonode = ProtoNode::value(ConstructionArgs::Value(TaggedValue::U32(2u32).into()), vec![]);
let context = TypingContext::default();
let future = tree.push_node(NodeId(0), val_1_protonode, &context);
futures::executor::block_on(future).unwrap();
let _node = tree.get(NodeId(0)).unwrap();
let result: Option<Item<u32>> = futures::executor::block_on(tree.eval(NodeId(0), ()));
assert_eq!(result.map(|item| *item.element()), Some(2_u32));
}
/// Builds a two-node network feeding the given value into Bounding Box, whose primary input registers both `Item<Vector>` and `List<Vector>` wire variants.
fn bounding_box_network(content: TaggedValue) -> ProtoNetwork {
let value_node = ProtoNode::value(ConstructionArgs::Value(content.into()), vec![NodeId(0)]);
let mut bounding_box_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
bounding_box_node.identifier = ProtoNodeIdentifier::new("core_types::vector::BoundingBoxNode");
ProtoNetwork {
inputs: vec![],
output: NodeId(1),
nodes: vec![(NodeId(0), value_node), (NodeId(1), bounding_box_node)],
}
}
fn compile_bounding_box_network(content: TaggedValue) -> BorrowTree {
let network = bounding_box_network(content);
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("The network should resolve against exactly one registered wire variant");
futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The resolved variant's constructor should instantiate")
}
#[test]
fn item_wire_variant_resolves_and_executes() {
let tree = compile_bounding_box_network(TaggedValue::TypeDefault(item!(Vector)));
let context: Context = None;
let result: Option<Item<Vector>> = futures::executor::block_on(tree.eval(NodeId(1), context.clone()));
assert!(result.is_some(), "The Item wire variant should downcast and execute end-to-end");
let wrong_type: Option<List<Vector>> = futures::executor::block_on(tree.eval(NodeId(1), context));
assert!(wrong_type.is_none(), "An Item wire should not downcast as a List");
}
#[test]
fn item_wire_promotes_to_list_connector() {
let value_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::TypeDefault(item!(f64)).into()), vec![NodeId(0)]);
// Box Corners takes a `List<f64>` primary, so feeding it an `Item<f64>` wire exercises the singleton raise
let mut box_corners_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
box_corners_node.identifier = graphene_std::vector::generator_nodes::box_corners::IDENTIFIER;
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(1),
nodes: vec![(NodeId(0), value_node), (NodeId(1), box_corners_node)],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("An Item wire should resolve a List connector via promotion");
assert!(typing_context.promotions(NodeId(1)).is_some(), "The typing pass should record the promotion");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The promotion adapter should instantiate");
let context: Context = None;
let result: Option<Item<graphene_std::vector::misc::BoxCorners>> = futures::executor::block_on(tree.eval(NodeId(1), context));
assert!(result.is_some(), "The promoted wire should execute end-to-end");
}
// The layer content path: a rank-0 content wire enters Into Group's `List` connector by singleton raise, and the
// grouped `Item<Graphic>` raises again at Extend's `List` connector, so layers accept rank-0 chains without new machinery
#[test]
fn rank_0_content_promotes_through_the_layer_coercion_path() {
let content_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::TypeDefault(item!(Vector)).into()), vec![NodeId(0)]);
let mut into_group_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
into_group_node.identifier = ProtoNodeIdentifier::new("graphic_nodes::graphic::IntoGroupNode");
let base_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::TypeDefault(list!(graphene_std::Graphic)).into()), vec![NodeId(2)]);
let mut extend_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(2), NodeId(1)]), vec![NodeId(3)]);
extend_node.identifier = ProtoNodeIdentifier::new("graphic_nodes::graphic::ExtendNode");
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(3),
nodes: vec![(NodeId(0), content_node), (NodeId(1), into_group_node), (NodeId(2), base_node), (NodeId(3), extend_node)],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("A rank-0 content wire should resolve the layer coercion path via promotion");
assert!(typing_context.promotions(NodeId(1)).is_some(), "The rank-0 content should be raised at Into Group's List connector");
assert!(typing_context.promotions(NodeId(3)).is_some(), "The grouped Item<Graphic> should be raised at Extend's List connector");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The promotion adapters should instantiate");
let context: Context = None;
let result: Option<List<graphene_std::Graphic>> = futures::executor::block_on(tree.eval(NodeId(3), context));
let stack = result.expect("The layer coercion path should execute end-to-end");
assert_eq!(stack.len(), 1, "The rank-0 content should contribute exactly one graphic to the stack");
}
/// Builds a network feeding the given content plus an f64 distance value into Offset Points, whose distance input is ranked `Item<f64>`.
fn offset_points_network(content: TaggedValue) -> ProtoNetwork {
let content_node = ProtoNode::value(ConstructionArgs::Value(content.into()), vec![NodeId(0)]);
let distance_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(10.).into()), vec![NodeId(1)]);
let mut input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(1)]), vec![NodeId(2)]);
input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<f64>");
let mut offset_points_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0), NodeId(2)]), vec![NodeId(3)]);
offset_points_node.identifier = ProtoNodeIdentifier::new("core_types::vector::OffsetPointsNode");
ProtoNetwork {
inputs: vec![],
output: NodeId(3),
nodes: vec![(NodeId(0), content_node), (NodeId(1), distance_node), (NodeId(2), input_adapter_node), (NodeId(3), offset_points_node)],
}
}
#[test]
fn mixed_rank_connectors_resolve_via_promotion() {
let network = offset_points_network(TaggedValue::TypeDefault(list!(Vector)));
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context
.update(&network)
.expect("A List primary with an Item parameter should resolve the mapped variant via promotion");
assert!(typing_context.promotions(NodeId(3)).is_some(), "The Item distance should be marked for promotion");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("Construction should wrap the promoted argument");
let context: Context = None;
let result: Option<List<Vector>> = futures::executor::block_on(tree.eval(NodeId(3), context));
assert!(result.is_some(), "The zipped mapped variant should execute end-to-end");
}
#[test]
fn all_item_connectors_resolve_without_promotion() {
let network = offset_points_network(TaggedValue::TypeDefault(item!(Vector)));
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("All-Item connectors should resolve the rank-0 variant exactly");
assert!(typing_context.promotions(NodeId(3)).is_none(), "No promotion should be needed at rank 0");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The rank-0 variant should instantiate");
let context: Context = None;
let result: Option<Item<Vector>> = futures::executor::block_on(tree.eval(NodeId(3), context));
assert!(result.is_some(), "The rank-0 variant should execute and stay rank 0");
}
/// Builds a Transform network: content (node 0) plus four parameter values, each promoted onto Item wires as the preprocessor would.
fn transform_network(content: TaggedValue, rotation: TaggedValue) -> ProtoNetwork {
let mut nodes = vec![(NodeId(0), ProtoNode::value(ConstructionArgs::Value(content.into()), vec![NodeId(0)]))];
let parameters = [
(TaggedValue::DVec2(glam::DVec2::new(5., 0.)), "DVec2"),
(rotation, "f64"),
(TaggedValue::DVec2(glam::DVec2::ONE), "DVec2"),
(TaggedValue::DVec2(glam::DVec2::ZERO), "DVec2"),
];
let mut transform_inputs = vec![NodeId(0)];
let mut next_id = 1;
for (value, element) in parameters {
let value_id = NodeId(next_id);
let input_adapter_id = NodeId(next_id + 1);
next_id += 2;
nodes.push((value_id, ProtoNode::value(ConstructionArgs::Value(value.into()), vec![value_id])));
let mut input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![value_id]), vec![input_adapter_id]);
input_adapter_node.identifier = ProtoNodeIdentifier::with_owned_string(format!("input_adapter<{element}>"));
nodes.push((input_adapter_id, input_adapter_node));
transform_inputs.push(input_adapter_id);
}
let output = NodeId(next_id);
let mut transform_node = ProtoNode::value(ConstructionArgs::Nodes(transform_inputs), vec![output]);
transform_node.identifier = graphene_std::transform_nodes::transform::IDENTIFIER;
nodes.push((output, transform_node));
ProtoNetwork { inputs: vec![], output, nodes }
}
#[test]
fn transform_composes_onto_item_wire() {
use glam::{DAffine2, DVec2};
let network = transform_network(TaggedValue::TypeDefault(item!(Vector)), TaggedValue::F64(0.));
let output = network.output;
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("Transform should resolve its rank-0 variant");
assert!(typing_context.promotions(output).is_none(), "All-Item connectors should need no promotion");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("Transform's rank-0 variant should instantiate");
let context: Context = None;
let result: Option<Item<Vector>> = futures::executor::block_on(tree.eval(output, context));
let item = result.expect("A rank-0 chain through Transform should stay rank 0");
let transform = item.attribute_cloned_or_default::<DAffine2>(core_types::ATTR_TRANSFORM);
assert_eq!(transform.translation, DVec2::new(5., 0.), "The translation should compose onto the item's transform attribute");
}
#[test]
fn transform_broadcasts_item_content_across_a_framed_parameter() {
use glam::DAffine2;
let network = transform_network(TaggedValue::TypeDefault(item!(Vector)), TaggedValue::F64Array(vec![0., 90.]));
let output = network.output;
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context
.update(&network)
.expect("A framed rotation should resolve the mapped variant via promotion of the other connectors");
assert!(typing_context.promotions(output).is_some(), "The Item-typed connectors should be raised into the frame");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The mapped variant should instantiate");
let context: Context = None;
let result: Option<List<Vector>> = futures::executor::block_on(tree.eval(output, context));
let list = result.expect("The broadcast should produce a List");
assert_eq!(list.len(), 2, "One output item per frame slot");
let first: DAffine2 = list.attribute_cloned_or_default(core_types::ATTR_TRANSFORM, 0);
let second: DAffine2 = list.attribute_cloned_or_default(core_types::ATTR_TRANSFORM, 1);
assert!((first.matrix2.col(0).y - 0.).abs() < 1e-10, "Slot 0 should be unrotated");
assert!((second.matrix2.col(0).y - 1.).abs() < 1e-10, "Slot 1 should be rotated 90 degrees");
}
#[test]
fn generator_frames_over_a_list_parameter() {
// A `()` generator (Circle) fed a `List<f64>` radius should frame into one circle per slot
let primary = ProtoNode::value(ConstructionArgs::Value(TaggedValue::None.into()), vec![NodeId(0)]);
let radii = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64Array(vec![10., 20., 30.]).into()), vec![NodeId(1)]);
let mut radius_adapter = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(1)]), vec![NodeId(2)]);
radius_adapter.identifier = ProtoNodeIdentifier::new("input_adapter<f64>");
let mut circle_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0), NodeId(2)]), vec![NodeId(3)]);
circle_node.identifier = graphene_std::vector_nodes::circle::IDENTIFIER;
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(3),
nodes: vec![(NodeId(0), primary), (NodeId(1), radii), (NodeId(2), radius_adapter), (NodeId(3), circle_node)],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("A List<f64> radius should resolve Circle's mapped generator variant");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The mapped generator variant should instantiate");
let context: Context = None;
let result: Option<List<Vector>> = futures::executor::block_on(tree.eval(NodeId(3), context));
let list = result.expect("The generator frame should produce a List<Vector>");
assert_eq!(list.len(), 3, "One circle per radius slot");
}
/// Builds the compiler's cache chain (child, then Memoize, then Context Modification) around a value, as `insert_context_nullification_node` does.
fn nullification_chain_network(value: TaggedValue) -> ProtoNetwork {
let value_node = ProtoNode::value(ConstructionArgs::Value(value.into()), vec![NodeId(0)]);
let mut memoize_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
memoize_node.identifier = graphene_core::memo::memoize::IDENTIFIER;
let features_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::ContextFeatures(Default::default()).into()), vec![NodeId(2)]);
let mut nullification_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(1), NodeId(2)]), vec![NodeId(3)]);
nullification_node.identifier = graphene_core::context_modification::context_modification::IDENTIFIER;
ProtoNetwork {
inputs: vec![],
output: NodeId(3),
nodes: vec![(NodeId(0), value_node), (NodeId(1), memoize_node), (NodeId(2), features_node), (NodeId(3), nullification_node)],
}
}
#[test]
fn the_nullification_chain_resolves_for_ranked_enum_wires() {
use graphene_std::vector::style::StrokeAlign;
// The Item form, as a wrapped input adapter's output presents to the chain
let network = nullification_chain_network(TaggedValue::TypeDefault(item!(StrokeAlign)));
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("An Item<StrokeAlign> wire should resolve through the compiler's cache chain");
// The List form, as a whole-list enum wire presents to the chain
let network = nullification_chain_network(TaggedValue::TypeDefault(list!(StrokeAlign)));
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("A List<StrokeAlign> wire should resolve through the compiler's cache chain");
}
#[test]
fn value_wires_materialize_as_items_at_resolution() {
use glam::{DAffine2, DVec2};
let values = [
TaggedValue::DAffine2(DAffine2::IDENTITY),
TaggedValue::DVec2(DVec2::new(7., 0.)),
TaggedValue::F64(0.),
TaggedValue::DVec2(DVec2::ONE),
TaggedValue::DVec2(DVec2::ZERO),
];
let mut nodes: Vec<_> = values
.into_iter()
.enumerate()
.map(|(index, value)| (NodeId(index as u64), ProtoNode::value(ConstructionArgs::Value(value.into()), vec![NodeId(index as u64)])))
.collect();
let mut transform_node = ProtoNode::value(ConstructionArgs::Nodes((0..5).map(NodeId).collect()), vec![NodeId(5)]);
transform_node.identifier = graphene_std::transform_nodes::transform::IDENTIFIER;
nodes.push((NodeId(5), transform_node));
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(5),
nodes,
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("Value wires should materialize as Items and resolve the all-Item variant");
assert!(typing_context.promotions(NodeId(5)).is_none(), "Already-Item value wires should need no promotion");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The all-Item variant should instantiate");
let context: Context = None;
let result: Option<Item<DAffine2>> = futures::executor::block_on(tree.eval(NodeId(5), context));
let item = result.expect("A value matrix should flow through Transform as an Item");
let transform = item.attribute_cloned_or_default::<DAffine2>(core_types::ATTR_TRANSFORM);
assert_eq!(transform.translation, DVec2::new(7., 0.), "The translation should compose onto the gained transform attribute");
}
// A position's Item wire converts through the vector input adapter into a single-anchor path, which the ItemToList promotion can then raise at a List connector
#[test]
fn position_value_converts_through_the_vector_input_adapter() {
let position_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::DVec2(glam::DVec2::new(3., 4.)).into()), vec![NodeId(0)]);
let mut input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<Vector>");
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(1),
nodes: vec![(NodeId(0), position_node), (NodeId(1), input_adapter_node)],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("An Item<DVec2> wire should resolve the adapter's element conversion row");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The conversion constructor should instantiate");
let context: Context = None;
let result: Option<Item<Vector>> = futures::executor::block_on(tree.eval(NodeId(1), context));
assert!(result.is_some(), "The position should arrive as an Item<Vector> single-anchor path");
}
// 'Into Group' reduces whole lists, so a rank-0 position reaches it by singleton raise rather than a row of its own
#[test]
fn position_value_raises_into_the_into_group_reducer() {
use graphene_std::Graphic;
let position_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::DVec2(glam::DVec2::new(3., 4.)).into()), vec![NodeId(0)]);
let mut into_group_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
into_group_node.identifier = ProtoNodeIdentifier::new("graphic_nodes::graphic::IntoGroupNode");
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(1),
nodes: vec![(NodeId(0), position_node), (NodeId(1), into_group_node)],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("An Item<DVec2> wire should raise into Into Group's List<DVec2> row");
assert!(typing_context.promotions(NodeId(1)).is_some(), "The rank-0 position should be raised at Into Group's List connector");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The reducer constructor should instantiate");
let context: Context = None;
let result: Option<Item<Graphic>> = futures::executor::block_on(tree.eval(NodeId(1), context));
let grouped = result.expect("The position should arrive as an Item<Graphic>");
let Graphic::VectorList(anchors) = grouped.element() else {
panic!("expected a vector list graphic")
};
assert_eq!(anchors.len(), 1, "The single position should group as one anchor point");
}
// The 'Colors to Gradient' node turns an entire color wire into one gradient with those colors as its stops,
// reaching its `List<Graphic>` connector through the embedding adapter
#[test]
fn color_list_wraps_through_the_colors_to_gradient_node() {
let color_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Color(graphene_std::Color::WHITE).into()), vec![NodeId(0)]);
let mut raise_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
raise_node.identifier = ProtoNodeIdentifier::new("graphene_core::ops::ItemToListNode<Color>");
let mut graphic_adapter = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(1)]), vec![NodeId(2)]);
graphic_adapter.identifier = ProtoNodeIdentifier::new("input_adapter<Graphic>");
let mut colors_to_gradient_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(2)]), vec![NodeId(3)]);
colors_to_gradient_node.identifier = ProtoNodeIdentifier::new("graphic_nodes::graphic::ColorsToGradientNode");
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(3),
nodes: vec![(NodeId(0), color_node), (NodeId(1), raise_node), (NodeId(2), graphic_adapter), (NodeId(3), colors_to_gradient_node)],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("A List<Color> wire should embed into the node's List<Graphic> connector");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The node constructor should instantiate");
let context: Context = None;
let result: Option<Item<graphene_std::vector::Gradient>> = futures::executor::block_on(tree.eval(NodeId(3), context));
let gradient = result.expect("The color list should arrive wrapped as a gradient");
assert_eq!(gradient.element().len(), 1, "The single color should become the gradient's one stop");
}
// As Graphic asserts the type without changing rank, so a vector list arrives as one graphic per item rather than one group
#[test]
fn as_graphic_converts_a_vector_list_element_wise() {
use graphene_std::Graphic;
// Two radii frame the Circle generator into a two-element `List<Vector>`, the wire As Graphic then converts
let primary = ProtoNode::value(ConstructionArgs::Value(TaggedValue::None.into()), vec![NodeId(0)]);
let radii = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64Array(vec![10., 20.]).into()), vec![NodeId(1)]);
let mut radius_adapter = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(1)]), vec![NodeId(2)]);
radius_adapter.identifier = ProtoNodeIdentifier::new("input_adapter<f64>");
let mut circle_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0), NodeId(2)]), vec![NodeId(3)]);
circle_node.identifier = graphene_std::vector_nodes::circle::IDENTIFIER;
let mut graphic_adapter = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(3)]), vec![NodeId(4)]);
graphic_adapter.identifier = ProtoNodeIdentifier::new("input_adapter<Graphic>");
let mut as_graphic_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(4)]), vec![NodeId(5)]);
as_graphic_node.identifier = ProtoNodeIdentifier::new("graphic_nodes::graphic::AsGraphicNode");
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(5),
nodes: vec![
(NodeId(0), primary),
(NodeId(1), radii),
(NodeId(2), radius_adapter),
(NodeId(3), circle_node),
(NodeId(4), graphic_adapter),
(NodeId(5), as_graphic_node),
],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context
.update(&network)
.expect("A List<Vector> wire should resolve As Graphic's mapped variant through the embedding adapter");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The mapped constructor should instantiate");
let context: Context = None;
let result: Option<List<Graphic>> = futures::executor::block_on(tree.eval(NodeId(5), context));
let graphics = result.expect("The vector list should arrive as a graphic list");
assert_eq!(graphics.len(), 2, "Each vector should become its own graphic rather than collapsing into one group");
assert!(
graphics.iter_element_values().all(|graphic| matches!(graphic, Graphic::Vector(_))),
"Each element should embed as the rank-0 vector variant that mirrors its wire"
);
}
// A paint wire feeding a `Graphic` connector embeds whole, so the gradient's own attributes stay on the item inside the variant
#[test]
fn gradient_value_embeds_through_the_graphic_input_adapter() {
use core_types::ATTR_GRADIENT_SPREAD;
use graphene_std::Graphic;
use graphene_std::vector::{Gradient, GradientRamp, GradientSpread};
let ramp = GradientRamp {
gradient_spread: GradientSpread::Reflect,
..GradientRamp::from(Gradient::default())
};
let gradient_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::GradientRamp(ramp).into()), vec![NodeId(0)]);
let mut input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<Graphic>");
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(1),
nodes: vec![(NodeId(0), gradient_node), (NodeId(1), input_adapter_node)],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("An Item<Gradient> wire should resolve the adapter's embedding row");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The embedding constructor should instantiate");
let context: Context = None;
let result: Option<Item<Graphic>> = futures::executor::block_on(tree.eval(NodeId(1), context));
let embedded = result.expect("The gradient should arrive as an Item<Graphic>");
assert!(embedded.attributes().iter_any().next().is_none(), "The fresh outer envelope describes the graphic, so it starts empty");
let Graphic::Gradient(inner) = embedded.element() else { panic!("expected a gradient graphic") };
assert_eq!(
inner.attribute::<GradientSpread>(ATTR_GRADIENT_SPREAD),
Some(&GradientSpread::Reflect),
"The gradient's placement attributes should ride the item inside the variant, where the renderer reads them"
);
}
// A scalar wire feeding a `DVec2` connector splats into both axes through the input adapter's `Convert` row
#[test]
fn number_value_splats_through_the_vec2_input_adapter() {
let number_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(-60.).into()), vec![NodeId(0)]);
let mut input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<DVec2>");
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(1),
nodes: vec![(NodeId(0), number_node), (NodeId(1), input_adapter_node)],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("An f64 wire should resolve the adapter's splat conversion row");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The splat constructor should instantiate");
let context: Context = None;
let result: Option<Item<glam::DVec2>> = futures::executor::block_on(tree.eval(NodeId(1), context));
assert_eq!(result.map(|item| *item.element()), Some(glam::DVec2::splat(-60.)), "The scalar should splat into both axes");
}
// A scalar wire feeding a `String` connector formats as text through the input adapter's `Convert` row
#[test]
fn number_value_formats_through_the_string_input_adapter() {
let number_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(42.).into()), vec![NodeId(0)]);
let mut input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<String>");
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(1),
nodes: vec![(NodeId(0), number_node), (NodeId(1), input_adapter_node)],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("An f64 wire should resolve the adapter's formatting conversion row");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The formatting constructor should instantiate");
let context: Context = None;
let result: Option<Item<String>> = futures::executor::block_on(tree.eval(NodeId(1), context));
assert_eq!(result.map(|item| item.element().clone()), Some("42".to_string()), "The number should format as its text representation");
}
// A `List` wire feeding a `ListDyn` connector erases its element type through the input adapter's `Into` row
#[test]
fn list_wire_erases_through_the_list_dyn_input_adapter() {
use core_types::list::ListDyn;
let list_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64Array(vec![1., 2., 3.]).into()), vec![NodeId(0)]);
let mut input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<ListDyn>");
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(1),
nodes: vec![(NodeId(0), list_node), (NodeId(1), input_adapter_node)],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("A List<f64> wire should resolve the ListDyn erasure row");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The erasure constructor should instantiate");
let context: Context = None;
let result: Option<ListDyn> = futures::executor::block_on(tree.eval(NodeId(1), context));
let erased = result.expect("The erased list should arrive as a ListDyn");
assert_eq!(erased.len(), 3, "The erased list should keep its row count");
}
#[test]
fn value_wire_passes_through_the_input_adapter_as_item() {
let value_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(3.).into()), vec![NodeId(0)]);
let mut input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<f64>");
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(1),
nodes: vec![(NodeId(0), value_node), (NodeId(1), input_adapter_node)],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("An f64 value's Item wire should resolve the adapter's passthrough row");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The passthrough constructor should instantiate");
let context: Context = None;
let result: Option<Item<f64>> = futures::executor::block_on(tree.eval(NodeId(1), context));
assert_eq!(result.map(|item| *item.element()), Some(3.), "The value should arrive as an Item");
}
// Path Modify's ranked modification parameter: a `Box<VectorModification>` value rides the `Item` wire through its input adapter,
// exercising the nested-generic identifier round-trip between the registered `stringify!` name and the preprocessor's simplified name
#[test]
fn modification_value_rides_the_item_wire_through_its_input_adapter() {
use graphene_std::vector::VectorModification;
let modification = TaggedValue::VectorModification(Default::default());
let value_node = ProtoNode::value(ConstructionArgs::Value(modification.into()), vec![NodeId(0)]);
let mut input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<Box<VectorModification>>");
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(1),
nodes: vec![(NodeId(0), value_node), (NodeId(1), input_adapter_node)],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("A modification value's Item wire should resolve the adapter's passthrough row");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The passthrough constructor should instantiate");
let context: Context = None;
let result: Option<Item<Box<VectorModification>>> = futures::executor::block_on(tree.eval(NodeId(1), context));
assert!(result.is_some(), "The modification should arrive as an Item");
}
// The Write Attribute value input: a value's Item wire boxes its element into a type-erased attribute value through the input adapter
#[test]
fn item_wire_boxes_into_the_attribute_value_connector() {
use graphene_std::list::AttributeValueDyn;
let value_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(3.).into()), vec![NodeId(0)]);
let mut attribute_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
attribute_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<AttributeValueDyn>");
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(1),
nodes: vec![(NodeId(0), value_node), (NodeId(1), attribute_adapter_node)],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("An Item<f64> wire should resolve the attribute value boxing row");
assert!(typing_context.promotions(NodeId(1)).is_none(), "The already-Item value wire should need no promotion");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The boxing constructor should instantiate");
let context: Context = None;
let result: Option<Item<AttributeValueDyn>> = futures::executor::block_on(tree.eval(NodeId(1), context));
let boxed = result.expect("The boxed attribute value should arrive as an Item");
assert_eq!(
boxed.element().0.as_any().downcast_ref::<f64>(),
Some(&3.),
"The stored value should be the bare element, not the whole Item"
);
}
#[test]
fn list_wire_variant_resolves_and_executes() {
let tree = compile_bounding_box_network(TaggedValue::TypeDefault(list!(Vector)));
let context: Context = None;
let result: Option<List<Vector>> = futures::executor::block_on(tree.eval(NodeId(1), context.clone()));
assert!(result.is_some(), "The mapped List wire variant should downcast and execute end-to-end");
let wrong_type: Option<Item<Vector>> = futures::executor::block_on(tree.eval(NodeId(1), context));
assert!(wrong_type.is_none(), "A List wire should not downcast as an Item");
}
#[test]
fn expander_flattens_under_the_frame() {
// A string value's Item wire feeds String Split's expander primary; its parameters ride Item wires through their input adapters
let string_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::String("a,b".into()).into()), vec![NodeId(0)]);
let delimiter_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::String(",".into()).into()), vec![NodeId(1)]);
let mut delimiter_input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(1)]), vec![NodeId(2)]);
delimiter_input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<String>");
let escaping_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Bool(false).into()), vec![NodeId(3)]);
let mut escaping_input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(3)]), vec![NodeId(4)]);
escaping_input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<bool>");
let output = NodeId(5);
let mut string_split_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0), NodeId(2), NodeId(4)]), vec![output]);
string_split_node.identifier = graphene_std::text_nodes::string_split::IDENTIFIER;
let network = ProtoNetwork {
inputs: vec![],
output,
nodes: vec![
(NodeId(0), string_node),
(NodeId(1), delimiter_node),
(NodeId(2), delimiter_input_adapter_node),
(NodeId(3), escaping_node),
(NodeId(4), escaping_input_adapter_node),
(output, string_split_node),
],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context
.update(&network)
.expect("All-Item connectors should resolve the expander's direct `Item -> List` variant");
assert!(typing_context.promotions(output).is_none(), "No promotion should be needed when every connector is already an Item");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The expander variant should instantiate");
let context: Context = None;
let result: Option<List<String>> = futures::executor::block_on(tree.eval(output, context));
let list = result.expect("An Item-wired expander should produce a List");
assert_eq!(list.len(), 2, "Splitting \"a,b\" on the comma should expand into two rows");
let substrings: Vec<_> = list.iter_element_values().map(|s| s.as_str()).collect();
assert_eq!(substrings, ["a", "b"], "The rows should hold the split substrings");
}
#[test]
fn whole_list_switches_as_one_bundle() {
// One bool selecting between two whole `List<f64>` stacks: each branch bundles into a rank-0 cell, and the result unbundles back to the flat stack
let condition_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Bool(true).into()), vec![NodeId(0)]);
let if_true_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64Array(vec![1., 2., 3.]).into()), vec![NodeId(1)]);
let if_false_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64Array(vec![4., 5.]).into()), vec![NodeId(2)]);
let mut switch_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0), NodeId(1), NodeId(2)]), vec![NodeId(3)]);
switch_node.identifier = ProtoNodeIdentifier::new("math_nodes::SwitchNode");
let mut unbundle_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(3)]), vec![NodeId(4)]);
unbundle_node.identifier = ProtoNodeIdentifier::new("graphene_core::ops::UnbundleNode<f64>");
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(4),
nodes: vec![
(NodeId(0), condition_node),
(NodeId(1), if_true_node),
(NodeId(2), if_false_node),
(NodeId(3), switch_node),
(NodeId(4), unbundle_node),
],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context
.update(&network)
.expect("A List<f64> branch should resolve the Item<Bundle<f64>> row via the bundle wrap");
let promotions = typing_context.promotions(NodeId(3)).expect("The condition wrap and both branch bundles should be recorded");
let branch_bundles = promotions
.iter()
.filter(|(index, adapter)| *index != 0 && matches!(adapter, graph_craft::proto::Promotion::Bundle(_)))
.count();
assert_eq!(branch_bundles, 2, "Both branches should bundle their whole list into one opaque cell");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The bundle, wrap, and unbundle adapters should instantiate");
let context: Context = None;
let result: Option<List<f64>> = futures::executor::block_on(tree.eval(NodeId(4), context));
let list = result.expect("The whole stack should round-trip through the bundle switch back to a flat List<f64>");
let values: Vec<f64> = list.iter_element_values().copied().collect();
assert_eq!(values, [1., 2., 3.], "The taken branch's whole list should come through unchanged");
}
#[test]
fn a_bundle_unbundles_into_a_list_connector() {
// A bundled wire (sourced here from a BundleNode, as a Switch branch produces one) feeding Extend's whole-`List` base connector
let stack_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::TypeDefault(list!(graphene_std::Graphic)).into()), vec![NodeId(0)]);
let mut bundle_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
bundle_node.identifier = ProtoNodeIdentifier::new("graphene_core::ops::BundleNode<Graphic>");
let new_layers_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::TypeDefault(list!(graphene_std::Graphic)).into()), vec![NodeId(2)]);
let mut extend_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(1), NodeId(2)]), vec![NodeId(3)]);
extend_node.identifier = ProtoNodeIdentifier::new("graphic_nodes::graphic::ExtendNode");
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(3),
nodes: vec![(NodeId(0), stack_node), (NodeId(1), bundle_node), (NodeId(2), new_layers_node), (NodeId(3), extend_node)],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("A bundled wire should feed Extend's List<Graphic> connector via the unbundle");
let promotions = typing_context.promotions(NodeId(3)).expect("Extend's bundled base should be marked for unbundling");
assert!(
promotions.iter().any(|(index, adapter)| *index == 0 && matches!(adapter, graph_craft::proto::Promotion::Unbundle(_))),
"The base connector should unbundle the whole list"
);
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The unbundle adapter should instantiate");
let context: Context = None;
let result: Option<List<graphene_std::Graphic>> = futures::executor::block_on(tree.eval(NodeId(3), context));
assert!(result.is_some(), "The unbundled stack should flow into Extend as a List<Graphic>");
}
#[test]
fn a_whole_list_of_scalars_switches_as_one_bundle() {
// A single bool selecting between two whole `List<f64>` values, covering a primitive element type and confirming the selected list survives intact
let condition_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Bool(true).into()), vec![NodeId(0)]);
let if_true_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64Array(vec![1., 2.]).into()), vec![NodeId(1)]);
let if_false_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64Array(vec![3., 4., 5.]).into()), vec![NodeId(2)]);
let mut switch_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0), NodeId(1), NodeId(2)]), vec![NodeId(3)]);
switch_node.identifier = ProtoNodeIdentifier::new("math_nodes::SwitchNode");
let mut unbundle_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(3)]), vec![NodeId(4)]);
unbundle_node.identifier = ProtoNodeIdentifier::new("graphene_core::ops::UnbundleNode<f64>");
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(4),
nodes: vec![
(NodeId(0), condition_node),
(NodeId(1), if_true_node),
(NodeId(2), if_false_node),
(NodeId(3), switch_node),
(NodeId(4), unbundle_node),
],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context
.update(&network)
.expect("A List<f64> branch should resolve the Item<Bundle<f64>> row via the bundle wrap");
let promotions = typing_context.promotions(NodeId(3)).expect("The condition wrap and both branch bundles should be recorded");
let branch_bundles = promotions
.iter()
.filter(|(index, adapter)| *index != 0 && matches!(adapter, graph_craft::proto::Promotion::Bundle(_)))
.count();
assert_eq!(branch_bundles, 2, "Both scalar-list branches should bundle into one opaque cell");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The bundle, wrap, and unbundle adapters should instantiate");
let context: Context = None;
let result: Option<List<f64>> = futures::executor::block_on(tree.eval(NodeId(4), context));
let list = result.expect("The whole scalar list should round-trip through the bundle switch");
assert_eq!(list.len(), 2, "The true branch's whole list should be selected and preserved intact");
}
+2 -3
View File
@@ -5,7 +5,6 @@ pub mod util;
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use core_types::*; use core_types::*;
use futures::executor::block_on;
use graphene_core::ops::passthrough; use graphene_core::ops::passthrough;
#[test] #[test]
@@ -45,8 +44,8 @@ mod tests {
use graph_craft::graphene_compiler::Compiler; use graph_craft::graphene_compiler::Compiler;
let compiler = Compiler {}; let compiler = Compiler {};
let protograph = compiler.compile_single(network).expect("Graph should be generated"); let protograph = compiler.compile_single(network, &crate::node_registry::NODE_REGISTRY).expect("Graph should be generated");
let _exec = block_on(DynamicExecutor::new(protograph)).map(|_e| panic!("The network should not type check ")).unwrap_err(); let _exec = DynamicExecutor::new(protograph).map(|_e| panic!("The network should not type check ")).unwrap_err();
} }
} }
File diff suppressed because it is too large. Load diff
+12 -27
View File
@@ -29,21 +29,15 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
DocumentNode { DocumentNode {
call_argument: concrete!(Context), call_argument: concrete!(Context),
inputs: vec![NodeInput::import(core_types::Type::Fn(Box::new(concrete!(Context)), Box::new(generic!(T))), 0)], inputs: vec![NodeInput::import(core_types::Type::Fn(Box::new(concrete!(Context)), Box::new(generic!(T))), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::render_intermediate::IDENTIFIER), implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::render_intermediate_leveled::IDENTIFIER),
context_features: graphene_std::ContextDependencies { context_features: graphene_std::ContextDependencies::new(ContextFeatures::VARARGS, ContextFeatures::INDEX),
extract: ContextFeatures::VARARGS,
inject: ContextFeatures::INDEX,
},
..Default::default() ..Default::default()
}, },
DocumentNode { DocumentNode {
call_argument: concrete!(Context), call_argument: concrete!(Context),
inputs: vec![NodeInput::scope(graphene_std::platform_application_io::try_wgpu_executor::IDENTIFIER), NodeInput::node(NodeId(0), 0)], inputs: vec![NodeInput::scope(graphene_std::platform_application_io::try_wgpu_executor::IDENTIFIER), NodeInput::node(NodeId(0), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::render::IDENTIFIER), implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::render::IDENTIFIER),
context_features: graphene_std::ContextDependencies { context_features: graphene_std::ContextDependencies::new(ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, ContextFeatures::empty()),
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
inject: ContextFeatures::empty(),
},
..Default::default() ..Default::default()
}, },
DocumentNode { DocumentNode {
@@ -54,20 +48,14 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
NodeInput::node(NodeId(1), 0), NodeInput::node(NodeId(1), 0),
], ],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_cache::render_output_cache::IDENTIFIER), implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_cache::render_output_cache::IDENTIFIER),
context_features: graphene_std::ContextDependencies { context_features: graphene_std::ContextDependencies::new(ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, ContextFeatures::VARARGS),
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
inject: ContextFeatures::VARARGS,
},
..Default::default() ..Default::default()
}, },
DocumentNode { DocumentNode {
call_argument: concrete!(Context), call_argument: concrete!(Context),
inputs: vec![NodeInput::scope(graphene_std::render_pixel_preview::pixel_preview_pipeline::IDENTIFIER), NodeInput::node(NodeId(2), 0)], inputs: vec![NodeInput::scope(graphene_std::render_pixel_preview::pixel_preview_pipeline::IDENTIFIER), NodeInput::node(NodeId(2), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_pixel_preview::render_pixel_preview::IDENTIFIER), implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_pixel_preview::render_pixel_preview::IDENTIFIER),
context_features: graphene_std::ContextDependencies { context_features: graphene_std::ContextDependencies::new(ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS),
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
inject: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
},
..Default::default() ..Default::default()
}, },
DocumentNode { DocumentNode {
@@ -77,21 +65,18 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
NodeInput::node(NodeId(3), 0), NodeInput::node(NodeId(3), 0),
], ],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_background::render_background::IDENTIFIER), implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_background::render_background::IDENTIFIER),
context_features: graphene_std::ContextDependencies { context_features: graphene_std::ContextDependencies::new(ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, ContextFeatures::empty()),
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
inject: ContextFeatures::empty(),
},
..Default::default() ..Default::default()
}, },
DocumentNode { DocumentNode {
call_argument: concrete!(Context), call_argument: concrete!(Context),
inputs: vec![NodeInput::node(NodeId(4), 0)], inputs: vec![NodeInput::node(NodeId(4), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::create_context::IDENTIFIER), implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::create_context::IDENTIFIER),
context_features: graphene_std::ContextDependencies { // We add the extract index annotation here to force the compiler to add a context nullification node before this node so the render context is properly nullified so the render cache node can do its's work
// INDEX is never read; it forces a nullification and cache pair onto the `data` parameter's wire so the render cache keys on a stable context context_features: graphene_std::ContextDependencies::new(
extract: ContextFeatures::VARARGS | ContextFeatures::INDEX, ContextFeatures::INDEX | ContextFeatures::VARARGS,
inject: ContextFeatures::REAL_TIME | ContextFeatures::ANIMATION_TIME | ContextFeatures::POINTER_POSITION | ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, ContextFeatures::REAL_TIME | ContextFeatures::ANIMATION_TIME | ContextFeatures::POINTER_POSITION | ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
}, ),
..Default::default() ..Default::default()
}, },
] ]
@@ -114,7 +99,7 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
..Default::default() ..Default::default()
}, },
]; ];
let scope_injections = vec![("editor-api".to_string(), (NodeId(2), item!(&PlatformEditorApi)))]; let scope_injections = vec![("editor-api".to_string(), (NodeId(2), concrete!(std::sync::Arc<PlatformEditorApi>)))];
NodeNetwork { NodeNetwork {
exports: vec![NodeInput::node(NodeId(1), 0)], exports: vec![NodeInput::node(NodeId(1), 0)],
@@ -1,5 +1,4 @@
use core_types::transform::Footprint; use core_types::transform::Footprint;
use core_types::{Context, OwnedContextImpl};
use dyn_any::{DynAny, StaticType, StaticTypeSized}; use dyn_any::{DynAny, StaticType, StaticTypeSized};
use glam::DVec2; use glam::DVec2;
use graphene_hash::CacheHash; use graphene_hash::CacheHash;
@@ -23,6 +22,9 @@ pub trait ApplicationIo {
fn gpu_executor(&self) -> Option<&Self::Executor> { fn gpu_executor(&self) -> Option<&Self::Executor> {
None None
} }
fn gpu_executor_arc(&self) -> Option<Arc<Self::Executor>> {
None
}
fn load_resource(&self, hash: resource::ResourceHash) -> resource::ResourceFuture<'_>; fn load_resource(&self, hash: resource::ResourceHash) -> resource::ResourceFuture<'_>;
} }
@@ -33,6 +35,10 @@ impl<T: ApplicationIo> ApplicationIo for &T {
(**self).gpu_executor() (**self).gpu_executor()
} }
fn gpu_executor_arc(&self) -> Option<Arc<T::Executor>> {
(**self).gpu_executor_arc()
}
fn load_resource(&self, hash: resource::ResourceHash) -> resource::ResourceFuture<'_> { fn load_resource(&self, hash: resource::ResourceHash) -> resource::ResourceFuture<'_> {
(**self).load_resource(hash) (**self).load_resource(hash)
} }
@@ -85,13 +91,6 @@ pub struct RenderConfig {
pub for_eyedropper: bool, pub for_eyedropper: bool,
} }
impl RenderConfig {
/// Wraps this render configuration as the sole vararg of a fresh context, the call argument of a compiled network's boundary node.
pub fn into_context(self) -> Context<'static> {
OwnedContextImpl::default().with_vararg(Box::new(self)).into_context()
}
}
struct Logger; struct Logger;
impl NodeGraphUpdateSender for Logger { impl NodeGraphUpdateSender for Logger {
@@ -114,6 +113,7 @@ pub struct EditorApi<Io> {
pub node_graph_message_sender: Box<dyn NodeGraphUpdateSender + Send + Sync>, pub node_graph_message_sender: Box<dyn NodeGraphUpdateSender + Send + Sync>,
/// Editor preferences made available to the graph through the `PlatformEditorApi`. /// Editor preferences made available to the graph through the `PlatformEditorApi`.
pub editor_preferences: Box<dyn GetEditorPreferences + Send + Sync>, pub editor_preferences: Box<dyn GetEditorPreferences + Send + Sync>,
pub runtime: core_types::runtime::RuntimeHandle,
} }
impl<Io> Eq for EditorApi<Io> {} impl<Io> Eq for EditorApi<Io> {}
@@ -124,6 +124,7 @@ impl<Io: Default> Default for EditorApi<Io> {
application_io: None, application_io: None,
node_graph_message_sender: Box::new(Logger), node_graph_message_sender: Box::new(Logger),
editor_preferences: Box::new(DummyPreferences), editor_preferences: Box::new(DummyPreferences),
runtime: Default::default(),
} }
} }
} }
@@ -0,0 +1,870 @@
use std::any::TypeId;
use std::cell::UnsafeCell;
use std::collections::HashMap;
use std::marker::PhantomData;
use std::mem::MaybeUninit;
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
/// Handle word layout: 24 generation bits above 40 offset bits, so a 1 TiB arena is
/// addressable and generations run out after ~3 days of 60fps resets.
const OFFSET_BITS: u32 = 40;
const OFFSET_MASK: u64 = (1 << OFFSET_BITS) - 1;
const GENERATION_MASK: u64 = (1 << (64 - OFFSET_BITS)) - 1;
/// Out of the encodable range, so no handle, including `NULL`, matches it.
const PARKED_GENERATION: u64 = GENERATION_MASK + 1;
pub struct Arena {
generation: AtomicU64,
offset: AtomicUsize,
buf: Box<[UnsafeCell<MaybeUninit<u8>>]>,
drops: Mutex<Vec<DropEntry>>,
/// Set by a refused reservation and cleared by [`Arena::reset`], so a region
/// no evaluation resets can be seen to need one.
exhausted: AtomicBool,
/// Heap the parked payloads keep alive, which occupancy does not measure:
/// a park costs one pointer in the arena and owns its content outside it.
retained_heap: AtomicUsize,
/// Where [`Arena::move_park`] sent each moved park, as its offset here to
/// the header's address in the receiving arena, the moved type's key and
/// that arena's generation, so a payload two records share is moved once
/// while a mistyped sharer, a sharer naming another destination, and a
/// sharer whose destination has since flushed are all refused. Cleared by
/// [`Arena::reset`], so a forwarding holds for one generation.
forwarded: Mutex<HashMap<usize, (usize, TypeId, u64)>>,
}
impl std::fmt::Debug for Arena {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Arena").field("generation", &self.generation).field("size", &self.buf.len()).finish()
}
}
struct DropEntry {
offset: usize,
/// The parked payload's static-type key, `None` where the park was
/// allocated without one and so never moves.
type_of: Option<TypeId>,
drop_fn: unsafe fn(*mut u8),
/// The park glue's estimate of the heap this payload owns, 0 where the
/// glue cannot measure it, so the counter is a lower bound.
retained: usize,
}
/// The glue a tombstoned entry carries: its payload was moved to another arena,
/// which now owns the obligation.
///
/// # Safety
/// None: the payload is neither read nor dropped, so any pointer is accepted.
unsafe fn inert(_: *mut u8) {}
/// The entry parking `offset`, `None` where the arena holds no obligation for
/// it. Entries are pushed in reserve order, which is offset order, so the
/// search is exact; the scan covers a push order that concurrency interleaved.
fn entry_at(entries: &[DropEntry], offset: usize) -> Option<usize> {
let probe = entries.partition_point(|entry| entry.offset < offset);
match entries.get(probe).is_some_and(|entry| entry.offset == offset) {
true => Some(probe),
false => entries.iter().rposition(|entry| entry.offset == offset),
}
}
// SAFETY: disjoint regions are handed out by an atomic bump; a region is written
// only by its allocating caller before publication, and cross-thread hand-off is
// ordered by the Release/Acquire pair on the published handle word. Payloads are
// `Send + Sync` by the bound on every allocating method.
unsafe impl Sync for Arena {}
unsafe impl Send for Arena {}
impl std::panic::UnwindSafe for Arena {}
impl std::panic::RefUnwindSafe for Arena {}
/// Shared by all arenas, so a foreign handle misses like a stale one.
static NEXT_GENERATION: AtomicU64 = AtomicU64::new(1);
static LIVE_ARENAS: AtomicUsize = AtomicUsize::new(0);
/// `None` past [`GENERATION_MASK`], where a reissued generation would let an ancient
/// handle upgrade against a current arena. Recovered by `reset_generation_counter`.
fn next_generation() -> Option<u64> {
let generation = NEXT_GENERATION.fetch_add(1, Ordering::Relaxed);
(generation <= GENERATION_MASK).then_some(generation)
}
/// Rewinds the shared generation counter so previously issued values are reused.
/// Returns `false` without rewinding when an [`Arena`] is live at the time of the
/// check, which is a debugging aid rather than a guarantee.
///
/// # Safety
///
/// No [`ArenaWeak`] minted before this call may be upgraded afterwards. Dropping
/// every [`Arena`] is not sufficient, since nodes also hold handles in
/// [`ArenaCell`]s; those nodes must be dropped too. No arena may be constructed
/// concurrently either, since the live check and the rewind are separate steps.
pub unsafe fn reset_generation_counter() -> bool {
if LIVE_ARENAS.load(Ordering::Acquire) != 0 {
return false;
}
NEXT_GENERATION.store(1, Ordering::Release);
true
}
impl Arena {
pub fn new(capacity: usize) -> Option<Self> {
let generation = next_generation()?;
let buf = (0..capacity).map(|_| UnsafeCell::new(MaybeUninit::uninit())).collect();
LIVE_ARENAS.fetch_add(1, Ordering::Release);
Some(Self {
generation: AtomicU64::new(generation),
offset: AtomicUsize::new(0),
buf,
drops: Mutex::new(Vec::new()),
exhausted: AtomicBool::new(false),
retained_heap: AtomicUsize::new(0),
forwarded: Mutex::new(HashMap::new()),
})
}
/// An arena that refuses every allocation and resolves no handle, so a caller that
/// cannot fail can degrade instead of propagating exhaustion.
pub fn parked() -> Self {
LIVE_ARENAS.fetch_add(1, Ordering::Release);
Self {
generation: AtomicU64::new(PARKED_GENERATION),
offset: AtomicUsize::new(0),
buf: Box::new([]),
drops: Mutex::new(Vec::new()),
exhausted: AtomicBool::new(false),
retained_heap: AtomicUsize::new(0),
forwarded: Mutex::new(HashMap::new()),
}
}
/// Whether a reservation has been refused since the last [`Arena::reset`].
pub fn exhausted(&self) -> bool {
self.exhausted.load(Ordering::Relaxed)
}
pub fn generation(&self) -> u64 {
self.generation.load(Ordering::Acquire)
}
/// Bytes handed out since the last [`Arena::reset`], including alignment
/// padding, so a caller can flush at a boundary before a refusal.
pub fn occupancy(&self) -> usize {
self.offset.load(Ordering::Relaxed)
}
pub fn capacity(&self) -> usize {
self.buf.len()
}
/// The heap the parked payloads own, summed from the park glue's hints.
/// A lower bound: glue that cannot measure its payload contributes 0.
pub fn retained_heap(&self) -> usize {
self.retained_heap.load(Ordering::Relaxed)
}
/// Whether `ptr` addresses this arena's backbone, which is the provenance
/// question a promote asks of every parked reference.
pub fn contains(&self, ptr: *const u8) -> bool {
let base = self.base() as usize;
(ptr as usize).wrapping_sub(base) < self.buf.len()
}
fn base(&self) -> *mut u8 {
self.buf.as_ptr() as *mut u8
}
fn reserve(&self, size: usize, align: usize) -> Option<usize> {
debug_assert!(align.is_power_of_two());
let base = self.base() as usize;
let mut start = 0;
let reserved = self
.offset
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
// Alignment is computed on the absolute address; the backbone
// allocation itself has no alignment guarantee.
let addr = (base.checked_add(current)?.checked_add(align - 1)?) & !(align - 1);
start = addr - base;
let end = start.checked_add(size)?;
(end <= self.buf.len()).then_some(end)
})
.ok();
#[cfg(debug_assertions)]
{
static ARENA_TRACE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
if *ARENA_TRACE.get_or_init(|| std::env::var_os("GRAPHENE_ARENA_DEBUG").is_some()) {
static COUNT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let count = COUNT.fetch_add(1, Ordering::Relaxed);
if reserved.is_none() {
eprintln!("arena> EXHAUSTED after {count} allocations, wanted {size} bytes\n{}", std::backtrace::Backtrace::force_capture());
} else if count.is_multiple_of(20000) {
eprintln!("arena> {count} allocations, offset {}, this {size} bytes", self.offset.load(Ordering::Relaxed));
}
}
}
if reserved.is_none() {
self.exhausted.store(true, Ordering::Relaxed);
return None;
}
Some(start)
}
pub fn alloc<T: Send + Sync>(&self, value: T) -> Option<(&T, ArenaWeak<T>)> {
self.alloc_sized(value, 0)
}
/// [`Arena::alloc`] with the park glue's estimate of the heap `value` owns,
/// which the region's own occupancy cannot see.
pub fn alloc_sized<T: Send + Sync>(&self, value: T, retained: usize) -> Option<(&T, ArenaWeak<T>)> {
self.alloc_stamped(value, retained, None)
}
/// [`Arena::alloc_sized`] stamping the park's static-type key, which is what
/// [`Arena::move_park`] matches on, so only a park allocated here can move.
pub fn alloc_sized_keyed<T: Send + Sync + dyn_any::StaticTypeSized>(&self, value: T, retained: usize) -> Option<(&T, ArenaWeak<T>)> {
self.alloc_stamped(value, retained, Some(TypeId::of::<T::Static>()))
}
/// [`Arena::alloc_sized_keyed`] for park glue already holding the element's
/// static form, which projects the key from the element type instead of
/// from the value's own. Crate-private: a wrong key mistypes a move.
pub(crate) fn alloc_sized_as<T: Send + Sync>(&self, value: T, retained: usize, type_of: TypeId) -> Option<(&T, ArenaWeak<T>)> {
self.alloc_stamped(value, retained, Some(type_of))
}
fn alloc_stamped<T: Send + Sync>(&self, value: T, retained: usize, type_of: Option<TypeId>) -> Option<(&T, ArenaWeak<T>)> {
let offset = self.reserve(size_of::<T>(), align_of::<T>())?;
// Built before the write so an unencodable offset drops `value` here
// rather than stranding it in the arena without drop glue.
let weak = ArenaWeak::new(self.generation(), offset)?;
// SAFETY: `reserve` returned `offset`, so it is within the backbone.
let ptr = unsafe { self.base().add(offset) }.cast::<T>();
// SAFETY: freshly reserved, aligned, in-bounds, unaliased.
unsafe { ptr.write(value) };
if std::mem::needs_drop::<T>() {
/// # Safety
/// `p` must address the live `T` this entry was registered for.
unsafe fn glue<T>(p: *mut u8) {
// SAFETY: the caller's contract.
unsafe { p.cast::<T>().drop_in_place() }
}
self.drops.lock().unwrap().push(DropEntry {
offset,
type_of,
drop_fn: glue::<T>,
retained,
});
self.retained_heap.fetch_add(retained, Ordering::Relaxed);
}
// SAFETY: initialized above; insert-only, so no `&mut` to it can exist.
Some((unsafe { &*ptr }, weak))
}
/// Moves the payload at `src` out of this arena and into `dst`: the header's
/// own bytes are copied, its drop obligation is pushed onto `dst` with the
/// `retained` hint, and the entry here is tombstoned in place, its glue
/// swapped for [`inert`] so the reset costs nothing per entry to honour it.
/// The heap the payload owns is neither copied nor freed; ownership travels
/// with the obligation and is discharged by `dst`'s flush.
///
/// THE MOVE'S OWNERSHIP CONTRACT: the source header keeps its bytes and
/// stays readable to this generation's remaining sharers, but it owns
/// nothing, so no read of it may outlive `dst`'s flush. A payload moved
/// once is not moved again: its recorded destination is returned, so a
/// fan-out sharer's second move reaches the one header and the obligation
/// is never duplicated.
///
/// A forwarding is to one destination generation, since the returned
/// pointer is only the caller's to publish where it lands in the `dst` it
/// named: a second move to another arena, or to one that has flushed since,
/// is refused rather than answered with a foreign or freed header. The
/// refusal reads as a decline, so the caller takes its clone path.
///
/// `dst` is credited `retained`, which is what a clone of the payload would
/// have credited it, and this arena is debited what its own park recorded,
/// so neither counter reads worse than it did before the move.
///
/// The move republishes the payload at `T::Static`, which is the key both
/// [`Arena::alloc_sized_keyed`] and this stamp, so a park and its move
/// project the type exactly once each and agree by construction.
///
/// `None` where `src` is not this arena's park keyed to `T::Static`, where
/// the type is zero-sized (whose parks share an offset and so cannot be
/// told apart), or where `dst` refused the header.
///
/// # Safety
/// `src` must address a live `T`, and `T` must own all of its content: the
/// moved header may reference no storage of this arena, which is also what
/// lets the payload be republished at `T::Static`. The key settles the
/// type, so the caller owes no size or identity argument beyond those two.
pub unsafe fn move_park<T: dyn_any::StaticTypeSized>(&self, src: *const u8, dst: &Arena, retained: usize) -> Option<*const T::Static>
where
T::Static: Send + Sync,
{
(size_of::<T::Static>() != 0).then_some(())?;
let offset = (src as usize).checked_sub(self.base() as usize)?;
(offset < self.buf.len()).then_some(())?;
let type_of = TypeId::of::<T::Static>();
let mut forwarded = self.forwarded.lock().unwrap();
if let Some(&(moved, moved_type, moved_generation)) = forwarded.get(&offset) {
(moved_type == type_of).then_some(())?;
// Generations are globally unique, so the match is `dst` itself and
// its current epoch; anything else declines.
(moved_generation == dst.generation()).then_some(())?;
return Some(moved as *const T::Static);
}
let mut entries = self.drops.lock().unwrap();
let entry = entry_at(&entries, offset)?;
(entries[entry].type_of == Some(type_of)).then_some(())?;
let slot = dst.alloc_scratch::<T::Static>(1)?;
let target = slot.as_mut_ptr().cast::<T::Static>();
// SAFETY: the caller's contract on `src`, into a freshly reserved,
// aligned, unaliased slot of the same type.
unsafe { std::ptr::copy_nonoverlapping(src.cast::<T::Static>(), target, 1) };
let parked = std::mem::replace(&mut entries[entry].retained, 0);
entries[entry].drop_fn = inert;
drop(entries);
/// # Safety
/// `p` must address the live `T` this entry was registered for.
unsafe fn glue<T>(p: *mut u8) {
// SAFETY: the caller's contract.
unsafe { p.cast::<T>().drop_in_place() }
}
dst.drops.lock().unwrap().push(DropEntry {
offset: target as usize - dst.base() as usize,
type_of: Some(type_of),
drop_fn: glue::<T::Static>,
retained,
});
dst.retained_heap.fetch_add(retained, Ordering::Relaxed);
let _ = self.retained_heap.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| Some(current.saturating_sub(parked)));
forwarded.insert(offset, (target as usize, type_of, dst.generation()));
Some(target.cast_const())
}
pub fn alloc_slice_copy<T: Copy + Send + Sync>(&self, src: &[T]) -> Option<&[T]> {
let buf = self.alloc_scratch::<T>(src.len())?;
for (slot, &value) in buf.iter_mut().zip(src) {
slot.write(value);
}
// SAFETY: every lane written above from `src`.
Some(unsafe { std::slice::from_raw_parts(buf.as_ptr().cast::<T>(), src.len()) })
}
// Not drop-tracked: callers must either consume every written lane or
// restrict themselves to `Copy` payloads (leak, not UB, otherwise).
#[allow(clippy::mut_from_ref)]
pub fn alloc_scratch<T: Send + Sync>(&self, len: usize) -> Option<&mut [MaybeUninit<T>]> {
let size = size_of::<T>().checked_mul(len)?;
let offset = self.reserve(size, align_of::<T>())?;
// SAFETY: `reserve` returned `offset`, so it is within the backbone.
let ptr = unsafe { self.base().add(offset) }.cast::<MaybeUninit<T>>();
// SAFETY: exclusive region; lifetime tied to `&self`, and `reset` takes
// `&mut self`, so the slice cannot outlive the generation.
Some(unsafe { std::slice::from_raw_parts_mut(ptr, len) })
}
/// The generation-checked handle for a region this arena holds, `None` for
/// a pointer from anywhere else. The handle keeps the region's provenance,
/// so a cache stores one where it would otherwise launder an address.
///
/// The offset must sit below the bump watermark, not merely inside the
/// backbone: [`ArenaWeak::upgrade`] hands out a `&T` at it, so only bytes a
/// reservation already handed out may be minted into a handle.
pub fn handle_at(&self, ptr: *const u8) -> Option<ArenaWeak<u8>> {
let offset = (ptr as usize).checked_sub(self.base() as usize)?;
(offset < self.offset.load(Ordering::Acquire)).then_some(())?;
ArenaWeak::new(self.generation(), offset)
}
/// `false` once generations are exhausted, parking the arena on [`PARKED_GENERATION`]
/// where every handle misses and further allocation is refused.
///
/// A park [`Arena::move_park`] handed to another arena carries [`inert`]
/// glue and a zeroed hint, so it costs the loop nothing beyond the call it
/// would have made anyway.
pub fn reset(&mut self) -> bool {
let base = self.base();
let entries = std::mem::take(self.drops.get_mut().unwrap());
self.forwarded.get_mut().unwrap().clear();
self.generation.store(PARKED_GENERATION, Ordering::Release);
for entry in entries.into_iter().rev() {
// Debited before the glue runs: a panicking destructor drops the
// remaining entries unglued, so a hint subtracted afterwards would
// strand on the counter for the arena's whole life.
let retained = self.retained_heap.get_mut();
*retained = retained.saturating_sub(entry.retained);
// SAFETY: registered at alloc time; insert-only means the region was
// never overwritten within this generation.
unsafe { (entry.drop_fn)(base.add(entry.offset)) }
}
*self.offset.get_mut() = 0;
*self.exhausted.get_mut() = false;
let Some(generation) = next_generation() else { return false };
self.generation.store(generation, Ordering::Release);
true
}
}
impl Drop for Arena {
fn drop(&mut self) {
self.reset();
LIVE_ARENAS.fetch_sub(1, Ordering::Release);
}
}
pub struct ArenaWeak<T> {
word: u64,
_marker: PhantomData<fn() -> T>,
}
impl<T> Clone for ArenaWeak<T> {
fn clone(&self) -> Self {
*self
}
}
impl<T> Copy for ArenaWeak<T> {}
impl<T> ArenaWeak<T> {
pub const NULL: Self = ArenaWeak { word: 0, _marker: PhantomData };
/// `None` once either field leaves its encodable range, so an oversized or parked
/// arena refuses to hand out a handle rather than truncating it to a live address.
fn new(generation: u64, offset: usize) -> Option<Self> {
let offset = u64::try_from(offset).ok().filter(|offset| *offset <= OFFSET_MASK)?;
(generation <= GENERATION_MASK).then_some(Self {
word: (generation << OFFSET_BITS) | offset,
_marker: PhantomData,
})
}
pub fn upgrade(self, arena: &Arena) -> Option<&T> {
let generation = self.word >> OFFSET_BITS;
if generation != arena.generation() {
return None;
}
let offset = (self.word & OFFSET_MASK) as usize;
// SAFETY: same generation means the entry was fully written before its
// word was published (Release) and cannot move or be overwritten within
// a generation (insert-only); the Acquire load that produced this word
// ordered the payload writes.
Some(unsafe { &*arena.base().add(offset).cast::<T>() })
}
}
pub struct ArenaCell<T> {
word: AtomicU64,
_marker: PhantomData<fn() -> T>,
}
impl<T> Clone for ArenaCell<T> {
fn clone(&self) -> Self {
Self {
word: AtomicU64::new(self.word.load(Ordering::Acquire)),
_marker: PhantomData,
}
}
}
impl<T> std::fmt::Debug for ArenaCell<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ArenaCell").field("word", &self.word.load(Ordering::Relaxed)).finish()
}
}
impl<T> Default for ArenaCell<T> {
fn default() -> Self {
Self {
word: AtomicU64::new(0),
_marker: PhantomData,
}
}
}
impl<T> ArenaCell<T> {
pub fn new() -> Self {
Self::default()
}
pub fn load<'e>(&self, arena: &'e Arena) -> Option<&'e T> {
let weak = ArenaWeak::<T> {
word: self.word.load(Ordering::Acquire),
_marker: PhantomData,
};
weak.upgrade(arena)
}
pub fn store(&self, weak: ArenaWeak<T>) {
self.word.store(weak.word, Ordering::Release);
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::PoisonError;
use std::sync::atomic::AtomicU32;
#[test]
fn alloc_upgrade_reset_miss() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
let mut arena = Arena::new(1024).unwrap();
let cell = ArenaCell::new();
let (value, weak) = arena.alloc(41u32).unwrap();
assert_eq!(*value, 41);
cell.store(weak);
assert_eq!(cell.load(&arena), Some(&41));
arena.reset();
assert_eq!(cell.load(&arena), None, "stale handle must miss");
}
#[test]
fn capacity_survives_reset() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
let mut arena = Arena::new(64 + align_of::<u32>() - 1).unwrap();
for _ in 0..10 {
for _ in 0..16 {
assert!(arena.alloc(0u32).is_some());
}
assert!(arena.alloc(0u32).is_none(), "exhausted within generation");
arena.reset();
}
}
#[test]
fn panics_leave_the_arena_coherent() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
fn assert_ref_unwind_safe<T: std::panic::RefUnwindSafe>() {}
assert_ref_unwind_safe::<Arena>();
static DROPS: AtomicU32 = AtomicU32::new(0);
struct Probe(#[allow(dead_code)] String);
impl Drop for Probe {
fn drop(&mut self) {
DROPS.fetch_add(1, Ordering::Relaxed);
}
}
let mut arena = Arena::new(1024).unwrap();
let cell = ArenaCell::new();
let result = std::panic::catch_unwind(|| {
let (_, weak) = arena.alloc(Probe("pre-panic".into())).unwrap();
cell.store(weak);
panic!("mid-eval");
});
assert!(result.is_err());
assert!(cell.load(&arena).is_some(), "the generation is still live after the caught panic");
arena.reset();
assert_eq!(DROPS.load(Ordering::Relaxed), 1, "reset reclaims pre-panic allocations");
assert!(cell.load(&arena).is_none(), "the bump kills stale handles");
assert!(arena.alloc(0u32).is_some(), "the arena stays usable");
}
#[test]
fn a_panicking_destructor_leaves_no_resolvable_handle() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
struct Bomb;
impl Drop for Bomb {
fn drop(&mut self) {
panic!("payload destructor");
}
}
let mut arena = Arena::new(1024).unwrap();
let cell = ArenaCell::new();
let (_, weak) = arena.alloc(Bomb).unwrap();
cell.store(weak);
let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| arena.reset()));
assert!(unwound.is_err(), "the panic must propagate out of reset");
assert!(cell.load(&arena).is_none(), "a half-dropped generation must resolve no handle");
}
#[test]
fn handles_mint_only_over_reserved_bytes() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
let arena = Arena::new(1024).unwrap();
let (value, _) = arena.alloc(41u32).unwrap();
let ptr = std::ptr::from_ref(value).cast::<u8>();
assert!(arena.handle_at(ptr).is_some(), "a byte the bump handed out mints a handle");
let unreserved = ptr.wrapping_add(64);
assert!(arena.contains(unreserved), "the fixture stays inside the backbone");
assert!(arena.handle_at(unreserved).is_none(), "a byte past the watermark mints nothing");
}
#[test]
fn a_forwarding_answers_only_the_destination_it_recorded() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
struct Probe(#[allow(dead_code)] String);
unsafe impl dyn_any::StaticType for Probe {
type Static = Probe;
}
let transient = Arena::new(1024).unwrap();
let mut first = Arena::new(1024).unwrap();
let second = Arena::new(1024).unwrap();
let (parked, _) = transient.alloc_sized_keyed(Probe(String::from("shared by two records")), 21).unwrap();
let src = std::ptr::from_ref(parked).cast::<u8>();
unsafe { transient.move_park::<Probe>(src, &first, 21) }.unwrap();
assert!(unsafe { transient.move_park::<Probe>(src, &second, 21) }.is_none(), "a sharer naming another destination is refused");
first.reset();
assert!(unsafe { transient.move_park::<Probe>(src, &first, 21) }.is_none(), "a flushed destination is refused too");
}
#[test]
fn a_panicking_destructor_does_not_strand_the_retained_hint() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
struct Bomb;
impl Drop for Bomb {
fn drop(&mut self) {
panic!("payload destructor");
}
}
let mut arena = Arena::new(1024).unwrap();
arena.alloc_sized(Bomb, 64).unwrap();
assert_eq!(arena.retained_heap(), 64);
let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| arena.reset()));
assert!(unwound.is_err(), "the panic must propagate out of reset");
assert_eq!(arena.retained_heap(), 0, "the hint is debited before the glue that panics");
}
/// Held by every test that perturbs [`NEXT_GENERATION`], so a swapped-out counter
/// is never observed by a concurrently constructing test.
static COUNTER_GUARD: Mutex<()> = Mutex::new(());
#[test]
fn an_exhausted_reset_parks_the_arena_and_refuses_handles() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
let mut arena = Arena::new(1024).unwrap();
let (_, weak) = arena.alloc(41u32).unwrap();
let restore = NEXT_GENERATION.swap(GENERATION_MASK + 1, Ordering::Relaxed);
assert!(!arena.reset(), "an exhausted counter must report failure");
NEXT_GENERATION.store(restore, Ordering::Relaxed);
assert_eq!(weak.upgrade(&arena), None, "a parked arena resolves no handle");
assert_eq!(ArenaWeak::<u32>::NULL.upgrade(&arena), None, "not even the null handle");
assert!(arena.alloc(0u32).is_none(), "a parked arena refuses allocation");
}
#[test]
fn the_generation_counter_rewinds_only_without_live_arenas() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
let arena = Arena::new(64).unwrap();
assert!(!unsafe { reset_generation_counter() }, "a live arena must block the rewind");
drop(arena);
}
#[test]
fn handles_do_not_upgrade_against_a_foreign_arena() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
let first = Arena::new(1024).unwrap();
let second = Arena::new(1024).unwrap();
let (_, weak) = first.alloc(41u32).unwrap();
assert_eq!(weak.upgrade(&first), Some(&41));
assert_eq!(weak.upgrade(&second), None, "a handle must not resolve against another arena");
assert_eq!(ArenaWeak::<u32>::NULL.upgrade(&second), None, "the null handle never upgrades");
}
#[test]
fn reset_drops_dependents_before_their_dependencies() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
static ORDER: Mutex<Vec<u32>> = Mutex::new(Vec::new());
struct Probe(u32);
impl Drop for Probe {
fn drop(&mut self) {
ORDER.lock().unwrap().push(self.0);
}
}
let mut arena = Arena::new(1024).unwrap();
for id in 0..3 {
arena.alloc(Probe(id)).unwrap();
}
arena.reset();
assert_eq!(*ORDER.lock().unwrap(), vec![2, 1, 0], "later allocations may borrow earlier ones, so they drop first");
}
#[test]
fn sized_parks_account_for_their_retained_heap() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
let mut arena = Arena::new(1024).unwrap();
assert_eq!(arena.retained_heap(), 0);
let owned = String::from("retained by the park");
let length = owned.len();
arena.alloc_sized(owned, length).unwrap();
assert_eq!(arena.retained_heap(), length, "the park's hint reaches the counter");
arena.alloc(String::from("unmeasured")).unwrap();
assert_eq!(arena.retained_heap(), length, "an unmeasured park contributes nothing");
arena.reset();
assert_eq!(arena.retained_heap(), 0, "the flush frees every parked payload");
}
#[test]
fn a_moved_park_carries_its_heap_and_its_obligation() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
let mut transient = Arena::new(1024).unwrap();
let mut persistent = Arena::new(1024).unwrap();
let owned = String::from("moved, never cloned");
let length = owned.len();
let heap = owned.as_ptr();
let (parked, _) = transient.alloc_sized_keyed(owned, length).unwrap();
let src = std::ptr::from_ref(parked).cast::<u8>();
let moved = unsafe { transient.move_park::<String>(src, &persistent, length) }.unwrap();
assert_eq!(unsafe { &*moved }.as_ptr(), heap, "the move copies the header and leaves the heap where it was");
assert!(persistent.contains(moved.cast()), "the header lands in the receiving arena");
assert_eq!(transient.retained_heap(), 0, "the parking arena gives the hint up");
assert_eq!(persistent.retained_heap(), length, "and the receiving arena takes it");
transient.reset();
assert_eq!(unsafe { &*moved }, "moved, never cloned", "the parking arena's reset leaves a moved payload alone");
persistent.reset();
assert_eq!(persistent.retained_heap(), 0, "the receiving flush frees it");
}
#[test]
fn a_park_two_records_share_moves_once_and_frees_once() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
static DROPS: AtomicU32 = AtomicU32::new(0);
struct Probe(#[allow(dead_code)] String);
unsafe impl dyn_any::StaticType for Probe {
type Static = Probe;
}
impl Drop for Probe {
fn drop(&mut self) {
DROPS.fetch_add(1, Ordering::Relaxed);
}
}
DROPS.store(0, Ordering::Relaxed);
let mut transient = Arena::new(1024).unwrap();
let mut persistent = Arena::new(1024).unwrap();
let (parked, _) = transient.alloc_sized_keyed(Probe(String::from("shared by two records")), 21).unwrap();
let src = std::ptr::from_ref(parked).cast::<u8>();
let first = unsafe { transient.move_park::<Probe>(src, &persistent, 21) }.unwrap();
let second = unsafe { transient.move_park::<Probe>(src, &persistent, 21) }.unwrap();
assert_eq!(first, second, "the second move forwards to the header the first wrote");
assert_eq!(persistent.retained_heap(), 21, "the hint transfers once, not once per sharer");
transient.reset();
assert_eq!(DROPS.load(Ordering::Relaxed), 0, "a tombstoned entry is skipped by its arena's reset");
persistent.reset();
assert_eq!(DROPS.load(Ordering::Relaxed), 1, "the flush that owns the obligation frees it exactly once");
}
#[test]
fn a_move_refuses_a_mistyped_park_and_its_forwarding() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
struct Owner(#[allow(dead_code)] String);
unsafe impl dyn_any::StaticType for Owner {
type Static = Owner;
}
/// Owner's layout exactly, so only the type key tells the two apart.
struct Twin(#[allow(dead_code)] String);
unsafe impl dyn_any::StaticType for Twin {
type Static = Twin;
}
let mut transient = Arena::new(1024).unwrap();
let mut persistent = Arena::new(1024).unwrap();
let (parked, _) = transient.alloc_sized_keyed(Owner(String::from("a keyed park")), 0).unwrap();
let src = std::ptr::from_ref(parked).cast::<u8>();
assert!(
unsafe { transient.move_park::<Twin>(src, &persistent, 0) }.is_none(),
"a park of another type of the same size is refused"
);
unsafe { transient.move_park::<Owner>(src, &persistent, 0) }.unwrap();
assert!(unsafe { transient.move_park::<Twin>(src, &persistent, 0) }.is_none(), "the forwarding refuses the same mistype");
let (unkeyed, _) = transient.alloc(Owner(String::from("an unkeyed park"))).unwrap();
let src = std::ptr::from_ref(unkeyed).cast::<u8>();
assert!(unsafe { transient.move_park::<Owner>(src, &persistent, 0) }.is_none(), "a park allocated without a key never moves");
transient.reset();
persistent.reset();
}
#[test]
fn the_forwarding_map_lives_one_generation() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
static DROPS: AtomicU32 = AtomicU32::new(0);
struct Probe(#[allow(dead_code)] String);
unsafe impl dyn_any::StaticType for Probe {
type Static = Probe;
}
impl Drop for Probe {
fn drop(&mut self) {
DROPS.fetch_add(1, Ordering::Relaxed);
}
}
DROPS.store(0, Ordering::Relaxed);
let mut transient = Arena::new(1024).unwrap();
let mut persistent = Arena::new(1024).unwrap();
let (parked, _) = transient.alloc_sized_keyed(Probe(String::from("first generation")), 16).unwrap();
let src = std::ptr::from_ref(parked).cast::<u8>();
unsafe { transient.move_park::<Probe>(src, &persistent, 16) }.unwrap();
assert_eq!(transient.forwarded.lock().unwrap().len(), 1, "the move tombstoned the entry it left");
transient.reset();
assert!(transient.forwarded.lock().unwrap().is_empty(), "the tombstone set is empty after the reset");
transient.alloc_sized(Probe(String::from("second generation")), 16).unwrap();
transient.reset();
assert_eq!(DROPS.load(Ordering::Relaxed), 1, "a fresh park at a tombstoned offset drops normally");
persistent.reset();
assert_eq!(DROPS.load(Ordering::Relaxed), 2);
}
#[test]
fn occupancy_tracks_the_bump_and_clears_on_reset() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
let mut arena = Arena::new(1024).unwrap();
assert_eq!(arena.occupancy(), 0);
assert_eq!(arena.capacity(), 1024);
arena.alloc(0u64).unwrap();
assert_eq!(arena.occupancy(), 8);
arena.reset();
assert_eq!(arena.occupancy(), 0);
}
#[test]
fn containment_answers_only_for_this_arena() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
let first = Arena::new(1024).unwrap();
let second = Arena::new(1024).unwrap();
let (value, _) = first.alloc(41u32).unwrap();
let ptr = std::ptr::from_ref(value).cast::<u8>();
assert!(first.contains(ptr));
assert!(!second.contains(ptr));
assert!(!first.contains(std::ptr::null()));
let heap = Box::new(7u32);
assert!(!first.contains(std::ptr::from_ref(&*heap).cast::<u8>()), "heap the arena does not back is outside it");
}
#[test]
fn drop_glue_runs_on_reset() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
static DROPS: AtomicU32 = AtomicU32::new(0);
struct Probe(#[allow(dead_code)] String);
impl Drop for Probe {
fn drop(&mut self) {
DROPS.fetch_add(1, Ordering::Relaxed);
}
}
let mut arena = Arena::new(1024).unwrap();
arena.alloc(Probe("owns heap".into())).unwrap();
arena.alloc(Probe("me too".into())).unwrap();
assert_eq!(DROPS.load(Ordering::Relaxed), 0);
arena.reset();
assert_eq!(DROPS.load(Ordering::Relaxed), 2);
}
}
@@ -0,0 +1,815 @@
//! Attribute markers and their census. A marker declares an attribute name
//! once, fixing its value type and its name-specific default; the census
//! collects every declaration so name resolution, defaults, and diagnostics
//! run at graph compile time. One name belongs to one marker, so a name can
//! never mean two different types.
//!
//! Values are `Copy` and pack directly into record fields. Data with drop
//! glue rides the arena instead: the marker declares a reference value
//! (`&str`), the writing kernel parks the payload in the arena, and the
//! record field carries the eval-lifetime reference.
use crate::list::AnyAttributeValue;
use glam::{DAffine2, DVec2};
use std::any::TypeId;
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::marker::PhantomData;
use std::ops::Deref;
use std::sync::{LazyLock, Mutex};
/// Declares an attribute name: one marker per name, fixing the value type and
/// the name-specific default. Declare markers through the [`attribute!`]
/// macro, which also registers them into the [`ATTRIBUTE_REGISTRY`] and emits
/// an impl meeting the obligations below.
///
/// # Safety
///
/// [`REPARK`](Self::REPARK) must be `Some` for every marker whose
/// [`Value<'e>`](Self::Value) can carry a borrow shorter than `'static`. The
/// plain-value arm of the census writer retypes the value [`from_stored`] hands
/// it from the stored form's lifetime to the field's, which is only a relabel
/// where the value borrows nothing; a re-parking marker instead writes a
/// reference into the arena it is given.
///
/// [`from_stored`](Self::from_stored) must accept exactly the erased form
/// [`read_erased`](Self::read_erased) produces, and [`read_erased`] must read
/// its `ptr` as this marker's own `Value`. The two are each other's inverse
/// across every persistence seam, so a marker that reads one type and stores
/// another writes a value of the wrong type into the field.
pub unsafe trait Attribute: 'static {
/// The name as it appears in documents and diagnostics.
const NAME: &'static str;
/// The value type every read and write of this name shares. The lifetime
/// is the evaluation the value flows in; non-reference values ignore it.
/// The value outlives that evaluation, so its `'static` instantiation is
/// the one the census registers and layouts stamp their type id from.
///
/// `Send + Sync` because a record's bytes are these values: `RecordValue`
/// is `Send + Sync` over whatever the field writes put there, and the write
/// path never consults the census, so the bound has to sit here.
type Value<'e>: Copy + Default + std::fmt::Debug + Send + Sync + 'e;
/// The name-specific default, filled where an item lacks the attribute.
/// Producing a value for any `'e` from no inputs, reference defaults can
/// only point at `'static` data, which is what lets the census fill them
/// as plain bytes.
fn default<'e>() -> Self::Value<'e> {
Default::default()
}
/// Borrows the value out of legacy list storage, whose stored form is the
/// owned clone [`Self::read_erased`] produces. `None` where the column is
/// absent or holds another type.
fn from_stored<'a>(stored: &'a dyn std::any::Any) -> Option<Self::Value<'a>>;
/// # Safety
/// `ptr` must point at a live field of this marker's value type.
unsafe fn read_erased(ptr: *const u8) -> Box<dyn AnyAttributeValue>;
/// Re-parks the owned clone [`Self::read_erased`] produced into fresh
/// field storage; `None` for plain values, which ride the byte copy.
const REPARK: Option<crate::list::ReparkFn> = None;
}
/// A kernel-facing attribute value. A parameter `Attr<A>` is a read of `A`
/// (yielding the declared default where the attribute is absent upstream), an
/// `Attr<A>` in the return tuple is a write, and the same marker on both
/// sides is a modify.
pub struct Attr<'e, A: Attribute>(pub A::Value<'e>);
impl<'e, A: Attribute> Deref for Attr<'e, A> {
type Target = A::Value<'e>;
fn deref(&self) -> &A::Value<'e> {
&self.0
}
}
impl<'e, A: Attribute> Clone for Attr<'e, A> {
fn clone(&self) -> Self {
*self
}
}
impl<'e, A: Attribute> Copy for Attr<'e, A> {}
impl<'e, A: Attribute> std::fmt::Debug for Attr<'e, A> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple(A::NAME).field(&self.0).finish()
}
}
/// An attribute write that outlives the evaluation producing it: an async
/// source's slot persists across generations, so a reference value cannot
/// cross as itself. The value crosses deep-copied through the field glue and
/// parks into the serving arena at every lift, which is why the copy is paid
/// once per invocation rather than once per evaluation.
pub struct OwnedAttr<A: Attribute>(Box<dyn AnyAttributeValue>, PhantomData<fn() -> A>);
impl<A: Attribute> OwnedAttr<A> {
/// Deep-copies `value` out of the evaluation that produced it.
pub fn new(value: A::Value<'_>) -> Self {
// SAFETY: the read addresses a live local of the marker's value type.
let erased = unsafe { A::read_erased((&raw const value).cast()) };
OwnedAttr(crate::record::deepen_field_value(erased), PhantomData)
}
/// Parks the copy into `arena` for one evaluation; `None` reports arena
/// exhaustion.
pub fn park<'e>(&self, arena: &'e crate::arena::Arena) -> Option<A::Value<'e>> {
let resident = crate::record::replay_field_value(&*self.0, arena)?;
let mut value = A::default();
// SAFETY: the slot is a live field of the marker's value type, and the
// stored value is the copy `new` took at that same type.
unsafe { write_stored::<A>(resident.as_deref().unwrap_or(&*self.0), (&raw mut value).cast(), arena) }?;
Some(value)
}
}
impl<A: Attribute> Clone for OwnedAttr<A> {
fn clone(&self) -> Self {
OwnedAttr(self.0.clone(), PhantomData)
}
}
impl<A: Attribute> std::fmt::Debug for OwnedAttr<A> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple(A::NAME).field(&self.0.display_string()).finish()
}
}
/// A deletion of `A` in a node's return tuple: the name leaves the output
/// layout, so downstream reads yield the declared default again. Functionally
/// a write of the default; the value carries nothing.
pub struct RemoveAttr<A: Attribute>(PhantomData<A>);
impl<A: Attribute> RemoveAttr<A> {
pub const fn new() -> Self {
RemoveAttr(PhantomData)
}
}
impl<A: Attribute> Default for RemoveAttr<A> {
fn default() -> Self {
Self::new()
}
}
/// The value-type half of an attribute: everything [`Attribute`] declares
/// except the name and its name-specific default. A name-generic write pairs
/// one of these with a name taken from the graph, so the value type stays
/// concrete in the signature while the name varies per instance.
///
/// # Safety
///
/// The obligations are [`Attribute`]'s, at this trait's value type:
/// [`REPARK`](Self::REPARK) must be `Some` for every row whose
/// [`Value<'e>`](Self::Value) can carry a borrow shorter than `'static`, and
/// [`from_stored`](Self::from_stored) and [`read_erased`](Self::read_erased)
/// must be each other's inverse.
pub unsafe trait AttrValue: 'static {
/// The value type every write of this row shares, as [`Attribute::Value`].
type Value<'e>: Copy + Default + std::fmt::Debug + Send + Sync + 'e;
/// Borrows the value out of legacy list storage, as [`Attribute::from_stored`].
fn from_stored<'a>(stored: &'a dyn std::any::Any) -> Option<Self::Value<'a>>;
/// # Safety
/// `ptr` must point at a live field of this row's value type.
unsafe fn read_erased(ptr: *const u8) -> Box<dyn AnyAttributeValue>;
/// Re-parks an owned clone into fresh field storage, as [`Attribute::REPARK`].
const REPARK: Option<crate::list::ReparkFn> = None;
}
/// The [`Attribute::NAME`] a [`Named`] marker carries before the compiler
/// fills it. A layout never holds it: the fold replaces it with the
/// instance's constant, and a node whose name input is not constant is
/// refused at that same point.
pub const NAMED_PLACEHOLDER: &str = "";
/// A name-generic attribute write. `X` is a placeholder that distinguishes
/// name-generic attributes within one signature, so a node writing two of
/// them takes two names; `V` fixes the value type. The name is absent by
/// construction: it comes from the instance's constant text input, folded
/// into the layout at graph compile time, so a computed name cannot exist.
///
/// Written `Named<X>` in parameter position, it declares where `X`'s name is
/// wired: the macro gives that input constant text, and the kernel receives
/// only the placeholder, since a folded name is a layout fact rather than a
/// value the kernel needs.
pub struct Named<X, V = Text>(PhantomData<fn() -> (X, V)>);
impl<X, V> Default for Named<X, V> {
fn default() -> Self {
Named(PhantomData)
}
}
/// The placeholders a signature distinguishes its name-generic attributes by.
/// A node writing one name uses [`Name0`]; a second name on the same node
/// takes [`Name1`], and so on, which is all the placeholder has to do.
pub struct Name0;
/// The second name-generic attribute in one signature. See [`Name0`].
pub struct Name1;
/// The third name-generic attribute in one signature. See [`Name0`].
pub struct Name2;
// SAFETY: every obligation is discharged by `V`, which carries the same
// contract at the same value type; only the name differs, and the compiler
// fold replaces the placeholder before a layout sees it.
unsafe impl<X: 'static, V: AttrValue> Attribute for Named<X, V> {
const NAME: &'static str = NAMED_PLACEHOLDER;
type Value<'e> = V::Value<'e>;
fn from_stored<'a>(stored: &'a dyn std::any::Any) -> Option<Self::Value<'a>> {
V::from_stored(stored)
}
unsafe fn read_erased(ptr: *const u8) -> Box<dyn AnyAttributeValue> {
// SAFETY: the caller's contract, at `V`'s own value type.
unsafe { V::read_erased(ptr) }
}
const REPARK: Option<crate::list::ReparkFn> = V::REPARK;
}
/// The value a name-generic write takes off the wire, and the row it lands
/// in. A plain row is its own wire form; a reference row's wire form is the
/// owned payload the kernel parks in the arena, so the field can carry a
/// borrow of it for the evaluation.
pub trait WireValue: 'static {
/// The row this value is written at, fixing the field's value type.
type Row: AttrValue;
/// Moves the value into `arena` where the row borrows it, or hands it back
/// unchanged where the row stores it plainly. `None` reports exhaustion.
fn park<'e>(self, arena: &'e crate::arena::Arena) -> Option<<Self::Row as AttrValue>::Value<'e>>;
}
/// Declares [`WireValue`] rows. `for T` is a plain value, carried and stored
/// as itself; `Wire => Row` parks `Wire`'s payload in the arena and stores the
/// borrow `Row` names.
#[macro_export]
macro_rules! wire_value {
() => {};
(for $value:ty; $($rest:tt)*) => {
impl $crate::attribute::WireValue for $value {
type Row = $value;
fn park<'e>(self, _: &'e $crate::arena::Arena) -> ::core::option::Option<$value> {
::core::option::Option::Some(self)
}
}
$crate::wire_value!($($rest)*);
};
($wire:ty => $row:ty; $($rest:tt)*) => {
impl $crate::attribute::WireValue for $wire {
type Row = $row;
fn park<'e>(self, arena: &'e $crate::arena::Arena) -> ::core::option::Option<<$row as $crate::attribute::AttrValue>::Value<'e>> {
let (parked, _) = arena.alloc(self)?;
::core::option::Option::Some(::std::borrow::Borrow::borrow(parked))
}
}
$crate::wire_value!($($rest)*);
};
}
wire_value! {
for f64;
for u32;
for u64;
for bool;
for DVec2;
for DAffine2;
for crate::Color;
for crate::blending::BlendMode;
::std::vec::Vec<crate::uuid::NodeId> => NodeIdPath;
::std::string::String => Text;
}
/// Interns a folded attribute name for the `&'static str` a layout field
/// holds. Census names never reach here; a document's novel names are finite
/// and repeat across instances, so the leak is one allocation per name.
pub fn intern_name(name: &str) -> &'static str {
static NAMES: LazyLock<Mutex<std::collections::HashSet<&'static str>>> = LazyLock::new(|| Mutex::new(std::collections::HashSet::new()));
let mut names = NAMES.lock().unwrap();
if let Some(interned) = names.get(name) {
return interned;
}
let interned: &'static str = Box::leak(name.to_owned().into_boxed_str());
names.insert(interned);
interned
}
/// Declares [`AttrValue`] rows, the value types a name-generic attribute can
/// be written at. `for T` implements the row on an existing plain value type;
/// `Row: &T` and `Row: Option<&T>` declare a token naming a reference value,
/// whose payload the writing kernel parks in the arena.
///
/// ```ignore
/// core_types::named_value! {
/// /// Plain rows, implemented on the value type itself.
/// for f64;
/// /// A reference row, whose token names the borrowed value.
/// pub Text: &str;
/// }
/// ```
///
/// The `for T` arm implements this crate's trait on `T`, so rows over types
/// this crate does not own are declared here rather than by a caller.
#[macro_export]
macro_rules! named_value {
() => {};
($(#[$meta:meta])* for $value:ty; $($rest:tt)*) => {
// SAFETY: a plain value type cannot name `'e`, so no re-park is owed,
// and the two glue fns below are each other's inverse at `$value`.
unsafe impl $crate::attribute::AttrValue for $value {
type Value<'e> = $value;
fn from_stored<'a>(stored: &'a dyn ::std::any::Any) -> ::core::option::Option<Self::Value<'a>> {
stored.downcast_ref::<$value>().copied()
}
unsafe fn read_erased(ptr: *const u8) -> ::std::boxed::Box<dyn $crate::list::AnyAttributeValue> {
::std::boxed::Box::new(unsafe { ptr.cast::<$value>().read() })
}
}
$crate::named_value!($($rest)*);
};
($(#[$meta:meta])* $vis:vis $row:ident: Option<&$value:ty>; $($rest:tt)*) => {
$(#[$meta])*
$vis struct $row;
// SAFETY: the reference arm emits `REPARK`, and the two glue fns below
// are each other's inverse at `Option<&$value>`.
unsafe impl $crate::attribute::AttrValue for $row {
type Value<'e> = ::core::option::Option<&'e $value>;
fn from_stored<'a>(stored: &'a dyn ::std::any::Any) -> ::core::option::Option<Self::Value<'a>> {
stored
.downcast_ref::<::core::option::Option<<$value as ::std::borrow::ToOwned>::Owned>>()
.map(|owned| owned.as_ref().map(::std::borrow::Borrow::borrow))
}
unsafe fn read_erased(ptr: *const u8) -> ::std::boxed::Box<dyn $crate::list::AnyAttributeValue> {
::std::boxed::Box::new(unsafe { ptr.cast::<::core::option::Option<&$value>>().read() }.map(|value| <$value as ::std::borrow::ToOwned>::to_owned(value)))
}
const REPARK: ::core::option::Option<$crate::list::ReparkFn> = {
unsafe fn repark(value: &dyn $crate::list::AnyAttributeValue, dst: *mut u8, arena: &$crate::arena::Arena) -> ::core::option::Option<()> {
let owned: &::core::option::Option<<$value as ::std::borrow::ToOwned>::Owned> =
value.as_any().downcast_ref().expect("an optional reference row replays its owned clone");
let parked = match owned {
::core::option::Option::Some(owned) => {
let (parked, _) = arena.alloc(<$value as ::std::borrow::ToOwned>::to_owned(::std::borrow::Borrow::borrow(owned)))?;
::core::option::Option::Some(::std::borrow::Borrow::borrow(parked))
}
::core::option::Option::None => ::core::option::Option::None,
};
unsafe { dst.cast::<::core::option::Option<&$value>>().write(parked) };
::core::option::Option::Some(())
}
::core::option::Option::Some(repark)
};
}
$crate::named_value!($($rest)*);
};
($(#[$meta:meta])* $vis:vis $row:ident: &$value:ty; $($rest:tt)*) => {
$(#[$meta])*
$vis struct $row;
// SAFETY: the reference arm emits `REPARK`, and the two glue fns below
// are each other's inverse at `&$value`.
unsafe impl $crate::attribute::AttrValue for $row {
type Value<'e> = &'e $value;
fn from_stored<'a>(stored: &'a dyn ::std::any::Any) -> ::core::option::Option<Self::Value<'a>> {
stored.downcast_ref::<<$value as ::std::borrow::ToOwned>::Owned>().map(::std::borrow::Borrow::borrow)
}
unsafe fn read_erased(ptr: *const u8) -> ::std::boxed::Box<dyn $crate::list::AnyAttributeValue> {
::std::boxed::Box::new(unsafe { ptr.cast::<&$value>().read() }.to_owned())
}
const REPARK: ::core::option::Option<$crate::list::ReparkFn> = {
unsafe fn repark(value: &dyn $crate::list::AnyAttributeValue, dst: *mut u8, arena: &$crate::arena::Arena) -> ::core::option::Option<()> {
let owned: &<$value as ::std::borrow::ToOwned>::Owned = value.as_any().downcast_ref().expect("a reference row replays its owned clone");
let (parked, _) = arena.alloc(<$value as ::std::borrow::ToOwned>::to_owned(::std::borrow::Borrow::borrow(owned)))?;
unsafe { dst.cast::<&$value>().write(::std::borrow::Borrow::borrow(parked)) };
::core::option::Option::Some(())
}
::core::option::Option::Some(repark)
};
}
$crate::named_value!($($rest)*);
};
}
named_value! {
for f64;
for u32;
for u64;
for bool;
for DVec2;
for DAffine2;
for crate::Color;
for crate::blending::BlendMode;
/// A document node path, the value type of `editor:layer_path`.
pub NodeIdPath: &[crate::uuid::NodeId];
/// Free text, parked in the arena by the writing kernel.
pub Text: &str;
}
/// A census row: what is known about one declared attribute name.
#[derive(Clone, Copy, Debug)]
pub struct AttributeInfo {
pub name: &'static str,
pub value_type: TypeId,
pub value_type_name: &'static str,
pub default: fn() -> Box<dyn AnyAttributeValue>,
pub size: usize,
pub align: usize,
/// Writes the declared default's bytes into a `size`-long slice.
pub write_default_bytes: fn(&mut [u8]),
/// The marker's field form at the given level, for layouts built at runtime.
pub field_write_at: fn(u8) -> crate::record::FieldWrite,
/// Writes a legacy stored value into a field of this marker, parking
/// droppable payloads. A wrong-typed stored value leaves the field
/// untouched; `None` reports arena exhaustion.
///
/// `dst` must address a live field of *this row's* value type: the glue
/// writes its own `Value`'s worth of bytes there, so a caller resolving the
/// field by [`name`](Self::name) checks [`size`](Self::size) and
/// [`value_type`](Self::value_type) against the field first. The fields
/// here are public and the struct is `Copy`, so a row is a claim about a
/// marker rather than a proof about a field.
pub write_stored: unsafe fn(&dyn AnyAttributeValue, *mut u8, &crate::arena::Arena) -> Option<()>,
}
/// The default's object representation, staged through zeroed storage so a
/// value with padding or an unused payload (`Option<f64>`'s `None`) hands the
/// caller deterministic bytes rather than whatever the stack held.
fn write_default_bytes<A: Attribute>(out: &mut [u8]) {
assert_eq!(out.len(), size_of::<A::Value<'static>>());
let mut staged = std::mem::MaybeUninit::<A::Value<'static>>::zeroed();
staged.write(A::default());
// SAFETY: the staging holds a live value of the type `out` is sized for.
unsafe { std::ptr::copy_nonoverlapping(staged.as_ptr().cast::<u8>(), out.as_mut_ptr(), size_of::<A::Value<'static>>()) };
}
fn field_write_at<A: Attribute>(level: u8) -> crate::record::FieldWrite
where
A::Value<'static>: graphene_hash::CacheHash + PartialEq,
{
crate::record::FieldWrite::of::<A>(level)
}
/// # Safety
/// `dst` must address a live field of `A`'s value type.
unsafe fn write_stored<A: Attribute>(stored: &dyn AnyAttributeValue, dst: *mut u8, arena: &crate::arena::Arena) -> Option<()> {
if A::from_stored(stored.as_any()).is_none() {
// A wrong-typed stored value reads as absent, so the field keeps its default.
return Some(());
}
match A::REPARK {
// SAFETY: the caller's contract; the glue is this marker's own.
Some(repark) => unsafe { repark(stored, dst, arena) },
None => {
let value = A::from_stored(stored.as_any()).expect("checked above");
// SAFETY: a marker without re-park glue stores a plain value, so the bytes carry no borrowed data.
unsafe { dst.cast::<A::Value<'_>>().write(value) };
Some(())
}
}
}
/// All declared attribute names, keyed by name.
pub static ATTRIBUTE_REGISTRY: LazyLock<Mutex<HashMap<&'static str, AttributeInfo>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
/// Registers `A` into the census. Called by the [`attribute!`] expansion at
/// startup (ctor natively, a `__node_registry_attribute_*` export on wasm).
/// Re-registration at the same value type is idempotent; a second marker
/// claiming the name at a different value type panics.
pub fn register<A: Attribute>()
where
A::Value<'static>: AnyAttributeValue + graphene_hash::CacheHash + PartialEq,
{
let info = AttributeInfo {
name: A::NAME,
value_type: TypeId::of::<A::Value<'static>>(),
value_type_name: std::any::type_name::<A::Value<'static>>(),
default: || Box::new(A::default()),
size: size_of::<A::Value<'static>>(),
align: align_of::<A::Value<'static>>(),
write_default_bytes: write_default_bytes::<A>,
field_write_at: field_write_at::<A>,
write_stored: write_stored::<A>,
};
let conflict = match ATTRIBUTE_REGISTRY.lock().unwrap().entry(A::NAME) {
Entry::Vacant(vacant) => {
vacant.insert(info);
None
}
Entry::Occupied(occupied) => (occupied.get().value_type != info.value_type).then(|| occupied.get().value_type_name),
};
if let Some(existing) = conflict {
panic!("attribute `{}` is declared at two value types: {existing} and {}", A::NAME, info.value_type_name);
}
}
/// Looks up a declared name.
pub fn info(name: &str) -> Option<AttributeInfo> {
ATTRIBUTE_REGISTRY.lock().unwrap().get(name).copied()
}
/// The name-specific default for `name`, if the name is declared.
pub fn default_value(name: &str) -> Option<Box<dyn AnyAttributeValue>> {
info(name).map(|info| (info.default)())
}
/// Declares attribute markers: for each entry, the marker struct, its
/// [`Attribute`] impl, and the census registration.
///
/// ```
/// core_types::attribute! {
/// /// How visible the content is.
/// pub Opacity("opacity"): f64 = 1.;
/// /// The item's label, parked in the arena by the writer.
/// pub Label("label"): &str;
/// }
/// ```
///
/// The trailing `= expr` is the name-specific default; without it the value
/// type's `Default` applies. A `&T` value carries the eval lifetime, so its
/// default must be `'static` data. An `Option<&T>` value is an optional
/// parked reference whose default is `None`, for attributes whose absence
/// means something a present value cannot.
#[macro_export]
macro_rules! attribute {
() => {};
($(#[$meta:meta])* $vis:vis $marker:ident($name:literal): Option<&$value:ty>; $($rest:tt)*) => {
$(#[$meta])*
$vis struct $marker;
// SAFETY: the reference-valued arms emit `REPARK`, the plain arm's value
// type cannot name `'e`, and `read_erased` and `from_stored` are emitted
// as each other's inverse.
unsafe impl $crate::attribute::Attribute for $marker {
const NAME: &'static str = $name;
type Value<'e> = ::core::option::Option<&'e $value>;
fn from_stored<'a>(stored: &'a dyn ::std::any::Any) -> ::core::option::Option<Self::Value<'a>> {
stored
.downcast_ref::<::core::option::Option<<$value as ::std::borrow::ToOwned>::Owned>>()
.map(|owned| owned.as_ref().map(::std::borrow::Borrow::borrow))
}
unsafe fn read_erased(ptr: *const u8) -> ::std::boxed::Box<dyn $crate::list::AnyAttributeValue> {
::std::boxed::Box::new(unsafe { ptr.cast::<::core::option::Option<&$value>>().read() }.map(|value| <$value as ::std::borrow::ToOwned>::to_owned(value)))
}
const REPARK: ::core::option::Option<unsafe fn(&dyn $crate::list::AnyAttributeValue, *mut u8, &$crate::arena::Arena) -> ::core::option::Option<()>> = {
unsafe fn repark(value: &dyn $crate::list::AnyAttributeValue, dst: *mut u8, arena: &$crate::arena::Arena) -> ::core::option::Option<()> {
let owned: &::core::option::Option<<$value as ::std::borrow::ToOwned>::Owned> =
value.as_any().downcast_ref().expect("an optional reference attribute replays its owned clone");
let parked = match owned {
::core::option::Option::Some(owned) => {
let (parked, _) = arena.alloc(<$value as ::std::borrow::ToOwned>::to_owned(::std::borrow::Borrow::borrow(owned)))?;
::core::option::Option::Some(::std::borrow::Borrow::borrow(parked))
}
::core::option::Option::None => ::core::option::Option::None,
};
unsafe { dst.cast::<::core::option::Option<&$value>>().write(parked) };
::core::option::Option::Some(())
}
::core::option::Option::Some(repark)
};
}
$crate::attribute!(@register $marker);
$crate::attribute!($($rest)*);
};
($(#[$meta:meta])* $vis:vis $marker:ident($name:literal): &$value:ty $(= $default:expr)?; $($rest:tt)*) => {
$(#[$meta])*
$vis struct $marker;
// SAFETY: the reference-valued arms emit `REPARK`, the plain arm's value
// type cannot name `'e`, and `read_erased` and `from_stored` are emitted
// as each other's inverse.
unsafe impl $crate::attribute::Attribute for $marker {
const NAME: &'static str = $name;
type Value<'e> = &'e $value;
$(
fn default<'e>() -> Self::Value<'e> {
$default
}
)?
fn from_stored<'a>(stored: &'a dyn ::std::any::Any) -> ::core::option::Option<Self::Value<'a>> {
stored.downcast_ref::<<$value as ::std::borrow::ToOwned>::Owned>().map(::std::borrow::Borrow::borrow)
}
unsafe fn read_erased(ptr: *const u8) -> ::std::boxed::Box<dyn $crate::list::AnyAttributeValue> {
::std::boxed::Box::new(unsafe { ptr.cast::<&$value>().read() }.to_owned())
}
const REPARK: ::core::option::Option<unsafe fn(&dyn $crate::list::AnyAttributeValue, *mut u8, &$crate::arena::Arena) -> ::core::option::Option<()>> = {
unsafe fn repark(value: &dyn $crate::list::AnyAttributeValue, dst: *mut u8, arena: &$crate::arena::Arena) -> ::core::option::Option<()> {
let owned: &<$value as ::std::borrow::ToOwned>::Owned = value.as_any().downcast_ref().expect("a reference attribute replays its owned clone");
let (parked, _) = arena.alloc(<$value as ::std::borrow::ToOwned>::to_owned(::std::borrow::Borrow::borrow(owned)))?;
unsafe { dst.cast::<&$value>().write(::std::borrow::Borrow::borrow(parked)) };
::core::option::Option::Some(())
}
::core::option::Option::Some(repark)
};
}
$crate::attribute!(@register $marker);
$crate::attribute!($($rest)*);
};
($(#[$meta:meta])* $vis:vis $marker:ident($name:literal): $value:ty $(= $default:expr)?; $($rest:tt)*) => {
$(#[$meta])*
$vis struct $marker;
// SAFETY: the reference-valued arms emit `REPARK`, the plain arm's value
// type cannot name `'e`, and `read_erased` and `from_stored` are emitted
// as each other's inverse.
unsafe impl $crate::attribute::Attribute for $marker {
const NAME: &'static str = $name;
type Value<'e> = $value;
$(
fn default<'e>() -> Self::Value<'e> {
$default
}
)?
fn from_stored<'a>(stored: &'a dyn ::std::any::Any) -> ::core::option::Option<Self::Value<'a>> {
stored.downcast_ref::<$value>().copied()
}
unsafe fn read_erased(ptr: *const u8) -> ::std::boxed::Box<dyn $crate::list::AnyAttributeValue> {
::std::boxed::Box::new(unsafe { ptr.cast::<$value>().read() })
}
}
$crate::attribute!(@register $marker);
$crate::attribute!($($rest)*);
};
(@register $marker:ident) => {
const _: () = {
#[cfg(not(target_family = "wasm"))]
#[$crate::ctor::ctor]
fn register() {
$crate::attribute::register::<$marker>();
}
#[cfg(target_family = "wasm")]
#[unsafe(export_name = concat!("__node_registry_attribute_", stringify!($marker)))]
extern "C" fn register() {
$crate::attribute::register::<$marker>();
}
};
};
}
attribute! {
/// Item's `DAffine2` transformation, composed multiplicatively through nested groups.
pub Transform("transform"): DAffine2;
/// Item's `BlendMode`, controlling how it composites with content beneath it.
pub BlendMode("blend_mode"): crate::blending::BlendMode;
/// Item's opacity multiplier, composed multiplicatively through nested groups.
/// Affects content clipped to the item.
pub Opacity("opacity"): f64 = 1.;
/// Item's fill opacity multiplier. Like opacity but does not affect content clipped to the item.
pub OpacityFill("opacity_fill"): f64 = 1.;
/// Whether an item inherits the alpha of the content beneath it (clipping mask).
pub ClippingMask("clipping_mask"): bool;
/// The document node path of the editor layer owning the item.
/// Editor tools read it to route clicks and selection back to the originating layer.
pub EditorLayerPath("editor:layer_path"): &[crate::uuid::NodeId];
/// Maps the unit square `[(0, 0), (1, 1)]` (top-left convention) onto the 'Text' node's
/// text frame in this item's local space. Each item carries the frame relative to its own
/// glyph origin so it survives 'Index Elements' filtering. The Text tool reads this to
/// position its drag cage.
pub EditorTextFrame("editor:text_frame"): DAffine2;
/// Byte offset where a regex match begins ('Regex Find All' and 'Regex Capture' text nodes).
pub Start("start"): u64;
/// Byte offset where a regex match ends ('Regex Find All' and 'Regex Capture' text nodes).
pub End("end"): u64;
/// A regex named-capture-group's name, or empty for unnamed groups.
pub Name("name"): &str;
/// A JSON value's type (`"string"`, `"number"`, `"object"`, etc.) from 'JSON Query All'.
pub Type("type"): &str;
/// Artboard's top-left corner in document coordinates.
pub Location("location"): DVec2;
/// Artboard's width and height.
pub Dimensions("dimensions"): DVec2;
/// Artboard's background fill.
pub Background("background"): crate::Color;
/// Whether an artboard clips content to its bounds.
pub Clip("clip"): bool;
/// Text item's font size in document-space units.
pub FontSize("font_size"): f64 = 24.;
/// Text item's line height as a ratio of the font size.
pub LineHeight("line_height"): f64 = 1.2;
/// Text item's extra spacing between letters in document-space units.
pub LetterSpacing("letter_spacing"): f64;
/// Text item's maximum line-wrap width in document-space units.
pub MaxWidth("max_width"): Option<f64>;
/// Text item's maximum block height in document-space units, past which lines are not drawn.
pub MaxHeight("max_height"): Option<f64>;
/// Text item's faux-italic letter tilt angle in degrees.
pub LetterTilt("letter_tilt"): f64;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn census_carries_declared_names() {
let row = info("opacity").unwrap();
assert_eq!(row.value_type, TypeId::of::<f64>());
assert_eq!(info("transform").unwrap().value_type, TypeId::of::<DAffine2>());
assert_eq!(info("max_width").unwrap().value_type, TypeId::of::<Option<f64>>());
assert_eq!(info("background").unwrap().value_type, TypeId::of::<crate::Color>());
assert!(info("never_declared").is_none());
}
#[test]
fn name_specific_default_overrides_the_type_default() {
assert_eq!(<Opacity as Attribute>::default(), 1.);
assert_eq!(<Name as Attribute>::default(), "");
assert_eq!(<FontSize as Attribute>::default(), 24.);
assert_eq!(<LineHeight as Attribute>::default(), 1.2);
assert_eq!(<MaxWidth as Attribute>::default(), None);
}
#[test]
fn erased_default_downcasts_to_the_declared_type() {
let value = default_value("opacity_fill").unwrap();
assert_eq!(*value.as_any().downcast_ref::<f64>().unwrap(), 1.);
}
#[test]
fn reference_values_register_at_the_static_instantiation() {
let row = info("name").unwrap();
assert_eq!(row.value_type, TypeId::of::<&'static str>());
assert_eq!(row.size, size_of::<&str>());
}
#[test]
fn an_owned_reference_crossing_parks_into_the_serving_arena() {
let owned = OwnedAttr::<Name>::new("crossing");
let arena = crate::arena::Arena::new(1024).unwrap();
assert_eq!(owned.park(&arena).unwrap(), "crossing");
assert_eq!(owned.clone().park(&arena).unwrap(), "crossing", "the crossing parks again on every evaluation");
}
#[test]
fn an_owned_plain_crossing_rides_its_bytes() {
let arena = crate::arena::Arena::new(64).unwrap();
assert_eq!(OwnedAttr::<Opacity>::new(0.25).park(&arena).unwrap(), 0.25);
}
#[test]
fn an_exhausted_arena_refuses_an_owned_reference_crossing() {
let owned = OwnedAttr::<Name>::new("too long for this arena");
let arena = crate::arena::Arena::new(8).unwrap();
assert!(owned.park(&arena).is_none());
}
#[test]
fn reregistration_at_the_same_type_is_idempotent() {
register::<Opacity>();
register::<Opacity>();
assert_eq!(info("opacity").unwrap().value_type, TypeId::of::<f64>());
}
#[test]
#[should_panic(expected = "two value types")]
fn a_second_marker_at_a_different_type_panics() {
struct Conflict;
// SAFETY: `bool` borrows nothing, so the plain-value arm is the right one.
unsafe impl Attribute for Conflict {
const NAME: &'static str = "opacity";
type Value<'e> = bool;
fn from_stored<'a>(stored: &'a dyn std::any::Any) -> Option<Self::Value<'a>> {
stored.downcast_ref::<bool>().copied()
}
unsafe fn read_erased(ptr: *const u8) -> Box<dyn AnyAttributeValue> {
Box::new(unsafe { ptr.cast::<bool>().read() })
}
}
register::<Conflict>();
}
}
@@ -1,4 +1,5 @@
use crate::Color; use crate::Color;
use crate::lane::{LaneColumn, LaneSource};
use glam::{DAffine2, DVec2}; use glam::{DAffine2, DVec2};
#[derive(Clone, Copy, Default, Debug, PartialEq)] #[derive(Clone, Copy, Default, Debug, PartialEq)]
@@ -51,3 +52,62 @@ impl BoundingBox for Color {
RenderBoundingBox::Infinite RenderBoundingBox::Infinite
} }
} }
/// Combined bounding box of a lane source's elements, composing each lane's
/// transform attribute with the given transform.
pub fn lane_bounding_box<S: LaneSource>(source: &S, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox
where
S::Element: BoundingBox,
{
let mut combined_bounds = None;
let transforms = source.column::<crate::attribute::Transform>();
for lane in 0..source.lane_count() {
let Some(element) = source.element(lane) else { continue };
let lane_transform: DAffine2 = transforms.get(lane);
match element.bounding_box(transform * lane_transform, include_stroke) {
RenderBoundingBox::None => continue,
RenderBoundingBox::Infinite => return RenderBoundingBox::Infinite,
RenderBoundingBox::Rectangle(bounds) => match combined_bounds {
Some(existing) => combined_bounds = Some(crate::math::quad::Quad::combine_bounds(existing, bounds)),
None => combined_bounds = Some(bounds),
},
}
}
match combined_bounds {
Some(bounds) => RenderBoundingBox::Rectangle(bounds),
None => RenderBoundingBox::None,
}
}
/// As [`lane_bounding_box`], but `Infinite` lanes are skipped (rather than
/// propagating outward) so a finite sibling in a mixed group dictates the
/// framing.
pub fn lane_thumbnail_bounding_box<S: LaneSource>(source: &S, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox
where
S::Element: BoundingBox,
{
let mut combined_bounds = None;
let mut any_infinite = false;
let transforms = source.column::<crate::attribute::Transform>();
for lane in 0..source.lane_count() {
let Some(element) = source.element(lane) else { continue };
let lane_transform: DAffine2 = transforms.get(lane);
match element.thumbnail_bounding_box(transform * lane_transform, include_stroke) {
RenderBoundingBox::None => continue,
RenderBoundingBox::Infinite => any_infinite = true,
RenderBoundingBox::Rectangle(bounds) => match combined_bounds {
Some(existing) => combined_bounds = Some(crate::math::quad::Quad::combine_bounds(existing, bounds)),
None => combined_bounds = Some(bounds),
},
}
}
match (combined_bounds, any_infinite) {
(Some(bounds), _) => RenderBoundingBox::Rectangle(bounds),
(None, true) => RenderBoundingBox::Infinite,
(None, false) => RenderBoundingBox::None,
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,93 @@
//! The typed surface handed to an `extent(fn)` helper: the node's inputs in
//! declaration order, then the queried level. Values read without unsafe or
//! internal fields, upstream extents query per level, and the one blessed
//! context modification is per-copy derived promotion. Anything beyond this
//! vocabulary uses `extent_raw(fn)`, which keeps the full node/ctx/level form.
use crate::gpoll::{Extent, GPoll};
/// A wired value input; `get` evaluates the input and yields the typed element.
pub struct ValueIn<'a, T> {
read: &'a dyn Fn() -> GPoll<T>,
}
impl<'a, T> ValueIn<'a, T> {
pub fn new(read: &'a dyn Fn() -> GPoll<T>) -> Self {
Self { read }
}
pub fn get(&self) -> GPoll<T> {
(self.read)()
}
}
/// An upstream input's extents. For derived (per-copy) content the query runs
/// at the given copy's promoted context; `at` queries copy 0, the uniform
/// default. For ordinary inputs the copy is ignored.
pub struct ExtentIn<'a> {
query: &'a dyn Fn(u64, u8) -> GPoll<Extent>,
}
impl<'a> ExtentIn<'a> {
pub fn new(query: &'a dyn Fn(u64, u8) -> GPoll<Extent>) -> Self {
Self { query }
}
pub fn at(&self, level: LevelIn) -> GPoll<Extent> {
(self.query)(0, level.level)
}
pub fn at_copy(&self, copy: u64, level: LevelIn) -> GPoll<Extent> {
(self.query)(copy, level.level)
}
}
/// A ranked (`IList`) input materialized whole: `get` drives the batch and
/// yields the level as a [`List`](crate::node::List), for extents that depend
/// on the input's data rather than its counts alone. `total` answers the
/// subject's flat count without materializing, so count-shaped extents stay
/// cheap: a materializing extent inside another's subject multiplies, and
/// nested emitters turn that into a blowup.
pub struct ListIn<'a, T> {
get: &'a dyn Fn() -> GPoll<crate::node::List<'a, T>>,
total: &'a dyn Fn() -> GPoll<crate::gpoll::Extent>,
}
impl<'a, T> ListIn<'a, T> {
pub fn new(get: &'a dyn Fn() -> GPoll<crate::node::List<'a, T>>, total: &'a dyn Fn() -> GPoll<crate::gpoll::Extent>) -> Self {
Self { get, total }
}
pub fn get(&self) -> GPoll<crate::node::List<'a, T>> {
(self.get)()
}
/// The subject input's total flat extent as a plain query.
pub fn total(&self) -> GPoll<crate::gpoll::Extent> {
(self.total)()
}
}
/// The queried absolute level (innermost `0`), paired with the node's depth.
#[derive(Clone, Copy, Debug)]
pub struct LevelIn {
pub level: u8,
pub depth: u8,
}
impl LevelIn {
pub fn new(level: u8, depth: u8) -> Self {
Self { level, depth }
}
/// Whether the query targets the node's own pushed (outermost) level.
pub fn pushed(&self) -> bool {
self.level + 1 == self.depth
}
/// Whether the query targets the topmost level; `pushed` under the name a
/// non-creator (concat, remap) reads naturally.
pub fn top(&self) -> bool {
self.pushed()
}
}
@@ -1,17 +0,0 @@
use crate::Node;
use std::marker::PhantomData;
#[derive(Clone)]
pub struct FnNode<T: Fn(I) -> O, I, O>(T, PhantomData<(I, O)>);
impl<'i, T: Fn(I) -> O + 'i, O: 'i, I: 'i> Node<'i, I> for FnNode<T, I, O> {
type Output = O;
fn eval(&'i self, input: I) -> Self::Output {
self.0(input)
}
}
impl<T: Fn(I) -> O, I, O> FnNode<T, I, O> {
pub fn new(f: T) -> Self {
FnNode(f, PhantomData)
}
}
@@ -0,0 +1,290 @@
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ErrorKind {
Node(&'static str),
ArenaExhausted,
Panic,
/// A lane past the end of a lower-bound (`Extent::AtLeast`) level: the
/// end-of-data signal for draining consumers, an error for everyone else.
PastEnd,
}
impl PartialEq<&str> for ErrorKind {
fn eq(&self, other: &&str) -> bool {
matches!(self, ErrorKind::Node(kind) if kind == other)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GraphError {
pub kind: ErrorKind,
pub trace: Vec<usize>,
}
impl GraphError {
pub fn new(kind: &'static str) -> Self {
Self {
kind: ErrorKind::Node(kind),
trace: Vec::new(),
}
}
pub fn traced(mut self, input_index: usize) -> Self {
self.trace.push(input_index);
self
}
pub fn past_end() -> Self {
Self {
kind: ErrorKind::PastEnd,
trace: Vec::new(),
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum GPoll<T> {
Pending,
Final(T),
Partial(T),
Fallback(Box<(T, GraphError)>),
Error(Box<GraphError>),
}
impl<T> GPoll<T> {
#[inline(always)]
pub fn map<U>(self, f: impl FnOnce(T) -> U) -> GPoll<U> {
match self {
GPoll::Pending => GPoll::Pending,
GPoll::Final(value) => GPoll::Final(f(value)),
GPoll::Partial(value) => GPoll::Partial(f(value)),
GPoll::Fallback(boxed) => {
let (value, e) = *boxed;
GPoll::Fallback(Box::new((f(value), e)))
}
GPoll::Error(e) => GPoll::Error(e),
}
}
#[inline(always)]
pub fn and_then<U>(self, f: impl FnOnce(T) -> GPoll<U>) -> GPoll<U> {
match self {
GPoll::Pending => GPoll::Pending,
GPoll::Final(value) => f(value),
GPoll::Partial(value) => match f(value) {
GPoll::Final(result) => GPoll::Partial(result),
other => other,
},
GPoll::Fallback(boxed) => {
let (value, e) = *boxed;
match f(value) {
GPoll::Pending => GPoll::Pending,
GPoll::Final(result) | GPoll::Partial(result) => GPoll::Fallback(Box::new((result, e))),
GPoll::Fallback(inner) => {
let (result, _) = *inner;
GPoll::Fallback(Box::new((result, e)))
}
GPoll::Error(inner) => GPoll::Error(inner),
}
}
GPoll::Error(e) => GPoll::Error(e),
}
}
#[inline(always)]
pub fn zip<U>(self, other: GPoll<U>) -> GPoll<(T, U)> {
match (self, other) {
(GPoll::Error(e), _) | (_, GPoll::Error(e)) => GPoll::Error(e),
(GPoll::Pending, _) | (_, GPoll::Pending) => GPoll::Pending,
(GPoll::Final(a), GPoll::Final(b)) => GPoll::Final((a, b)),
(GPoll::Fallback(boxed), GPoll::Final(b) | GPoll::Partial(b)) => {
let (a, e) = *boxed;
GPoll::Fallback(Box::new(((a, b), e)))
}
(GPoll::Final(a) | GPoll::Partial(a), GPoll::Fallback(boxed)) => {
let (b, e) = *boxed;
GPoll::Fallback(Box::new(((a, b), e)))
}
(GPoll::Fallback(first), GPoll::Fallback(second)) => {
let (a, e) = *first;
let (b, _) = *second;
GPoll::Fallback(Box::new(((a, b), e)))
}
(GPoll::Partial(a), GPoll::Final(b) | GPoll::Partial(b)) | (GPoll::Final(a), GPoll::Partial(b)) => GPoll::Partial((a, b)),
}
}
#[inline(always)]
pub fn trace(self, input: usize) -> Self {
match self {
GPoll::Fallback(mut boxed) => {
boxed.1.trace.push(input);
GPoll::Fallback(boxed)
}
GPoll::Error(mut e) => {
e.trace.push(input);
GPoll::Error(e)
}
other => other,
}
}
pub fn fallback(value: T, kind: &'static str) -> Self {
GPoll::Fallback(Box::new((value, GraphError::new(kind))))
}
pub fn error(kind: &'static str) -> Self {
GPoll::Error(Box::new(GraphError::new(kind)))
}
pub fn arena_exhausted() -> Self {
GPoll::Error(Box::new(GraphError {
kind: ErrorKind::ArenaExhausted,
trace: Vec::new(),
}))
}
pub fn panicked() -> Self {
GPoll::Error(Box::new(GraphError {
kind: ErrorKind::Panic,
trace: Vec::new(),
}))
}
pub fn past_end() -> Self {
GPoll::Error(Box::new(GraphError::past_end()))
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum Interrupt {
Pending,
Error(Box<GraphError>),
}
impl From<GraphError> for Interrupt {
fn from(error: GraphError) -> Self {
Interrupt::Error(Box::new(error))
}
}
impl<T> From<Interrupt> for GPoll<T> {
fn from(interrupt: Interrupt) -> Self {
match interrupt {
Interrupt::Pending => GPoll::Pending,
Interrupt::Error(e) => GPoll::Error(e),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Extent {
Free,
Exactly(usize),
/// A sound lower bound; the true count is discoverable only by draining.
AtLeast(usize),
}
impl Extent {
pub fn meet(a: GPoll<Extent>, b: GPoll<Extent>) -> GPoll<Extent> {
a.zip(b).and_then(|(a, b)| match (a, b) {
(Extent::Free, other) | (other, Extent::Free) => GPoll::Final(other),
(Extent::Exactly(n), Extent::Exactly(m)) if n == m => GPoll::Final(Extent::Exactly(n)),
(Extent::AtLeast(a), Extent::AtLeast(b)) => GPoll::Final(Extent::AtLeast(a.max(b))),
(Extent::AtLeast(bound), Extent::Exactly(n)) | (Extent::Exactly(n), Extent::AtLeast(bound)) if n >= bound => GPoll::Final(Extent::Exactly(n)),
(Extent::AtLeast(_), Extent::Exactly(n)) | (Extent::Exactly(n), Extent::AtLeast(_)) => GPoll::fallback(Extent::Exactly(n), "extent mismatch"),
(Extent::Exactly(n), Extent::Exactly(m)) => GPoll::fallback(Extent::Exactly(n.min(m)), "extent mismatch"),
})
}
/// The product of two extents, used to compose nested-level counts; an
/// unbounded operand leaves the product unbounded, a lower-bound operand
/// keeps the product a lower bound.
pub fn mul(a: GPoll<Extent>, b: GPoll<Extent>) -> GPoll<Extent> {
a.zip(b).map(|(a, b)| match (a, b) {
(Extent::Free, _) | (_, Extent::Free) => Extent::Free,
(Extent::Exactly(n), Extent::Exactly(m)) => Extent::Exactly(n * m),
(Extent::AtLeast(n) | Extent::Exactly(n), Extent::AtLeast(m) | Extent::Exactly(m)) => Extent::AtLeast(n * m),
})
}
/// The sum of two extents, used to concatenate a level; a free operand
/// counts as one lane, so a scalar input joins a concat as a single item,
/// and a lower-bound operand keeps the sum a lower bound.
pub fn sum(a: GPoll<Extent>, b: GPoll<Extent>) -> GPoll<Extent> {
let lanes = |extent| match extent {
Extent::Exactly(count) | Extent::AtLeast(count) => count,
Extent::Free => 1,
};
a.zip(b).map(|(a, b)| match (a, b) {
(Extent::AtLeast(_), _) | (_, Extent::AtLeast(_)) => Extent::AtLeast(lanes(a) + lanes(b)),
_ => Extent::Exactly(lanes(a) + lanes(b)),
})
}
}
/// A query over a node's nesting levels: one level, the product below or above
/// it, or the whole domain. The composite [`Node::extent`](crate::node::Node::extent)
/// derives these from the per-level [`extent_at`](crate::node::Node::extent_at).
#[derive(Clone, Copy, Debug)]
pub enum Level {
At(u8),
Below(u8),
Above(u8),
Total,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Finality {
AllFinal,
Partial,
}
impl Finality {
pub fn meet(self, other: Finality) -> Finality {
match (self, other) {
(Finality::AllFinal, Finality::AllFinal) => Finality::AllFinal,
_ => Finality::Partial,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn free_is_the_meet_identity() {
let meet = Extent::meet(GPoll::Final(Extent::Free), GPoll::Final(Extent::Exactly(4)));
assert_eq!(meet, GPoll::Final(Extent::Exactly(4)));
}
#[test]
fn extent_mismatch_truncates_and_reports() {
let meet = Extent::meet(GPoll::Final(Extent::Exactly(3)), GPoll::Final(Extent::Exactly(5)));
let GPoll::Fallback(boxed) = meet else {
panic!("expected fallback, got {meet:?}");
};
assert_eq!(boxed.0, Extent::Exactly(3));
assert!(boxed.1.kind == "extent mismatch");
}
#[test]
fn error_dominates_pending_in_zip() {
let zipped = GPoll::<u32>::error("boom").zip(GPoll::<u32>::Pending);
assert!(matches!(zipped, GPoll::Error(_)));
}
#[test]
fn trace_builds_root_to_source_path() {
let poll = GPoll::<u32>::error("boom").trace(2).trace(0);
let GPoll::Error(e) = poll else { unreachable!() };
assert_eq!(e.trace, vec![2, 0]);
}
#[test]
fn interrupt_round_trips_to_gpoll() {
assert_eq!(GPoll::<u32>::from(Interrupt::Pending), GPoll::Pending);
let interrupt = Interrupt::from(GraphError::new("boom"));
assert!(matches!(GPoll::<u32>::from(interrupt), GPoll::Error(e) if e.kind == "boom"));
}
}
+177
View File
@@ -0,0 +1,177 @@
//! The read surface over a source of lanes, so readers name census markers
//! instead of a storage shape.
use crate::attribute::Attribute;
/// One marker's column on a source, resolved once so lane reads skip the key
/// lookup.
pub trait LaneColumn<'a, A: Attribute> {
/// The lane's value, `None` where the source carries no such column.
fn try_get(&self, lane: usize) -> Option<A::Value<'a>>;
/// The lane's value, falling back to the marker's census default.
fn get(&self, lane: usize) -> A::Value<'a> {
self.try_get(lane).unwrap_or_else(A::default)
}
}
/// A source of lanes carrying an element and census attributes.
pub trait LaneSource {
type Element;
type Column<'a, A: Attribute>: LaneColumn<'a, A>
where
Self: 'a;
fn lane_count(&self) -> usize;
fn element(&self, lane: usize) -> Option<&Self::Element>;
fn column<A: Attribute>(&self) -> Self::Column<'_, A>;
fn attr<A: Attribute>(&self, lane: usize) -> A::Value<'_> {
self.column::<A>().get(lane)
}
/// Distinguishes an absent column from one holding the census default.
fn try_attr<A: Attribute>(&self, lane: usize) -> Option<A::Value<'_>> {
self.column::<A>().try_get(lane)
}
}
/// A bare element as a one-lane source: no columns, so every marker reads its
/// census default. The read surface for a de-tabled leaf, whose attributes
/// ride the containing lane.
pub struct Single<'a, T>(pub &'a T);
/// The column of a [`Single`]: always absent, so reads fall to the census
/// default.
pub struct NoColumn;
impl<'a, A: Attribute> LaneColumn<'a, A> for NoColumn {
fn try_get(&self, _lane: usize) -> Option<A::Value<'a>> {
None
}
}
impl<T> LaneSource for Single<'_, T> {
type Element = T;
type Column<'a, A: Attribute>
= NoColumn
where
Self: 'a;
fn lane_count(&self) -> usize {
1
}
fn element(&self, lane: usize) -> Option<&T> {
(lane == 0).then_some(self.0)
}
fn column<A: Attribute>(&self) -> NoColumn {
NoColumn
}
}
impl<T: crate::bounds::BoundingBox> crate::bounds::BoundingBox for Single<'_, T> {
fn bounding_box(&self, transform: glam::DAffine2, include_stroke: bool) -> crate::bounds::RenderBoundingBox {
self.0.bounding_box(transform, include_stroke)
}
fn thumbnail_bounding_box(&self, transform: glam::DAffine2, include_stroke: bool) -> crate::bounds::RenderBoundingBox {
self.0.thumbnail_bounding_box(transform, include_stroke)
}
}
/// One lane of a source re-based as a one-lane source of a leaf element: the
/// de-tabled leaf read with its containing lane's attributes.
pub struct LeafLane<'a, S, T> {
source: &'a S,
index: usize,
element: &'a T,
}
impl<'a, S, T> LeafLane<'a, S, T> {
pub fn new(source: &'a S, index: usize, element: &'a T) -> Self {
Self { source, index, element }
}
}
pub struct LaneColumnAt<'a, S: LaneSource + 'a, A: Attribute> {
inner: S::Column<'a, A>,
index: usize,
}
impl<'a, S: LaneSource, A: Attribute> LaneColumn<'a, A> for LaneColumnAt<'a, S, A> {
fn try_get(&self, lane: usize) -> Option<A::Value<'a>> {
(lane == 0).then(|| self.inner.try_get(self.index)).flatten()
}
}
impl<S: LaneSource, T> LaneSource for LeafLane<'_, S, T> {
type Element = T;
type Column<'a, A: Attribute>
= LaneColumnAt<'a, S, A>
where
Self: 'a;
fn lane_count(&self) -> usize {
1
}
fn element(&self, lane: usize) -> Option<&T> {
(lane == 0).then_some(self.element)
}
fn column<A: Attribute>(&self) -> LaneColumnAt<'_, S, A> {
LaneColumnAt {
inner: self.source.column::<A>(),
index: self.index,
}
}
}
#[cfg(test)]
mod tests {
use super::LaneSource;
use crate::attribute::{EditorLayerPath, Opacity, Transform};
use crate::list::List;
use crate::uuid::NodeId;
use glam::DAffine2;
#[test]
fn a_plain_marker_reads_what_the_legacy_column_stores() {
let mut list = List::new_from_element(1u32);
let transform = DAffine2::from_translation((3., 4.).into());
list.set_attribute(crate::ATTR_TRANSFORM, 0, transform);
assert_eq!(list.attr::<Transform>(0), transform);
}
#[test]
fn an_absent_marker_reads_its_census_default_not_the_value_default() {
let list = List::new_from_element(1u32);
// `Opacity` declares `= 1.`, so the census default must win over `f64::default()`.
assert_eq!(list.attr::<Opacity>(0), 1.);
assert_eq!(list.attr::<Transform>(0), DAffine2::IDENTITY);
}
#[test]
fn a_reference_marker_borrows_the_stored_owned_form() {
let mut list = List::new_from_element(1u32);
let path = vec![NodeId(7), NodeId(9)];
list.set_attribute(crate::ATTR_EDITOR_LAYER_PATH, 0, path.clone());
assert_eq!(list.attr::<EditorLayerPath>(0), path.as_slice());
assert!(List::new_from_element(1u32).attr::<EditorLayerPath>(0).is_empty());
}
#[test]
fn a_column_of_the_wrong_stored_type_reads_as_absent() {
let mut list = List::new_from_element(1u32);
list.set_attribute(crate::ATTR_OPACITY, 0, "not an f64".to_string());
assert_eq!(list.attr::<Opacity>(0), 1.);
}
}
+31 -107
View File
@@ -1,17 +1,24 @@
extern crate log; extern crate log;
pub mod arena;
pub mod attribute;
pub mod bounds; pub mod bounds;
pub mod consts; pub mod consts;
pub mod context; pub mod context;
pub mod generic; pub mod extent;
pub mod gpoll;
pub mod lane;
pub mod list; pub mod list;
pub mod math; pub mod math;
pub mod memo; pub mod memo;
pub mod misc; pub mod misc;
pub mod node;
pub mod none; pub mod none;
pub mod ops; pub mod ops;
pub mod record;
pub mod registry; pub mod registry;
pub mod render_complexity; pub mod render_complexity;
pub mod runtime;
pub mod transform; pub mod transform;
pub mod uuid; pub mod uuid;
pub mod value; pub mod value;
@@ -25,9 +32,9 @@ pub use dyn_any::{StaticTypeSized, WasmNotSend, WasmNotSync};
pub use graphene_hash; pub use graphene_hash;
pub use graphene_hash::CacheHash; pub use graphene_hash::CacheHash;
pub use list::{ pub use list::{
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME, ATTR_END, ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_TEXT_FRAME, ATTR_END, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC,
ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_FORM, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_LETTER_SPACING, ATTR_GRADIENT_FORM, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION,
ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM, ATTR_TYPE, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TRANSFORM, ATTR_TYPE,
}; };
pub use memo::MemoHash; pub use memo::MemoHash;
pub use no_std_types::AsU32; pub use no_std_types::AsU32;
@@ -35,123 +42,40 @@ pub use no_std_types::blending;
pub use no_std_types::choice_type; pub use no_std_types::choice_type;
pub use no_std_types::color; pub use no_std_types::color;
pub use no_std_types::shaders; pub use no_std_types::shaders;
pub use node::Node;
pub use num_traits; pub use num_traits;
use std::any::TypeId;
use std::future::Future;
use std::pin::Pin;
#[cfg(feature = "wasm")] #[cfg(feature = "wasm")]
pub use tsify; pub use tsify;
pub use types::Cow; pub use types::Cow;
// pub trait Node: for<'n> NodeIO<'n> {
/// The node trait allows for defining any node. Nodes can only take one call argument input, however they can store references to other nodes inside the struct.
/// See `node-graph/README.md` for information on how to define a new node.
pub trait Node<'i, Input> {
type Output: 'i;
/// Evaluates the node with the single specified input.
fn eval(&'i self, input: Input) -> Self::Output;
/// Resets the node, e.g. the LetNode's cache is set to None.
fn reset(&self) {}
/// Returns the name of the node for diagnostic purposes.
fn node_name(&self) -> &'static str {
std::any::type_name::<Self>()
}
/// Serialize the node which is used for the `introspect` function which can retrieve values from monitor nodes.
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
log::warn!("Node::serialize not implemented for {}", std::any::type_name::<Self>());
None
}
}
mod types; mod types;
pub use types::*; pub use types::*;
pub trait NodeIO<'i, Input>: Node<'i, Input> pub trait InputAccessorSource<'a, T>: InputAccessorSourceIdentifier + std::fmt::Debug {
fn get_input(&'a self, index: usize) -> Option<&'a T>;
fn set_input(&'a mut self, index: usize, value: T);
}
pub trait InputAccessorSourceIdentifier {
fn has_identifier(&self, identifier: &str) -> bool;
}
pub trait InputAccessor<'n, Source: 'n>
where where
Self::Output: 'i + StaticTypeSized, Self: Sized,
Input: StaticTypeSized,
{ {
fn input_type(&self) -> TypeId { fn new_with_source(source: &'n Source) -> Option<Self>;
TypeId::of::<Input::Static>()
}
fn input_type_name(&self) -> &'static str {
std::any::type_name::<Input>()
}
fn output_type(&self) -> TypeId {
TypeId::of::<<Self::Output as StaticTypeSized>::Static>()
}
fn output_type_name(&self) -> &'static str {
std::any::type_name::<Self::Output>()
}
fn to_node_io(&self, inputs: Vec<Type>) -> NodeIOTypes {
NodeIOTypes {
call_argument: concrete!(<Input as StaticTypeSized>::Static),
return_value: concrete!(<Self::Output as StaticTypeSized>::Static),
inputs,
}
}
fn to_async_node_io(&self, inputs: Vec<Type>) -> NodeIOTypes
where
<Self::Output as Future>::Output: StaticTypeSized,
Self::Output: Future,
{
NodeIOTypes {
call_argument: concrete!(<Input as StaticTypeSized>::Static),
return_value: future!(<<Self::Output as Future>::Output as StaticTypeSized>::Static),
inputs,
}
}
} }
impl<'i, N: Node<'i, I>, I> NodeIO<'i, I> for N pub trait NodeInputDecleration {
where
N::Output: 'i + StaticTypeSized,
I: StaticTypeSized,
{
}
impl<'i, I: 'i, N: Node<'i, I> + ?Sized> Node<'i, I> for &'i N {
type Output = N::Output;
fn eval(&'i self, input: I) -> N::Output {
(*self).eval(input)
}
}
impl<'i, I: 'i, O: 'i, N: Node<'i, I, Output = O> + ?Sized> Node<'i, I> for Box<N> {
type Output = O;
fn eval(&'i self, input: I) -> O {
(**self).eval(input)
}
}
impl<'i, I: 'i, O: 'i, N: Node<'i, I, Output = O> + ?Sized> Node<'i, I> for std::sync::Arc<N> {
type Output = O;
fn eval(&'i self, input: I) -> O {
(**self).eval(input)
}
}
impl<'i, I, O: 'i> Node<'i, I> for Pin<Box<dyn Node<'i, I, Output = O> + 'i>> {
type Output = O;
fn eval(&'i self, input: I) -> O {
(**self).eval(input)
}
}
impl<'i, I, O: 'i> Node<'i, I> for Pin<&'i (dyn NodeIO<'i, I, Output = O> + 'i)> {
type Output = O;
fn eval(&'i self, input: I) -> O {
(**self).eval(input)
}
}
/// A compile-time symbol naming one parameter of one proto node.
/// The node macro generates a unit struct implementing this for every parameter, so code can pass the type itself (e.g. `stroke::WeightInput`) instead of a raw input index.
pub trait NodeParameter {
/// The proto node this parameter belongs to.
const NODE_IDENTIFIER: ProtoNodeIdentifier;
/// Position of this parameter among the node's inputs.
/// Prefer passing the symbol to an API that accepts it; reach for this only at genuinely index-based boundaries.
const INDEX: usize; const INDEX: usize;
fn identifier() -> ProtoNodeIdentifier;
type Result;
} }
/// Master spells this trait `NodeParameter`; our node macro emits `NodeInputDecleration`.
pub use NodeInputDecleration as NodeParameter;
/// A runtime reference to one parameter of one proto node, for heterogeneous tables and runtime-chosen parameters. /// A runtime reference to one parameter of one proto node, for heterogeneous tables and runtime-chosen parameters.
/// Convert a symbol with `.into()`; unlike a raw index, the node identifier and index always stay paired. /// Convert a symbol with `.into()`; unlike a raw index, the node identifier and index always stay paired.
#[derive(Debug, Clone, PartialEq, Eq, Hash)] #[derive(Debug, Clone, PartialEq, Eq, Hash)]
@@ -163,7 +87,7 @@ pub struct ParameterRef {
impl<P: NodeParameter> From<P> for ParameterRef { impl<P: NodeParameter> From<P> for ParameterRef {
fn from(_: P) -> Self { fn from(_: P) -> Self {
ParameterRef { ParameterRef {
node_identifier: P::NODE_IDENTIFIER, node_identifier: P::identifier(),
input_index: P::INDEX, input_index: P::INDEX,
} }
} }
+155 -151
View File
@@ -1,5 +1,5 @@
use crate::attribute::Attribute as _;
use crate::bounds::{BoundingBox, RenderBoundingBox}; use crate::bounds::{BoundingBox, RenderBoundingBox};
use crate::math::quad::Quad;
use crate::transform::ApplyTransform; use crate::transform::ApplyTransform;
use crate::uuid::NodeId; use crate::uuid::NodeId;
use dyn_any::{DynAny, StaticType, StaticTypeSized}; use dyn_any::{DynAny, StaticType, StaticTypeSized};
@@ -10,118 +10,63 @@ use std::fmt::Debug;
// ================================================= // =================================================
// Standard attribute keys used across the data flow // Standard attribute keys used across the data flow
// ================================================= // =================================================
// Each name is declared once by its marker, which documents the attribute and
// fixes its value type. The constants re-export the markers' names for the
// string-keyed legacy readers and writers. Markers whose value types live
// below core-types are declared in their types' crates (vector-types, the
// text nodes, graphic-types), each with its own name constants.
/// Item's `DAffine2` transformation, composed multiplicatively through nested groups. pub const ATTR_TRANSFORM: &str = crate::attribute::Transform::NAME;
pub const ATTR_TRANSFORM: &str = "transform"; pub const ATTR_BLEND_MODE: &str = crate::attribute::BlendMode::NAME;
/// Item's `BlendMode`, controlling how it composites with content beneath it. pub const ATTR_OPACITY: &str = crate::attribute::Opacity::NAME;
pub const ATTR_BLEND_MODE: &str = "blend_mode"; pub const ATTR_OPACITY_FILL: &str = crate::attribute::OpacityFill::NAME;
/// Item's opacity multiplier (`f64`, implicit default `1.`). pub const ATTR_CLIPPING_MASK: &str = crate::attribute::ClippingMask::NAME;
/// Composed multiplicatively through nested groups. Affects content clipped to the item. pub const ATTR_EDITOR_LAYER_PATH: &str = crate::attribute::EditorLayerPath::NAME;
pub const ATTR_OPACITY: &str = "opacity"; pub const ATTR_EDITOR_TEXT_FRAME: &str = crate::attribute::EditorTextFrame::NAME;
/// Item's fill opacity multiplier (`f64`, implicit default `1.`). pub const ATTR_START: &str = crate::attribute::Start::NAME;
/// Like opacity but does not affect content clipped to the item. pub const ATTR_END: &str = crate::attribute::End::NAME;
pub const ATTR_OPACITY_FILL: &str = "opacity_fill"; pub const ATTR_NAME: &str = crate::attribute::Name::NAME;
/// `bool` for whether an item inherits the alpha of the content beneath it (clipping mask). pub const ATTR_TYPE: &str = crate::attribute::Type::NAME;
pub const ATTR_CLIPPING_MASK: &str = "clipping_mask"; pub const ATTR_LOCATION: &str = crate::attribute::Location::NAME;
/// `NodeIdPath` path from the root network to the layer node owning this item. pub const ATTR_DIMENSIONS: &str = crate::attribute::Dimensions::NAME;
/// Used by editor tools to route clicks/selection back to the originating layer. pub const ATTR_BACKGROUND: &str = crate::attribute::Background::NAME;
pub const ATTR_EDITOR_LAYER_PATH: &str = "editor:layer_path"; pub const ATTR_CLIP: &str = crate::attribute::Clip::NAME;
/// `List<Graphic>` snapshot of the upstream content that fed into a destructive merge pub const ATTR_FONT_SIZE: &str = crate::attribute::FontSize::NAME;
/// (Boolean Operation, Rasterize, etc.), so the editor can still surface click targets for pub const ATTR_LINE_HEIGHT: &str = crate::attribute::LineHeight::NAME;
/// the original child layers after their content has been collapsed. pub const ATTR_LETTER_SPACING: &str = crate::attribute::LetterSpacing::NAME;
pub const ATTR_EDITOR_MERGED_LAYERS: &str = "editor:merged_layers"; pub const ATTR_MAX_WIDTH: &str = crate::attribute::MaxWidth::NAME;
/// Optional `Vector` that overrides the item's own geometry for click-target generation. pub const ATTR_MAX_HEIGHT: &str = crate::attribute::MaxHeight::NAME;
/// Used by the 'Text' node for per-glyph bounding-box rectangles so glyphs are selectable pub const ATTR_LETTER_TILT: &str = crate::attribute::LetterTilt::NAME;
/// by clicking anywhere within their bounds, not just the filled letterform.
pub const ATTR_EDITOR_CLICK_TARGET: &str = "editor:click_target"; // Name aliases for markers declared below core-types, so code here and in
/// `DAffine2` mapping the unit square `[(0, 0), (1, 1)]` (top-left convention) onto the 'Text' // sibling crates can spell the name without depending on the owning crate.
/// node's text frame in this item's local space. Each item carries the frame relative to its own // The marker, and with it the value type and the default, lives in the crate
/// glyph origin so it survives `Index Elements` filtering. The Text tool reads this to position // named beside each name; these are the string only.
/// its drag cage. Stored as an affine to allow non-axis-aligned frames in the future. // vector-types (gradient and stroke coverage):
pub const ATTR_EDITOR_TEXT_FRAME: &str = "editor:text_frame";
/// `u64` byte offset where a regex match begins ('Regex Find All', 'Regex Capture' text nodes).
pub const ATTR_START: &str = "start";
/// `u64` byte offset where a regex match ends ('Regex Find All', 'Regex Capture' text nodes).
pub const ATTR_END: &str = "end";
/// `String` for a regex named-capture-group's name, or empty for unnamed groups ('Regex Capture' text node).
pub const ATTR_NAME: &str = "name";
/// `String` for a JSON value's type (`"string"`, `"number"`, `"object"`, etc.) from 'JSON Query All'.
pub const ATTR_TYPE: &str = "type";
/// Artboard's `DVec2` top-left corner in document coordinates.
pub const ATTR_LOCATION: &str = "location";
/// Artboard's `DVec2` width and height.
pub const ATTR_DIMENSIONS: &str = "dimensions";
/// Artboard's `Color` background fill.
pub const ATTR_BACKGROUND: &str = "background";
/// `bool` for whether an artboard clips content to its bounds.
pub const ATTR_CLIP: &str = "clip";
// TODO: Consider adding "gradient_spread_left" and "gradient_spread_right" override attributes to allow setting different gradient spreads on each side of a gradient
/// Gradient's `GradientSpread` (`Pad`, `Reflect`, `Repeat`, or `Clear`).
pub const ATTR_GRADIENT_SPREAD: &str = "gradient_spread"; pub const ATTR_GRADIENT_SPREAD: &str = "gradient_spread";
/// Gradient's `GradientForm` (`Linear` or `Radial`).
pub const ATTR_GRADIENT_FORM: &str = "gradient_form"; pub const ATTR_GRADIENT_FORM: &str = "gradient_form";
/// Gradient's `GradientSpace`, the color space its stops interpolate in.
pub const ATTR_GRADIENT_SPACE: &str = "gradient_space"; pub const ATTR_GRADIENT_SPACE: &str = "gradient_space";
/// Gradient's `GradientHueDirection` (`Shorter`, `Longer`, `Increasing`, or `Decreasing`), which way around the
/// hue wheel the stops interpolate when the gradient space is polar.
pub const ATTR_GRADIENT_HUE_DIRECTION: &str = "gradient_hue_direction"; pub const ATTR_GRADIENT_HUE_DIRECTION: &str = "gradient_hue_direction";
/// Gradient's `GradientInterpolation` (`Stepped`, `Linear`, or `Smooth`), the path its stops interpolate along
/// and thus whether the ramp jumps, turns corners, or flows smoothly through them.
pub const ATTR_GRADIENT_INTERPOLATION: &str = "gradient_interpolation"; pub const ATTR_GRADIENT_INTERPOLATION: &str = "gradient_interpolation";
/// Gradient's `bool` (implicit default `false`) for treating the stop list as a cycle, where a wrapped interval
/// interpolates from the last stop through the 1|0 boundary back to the first.
pub const ATTR_GRADIENT_CYCLIC: &str = "gradient_cyclic"; pub const ATTR_GRADIENT_CYCLIC: &str = "gradient_cyclic";
/// Gradient stop's `f64` position from 0 to 1 along the gradient, on the `List<Color>` inside a `Gradient`.
/// When the attribute is absent, stops distribute evenly across the 0 to 1 range.
pub const ATTR_POSITION: &str = "position"; pub const ATTR_POSITION: &str = "position";
/// Gradient stop's `f64` midpoint (implicit default `0.5`, linear), a factor from 0 to 1 across the distance to the next
/// stop, on the `List<Color>` inside a `Gradient`. The final stop's midpoint is ignored if "gradient_cyclic" is false.
pub const ATTR_MIDPOINT: &str = "midpoint"; pub const ATTR_MIDPOINT: &str = "midpoint";
/// Item's ordered list of paint passes, of type `Appearance`. Earlier coverages paint first, compositing below later ones.
pub const ATTR_APPEARANCE: &str = "appearance";
// TODO: Add a "fill_rule" attribute as a sibling of "paint" on the coverage list (uniform across covers) once a FillRule type ships
/// Coverage's `Graphic` paint (implicit default `Graphic::None`, painting nothing), on the
/// `List<Coverage>` inside an `Appearance`.
pub const ATTR_PAINT: &str = "paint";
/// Stroke coverage's line thickness (`f64`, implicit default `0.`), on the `Item<Cover>` inside a `Coverage`.
pub const ATTR_WEIGHT: &str = "weight"; pub const ATTR_WEIGHT: &str = "weight";
/// Stroke coverage's `DashPattern` (implicit default empty, a solid line), on the `Item<Cover>` inside a `Coverage`.
pub const ATTR_DASH_PATTERN: &str = "dash_pattern";
/// Stroke coverage's dash phase offset distance (`f64`, implicit default `0.`), on the `Item<Cover>` inside a `Coverage`.
pub const ATTR_DASH_OFFSET: &str = "dash_offset"; pub const ATTR_DASH_OFFSET: &str = "dash_offset";
/// Stroke coverage's `StrokeCap` (implicit default `Butt`), on the `Item<Cover>` inside a `Coverage`.
pub const ATTR_CAP: &str = "cap"; pub const ATTR_CAP: &str = "cap";
/// Stroke coverage's `StrokeJoin` (implicit default `Miter`), on the `Item<Cover>` inside a `Coverage`.
pub const ATTR_JOIN: &str = "join"; pub const ATTR_JOIN: &str = "join";
/// Stroke coverage's miter limit threshold (`f64`, implicit default `4.`), on the `Item<Cover>` inside a `Coverage`.
pub const ATTR_JOIN_MITER_LIMIT: &str = "join_miter_limit"; pub const ATTR_JOIN_MITER_LIMIT: &str = "join_miter_limit";
/// Stroke coverage's `StrokeAlign` (implicit default `Center`), on the `Item<Cover>` inside a `Coverage`.
pub const ATTR_ALIGN: &str = "align"; pub const ATTR_ALIGN: &str = "align";
/// Brush stroke item's `Color` its strokes are painted with. // graphic-types (paint):
pub const ATTR_APPEARANCE: &str = "appearance";
pub const ATTR_PAINT: &str = "paint";
// vector-types (stroke coverage, value type is not `Copy` so it has no marker yet):
pub const ATTR_DASH_PATTERN: &str = "dash_pattern";
// brush-types (per-stroke styling):
pub const ATTR_COLOR: &str = "color"; pub const ATTR_COLOR: &str = "color";
/// Brush stroke item's tip diameter in document-space units (`f64`).
pub const ATTR_DIAMETER: &str = "diameter"; pub const ATTR_DIAMETER: &str = "diameter";
/// Brush stroke item's edge hardness from `0.` (softest) to `1.` (hardest) (`f64`).
pub const ATTR_HARDNESS: &str = "hardness"; pub const ATTR_HARDNESS: &str = "hardness";
/// Brush stroke item's per-pass paint coverage from `0.` to `1.` (`f64`).
pub const ATTR_FLOW: &str = "flow"; pub const ATTR_FLOW: &str = "flow";
/// Text item's font size in document-space units (`f64`, implicit default `24.`).
pub const ATTR_FONT_SIZE: &str = "font_size";
/// Text item's font, as a `Resource` of the loaded font file.
pub const ATTR_FONT: &str = "font";
/// Text item's line height as a ratio of the font size (`f64`, implicit default `1.2`).
pub const ATTR_LINE_HEIGHT: &str = "line_height";
/// Text item's extra spacing between letters in document-space units (`f64`, implicit default `0.`).
pub const ATTR_LETTER_SPACING: &str = "letter_spacing";
/// Text item's maximum line-wrap width in document-space units (`Option<f64>`, implicit default `None`).
pub const ATTR_MAX_WIDTH: &str = "max_width";
/// Text item's maximum block height in document-space units, past which lines are not drawn
/// (`Option<f64>`, implicit default `None`).
pub const ATTR_MAX_HEIGHT: &str = "max_height";
/// Text item's faux-italic letter tilt angle in degrees (`f64`, implicit default `0.`).
pub const ATTR_LETTER_TILT: &str = "letter_tilt";
/// Text item's `TextAlign` horizontal alignment of lines within the block.
pub const ATTR_TEXT_ALIGN: &str = "text_align";
// ===================== // =====================
// TYPE: NodeIdPath // TYPE: NodeIdPath
@@ -175,13 +120,10 @@ unsafe impl<T: StaticTypeSized> StaticType for Bundle<T> {
// Implicit attribute defaults // Implicit attribute defaults
// =========================== // ===========================
/// Overrides the type's default value for certain attributes. /// The census-declared default for `key`; a mismatched value type degrades
/// to the column type's own default in `push_repeated`.
fn implicit_default_value(key: &str) -> Option<Box<dyn AnyAttributeValue>> { fn implicit_default_value(key: &str) -> Option<Box<dyn AnyAttributeValue>> {
match key { crate::attribute::ATTRIBUTE_REGISTRY.lock().unwrap().get(key).map(|info| (info.default)())
ATTR_OPACITY | ATTR_OPACITY_FILL => Some(Box::new(1_f64)),
ATTR_MIDPOINT => Some(Box::new(0.5_f64)),
_ => None,
}
} }
/// Appends `count` copies of `key`'s implicit default to `attribute` (see [`implicit_default_value`]). /// Appends `count` copies of `key`'s implicit default to `attribute` (see [`implicit_default_value`]).
@@ -229,6 +171,12 @@ pub trait AnyAttributeValue: std::any::Any + Send + Sync {
fn into_attribute(self: Box<Self>, key: &str, preceding_defaults: usize) -> Box<dyn AnyAttribute>; fn into_attribute(self: Box<Self>, key: &str, preceding_defaults: usize) -> Box<dyn AnyAttribute>;
} }
/// Re-parks an owned attribute value into fresh field storage; `None` reports arena exhaustion.
pub type ReparkFn = unsafe fn(&dyn AnyAttributeValue, *mut u8, &crate::arena::Arena) -> Option<()>;
/// Replays an owned attribute value into a serving arena; `Some(None)` is unchanged, `None` reports arena exhaustion.
pub type FieldReplayFn = fn(&dyn AnyAttributeValue, &crate::arena::Arena) -> Option<Option<Box<dyn AnyAttributeValue>>>;
impl<T: Clone + Send + Sync + Default + Sized + Debug + PartialEq + CacheHash + 'static> AnyAttributeValue for T { impl<T: Clone + Send + Sync + Default + Sized + Debug + PartialEq + CacheHash + 'static> AnyAttributeValue for T {
/// Clones this value into a new boxed trait object. /// Clones this value into a new boxed trait object.
fn clone_box(&self) -> Box<dyn AnyAttributeValue> { fn clone_box(&self) -> Box<dyn AnyAttributeValue> {
@@ -472,6 +420,62 @@ impl<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>
} }
} }
// ============
// AttributeDyn
// ============
/// Type-erased list of attribute values, used as a node graph parameter type.
/// Lets a node accept any `List<U>` source via the auto-inserted `Convert<AttributeDyn, ()>`
/// without monomorphizing over `U` (so the cartesian product of `(content T, source U)` collapses to just `T`).
pub struct AttributeDyn(pub Box<dyn AnyAttribute>);
impl AttributeDyn {
/// Number of values in this attribute.
pub fn len(&self) -> usize {
self.0.len()
}
/// Whether this attribute has zero values.
pub fn is_empty(&self) -> bool {
self.0.len() == 0
}
}
impl Clone for AttributeDyn {
fn clone(&self) -> Self {
Self(self.0.clone_box())
}
}
impl Default for AttributeDyn {
fn default() -> Self {
Self(Box::new(Attribute::<bool>(Vec::new())))
}
}
impl Debug for AttributeDyn {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "AttributeDyn(len: {})", self.0.len())
}
}
impl PartialEq for AttributeDyn {
fn eq(&self, other: &Self) -> bool {
self.0.eq_dyn(&*other.0)
}
}
impl CacheHash for AttributeDyn {
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.0.cache_hash_dyn(state);
}
}
// SAFETY: the type carries no lifetime, so it is its own static form.
unsafe impl StaticType for AttributeDyn {
type Static = Self;
}
// ================== // ==================
// AttributeValueDyn // AttributeValueDyn
// ================== // ==================
@@ -510,6 +514,7 @@ impl CacheHash for AttributeValueDyn {
} }
} }
// SAFETY: as for AttributeDyn.
unsafe impl StaticType for AttributeValueDyn { unsafe impl StaticType for AttributeValueDyn {
type Static = Self; type Static = Self;
} }
@@ -593,6 +598,7 @@ impl CacheHash for ListDyn {
} }
} }
// SAFETY: as for AttributeDyn.
unsafe impl StaticType for ListDyn { unsafe impl StaticType for ListDyn {
type Static = Self; type Static = Self;
} }
@@ -697,6 +703,11 @@ impl ItemAttributeValues {
self.0.iter().map(|(key, _)| key.as_str()) self.0.iter().map(|(key, _)| key.as_str())
} }
/// Returns an iterator over the stored (key, value) pairs, in insertion order.
pub fn iter(&self) -> impl Iterator<Item = (&str, &dyn AnyAttributeValue)> {
self.0.iter().map(|(key, value)| (key.as_str(), &**value))
}
/// Returns a type-erased reference to the value of the attribute with the given key, if it exists. /// Returns a type-erased reference to the value of the attribute with the given key, if it exists.
pub fn get_any(&self, key: &str) -> Option<&dyn std::any::Any> { pub fn get_any(&self, key: &str) -> Option<&dyn std::any::Any> {
self.0.iter().find_map(|(existing_key, value)| if existing_key == key { Some((**value).as_any()) } else { None }) self.0.iter().find_map(|(existing_key, value)| if existing_key == key { Some((**value).as_any()) } else { None })
@@ -842,6 +853,11 @@ impl Attributes {
.find_map(|(k, attribute)| if k == key { attribute.get_any(index)?.downcast_ref::<T>() } else { None }) .find_map(|(k, attribute)| if k == key { attribute.get_any(index)?.downcast_ref::<T>() } else { None })
} }
/// The whole column for the given key, resolved once for repeated lane reads.
fn column(&self, key: &str) -> Option<&dyn AnyAttribute> {
self.attributes.iter().find_map(|(k, attribute)| (k == key).then_some(&**attribute))
}
/// Removes the entire attribute for the given key, if present. /// Removes the entire attribute for the given key, if present.
fn remove_attribute(&mut self, key: &str) { fn remove_attribute(&mut self, key: &str) {
if let Some(position) = self.attributes.iter().position(|(k, _)| k == key) { if let Some(position) = self.attributes.iter().position(|(k, _)| k == key) {
@@ -879,13 +895,6 @@ impl Attributes {
} }
} }
/// Gets a mutable reference to the value at the given index, creating the attribute if it doesn't exist or has the wrong type.
fn get_or_insert_default_value<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>(&mut self, key: &str, index: usize) -> &mut T {
let attribute_position = self.find_or_create_attribute::<T>(key);
let attribute = (*self.attributes[attribute_position].1).as_any_mut().downcast_mut::<Attribute<T>>().unwrap();
&mut attribute.0[index]
}
/// Sets the value at the given index in the attribute for the given key. /// Sets the value at the given index in the attribute for the given key.
/// Creates the attribute with defaults if it doesn't exist. /// Creates the attribute with defaults if it doesn't exist.
fn set_value<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>(&mut self, key: impl Into<String>, index: usize, value: T) { fn set_value<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>(&mut self, key: impl Into<String>, index: usize, value: T) {
@@ -1145,12 +1154,6 @@ impl<T> List<T> {
self.attributes.remove_attribute(key); self.attributes.remove_attribute(key);
} }
/// Runs the given closure on a mutable reference to the attribute value at the given item index,
/// creating the attribute with defaults if it doesn't exist, and returns the closure's result.
pub fn with_attribute_mut_or_default<U: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static, R, F: FnOnce(&mut U) -> R>(&mut self, key: &str, index: usize, f: F) -> R {
f(self.attributes.get_or_insert_default_value::<U>(key, index))
}
/// Returns a debug-formatted display string for the attribute at the given item index and key. /// Returns a debug-formatted display string for the attribute at the given item index and key.
pub fn attribute_display_value(&self, key: &str, index: usize, overrides: fn(&dyn std::any::Any) -> Option<String>) -> Option<String> { pub fn attribute_display_value(&self, key: &str, index: usize, overrides: fn(&dyn std::any::Any) -> Option<String>) -> Option<String> {
self.attributes.display_value(key, index, overrides) self.attributes.display_value(key, index, overrides)
@@ -1196,48 +1199,12 @@ impl<T> List<T> {
} }
impl<T: BoundingBox> BoundingBox for List<T> { impl<T: BoundingBox> BoundingBox for List<T> {
/// Computes the combined bounding box of all items, composing each item's transform attribute with the given transform.
fn bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox { fn bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
let mut combined_bounds = None; crate::bounds::lane_bounding_box(self, transform, include_stroke)
for (element, item_transform) in self.iter_element_values().zip(self.iter_attribute_values_or_default::<DAffine2>(ATTR_TRANSFORM)) {
match element.bounding_box(transform * item_transform, include_stroke) {
RenderBoundingBox::None => continue,
RenderBoundingBox::Infinite => return RenderBoundingBox::Infinite,
RenderBoundingBox::Rectangle(bounds) => match combined_bounds {
Some(existing) => combined_bounds = Some(Quad::combine_bounds(existing, bounds)),
None => combined_bounds = Some(bounds),
},
}
}
match combined_bounds {
Some(bounds) => RenderBoundingBox::Rectangle(bounds),
None => RenderBoundingBox::None,
}
} }
fn thumbnail_bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox { fn thumbnail_bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
// `Infinite` items are skipped here (rather than propagating outward as in `bounding_box`) so a finite sibling in a mixed group dictates the framing crate::bounds::lane_thumbnail_bounding_box(self, transform, include_stroke)
let mut combined_bounds = None;
let mut any_infinite = false;
for (element, item_transform) in self.iter_element_values().zip(self.iter_attribute_values_or_default::<DAffine2>(ATTR_TRANSFORM)) {
match element.thumbnail_bounding_box(transform * item_transform, include_stroke) {
RenderBoundingBox::None => continue,
RenderBoundingBox::Infinite => any_infinite = true,
RenderBoundingBox::Rectangle(bounds) => match combined_bounds {
Some(existing) => combined_bounds = Some(Quad::combine_bounds(existing, bounds)),
None => combined_bounds = Some(bounds),
},
}
}
match (combined_bounds, any_infinite) {
(Some(bounds), _) => RenderBoundingBox::Rectangle(bounds),
(None, true) => RenderBoundingBox::Infinite,
(None, false) => RenderBoundingBox::None,
}
} }
} }
@@ -1264,6 +1231,41 @@ impl<T> Default for List<T> {
} }
} }
/// A marker's column on a [`List`], absent when the list carries no such key.
pub struct ListColumn<'a, A: crate::attribute::Attribute> {
stored: Option<&'a dyn AnyAttribute>,
marker: std::marker::PhantomData<A>,
}
impl<'a, A: crate::attribute::Attribute> crate::lane::LaneColumn<'a, A> for ListColumn<'a, A> {
fn try_get(&self, lane: usize) -> Option<A::Value<'a>> {
self.stored.and_then(|column| column.get_any(lane)).and_then(A::from_stored)
}
}
impl<T> crate::lane::LaneSource for List<T> {
type Element = T;
type Column<'a, A: crate::attribute::Attribute>
= ListColumn<'a, A>
where
Self: 'a;
fn lane_count(&self) -> usize {
List::len(self)
}
fn element(&self, lane: usize) -> Option<&T> {
List::element(self, lane)
}
fn column<A: crate::attribute::Attribute>(&self) -> ListColumn<'_, A> {
ListColumn {
stored: self.attributes.column(A::NAME),
marker: std::marker::PhantomData,
}
}
}
impl<T: CacheHash> CacheHash for List<T> { impl<T: CacheHash> CacheHash for List<T> {
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) { fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.element.cache_hash(state); self.element.cache_hash(state);
@@ -1307,6 +1309,8 @@ impl<T> ApplyTransform for List<T> {
} }
} }
// SAFETY: the list carries its lifetime only through T, so substituting T's
// static form substitutes the list's and keeps the layout identical.
unsafe impl<T: StaticTypeSized> StaticType for List<T> { unsafe impl<T: StaticTypeSized> StaticType for List<T> {
type Static = List<T::Static>; type Static = List<T::Static>;
} }
+685
View File
@@ -0,0 +1,685 @@
use crate::context::InjectIndex;
use crate::gpoll::{Extent, Finality, GPoll, GraphError, Interrupt, Level};
use std::cell::Cell;
use std::marker::PhantomData;
use std::mem::MaybeUninit;
use std::ops::{Deref, Range};
#[derive(Debug)]
pub enum BatchStatus<'a> {
/// Producer-resident lanes, shared: read-only for the caller. The extent
/// is the producer's knowledge of the level's total after serving the
/// range: a sound lower bound, or exact; a batch shorter than the
/// requested range carries `Exactly` and marks the end of the data.
Lent(RecordBatch<'a>, Finality, Extent),
/// The caller's scratch, filled: the caller is the exclusive owner and may
/// mutate the lanes or reclaim the buffer for in-place reuse. The extent
/// hint is as for `Lent`.
Filled(RecordBatchMut<'a>, Finality, Extent),
/// No batch implementation behind this input; a driver answers with the
/// per-lane serve and copy-out loop ([`crate::record::fill_frames`]).
Unbatched,
Pending,
Error(GraphError),
NeedBuffer,
InvalidRange,
}
impl From<Interrupt> for BatchStatus<'_> {
fn from(interrupt: Interrupt) -> Self {
match interrupt {
Interrupt::Pending => BatchStatus::Pending,
Interrupt::Error(error) => BatchStatus::Error(*error),
}
}
}
/// A shared view over a batch of records in one flat frame buffer: lane `i`
/// starts at `frames + i * stride` with `stride = layout.lane_stride()`.
/// Frame bytes carry no drop glue (droppable elements ride parked,
/// arena-owned), so the view has no drop obligation; `'a` covers the frames
/// and the layout.
#[derive(Clone, Copy, Debug)]
pub struct RecordBatch<'a> {
frames: *const u8,
stride: usize,
len: usize,
layout: &'a crate::record::Layout,
_lifetime: PhantomData<&'a [u8]>,
}
impl<'a> RecordBatch<'a> {
/// # Safety
/// `frames` must hold `len` initialized records of `layout`, packed at
/// `layout.lane_stride()` stride and valid for `'a`.
pub unsafe fn new(frames: *const u8, len: usize, layout: &'a crate::record::Layout) -> Self {
Self {
frames,
stride: layout.lane_stride(),
len,
layout,
_lifetime: PhantomData,
}
}
pub fn len(&self) -> usize {
self.len
}
pub fn is_empty(&self) -> bool {
self.len == 0
}
pub fn layout(&self) -> &'a crate::record::Layout {
self.layout
}
pub(crate) fn frames_ptr(&self) -> *const u8 {
self.frames
}
pub fn get(&self, lane: usize) -> RecordLane<'a> {
assert!(lane < self.len, "lane {lane} out of bounds for a batch of {}", self.len);
RecordLane {
// SAFETY: in-bounds by the assert against the constructor's contract.
rec: unsafe { crate::record::Rec::new(self.frames.add(lane * self.stride)) },
layout: self.layout,
}
}
pub fn for_each(&self, mut f: impl FnMut(usize, RecordLane<'a>)) {
for lane in 0..self.len {
f(lane, self.get(lane));
}
}
}
/// The exclusive view over caller-owned frames (the `Filled` status): while it
/// lives, the borrow of the caller's scratch guarantees nobody else can read
/// the lanes, so mutating them or reclaiming the buffer is sound.
#[derive(Debug)]
pub struct RecordBatchMut<'a> {
scratch: &'a mut [MaybeUninit<u64>],
len: usize,
layout: &'a crate::record::Layout,
}
impl<'a> RecordBatchMut<'a> {
/// Minted only by a [`crate::record::SlotRun`] finishing its served lanes,
/// which serve in ascending order with no gaps, so the initialized prefix is
/// a fact rather than a contract.
pub(crate) fn new(scratch: &'a mut [MaybeUninit<u64>], len: usize, layout: &'a crate::record::Layout) -> Self {
debug_assert!(len.checked_mul(layout.lane_stride()).is_some_and(|need| need <= scratch.len() * 8));
Self { scratch, len, layout }
}
pub fn len(&self) -> usize {
self.len
}
pub fn is_empty(&self) -> bool {
self.len == 0
}
pub fn layout(&self) -> &'a crate::record::Layout {
self.layout
}
/// Reads the lanes without giving up exclusivity.
pub fn share(&self) -> RecordBatch<'_> {
// SAFETY: the constructor's contract, narrowed to the reborrow's scope.
unsafe { RecordBatch::new(self.scratch.as_ptr().cast(), self.len, self.layout) }
}
/// Gives up exclusivity for the batch's whole lifetime.
pub fn into_shared(self) -> RecordBatch<'a> {
// SAFETY: the constructor's contract; the exclusive borrow is consumed.
unsafe { RecordBatch::new(self.scratch.as_ptr().cast(), self.len, self.layout) }
}
}
/// One lane's record: its pointer paired with the batch's layout.
#[derive(Clone, Copy, Debug)]
pub struct RecordLane<'a> {
rec: crate::record::Rec<'a>,
layout: &'a crate::record::Layout,
}
impl<'a> RecordLane<'a> {
pub fn layout(&self) -> &'a crate::record::Layout {
self.layout
}
pub fn rec(&self) -> crate::record::Rec<'a> {
self.rec
}
/// The element at offset 0.
///
/// # Safety
/// `U` must be the record's element type, proven at the consumer's wiring.
pub unsafe fn element<U: Copy>(&self) -> U {
unsafe { self.rec.element::<U>() }
}
/// Attribute `A` through a token, `None` where the token was minted against
/// another layout than this lane's.
pub fn try_attr_at<A: crate::attribute::Attribute>(&self, field: crate::record::FieldOffset<A>) -> Option<A::Value<'a>> {
let offset = field.resolve(self.layout)?;
// SAFETY: resolving against this lane's own layout pins the offset and
// the field's value type, and the batch's contract makes the lane a live
// record of that layout.
Some(unsafe { self.rec.read::<A::Value<'a>>(offset) })
}
/// Attribute `A` through a token, or its census default where the token is
/// absent or names another layout.
pub fn attr_at<A: crate::attribute::Attribute>(&self, field: Option<crate::record::FieldOffset<A>>) -> A::Value<'a> {
field.and_then(|field| self.try_attr_at(field)).unwrap_or_else(A::default)
}
/// Attribute `A` at the record's top level, or its census default when the
/// layout does not carry it. Mints a token per call; lane loops hoist the
/// mint instead.
pub fn attr<A: crate::attribute::Attribute>(&self) -> A::Value<'a> {
self.attr_at(crate::record::FieldOffset::<A>::of(self.layout, 0))
}
}
/// One lane of a materialized level, element-typed. In a kernel's element
/// position the output frame is copied from this lane.
#[derive(Debug)]
pub struct Lane<'a, T> {
lane: RecordLane<'a>,
_element: PhantomData<T>,
}
// A view regardless of `T`: copying a lane copies no record.
impl<T> Clone for Lane<'_, T> {
fn clone(&self) -> Self {
*self
}
}
impl<T> Copy for Lane<'_, T> {}
impl<'a, T> Deref for Lane<'a, T> {
type Target = RecordLane<'a>;
fn deref(&self) -> &RecordLane<'a> {
&self.lane
}
}
/// A materialized nesting level handed to a folding kernel: a thin element-typed
/// view over the [`RecordBatch`] the level was collected into.
#[derive(Debug)]
pub struct List<'a, T> {
batch: RecordBatch<'a>,
_element: PhantomData<T>,
}
// A shared view regardless of `T`: copying the list copies no elements.
impl<T> Clone for List<'_, T> {
fn clone(&self) -> Self {
*self
}
}
impl<T> Copy for List<'_, T> {}
impl<'a, T> List<'a, T> {
/// # Safety
/// `T` must be the batch's record element type, proven at the consumer's
/// wiring, and the batch's frames must stay valid for the evaluation:
/// arena-resident batches qualify, caller stack scratch does not.
pub unsafe fn new(batch: RecordBatch<'a>) -> Self {
Self { batch, _element: PhantomData }
}
/// The level as a group item over the same frames, without copying.
/// Panics where a parked element or field lacks content glue.
pub fn as_group_item(&self) -> crate::record::GroupItem<'a> {
// SAFETY: `List::new` established the frames stay valid for the
// evaluation.
unsafe { crate::record::GroupItem::from_resident(self.batch) }
}
pub fn len(&self) -> usize {
self.batch.len()
}
pub fn is_empty(&self) -> bool {
self.batch.is_empty()
}
pub fn batch(&self) -> RecordBatch<'a> {
self.batch
}
pub fn get(&self, index: usize) -> T
where
T: Copy,
{
// SAFETY: `List::new` established that `T` is the batch's element type.
unsafe { self.batch.get(index).element::<T>() }
}
/// Borrows lane `index`'s element, through the park for droppable types.
pub fn element_ref(&self, index: usize) -> &T {
// SAFETY: `List::new` established that `T` is the batch's element type,
// and the borrow lives within the batch's own lifetime.
unsafe { crate::record::borrow_element::<T>(self.batch.get(index).rec()) }
}
/// Lane `index`'s record, for attribute reads beside the element.
pub fn lane(&self, index: usize) -> Lane<'a, T> {
Lane {
lane: self.batch.get(index),
_element: PhantomData,
}
}
pub fn iter(&self) -> impl Iterator<Item = T> + '_
where
T: Copy,
{
(0..self.len()).map(move |index| self.get(index))
}
}
impl<'a, T: Copy> IntoIterator for List<'a, T> {
type Item = T;
type IntoIter = ListIter<'a, T>;
fn into_iter(self) -> ListIter<'a, T> {
ListIter { list: self, position: 0 }
}
}
pub struct ListIter<'a, T> {
list: List<'a, T>,
position: usize,
}
impl<T: Copy> Iterator for ListIter<'_, T> {
type Item = T;
fn next(&mut self) -> Option<T> {
(self.position < self.list.len()).then(|| {
let value = self.list.get(self.position);
self.position += 1;
value
})
}
}
pub trait Node<Input> {
/// Serves the node's record through the caller's claim: the writes land
/// in the claim and the returned proof is mintable only by its closing
/// methods, so the served record is of the claimed layout by
/// construction. The caller claims the frame at [`Node::layout`] out of
/// its own frame space, and the claim carries what is left, so the node
/// takes exactly its own frame out of the caller's free space.
fn serve<'e, 'l>(&self, input: &Input, slot: crate::record::FrameClaim<'e, 'l>) -> GPoll<crate::record::Served<'e>>
where
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>;
/// The count of items at one absolute nesting level (innermost `0`). The
/// leveled primitive a structure node overrides to report a pushed level's
/// size; the scalar base is one item at every level. Uncertainty rides the
/// `GPoll` status axis.
fn extent_at<'e>(&self, _input: &Input, _level: u8, _frames: &crate::record::Frames<'e>) -> GPoll<Extent>
where
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
GPoll::Final(Extent::Exactly(1))
}
/// The composite domain query derived from [`extent_at`](Node::extent_at):
/// one level, the product of the levels below or above it, or the whole
/// domain's flat count. Consumers query this; nodes only write `extent_at`.
fn extent<'e>(&self, input: &Input, at: Level, frames: &crate::record::Frames<'e>) -> GPoll<Extent>
where
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
let product =
|range: core::ops::Range<u8>, frames: &crate::record::Frames<'e>| range.fold(GPoll::Final(Extent::Exactly(1)), |acc, level| Extent::mul(acc, self.extent_at(input, level, frames)));
match at {
Level::At(level) => self.extent_at(input, level, frames),
Level::Below(level) => product(0..level, frames),
Level::Above(level) => product((level + 1)..self.depth(), frames),
Level::Total => product(0..self.depth(), frames),
}
}
/// The node's domain depth (number of nesting levels; `0` = scalar), baked
/// into the record layout at wiring.
fn depth(&self) -> u8 {
self.layout().depth
}
/// Introspection access to node-resident records; `None` for ordinary nodes.
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
None
}
/// The record layout of this node's output; the shared empty layout for
/// element-only producers. Consumers read their carrier's layout through
/// this at wiring, and the wiring layer derives the root buffer's sizing from
/// the same layouts, in the dynamic executor and exported source alike.
fn layout(&self) -> &crate::record::Layout {
crate::record::empty_layout()
}
/// Installs this node's resolved record layout; a no-op unless it produces records.
fn set_layout(&mut self, _layout: crate::record::RecordLayout) {}
/// Batched evaluation of `range` into caller-provided frame storage of
/// `range.len() * layout.lane_stride()` bytes; see [`BatchStatus`]. The
/// default advertises no support and drivers fall back to per-lane serves
/// with copy-out ([`crate::record::fill_frames`]); overrides exist to beat
/// that loop (resident lanes, direct fills, fewer erased calls), never for
/// correctness.
fn eval_batch<'a, 'e>(&'a self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<u64>]>, frames: &crate::record::Frames<'e>) -> BatchStatus<'a>
where
Input: InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
let _ = (input, range, scratch, frames);
BatchStatus::Unbatched
}
}
impl<Input, N> Node<Input> for &N
where
N: Node<Input> + ?Sized,
{
fn serve<'e, 'l>(&self, input: &Input, slot: crate::record::FrameClaim<'e, 'l>) -> GPoll<crate::record::Served<'e>>
where
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
(**self).serve(input, slot)
}
fn extent_at<'e>(&self, input: &Input, level: u8, frames: &crate::record::Frames<'e>) -> GPoll<Extent>
where
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
(**self).extent_at(input, level, frames)
}
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
(**self).serialize()
}
fn layout(&self) -> &crate::record::Layout {
(**self).layout()
}
fn eval_batch<'a, 'e>(&'a self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<u64>]>, frames: &crate::record::Frames<'e>) -> BatchStatus<'a>
where
Input: InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
(**self).eval_batch(input, range, scratch, frames)
}
}
impl<Input, N> Node<Input> for Box<N>
where
N: Node<Input> + ?Sized,
{
fn serve<'e, 'l>(&self, input: &Input, slot: crate::record::FrameClaim<'e, 'l>) -> GPoll<crate::record::Served<'e>>
where
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
(**self).serve(input, slot)
}
fn extent_at<'e>(&self, input: &Input, level: u8, frames: &crate::record::Frames<'e>) -> GPoll<Extent>
where
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
(**self).extent_at(input, level, frames)
}
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
(**self).serialize()
}
fn layout(&self) -> &crate::record::Layout {
(**self).layout()
}
fn eval_batch<'a, 'e>(&'a self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<u64>]>, frames: &crate::record::Frames<'e>) -> BatchStatus<'a>
where
Input: InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
(**self).eval_batch(input, range, scratch, frames)
}
}
impl<Input, N> Node<Input> for std::sync::Arc<N>
where
N: Node<Input> + ?Sized,
{
fn serve<'e, 'l>(&self, input: &Input, slot: crate::record::FrameClaim<'e, 'l>) -> GPoll<crate::record::Served<'e>>
where
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
(**self).serve(input, slot)
}
fn extent_at<'e>(&self, input: &Input, level: u8, frames: &crate::record::Frames<'e>) -> GPoll<Extent>
where
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
(**self).extent_at(input, level, frames)
}
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
(**self).serialize()
}
fn layout(&self) -> &crate::record::Layout {
(**self).layout()
}
fn eval_batch<'a, 'e>(&'a self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<u64>]>, frames: &crate::record::Frames<'e>) -> BatchStatus<'a>
where
Input: InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
(**self).eval_batch(input, range, scratch, frames)
}
}
pub struct StatusCell {
finality: Cell<Finality>,
error: Cell<Option<GraphError>>,
no_partial: bool,
}
impl Default for StatusCell {
fn default() -> Self {
Self::new()
}
}
impl StatusCell {
pub fn new() -> Self {
Self {
finality: Cell::new(Finality::AllFinal),
error: Cell::new(None),
no_partial: false,
}
}
#[inline(always)]
pub fn no_partial() -> Self {
Self { no_partial: true, ..Self::new() }
}
/// Claims the input's own frame out of `frames`, serves through it, and
/// folds the poll's status into the cell. The claim is the caller's, so
/// the input's frame is claimed exactly once per evaluation.
#[inline(always)]
pub fn eval_input<'e, Input, N: Node<Input> + ?Sized>(&self, input_index: usize, node: &N, input: &Input, frames: &crate::record::Frames<'e>) -> Result<crate::record::RecordValue<'e>, Interrupt>
where
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
let slot = frames.claim(node.layout());
match node.serve(input, slot) {
GPoll::Final(served) => Ok(served.value()),
GPoll::Partial(_) if self.no_partial => Err(Interrupt::Pending),
GPoll::Partial(served) => {
self.finality.set(Finality::Partial);
Ok(served.value())
}
GPoll::Fallback(boxed) => {
let (served, error) = *boxed;
let first = self.error.take();
self.error.set(first.or(Some(error.traced(input_index))));
Ok(served.value())
}
GPoll::Pending => Err(Interrupt::Pending),
GPoll::Error(mut error) => {
error.trace.push(input_index);
Err(Interrupt::Error(error))
}
}
}
/// A new cell holding a copy of the accumulated status; the error stays in
/// place, cloned rather than taken.
#[inline(always)]
pub fn snapshot(&self) -> StatusCell {
let error = self.error.take();
self.error.set(error.clone());
StatusCell {
finality: Cell::new(self.finality.get()),
error: Cell::new(error),
no_partial: self.no_partial,
}
}
#[inline(always)]
pub fn finish<T>(self, value: T) -> GPoll<T> {
match (self.error.take(), self.finality.get()) {
(Some(error), _) => GPoll::Fallback(Box::new((value, error))),
(None, Finality::AllFinal) => GPoll::Final(value),
(None, Finality::Partial) => GPoll::Partial(value),
}
}
#[inline(always)]
pub fn merge<T>(self, poll: GPoll<T>) -> GPoll<T> {
match poll {
GPoll::Final(value) => self.finish(value),
GPoll::Partial(_) if self.no_partial => GPoll::Pending,
GPoll::Partial(value) => match self.finish(value) {
GPoll::Final(value) => GPoll::Partial(value),
other => other,
},
GPoll::Fallback(boxed) => {
let (value, error) = *boxed;
let first = self.error.take().unwrap_or(error);
GPoll::Fallback(Box::new((value, first)))
}
interrupted => interrupted,
}
}
}
#[derive(Clone, Copy)]
pub struct LazyInput<'a, 'f, N> {
node: &'a N,
cell: &'a StatusCell,
input_index: usize,
frames: &'a crate::record::Frames<'f>,
}
impl<'a, 'f, N> LazyInput<'a, 'f, N> {
pub fn new(node: &'a N, cell: &'a StatusCell, input_index: usize, frames: &'a crate::record::Frames<'f>) -> Self {
Self { node, cell, input_index, frames }
}
#[inline(always)]
pub fn eval<'e, Input>(&self, ctx: &Input) -> Result<crate::record::RecordValue<'e>, Interrupt>
where
N: crate::record::DerivedRecordInput<'e, Input>,
'f: 'e,
{
self.node.eval_derived(self.cell, self.input_index, ctx, self.frames)
}
/// The input's composite extent, for kernels that split or shift indices
/// over their sources.
#[inline(always)]
pub fn extent<'e, Input>(&self, ctx: &Input, at: Level) -> GPoll<Extent>
where
N: Node<Input>,
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
'f: 'e,
{
self.node.extent(ctx, at, self.frames)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::arena::Arena;
use crate::context::ExtractArena;
use crate::record::{LiftedSource, serve_input};
#[derive(Clone, Copy)]
struct TestInput<'a> {
index: u64,
arena: &'a Arena,
}
impl InjectIndex for TestInput<'_> {
fn set_index(&mut self, index: u64) {
self.index = index;
}
}
impl<'a> ExtractArena for TestInput<'a> {
type ArenaRef = &'a Arena;
fn arena(&self) -> &'a Arena {
self.arena
}
}
fn double<'a>() -> LiftedSource<u64, impl Fn(&TestInput<'a>) -> GPoll<u64>> {
LiftedSource::new(|input: &TestInput<'a>| GPoll::Final(input.index * 2))
}
#[test]
fn the_default_advertises_no_batch_support() {
let frames = crate::record::test_frames(1 << 16);
let arena = Arena::new(1024).unwrap();
let input = TestInput { index: 0, arena: &arena };
let mut scratch = [const { MaybeUninit::uninit() }; 4];
let node = double();
assert!(matches!(node.eval_batch(&input, 2..6, Some(&mut scratch), &frames), BatchStatus::Unbatched));
assert!(matches!(node.eval_batch(&input, 2..6, None, &frames), BatchStatus::Unbatched));
}
#[test]
fn trait_is_object_safe_across_erased_edges() {
let arena = Arena::new(1024).unwrap();
let input = TestInput { index: 21, arena: &arena };
let node = double();
let layout = Node::<TestInput>::layout(&node).clone();
let erased: Box<dyn Node<TestInput>> = Box::new(node);
let frames = crate::record::test_frames(1 << 12);
let GPoll::Final(value) = serve_input(&*erased, &input, &frames) else {
panic!("the erased edge must serve a final record");
};
// SAFETY: the record was served at `layout`, whose element is the output.
assert_eq!(unsafe { crate::record::read_element::<u64>(layout.rec(&value)) }, 42);
assert!(matches!(erased.eval_batch(&input, 0..2, None, &frames), BatchStatus::Unbatched));
}
}
+73 -43
View File
@@ -1,49 +1,21 @@
use crate::Node; use crate::list::{Attribute, AttributeDyn, AttributeValueDyn, Item, List, ListDyn};
use crate::math::float_noise::round_away_float_noise; use crate::math::float_noise::round_away_float_noise;
use crate::transform::Footprint; use crate::transform::Footprint;
use glam::{DAffine2, DVec2}; use glam::{DAffine2, DVec2, IVec2};
use std::future::Future; use graphene_hash::CacheHash;
use std::marker::PhantomData;
// Type
// TODO: Document this
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct TypeNode<N: for<'a> Node<'a, I>, I, O>(pub N, pub PhantomData<(I, O)>);
impl<'i, N, I: 'i, O: 'i> Node<'i, I> for TypeNode<N, I, O>
where
N: for<'n> Node<'n, I, Output = O>,
{
type Output = O;
fn eval(&'i self, input: I) -> Self::Output {
self.0.eval(input)
}
fn reset(&self) {
self.0.reset();
}
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
self.0.serialize()
}
}
impl<'i, N: for<'a> Node<'a, I>, I: 'i> TypeNode<N, I, <N as Node<'i, I>>::Output> {
pub fn new(node: N) -> Self {
Self(node, PhantomData)
}
}
impl<'i, N: for<'a> Node<'a, I> + Clone, I: 'i> Clone for TypeNode<N, I, <N as Node<'i, I>>::Output> {
fn clone(&self) -> Self {
Self(self.0.clone(), self.1)
}
}
impl<'i, N: for<'a> Node<'a, I> + Copy, I: 'i> Copy for TypeNode<N, I, <N as Node<'i, I>>::Output> {}
/// The [`Convert`] trait allows for conversion between Rust primitive numeric types. /// The [`Convert`] trait allows for conversion between Rust primitive numeric types.
/// Because number casting is lossy, we cannot use the normal [`Into`] trait like we do for other types. /// Because number casting is lossy, we cannot use the normal [`Into`] trait like we do for other types.
pub trait Convert<T, C>: Sized { pub trait Convert<T, C>: Sized {
/// Converts this type into the (usually inferred) output type. /// Converts this type into the (usually inferred) output type.
#[must_use] #[must_use]
fn convert(self, footprint: Footprint, converter: C) -> impl Future<Output = T> + Send; fn convert(self, footprint: Footprint, converter: C) -> T;
}
/// The asynchronous counterpart of [`Convert`]; a conversion pair implements exactly one of the two traits.
pub trait ConvertAsync<T, C>: Sized {
#[must_use]
fn convert(self, footprint: Footprint, converter: C) -> crate::runtime::SourceFuture<T>;
} }
/// Implements the [`Convert`] trait for formatting a type into a `String` via [`ToString`]. /// Implements the [`Convert`] trait for formatting a type into a `String` via [`ToString`].
@@ -52,34 +24,92 @@ macro_rules! impl_convert_to_string {
$( $(
impl Convert<String, ()> for $from { impl Convert<String, ()> for $from {
#[inline] #[inline]
async fn convert(self, _: Footprint, _converter: ()) -> String { fn convert(self, _: Footprint, _converter: ()) -> String {
self.to_string() self.to_string()
} }
} }
)* )*
}; };
} }
impl_convert_to_string!(f32, u32, u64, i32, i64, bool, DVec2, DAffine2); impl_convert_to_string!(f32, u32, u64, i32, i64, bool, DVec2, DAffine2, String, IVec2, i8, u8, u16, i16, u128, i128, usize, isize);
// Denoised so 0.1 + 0.2 reaches the string as "0.3" rather than "0.30000000000000004" // Denoised so 0.1 + 0.2 reaches the string as "0.3" rather than "0.30000000000000004"
impl Convert<String, ()> for f64 { impl Convert<String, ()> for f64 {
#[inline] #[inline]
async fn convert(self, _: Footprint, _converter: ()) -> String { fn convert(self, _: Footprint, _converter: ()) -> String {
round_away_float_noise(self).to_string() round_away_float_noise(self).to_string()
} }
} }
pub trait ListConvert<U> {
fn convert_item(self) -> U;
}
impl<U, T: ListConvert<U> + Send> Convert<List<U>, ()> for List<T> {
fn convert(self, _: Footprint, _: ()) -> List<U> {
let list: List<U> = self
.into_iter()
.map(|row| {
let (element, attributes) = row.into_parts();
Item::from_parts(element.convert_item(), attributes)
})
.collect();
list
}
}
/// Wraps each row's element into a type-erased attribute. Lets nodes that accept a source attribute
/// from any `List<U>` express their signature as `AttributeDyn` and avoid monomorphizing
/// over `U`; the compiler inserts this convert to bridge concrete-typed graph sources to the dyn input.
impl<T: Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash + 'static> Convert<AttributeDyn, ()> for List<T> {
fn convert(self, _: Footprint, _: ()) -> AttributeDyn {
let values: Vec<T> = self.into_iter().map(|row| row.into_element()).collect();
AttributeDyn(Box::new(Attribute(values)))
}
}
/// Wraps a value into a type-erased attribute value. Lets nodes that take a per-item value source
/// (such as `write_attribute`'s value-producing input) be generic over the destination list type
/// alone, with the compiler-inserted convert handling each concrete value type at the input level.
impl<T: Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash + 'static> Convert<AttributeValueDyn, ()> for T {
fn convert(self, _: Footprint, _: ()) -> AttributeValueDyn {
AttributeValueDyn(Box::new(self))
}
}
/// Erases a `List<T>`'s element type, exposing only its attributes and row count. Lets nodes that
/// only need attribute access (such as the `read_attribute_*` family) take a single `ListDyn` input
/// instead of monomorphizing over every possible carrier list type.
impl<T: Send> Convert<ListDyn, ()> for List<T> {
fn convert(self, _: Footprint, _: ()) -> ListDyn {
self.into()
}
}
impl Convert<DVec2, ()> for DVec2 {
fn convert(self, _: Footprint, _: ()) -> DVec2 {
self
}
}
/// Constructs `Self` from a single anchor point at the given position. Implemented by the vector crate's /// Constructs `Self` from a single anchor point at the given position. Implemented by the vector crate's
/// path type so a position wire can convert to a single-point path without core-types depending on that crate. /// path type so a position wire can convert to a single-point path without core-types depending on that crate.
pub trait FromAnchorPosition { pub trait FromAnchorPosition {
fn from_anchor_position(position: DVec2) -> Self; fn from_anchor_position(position: DVec2) -> Self;
} }
// Converts a position into a vector path composed of a single anchor point
impl<T: FromAnchorPosition + Send> Convert<List<T>, ()> for DVec2 {
fn convert(self, _: Footprint, _: ()) -> List<T> {
List::new_from_item(Item::new_from_element(T::from_anchor_position(self)))
}
}
/// Implements the [`Convert`] trait for conversion between the cartesian product of Rust's primitive numeric types. /// Implements the [`Convert`] trait for conversion between the cartesian product of Rust's primitive numeric types.
macro_rules! impl_convert { macro_rules! impl_convert {
($from:ty, $to:ty) => { ($from:ty, $to:ty) => {
impl Convert<$to, ()> for $from { impl Convert<$to, ()> for $from {
async fn convert(self, _: Footprint, _: ()) -> $to { fn convert(self, _: Footprint, _: ()) -> $to {
self as $to self as $to
} }
} }
@@ -101,7 +131,7 @@ macro_rules! impl_convert {
impl_convert!(usize, $to); impl_convert!(usize, $to);
impl Convert<DVec2, ()> for $to { impl Convert<DVec2, ()> for $to {
async fn convert(self, _: Footprint, _: ()) -> DVec2 { fn convert(self, _: Footprint, _: ()) -> DVec2 {
DVec2::splat(self as f64) DVec2::splat(self as f64)
} }
} }
@@ -0,0 +1,298 @@
//! Raw typed access to a record at a wiring-proven layout.
use super::layout::element_parked;
use crate::attribute;
use crate::gpoll::GPoll;
/// A view of one record: a pointer whose layout is proven at wiring, borrowing
/// the storage it points into for `'r`.
#[derive(Clone, Copy, Debug)]
pub struct Rec<'r>(pub(in crate::record) *const u8, pub(in crate::record) std::marker::PhantomData<&'r u8>);
impl<'r> Rec<'r> {
/// # Safety
/// `ptr` must point to a live record of the layout the consumer resolved
/// at wiring, valid for `'r` and until the owning slot is next written.
pub unsafe fn new(ptr: *const u8) -> Self {
Rec(ptr, std::marker::PhantomData)
}
/// # Safety
/// `offset` must be a field offset of the record's layout and `T` the
/// field's type; both are proven at wiring. The record's base is aligned
/// to its layout, so field reads are aligned.
pub unsafe fn read<T: Copy>(self, offset: usize) -> T {
unsafe { self.0.add(offset).cast::<T>().read() }
}
/// # Safety
/// `T` must be the record's element type; the element sits at offset 0.
pub unsafe fn element<T: Copy>(self) -> T {
unsafe { self.read(0) }
}
pub fn ptr(self) -> *const u8 {
self.0
}
}
/// An opaque record value: every non-empty record spills to a claimed frame
/// and the value carries its pointer, while an empty record carries nothing.
#[derive(Clone, Copy)]
pub struct RecordValue<'e> {
pub(in crate::record) ptr: *const u8,
_lifetime: std::marker::PhantomData<&'e ()>,
}
impl std::fmt::Debug for RecordValue<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("RecordValue(..)")
}
}
// SAFETY: `element_write` requires the element `Send + Sync` and every field holds an
// `Attribute::Value`, which the trait bounds `Send + Sync`, so the record bytes behind
// the pointer are thread-safe; `'e` ties the pointer's validity to the shared arena and
// record-stack discipline.
unsafe impl Send for RecordValue<'_> {}
// SAFETY: as `Send`.
unsafe impl Sync for RecordValue<'_> {}
impl<'e> RecordValue<'e> {
#[doc(hidden)]
pub fn zeroed() -> Self {
RecordValue {
ptr: std::ptr::null(),
_lifetime: std::marker::PhantomData,
}
}
/// The inline storage under construction; writes land in the value itself.
#[doc(hidden)]
pub fn as_mut_ptr(&mut self) -> *mut u8 {
(&raw mut *self).cast()
}
#[doc(hidden)]
pub fn spilled(rec: Rec<'_>) -> Self {
RecordValue {
ptr: rec.ptr(),
_lifetime: std::marker::PhantomData,
}
}
/// Rebinds the eval lifetime, lengthening a derived scope's record back
/// onto the outer evaluation's. Sound only because the record's bytes live
/// in the outer caller's slot region: a derived context shortens the
/// caller's frame space rather than owning any, so the frame the record
/// sits in outlives the derivation, exactly as it outlives the arena
/// borrow the derived context carries.
pub(in crate::record) fn rebind<'a>(self) -> RecordValue<'a> {
RecordValue {
ptr: self.ptr,
_lifetime: std::marker::PhantomData,
}
}
}
/// Reads a declared attribute out of a record at a wiring-resolved offset,
/// falling back to the marker's census default where the layout does not carry
/// the name.
///
/// # Safety
/// `rec` must be a live record of the layout `offset` was resolved against,
/// and `offset`, where present, must be that layout's offset for `A` at the
/// read's level. The census admits one value type per attribute name and
/// panics on a conflicting declaration, so that field's bytes are a value of
/// `A::Value`, differing from the read type only in `'e`, which must not
/// outlive the evaluation a parked payload is arena-resident for.
pub unsafe fn read_at<'e, A: attribute::Attribute>(rec: Rec<'_>, offset: Option<usize>) -> attribute::Attr<'e, A> {
attribute::Attr(match offset {
// SAFETY: the caller's contract.
Some(offset) => unsafe { rec.read::<A::Value<'e>>(offset) },
None => A::default(),
})
}
/// [`read_at`] for a name-generic read, whose marker carries the value type
/// but not the name and so cannot know the name's own default. `absent` is
/// that default's bytes, which the compiler takes from the census once the
/// name is folded; without one the value type's default applies, which is
/// exactly the rule for a name the census does not declare.
///
/// # Safety
/// As [`read_at`]. `absent`, where present, must hold the object
/// representation of `A::Value`, which the compiler takes from the census row
/// for the folded name after checking that row's value type against `A`'s. A
/// reference-valued default addresses `'static` data, so the value it yields
/// outlives any evaluation.
pub unsafe fn read_at_defaulting<'e, A: attribute::Attribute>(rec: Rec<'_>, offset: Option<usize>, absent: Option<&[u8]>) -> attribute::Attr<'e, A> {
attribute::Attr(match (offset, absent) {
// SAFETY: the caller's contract.
(Some(offset), _) => unsafe { rec.read::<A::Value<'e>>(offset) },
// SAFETY: the caller's contract; the bytes are unaligned storage, so
// the value is read out rather than referenced in place.
(None, Some(bytes)) => unsafe { bytes.as_ptr().cast::<A::Value<'e>>().read_unaligned() },
(None, None) => A::default(),
})
}
/// The read-less [`DerivedLazyInput`] glue: the token alone.
///
/// # Safety
/// `rec` must be a spilled record's frame.
pub unsafe fn token_only<'e>(rec: Rec<'_>, _reads: &[Option<usize>]) -> RecordValue<'e> {
RecordValue::spilled(rec)
}
/// # Safety
/// `offset` must be a field offset of the layout of the record under
/// construction at `dst` and `T` the field's type; both are proven at wiring.
pub unsafe fn write_field<T>(dst: *mut u8, offset: usize, value: T) {
unsafe { dst.add(offset).cast::<T>().write(value) }
}
/// # Safety
/// The record's element must be a `T` in the form [`element_parked`] picks,
/// and the borrow is only valid while the record is.
pub unsafe fn borrow_element<'e, T>(rec: Rec<'_>) -> &'e T {
match element_parked::<T>() {
true => unsafe { rec.element::<&T>() },
false => unsafe { &*rec.ptr().cast::<T>() },
}
}
/// # Safety
/// The record's element must be a `T` in the form [`element_parked`] picks.
pub unsafe fn read_element<T: Clone>(rec: Rec<'_>) -> T {
unsafe { borrow_element::<T>(rec) }.clone()
}
/// # Safety
/// `dst` must be fresh element storage of a record whose element is `T`.
/// `None` reports arena exhaustion for a parked element.
pub unsafe fn write_element<T: Send + Sync + dyn_any::StaticTypeSized>(dst: *mut u8, value: T, arena: &crate::arena::Arena) -> Option<()> {
unsafe { write_element_sized(dst, value, arena, 0) }
}
/// [`write_element`] with the park glue's estimate of the heap `value` owns.
///
/// # Safety
/// As [`write_element`].
pub unsafe fn write_element_sized<T: Send + Sync + dyn_any::StaticTypeSized>(dst: *mut u8, value: T, arena: &crate::arena::Arena, retained: usize) -> Option<()> {
// SAFETY: the caller's contract; `T::Static` is the element type's own key.
unsafe { write_element_keyed(dst, value, arena, retained, std::any::TypeId::of::<T::Static>()) }
}
/// [`write_element_sized`] for replay glue already holding the element's
/// static form, whose key the element type it replays into supplies.
///
/// # Safety
/// As [`write_element`], and `type_of` must be that element type's key, since
/// a park carrying it is what [`Promotion::move_park`] moves at.
pub(in crate::record) unsafe fn write_element_keyed<T: Send + Sync>(dst: *mut u8, value: T, arena: &crate::arena::Arena, retained: usize, type_of: std::any::TypeId) -> Option<()> {
match element_parked::<T>() {
true => {
let (parked, _) = arena.alloc_sized_as(value, retained, type_of)?;
unsafe { dst.cast::<&T>().write(parked) };
Some(())
}
false => {
unsafe { dst.cast::<T>().write(value) };
Some(())
}
}
}
/// Finishes a carried record frame: the element lands beside the fields
/// already carried into `dst`, and inline frames copy out of the scratch
/// bytes. Arena exhaustion of a parked element reports as an error poll.
///
/// # Safety
/// `dst` must be the claimed frame (or inline scratch when `frame_bytes` is
/// 0) of a record whose element is `T` and whose frame size is `frame_bytes`,
/// with every carried field already written.
pub(in crate::record) unsafe fn lift_poll_into<'e, T: Send + Sync + dyn_any::StaticTypeSized>(
poll: GPoll<T>,
dst: *mut u8,
frame_bytes: usize,
arena: &'e crate::arena::Arena,
) -> GPoll<RecordValue<'e>> {
let build = |element: T| {
let written = unsafe { write_element(dst, element, arena) };
written.map(|()| match frame_bytes {
0 => unsafe { dst.cast::<RecordValue>().read() },
_ => RecordValue::spilled(unsafe { Rec::new(dst.cast_const()) }),
})
};
let exhausted = || {
GPoll::Error(Box::new(crate::gpoll::GraphError {
kind: crate::gpoll::ErrorKind::ArenaExhausted,
trace: Vec::new(),
}))
};
match poll {
GPoll::Final(element) => build(element).map_or_else(exhausted, GPoll::Final),
GPoll::Partial(element) => build(element).map_or_else(exhausted, GPoll::Partial),
GPoll::Fallback(boxed) => {
let (element, error) = *boxed;
build(element).map_or_else(exhausted, |value| GPoll::Fallback(Box::new((value, error))))
}
GPoll::Pending => GPoll::Pending,
GPoll::Error(error) => GPoll::Error(error),
}
}
/// # Safety
/// `src` must be a record of the plan's source layout and `dst` a buffer of
/// the plan's target layout; both are proven at wiring. The two records must
/// not overlap: a plan routinely carries identity moves, so each entry copies
/// non-overlapping and an aliasing pair is undefined on the first copy.
pub unsafe fn apply_plan(src: Rec<'_>, dst: *mut u8, plan: &[(usize, usize, usize)]) {
for &(from, to, size) in plan {
unsafe { std::ptr::copy_nonoverlapping(src.ptr().add(from), dst.add(to), size) };
}
}
/// The value with its lifetimes substituted by `'static`, for erased storage
/// whose reads re-bind a live lifetime.
///
/// # Safety
/// The erased value's borrows must not be used past their real lifetimes: the
/// stored form may only be read through a surface that re-binds a lifetime no
/// longer than the borrows' own, or after deep glue replaced every borrow with
/// owned content.
pub unsafe fn erase_static<T: dyn_any::StaticTypeSized>(value: T) -> T::Static {
let value = std::mem::ManuallyDrop::new(value);
// SAFETY: `Static` is `Self` with lifetimes substituted, layout-identical
// by `StaticTypeSized`'s contract.
unsafe { std::ptr::read((&raw const value).cast::<T::Static>()) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn elements_write_and_read_in_their_picked_form() {
let arena = crate::arena::Arena::new(256).unwrap();
let mut inline = [0u64; 2];
unsafe { write_element(inline.as_mut_ptr().cast(), 4.5f64, &arena) }.unwrap();
let rec = unsafe { Rec::new(inline.as_ptr().cast()) };
assert_eq!(unsafe { *borrow_element::<f64>(rec) }, 4.5);
assert_eq!(unsafe { read_element::<f64>(rec) }, 4.5);
let mut parked = [0u64; 2];
unsafe { write_element(parked.as_mut_ptr().cast(), String::from("moved once"), &arena) }.unwrap();
let rec = unsafe { Rec::new(parked.as_ptr().cast()) };
assert_eq!(unsafe { borrow_element::<String>(rec) }.as_str(), "moved once");
assert_eq!(unsafe { read_element::<String>(rec) }, "moved once");
}
#[test]
fn record_values_are_one_word() {
assert_eq!(size_of::<RecordValue>(), 8);
assert_eq!(align_of::<RecordValue>(), 8);
}
}
@@ -0,0 +1,185 @@
//! The evaluation's record frame storage.
use super::access::RecordValue;
use super::layout::Layout;
use super::serve::{FrameClaim, SlotRun};
/// The evaluation's record frame space: a grow-only buffer the executor owns
/// and lends by `&mut`, sized by the wiring-derived frame need, so exhaustion
/// is an accounting failure the debug assertion catches rather than a hot-path
/// branch. Frame bytes carry no drop glue, so growth and reuse are plain
/// buffer operations.
#[derive(Debug, Default)]
pub struct FrameArena {
buf: Vec<u64>,
}
impl FrameArena {
pub fn new() -> Self {
Self { buf: Vec::new() }
}
/// Grows the buffer to hold `bytes`, the root's wiring-derived frame need.
/// Grow-only, so repeated evaluations reuse one allocation.
pub fn reserve(&mut self, bytes: usize) {
let words = bytes.div_ceil(8).max(1);
if self.buf.len() < words {
self.buf.resize(words, 0);
}
}
/// The whole buffer as free space, for one evaluation.
pub fn frames(&mut self) -> Frames<'_> {
let base = self.buf.as_mut_ptr().cast::<u8>();
Frames {
base: std::cell::Cell::new(base),
words: std::cell::Cell::new(self.buf.len()),
bounds: (base as usize, self.buf.len() * 8),
_lifetime: std::marker::PhantomData,
}
}
}
/// The free frame space at one point of an evaluation. [`Self::claim`] splits
/// a node's own frame off the front and the claim carries the remainder, so a
/// node's inputs claim beyond its frame, one after another, and the space they
/// used is free again once the claim dies: the release is the claim's
/// lifetime, not a rewind contract. The cursor is shared through `&self` so
/// the lazy inputs a kernel holds claim beyond each other rather than over each
/// other. Covariant in `'e`, so a claim minted at the evaluation shortens onto
/// a derived context's arena lifetime.
pub struct Frames<'e> {
base: std::cell::Cell<*mut u8>,
words: std::cell::Cell<usize>,
/// The whole buffer as (address, bytes), which stays fixed while claims
/// advance the cursor, so a promote can range-check a reference against it.
bounds: (usize, usize),
_lifetime: std::marker::PhantomData<&'e ()>,
}
impl std::fmt::Debug for Frames<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Frames").field("free_words", &self.words.get()).finish()
}
}
impl<'e> Frames<'e> {
/// An independent cursor over the same free space: claims made through it
/// are free again when it dies, so a repeated evaluation reuses one region.
/// Two live cursors hand out the same region, so only one may be claimed
/// from at a time.
pub fn reborrow(&self) -> Frames<'e> {
Frames {
base: std::cell::Cell::new(self.base.get()),
words: std::cell::Cell::new(self.words.get()),
bounds: self.bounds,
_lifetime: std::marker::PhantomData,
}
}
/// The whole frame buffer as (address, bytes), the range a promote treats
/// as evaluation-lived.
pub fn bounds(&self) -> (usize, usize) {
self.bounds
}
/// Runs claims against this space and gives it back on the guard's drop, so
/// a loop that evaluates a subtree per iteration reuses the same region.
pub fn scope(&self) -> FrameScope<'_, 'e> {
FrameScope {
frames: self,
base: self.base.get(),
words: self.words.get(),
}
}
/// The words still free, the observable the frame accounting asserts on.
pub fn free_words(&self) -> usize {
self.words.get()
}
/// Claims `layout`'s frame at the front of the free space; the claim
/// carries the remainder, and an inline layout's record builds in the
/// claim itself.
pub fn claim<'l>(&self, layout: &'l Layout) -> FrameClaim<'e, 'l> {
let frame = match layout.frame_bytes() {
0 => None,
bytes => Some(self.split(bytes)),
};
FrameClaim {
layout,
inline: RecordValue::zeroed(),
frame,
free: self.reborrow(),
filled_fields: false,
}
}
/// Splits `bytes` (rounded to word alignment) off the front.
fn split(&self, bytes: usize) -> *mut u8 {
let words = bytes.div_ceil(8);
debug_assert!(words <= self.words.get(), "record frame space exhausted: the root buffer must cover the graph's frame need");
let frame = self.base.get();
// SAFETY: the buffer covers the wiring-derived need, so the advanced
// cursor stays within it.
self.base.set(unsafe { frame.add(words * 8) });
self.words.set(self.words.get() - words);
frame
}
/// A run of same-layout slots over caller scratch: lanes serve in place,
/// each backed by its own region of the slab, and the collected proofs
/// certify the filled prefix. `None` where the scratch cannot hold `len`
/// lanes.
pub fn run<'a>(&self, scratch: &'a mut [std::mem::MaybeUninit<u64>], len: usize, layout: &'a Layout) -> Option<SlotRun<'a>> {
SlotRun::new(scratch, len, layout)
}
}
/// See [`Frames::scope`]. A forgotten guard leaks its region until the frame
/// space itself dies, rather than releasing it.
pub struct FrameScope<'s, 'e> {
frames: &'s Frames<'e>,
base: *mut u8,
words: usize,
}
impl<'e> std::ops::Deref for FrameScope<'_, 'e> {
type Target = Frames<'e>;
fn deref(&self) -> &Frames<'e> {
self.frames
}
}
impl Drop for FrameScope<'_, '_> {
fn drop(&mut self) {
self.frames.base.set(self.base);
self.frames.words.set(self.words);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::record::layout::element_write;
use crate::record::test_support::f64_field;
#[test]
fn a_scope_releases_and_reuses_its_frames() {
let layout = Layout::default().with_writes(0, element_write::<f64>(), &[f64_field("opacity")]);
let mut frame_arena = FrameArena::new();
frame_arena.reserve(1 << 10);
let frames = frame_arena.frames();
let free = frames.free_words();
let mut addresses = Vec::new();
for _ in 0..3 {
let scope = frames.scope();
let mut claim = scope.claim(&layout);
addresses.push(claim.dst() as usize);
drop(scope);
assert_eq!(frames.free_words(), free, "the scope returns its claims");
}
assert!(addresses.windows(2).all(|pair| pair[0] == pair[1]), "each claim reuses the same region");
}
}
@@ -0,0 +1,524 @@
//! Consumer-side bindings onto a record input, and the drivers they run.
use super::access::{Rec, RecordValue, read_element};
use super::frames::Frames;
use super::layout::Layout;
use super::serve::{FrameClaim, Served, serve_input};
use crate::gpoll::GPoll;
use crate::node::Node;
/// A record input evaluable at a derived context, yielding the record at that
/// context's lifetime. The lifetime is a trait parameter because a bound like
/// `for<'d> Node<Derived<'d, C>>` cannot also say the derived context's arena
/// is at `'d`: the equality binding `ExtractArena<ArenaRef = &'d Arena>` is an
/// unconstrained position under a higher rank.
pub trait DerivedRecordInput<'derived, C> {
fn eval_derived(&self, cell: &crate::node::StatusCell, input_index: usize, ctx: &C, frames: &Frames<'derived>) -> Result<RecordValue<'derived>, crate::gpoll::Interrupt>;
fn extent_at_derived(&self, ctx: &C, level: u8, frames: &Frames<'derived>) -> GPoll<crate::gpoll::Extent>;
}
impl<'derived, C, N> DerivedRecordInput<'derived, C> for N
where
N: Node<C>,
C: crate::context::ExtractArena<ArenaRef = &'derived crate::arena::Arena>,
{
fn eval_derived(&self, cell: &crate::node::StatusCell, input_index: usize, ctx: &C, frames: &Frames<'derived>) -> Result<RecordValue<'derived>, crate::gpoll::Interrupt> {
cell.eval_input(input_index, self, ctx, frames)
}
fn extent_at_derived(&self, ctx: &C, level: u8, frames: &Frames<'derived>) -> GPoll<crate::gpoll::Extent> {
self.extent_at(ctx, level, frames)
}
}
/// Fills caller scratch with one frame per lane of `range`: the input serves
/// into the lane's own region of the slab, and the lane's own frame space is
/// free again at the next lane, so the frame peak stays at one lane's need and
/// every lane's bytes are distinct.
pub fn fill_frames<'a, 'e, C, N>(node: &'a N, input: &C, range: std::ops::Range<u64>, scratch: Option<&'a mut [std::mem::MaybeUninit<u64>]>, frames: &Frames<'e>) -> crate::node::BatchStatus<'a>
where
C: crate::context::InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
N: Node<C>,
{
use crate::node::BatchStatus;
let Some(scratch) = scratch else {
return BatchStatus::NeedBuffer;
};
let Some(len) = range.end.checked_sub(range.start).and_then(|len| usize::try_from(len).ok()) else {
return BatchStatus::InvalidRange;
};
let Some(mut run) = frames.run(scratch, len, node.layout()) else {
return BatchStatus::InvalidRange;
};
let mut local = *input;
let mut finality = crate::gpoll::Finality::AllFinal;
let mut hint = crate::gpoll::Extent::AtLeast(range.end as usize);
for lane in 0..len {
local.set_index(range.start + lane as u64);
let lane_frames = frames.scope();
let slot = run.slot(lane, &lane_frames);
let served = match node.serve(&local, slot) {
GPoll::Final(served) => served,
GPoll::Partial(served) => {
finality = crate::gpoll::Finality::Partial;
served
}
GPoll::Pending => return BatchStatus::Pending,
GPoll::Fallback(boxed) => return BatchStatus::Error(boxed.1),
// A lane past a lower-bound level ends the data: the fill comes
// back short and the hint turns exact.
GPoll::Error(error) if error.kind == crate::gpoll::ErrorKind::PastEnd => {
hint = crate::gpoll::Extent::Exactly(range.start as usize + lane);
break;
}
GPoll::Error(error) => return BatchStatus::Error(*error),
};
run.served(lane, &served);
}
BatchStatus::Filled(run.finish(), finality, hint)
}
/// The driver a consumer runs on a record input: a resident batch returns with
/// no allocation, a node's own batch impl gets `n * frame_bytes` of arena
/// scratch, and an unbatched input falls back to the [`fill_frames`] loop.
pub fn materialize_batch<'a, 'e, C, N>(node: &'a N, input: &'a C, range: std::ops::Range<u64>, arena: &'a crate::arena::Arena, frames: &Frames<'e>) -> crate::node::BatchStatus<'a>
where
C: crate::context::InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
N: Node<C>,
{
use crate::node::BatchStatus;
let Some(len) = range.end.checked_sub(range.start).and_then(|len| usize::try_from(len).ok()) else {
return BatchStatus::InvalidRange;
};
// Checked: a wrapped product would size the scratch below the run.
let Some(words) = len.checked_mul(node.layout().lane_stride()).map(|bytes| bytes / 8) else {
return BatchStatus::InvalidRange;
};
let exhausted = || {
BatchStatus::Error(crate::gpoll::GraphError {
kind: crate::gpoll::ErrorKind::ArenaExhausted,
trace: Vec::new(),
})
};
match node.eval_batch(input, range.clone(), None, frames) {
BatchStatus::Unbatched => match arena.alloc_scratch::<u64>(words) {
Some(scratch) => fill_frames(node, input, range, Some(scratch), frames),
None => exhausted(),
},
BatchStatus::NeedBuffer => match arena.alloc_scratch::<u64>(words) {
Some(scratch) => node.eval_batch(input, range, Some(scratch), frames),
None => exhausted(),
},
status => status,
}
}
/// The outcome of materializing a leveled input's whole flat span.
pub enum LevelStatus<'a> {
Batch(crate::node::RecordBatch<'a>, crate::gpoll::Finality),
Pending,
Error(crate::gpoll::GraphError),
}
/// Evaluates a leveled input's whole flat span into one batch: an exact total
/// fills once, a lower bound drains by guess-and-double until a short fill,
/// each reply's hint seeding the next guess. The boundary consumers' driver;
/// reducers inline the same protocol with their span offsets.
pub fn materialize_level<'a, 'e, C, N>(node: &'a N, input: &'a C, arena: &'a crate::arena::Arena, frames: &Frames<'e>) -> LevelStatus<'a>
where
C: crate::context::InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
N: Node<C>,
{
use crate::gpoll::{Extent, GraphError, Level};
use crate::node::BatchStatus;
let sized = match node.extent(input, Level::Total, frames) {
GPoll::Final(Extent::Exactly(count)) => Ok(count),
GPoll::Final(Extent::AtLeast(bound)) => Err(bound),
GPoll::Pending => return LevelStatus::Pending,
_ => return LevelStatus::Error(GraphError::new("materialize over a non-exact extent")),
};
match sized {
Ok(count) => match materialize_batch(node, input, 0..count as u64, arena, frames) {
BatchStatus::Lent(batch, finality, _) => LevelStatus::Batch(batch, finality),
BatchStatus::Filled(batch, finality, _) => LevelStatus::Batch(batch.into_shared(), finality),
BatchStatus::Pending => LevelStatus::Pending,
BatchStatus::Error(error) => LevelStatus::Error(error),
_ => LevelStatus::Error(GraphError::new("materialize batch failed")),
},
Err(bound) => {
let mut guess = bound.max(16);
loop {
let (batch, finality, hint) = match materialize_batch(node, input, 0..guess as u64, arena, frames) {
BatchStatus::Lent(batch, finality, hint) => (batch, finality, hint),
BatchStatus::Filled(batch, finality, hint) => (batch.into_shared(), finality, hint),
BatchStatus::Pending => return LevelStatus::Pending,
BatchStatus::Error(error) => return LevelStatus::Error(error),
_ => return LevelStatus::Error(GraphError::new("materialize batch failed")),
};
let filled = batch.len();
if filled < guess {
break LevelStatus::Batch(batch, finality);
}
match hint {
Extent::Exactly(total) if total <= filled => break LevelStatus::Batch(batch, finality),
Extent::Exactly(total) => guess = total,
Extent::AtLeast(more) => guess = (guess * 2).max(more),
Extent::Free => guess *= 2,
}
}
}
}
}
/// The raw lazy record input handed to a record-opaque kernel: the input plus
/// its wiring-proven layout, the pairing the kernel's unsafe record
/// operations rely on. The kernel must only pair the layout with values this
/// input produced.
pub struct RecordInput<'a, 'e, N> {
node: &'a N,
layout: &'a Layout,
frames: &'a Frames<'e>,
}
impl<'a, 'e, N> RecordInput<'a, 'e, N> {
pub fn new(node: &'a N, layout: &'a Layout, frames: &'a Frames<'e>) -> Self {
Self { node, layout, frames }
}
pub fn layout(&self) -> &Layout {
self.layout
}
/// Serves the input through the kernel's own claim: the kernel's output
/// layout is the input's, so the claim it was handed is the input's frame.
pub fn serve<'l, C>(&self, ctx: &C, slot: FrameClaim<'e, 'l>) -> GPoll<Served<'e>>
where
N: Node<C>,
C: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
self.node.serve(ctx, slot)
}
/// [`materialize_level`] over the input: the input's whole flat span as one
/// batch.
pub fn materialize_level<'b, C>(&'b self, ctx: &'b C, arena: &'b crate::arena::Arena) -> LevelStatus<'b>
where
N: Node<C>,
C: crate::context::InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
materialize_level(self.node, ctx, arena, self.frames)
}
}
/// # Safety
/// `rec` must be a record of the layout the offsets were resolved against
/// and `El` its element type; both are proven at wiring.
unsafe fn element_only<El: Clone>(rec: Rec<'_>, _reads: &[Option<usize>]) -> El {
// SAFETY: the caller's contract.
unsafe { read_element::<El>(rec) }
}
/// The raw lazy input handed to a poll kernel whose input rides records while
/// the kernel consumes the plain element.
pub struct ElementInput<'a, 'e, Out, N> {
node: &'a N,
layout: &'a Layout,
reads: &'a [Option<usize>],
read: unsafe fn(Rec<'_>, &[Option<usize>]) -> Out,
frames: &'a Frames<'e>,
}
impl<'a, 'e, El: Clone, N> ElementInput<'a, 'e, El, N> {
pub fn new(node: &'a N, layout: &'a Layout, frames: &'a Frames<'e>) -> Self {
Self {
node,
layout,
reads: &[],
read: element_only::<El>,
frames,
}
}
}
impl<'a, 'e, Out, N> ElementInput<'a, 'e, Out, N> {
/// `read` must be sound against the layout the offsets in `reads` were
/// resolved from; the macro proves both at wiring.
pub fn with_reads(node: &'a N, layout: &'a Layout, reads: &'a [Option<usize>], read: unsafe fn(Rec<'_>, &[Option<usize>]) -> Out, frames: &'a Frames<'e>) -> Self {
Self { node, layout, reads, read, frames }
}
/// The input's element at `ctx`, read out of a record claimed beyond the
/// kernel's own frame; the claim dies with the call, so the record is free
/// again at the next one.
pub fn eval<'d, C>(&self, ctx: &C) -> GPoll<Out>
where
N: DerivedRecordInput<'d, C>,
'e: 'd,
{
let cell = crate::node::StatusCell::new();
let scope = self.frames.scope();
match self.node.eval_derived(&cell, 0, ctx, &scope) {
// SAFETY: the read copies out by value against the input's own layout.
Ok(value) => cell.finish(unsafe { (self.read)(self.layout.rec(&value), self.reads) }),
Err(interrupt) => interrupt.into(),
}
}
}
/// The lazy input handed to a kernel whose input rides a record while
/// the kernel consumes the plain element, or the element beside its declared
/// attribute reads.
#[derive(Clone, Copy)]
pub struct ElementLazyInput<'a, 'e, Out, N> {
node: &'a N,
cell: &'a crate::node::StatusCell,
input_index: usize,
layout: &'a Layout,
reads: &'a [Option<usize>],
read: unsafe fn(Rec<'_>, &[Option<usize>]) -> Out,
frames: &'a Frames<'e>,
}
impl<'a, 'e, El: Clone, N> ElementLazyInput<'a, 'e, El, N> {
pub fn new(node: &'a N, cell: &'a crate::node::StatusCell, input_index: usize, layout: &'a Layout, frames: &'a Frames<'e>) -> Self {
Self {
node,
cell,
input_index,
layout,
reads: &[],
read: element_only::<El>,
frames,
}
}
}
impl<'a, 'e, Out, N> ElementLazyInput<'a, 'e, Out, N> {
/// `read` must be sound against the layout the offsets in `reads` were
/// resolved from; the macro proves both at wiring.
pub fn with_reads(
node: &'a N,
cell: &'a crate::node::StatusCell,
input_index: usize,
layout: &'a Layout,
reads: &'a [Option<usize>],
read: unsafe fn(Rec<'_>, &[Option<usize>]) -> Out,
frames: &'a Frames<'e>,
) -> Self {
Self {
node,
cell,
input_index,
layout,
reads,
read,
frames,
}
}
/// The read copies the element and declared attributes out by value, so
/// the record's claim dies with the call.
pub fn eval<'d, C>(&self, ctx: &C) -> Result<Out, crate::gpoll::Interrupt>
where
N: DerivedRecordInput<'d, C>,
'e: 'd,
{
let scope = self.frames.scope();
let value = self.node.eval_derived(self.cell, self.input_index, ctx, &scope)?;
// SAFETY: the reads are the input's own layout's, resolved at wiring.
Ok(unsafe { (self.read)(self.layout.rec(&value), self.reads) })
}
}
/// The lazy record input handed to a kernel that evaluates its inputs under
/// derived contexts: evaluating rebinds the record to the kernel's routing
/// lifetime, so the value escapes the derivation scope.
#[derive(Clone, Copy)]
pub struct RecordLazyInput<'a, 'e, N> {
node: &'a N,
cell: &'a crate::node::StatusCell,
input_index: usize,
inner_levels: u8,
frames: &'a Frames<'e>,
}
impl<'a, 'e, N> RecordLazyInput<'a, 'e, N> {
pub fn new(node: &'a N, cell: &'a crate::node::StatusCell, input_index: usize, inner_levels: u8, frames: &'a Frames<'e>) -> Self {
Self {
node,
cell,
input_index,
inner_levels,
frames,
}
}
pub fn eval<'d, C>(&self, ctx: &C) -> Result<RecordValue<'e>, crate::gpoll::Interrupt>
where
N: DerivedRecordInput<'d, C>,
'e: 'd,
{
Ok(self.node.eval_derived(self.cell, self.input_index, ctx, self.frames)?.rebind())
}
/// The flat lane count of one copy: the product of the input's inner-level
/// extents, queried uniform across copies (at copy 0). The dividend of a
/// structure node's decompose-and-promote.
pub fn inner_extent<B>(&self, ctx: &B) -> Result<u64, crate::gpoll::Interrupt>
where
B: crate::context::DeriveCtx,
N: for<'d> DerivedRecordInput<'d, crate::context::Derived<'d, B>>,
{
inner_extent_of(self.node, ctx, 0, self.inner_levels, self.input_index, self.frames)
}
/// The flat lane count of the copy at `copy`, for inputs whose inner
/// extents vary per copy.
pub fn inner_extent_at<B>(&self, ctx: &B, copy: u64) -> Result<u64, crate::gpoll::Interrupt>
where
B: crate::context::DeriveCtx,
N: for<'d> DerivedRecordInput<'d, crate::context::Derived<'d, B>>,
{
inner_extent_of(self.node, ctx, copy, self.inner_levels, self.input_index, self.frames)
}
}
/// See [`RecordLazyInput::inner_extent`].
fn inner_extent_of<B, N>(node: &N, ctx: &B, copy: u64, levels: u8, input_index: usize, frames: &Frames<'_>) -> Result<u64, crate::gpoll::Interrupt>
where
B: crate::context::DeriveCtx,
N: for<'d> DerivedRecordInput<'d, crate::context::Derived<'d, B>>,
{
let mut frame = crate::context::IndexLink { index: 0, outer: None };
let derived = ctx.push_level(&mut frame, copy, 0);
let mut inner: u64 = 1;
for level in 0..levels {
match node.extent_at_derived(&derived, level, frames) {
GPoll::Final(crate::gpoll::Extent::Exactly(count)) => inner *= count as u64,
GPoll::Final(crate::gpoll::Extent::AtLeast(_)) => return probed_inner(node, ctx, copy, input_index, frames),
GPoll::Pending => return Err(crate::gpoll::Interrupt::Pending),
_ => return Err(crate::gpoll::GraphError::new("structure decomposition over a non-exact extent").into()),
}
}
Ok(inner)
}
/// The flat lane count of one copy of a lower-bound input, probed by
/// evaluating lanes to the past-end signal. The probed records are
/// discarded, and their statuses land in a scratch cell.
fn probed_inner<B, N>(node: &N, ctx: &B, copy: u64, input_index: usize, frames: &Frames<'_>) -> Result<u64, crate::gpoll::Interrupt>
where
B: crate::context::DeriveCtx,
N: for<'d> DerivedRecordInput<'d, crate::context::Derived<'d, B>>,
{
let cell = crate::node::StatusCell::new();
let mut count: u64 = 0;
loop {
// The probed record is discarded, so the probe's claim is free again
// at the next iteration.
let probe_frames = frames.scope();
let mut frame = crate::context::IndexLink { index: 0, outer: None };
let probe = ctx.push_level(&mut frame, copy, count);
let result = node.eval_derived(&cell, input_index, &probe, &probe_frames);
match result {
Ok(_) => count += 1,
Err(crate::gpoll::Interrupt::Error(error)) if error.kind == crate::gpoll::ErrorKind::PastEnd => return Ok(count),
Err(interrupt) => return Err(interrupt),
}
}
}
/// The derive-routing carrier beside its declared attribute reads: evaluating
/// at a derived context yields the opaque row token and the read values in one
/// step, so the kernel drives the per-copy eval while reads stay resolved
/// against the source's wired layout.
#[derive(Clone, Copy)]
pub struct DerivedLazyInput<'a, 'e, Out, N> {
node: &'a N,
cell: &'a crate::node::StatusCell,
input_index: usize,
inner_levels: u8,
reads: &'a [Option<usize>],
read: unsafe fn(Rec<'_>, &[Option<usize>]) -> Out,
frames: &'a Frames<'e>,
}
impl<'a, 'e, Out, N> DerivedLazyInput<'a, 'e, Out, N> {
/// `read` must be sound against the layout the offsets in `reads` were
/// resolved from; the macro proves both at wiring.
pub fn new(
node: &'a N,
cell: &'a crate::node::StatusCell,
input_index: usize,
inner_levels: u8,
reads: &'a [Option<usize>],
read: unsafe fn(Rec<'_>, &[Option<usize>]) -> Out,
frames: &'a Frames<'e>,
) -> Self {
Self {
node,
cell,
input_index,
inner_levels,
reads,
read,
frames,
}
}
/// The flat lane count of one copy; see [`RecordLazyInput::inner_extent`].
pub fn inner_extent<B>(&self, ctx: &B) -> Result<u64, crate::gpoll::Interrupt>
where
B: crate::context::DeriveCtx,
N: for<'d> DerivedRecordInput<'d, crate::context::Derived<'d, B>>,
{
inner_extent_of(self.node, ctx, 0, self.inner_levels, self.input_index, self.frames)
}
pub fn eval<'d, C>(&self, ctx: &C) -> Result<Out, crate::gpoll::Interrupt>
where
N: DerivedRecordInput<'d, C>,
'e: 'd,
{
let value: RecordValue<'e> = self.node.eval_derived(self.cell, self.input_index, ctx, self.frames)?.rebind();
// SAFETY: declared reads imply a non-empty layout, so the record is
// spilled and its pointer is the frame the offsets index into.
Ok(unsafe { (self.read)(Rec::new(value.ptr), self.reads) })
}
}
/// A plain probe over a record input, cloning the element out of the parked
/// reference when it carries drop glue. Registry constructors wrap a record
/// input in one to feed a node's plain value input, keeping the input kind
/// uniform.
pub struct RecordExtract<El, N> {
edge: N,
layout: Layout,
_marker: std::marker::PhantomData<fn() -> El>,
}
impl<El, N> RecordExtract<El, N> {
pub fn new(edge: N, layout: &Layout) -> Self {
Self {
edge,
layout: layout.clone(),
_marker: std::marker::PhantomData,
}
}
}
impl<El: Clone + 'static, N> RecordExtract<El, N> {
/// The input's element, copied out of its record.
pub fn eval<'e, C>(&self, input: &C, frames: &Frames<'e>) -> GPoll<El>
where
N: Node<C>,
C: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
// The element copies out by value, so the input's claim dies with
// the scope.
let scope = frames.scope();
// SAFETY: the served value is a record of `self.layout`, whose element is
// `El` by the wiring that built this extract.
serve_input(&self.edge, input, &scope).map(|value| unsafe { read_element::<El>(self.layout.rec(&value)) })
}
}
@@ -0,0 +1,882 @@
//! Wiring-time shape facts: the layout a record takes and the writes it folds from.
use super::access::{Rec, RecordValue, borrow_element, erase_static, read_element, write_element_keyed};
use super::owned::deep_element_glue;
use super::promote::{Promotion, retained_measure};
use crate::attribute;
/// A field write declared at wiring, carrying the marker's erased-read glue
/// so introspection and persistence never consult the census at runtime.
#[derive(Clone, Copy, Debug)]
pub struct FieldWrite {
pub name: &'static str,
pub level: u8,
pub size: usize,
pub align: usize,
pub type_id: std::any::TypeId,
pub read_erased: unsafe fn(*const u8) -> Box<dyn crate::list::AnyAttributeValue>,
pub repark: Option<crate::list::ReparkFn>,
/// Hashes the field's content. `None` means the stored bytes are the
/// content, which holds for every unparked value.
pub content_hash: Option<unsafe fn(*const u8, &mut dyn core::hash::Hasher)>,
/// Compares two fields' content. `None` as for `content_hash`.
pub content_eq: Option<unsafe fn(*const u8, *const u8) -> bool>,
}
impl FieldWrite {
pub fn of<A: crate::attribute::Attribute>(level: u8) -> Self
where
A::Value<'static>: graphene_hash::CacheHash + PartialEq + 'static,
{
/// # Safety
/// `ptr` must address a live `V`.
unsafe fn content_hash<V: graphene_hash::CacheHash>(ptr: *const u8, state: &mut dyn core::hash::Hasher) {
let mut state = state;
// SAFETY: the caller's contract.
unsafe { &*ptr.cast::<V>() }.cache_hash(&mut state);
}
/// # Safety
/// `a` and `b` must both address a live `V`.
unsafe fn content_eq<V: PartialEq>(a: *const u8, b: *const u8) -> bool {
// SAFETY: the caller's contract.
unsafe { *a.cast::<V>() == *b.cast::<V>() }
}
Self {
name: A::NAME,
level,
size: size_of::<A::Value<'static>>(),
align: align_of::<A::Value<'static>>(),
type_id: std::any::TypeId::of::<A::Value<'static>>(),
read_erased: A::read_erased,
repark: A::REPARK,
content_hash: Some(content_hash::<A::Value<'static>>),
content_eq: Some(content_eq::<A::Value<'static>>),
}
}
}
/// One field of a [`Layout`]: a (name, level) key resolved to an offset.
/// Levels are numbered innermost-out; only level 0 exists at rank 0.
/// Equality is structural over the field's identity, its value type
/// included; only the glue pointers are excluded, since fn-pointer identity
/// is not guaranteed across codegen units and layout equality drives
/// identity forwarding.
#[derive(Clone, Debug)]
pub struct FieldDesc {
pub name: &'static str,
pub level: u8,
pub offset: usize,
pub size: usize,
pub align: usize,
pub type_id: std::any::TypeId,
pub read_erased: unsafe fn(*const u8) -> Box<dyn crate::list::AnyAttributeValue>,
pub repark: Option<crate::list::ReparkFn>,
/// Hashes the field's content. `None` means the stored bytes are the
/// content, which holds for every unparked value.
pub content_hash: Option<unsafe fn(*const u8, &mut dyn core::hash::Hasher)>,
/// Compares two fields' content. `None` as for `content_hash`.
pub content_eq: Option<unsafe fn(*const u8, *const u8) -> bool>,
}
impl PartialEq for FieldDesc {
fn eq(&self, other: &Self) -> bool {
(self.name, self.level, self.offset, self.size, self.align, self.type_id) == (other.name, other.level, other.offset, other.size, other.align, other.type_id)
}
}
impl FieldDesc {
/// The write this field re-declares when a layout's fields fold into
/// another layout.
pub fn as_write(&self) -> FieldWrite {
FieldWrite {
name: self.name,
level: self.level,
size: self.size,
align: self.align,
type_id: self.type_id,
read_erased: self.read_erased,
repark: self.repark,
content_hash: self.content_hash,
content_eq: self.content_eq,
}
}
}
impl Eq for FieldDesc {}
/// The element slot of a layout: its dimensions plus erased glue bound where
/// the element type is statically known, so generic consumers read or
/// deep-copy the element without it. Equality is structural over the
/// element's identity, its type included; glue pointers are excluded for the
/// same reason as [`FieldDesc`]'s.
#[derive(Clone, Copy, Debug)]
pub struct ElementWrite {
pub size: usize,
pub align: usize,
pub parked: bool,
pub type_id: std::any::TypeId,
pub clone_out: unsafe fn(*const u8) -> Box<dyn std::any::Any + Send + Sync>,
pub repark: unsafe fn(&(dyn std::any::Any + Send + Sync), *mut u8, &crate::arena::Arena) -> Option<()>,
/// Moves a parked payload's header into the persistent region rather than
/// cloning the heap it owns, returning the new header. `None` declines,
/// which leaves the caller its clone path.
pub park_move: unsafe fn(*const u8, &Promotion<'_>) -> Option<*const u8>,
/// Hashes the element's content. `None` means the stored bytes are the
/// content, which holds for every unparked element.
pub content_hash: Option<unsafe fn(*const u8, &mut dyn core::hash::Hasher)>,
/// Compares two elements' content. `None` as for `content_hash`.
pub content_eq: Option<unsafe fn(*const u8, *const u8) -> bool>,
}
impl PartialEq for ElementWrite {
fn eq(&self, other: &Self) -> bool {
(self.size, self.align, self.parked, self.type_id) == (other.size, other.align, other.parked, other.type_id)
}
}
impl Eq for ElementWrite {}
impl Default for ElementWrite {
fn default() -> Self {
/// # Safety
/// None: the empty element has no bytes, so nothing is read.
unsafe fn clone_out(_ptr: *const u8) -> Box<dyn std::any::Any + Send + Sync> {
Box::new(())
}
/// # Safety
/// None: nothing is written, the empty element having no slot.
unsafe fn repark(_value: &(dyn std::any::Any + Send + Sync), _dst: *mut u8, _arena: &crate::arena::Arena) -> Option<()> {
Some(())
}
/// # Safety
/// None: the move always declines, so `parked` is never read.
unsafe fn park_move(_parked: *const u8, _promotion: &Promotion<'_>) -> Option<*const u8> {
None
}
Self {
size: 0,
align: 0,
parked: false,
type_id: std::any::TypeId::of::<()>(),
clone_out,
repark,
park_move,
content_hash: None,
content_eq: None,
}
}
}
/// The widest alignment a record may need. Frames are a `Vec<u64>`, lanes
/// stride at a multiple of 8, and run slabs come from `alloc_scratch::<u64>`,
/// so nothing below a record can promise more.
pub const MAX_ALIGN: usize = 8;
/// A record layout: the element at offset 0, then the written attributes in
/// canonical order (descending alignment, then size, then name, then level).
/// Layouts are derived data, a pure function of the upstream write set.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Layout {
pub depth: u8,
pub element: ElementWrite,
pub fields: Vec<FieldDesc>,
pub size: usize,
pub align: usize,
}
impl Layout {
pub fn offset_of(&self, name: &str, level: u8) -> Option<usize> {
self.fields.iter().find(|field| field.name == name && field.level == level).map(|field| field.offset)
}
pub fn frame_bytes(&self) -> usize {
self.size.next_multiple_of(8)
}
/// One batch lane's stride: a spilled record's frame, or the value itself
/// for records this layout keeps inline (`size == 0`), whose payload rides
/// in the `RecordValue`'s own storage exactly as [`Layout::rec`] resolves.
pub fn lane_stride(&self) -> usize {
match self.size == 0 {
true => size_of::<RecordValue<'static>>(),
false => self.frame_bytes(),
}
}
/// Resolves a value of this layout, which must be its wiring-proven one,
/// to its record bytes. An empty record carries nothing and resolves to the
/// value's own storage; every other record spills and rides the pointer.
pub fn rec<'v>(&self, value: &'v RecordValue<'_>) -> Rec<'v> {
match self.size == 0 {
true => Rec((&raw const *value).cast(), std::marker::PhantomData),
false => Rec(value.ptr, std::marker::PhantomData),
}
}
/// The union of this layout's fields and `writes` over `element` at
/// `depth`, in canonical order. A (name, level) written at a different
/// size is a type conflict and panics, as does an element or attribute
/// wider than [`MAX_ALIGN`]; the census keeps declared names to one type,
/// so these only fire on wiring bugs.
pub fn with_writes(&self, depth: u8, element: ElementWrite, writes: &[FieldWrite]) -> Layout {
let mut merged: Vec<FieldWrite> = self.fields.iter().map(FieldDesc::as_write).collect();
for &write in writes {
match merged.iter().find(|field| field.name == write.name && field.level == write.level) {
Some(existing) => assert_eq!(existing.type_id, write.type_id, "attribute `{}` written at two different types", write.name),
None => merged.push(write),
}
}
assert!(element.align <= MAX_ALIGN, "a record element aligns to at most {MAX_ALIGN} bytes, but this one needs {}", element.align);
for write in &merged {
assert!(write.align <= MAX_ALIGN, "attribute `{}` aligns to at most {MAX_ALIGN} bytes, but needs {}", write.name, write.align);
}
merged.sort_by(|a, b| b.align.cmp(&a.align).then(b.size.cmp(&a.size)).then(a.name.cmp(b.name)).then(a.level.cmp(&b.level)));
let mut offset = element.size;
let mut align = element.align.max(1);
let fields = merged
.into_iter()
.map(|write| {
offset = offset.next_multiple_of(write.align.max(1));
align = align.max(write.align);
let desc = FieldDesc {
name: write.name,
level: write.level,
offset,
size: write.size,
align: write.align,
type_id: write.type_id,
read_erased: write.read_erased,
repark: write.repark,
content_hash: write.content_hash,
content_eq: write.content_eq,
};
offset += write.size;
desc
})
.collect();
Layout {
depth,
element,
fields,
size: offset,
align,
}
}
/// This layout minus the named fields, offsets recomputed. Removing an
/// absent name is a no-op: downstream reads yield the default either way.
pub fn without(&self, removes: &[(&str, u8)]) -> Layout {
let retained: Vec<FieldWrite> = self.fields.iter().filter(|field| !removes.contains(&(field.name, field.level))).map(FieldDesc::as_write).collect();
Layout::default().with_writes(self.depth, self.element, &retained)
}
/// The union of several layouts over the same element and depth.
pub fn union(layouts: &[&Layout]) -> Layout {
let first = layouts.first().expect("a union needs at least one layout");
// A shallower source joins the union lifted: a scalar concatenates as
// one lane, its fields sitting at the innermost level like any lane's.
let depth = layouts.iter().map(|layout| layout.depth).max().unwrap_or(first.depth);
let mut union = Layout::default().with_writes(depth, first.element, &[]);
for layout in layouts {
assert_eq!(union.element, layout.element, "union layouts must share the element");
let writes: Vec<FieldWrite> = layout.fields.iter().map(FieldDesc::as_write).collect();
union = union.with_writes(union.depth, union.element, &writes);
}
union
}
}
/// A field handle minted once against a layout: the marker's (name, level)
/// resolved to a field index and offset, with the marker-to-type proof taken
/// there. Resolving it against a layout re-checks that one index instead of
/// scanning names, so a token paired with any other layout resolves to
/// nothing rather than to the wrong bytes.
pub struct FieldOffset<A: attribute::Attribute> {
index: usize,
offset: usize,
level: u8,
marker: std::marker::PhantomData<fn() -> A>,
}
impl<A: attribute::Attribute> Clone for FieldOffset<A> {
fn clone(&self) -> Self {
*self
}
}
impl<A: attribute::Attribute> Copy for FieldOffset<A> {}
impl<A: attribute::Attribute> std::fmt::Debug for FieldOffset<A> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FieldOffset").field("name", &A::NAME).field("offset", &self.offset).field("level", &self.level).finish()
}
}
impl<A: attribute::Attribute> FieldOffset<A> {
/// The marker's field at `level`, `None` where the layout does not carry
/// it. Panics where the layout declares the name at another value type,
/// which the census forbids.
pub fn of(layout: &Layout, level: u8) -> Option<Self> {
let (index, field) = layout.fields.iter().enumerate().find(|(_, field)| field.name == A::NAME && field.level == level)?;
assert_eq!(field.type_id, std::any::TypeId::of::<A::Value<'static>>(), "attribute `{}` is declared at another value type", A::NAME);
Some(Self {
index,
offset: field.offset,
level,
marker: std::marker::PhantomData,
})
}
pub fn offset(self) -> usize {
self.offset
}
/// The offset this token names in `layout`, `None` unless `layout` is the
/// one it was minted against. The field's value type is re-checked, so a
/// resolved offset carries the marker-to-type proof into `layout`.
pub fn resolve(self, layout: &Layout) -> Option<usize> {
let field = layout.fields.get(self.index)?;
let same = field.offset == self.offset && field.level == self.level && field.name == A::NAME && field.type_id == std::any::TypeId::of::<A::Value<'static>>();
same.then_some(self.offset)
}
}
/// The stand-in fed to a kernel's unbounded `element: T` parameter. The type
/// system forces the kernel to route it to the element position of its return
/// tuple, so the passthrough is explicit in the signature while the lowering
/// carries the element bytes untyped through the copy plan.
#[derive(Clone, Copy, Debug, Default)]
pub struct ElToken;
/// The shared empty layout: `depth` 0, no element, no fields, so `frame_bytes`
/// is 0. The `Node::layout` default returns it for element-only and test nodes,
/// which carry no record.
pub fn empty_layout() -> &'static Layout {
static EMPTY: std::sync::OnceLock<Layout> = std::sync::OnceLock::new();
EMPTY.get_or_init(Layout::default)
}
/// A record node's output layout with the frame size and carrier copy plan derived from it.
#[derive(Clone, Debug, Default)]
pub struct RecordLayout {
pub layout: Layout,
pub frame_bytes: usize,
pub plan: Vec<(usize, usize, usize)>,
/// Inputs whose value cannot change with the innermost index, as a bitmask
/// over input positions. Empty is the safe default: an uninstalled layout
/// rebinds every input per lane.
pub lane_invariant: u32,
/// The names the fold gave this node's name-from-input writes, in the
/// order the signature declares its placeholders. A marker-only node
/// leaves it empty; `set_layout` resolves its offsets through these
/// instead of through a marker's `NAME`.
pub named_writes: Vec<&'static str>,
/// The offsets the fold resolved for this node's name-from-input reads, in
/// placeholder order. `None` is an absent attribute, which the read serves
/// as the name's forced default. Resolved in the compiler, where the folded
/// name and the read input's finished layout sit together, so `set_layout`
/// only copies the numbers into the read slots.
pub named_reads: Vec<Option<usize>>,
/// The census default's bytes for each absent name-from-input read whose
/// name the census declares, in the same order. A name the census does not
/// declare has `None` and reads as its value type's default, which is that
/// case's own rule; a read that resolved to an offset needs no default.
pub named_read_defaults: Vec<Option<Box<[u8]>>>,
}
/// A write whose name comes from the graph rather than from a marker: the
/// input carrying the name, and the field descriptor with every facet but the
/// name already minted from the concrete value type.
#[derive(Clone, Copy, Debug)]
pub struct NamedWrite {
/// The proto input position holding the name's constant text.
pub name_input: u8,
/// The write this becomes once the fold supplies the name.
pub template: FieldWrite,
}
impl NamedWrite {
/// The template for a name-generic marker's write at `level`. Every facet
/// but the name is the concrete value type's, exactly as for a census
/// marker; [`FieldWrite::name`] holds the placeholder until the fold runs.
pub fn of<X: 'static, V: crate::attribute::AttrValue>(name_input: u8, level: u8) -> Self
where
V::Value<'static>: graphene_hash::CacheHash + PartialEq + 'static,
{
Self {
name_input,
template: FieldWrite::of::<crate::attribute::Named<X, V>>(level),
}
}
}
/// A read whose name comes from the graph rather than from a marker. The
/// compiler resolves it to an offset in the read input's own layout, where
/// the folded name and that finished layout already sit together.
#[derive(Clone, Copy, Debug)]
pub struct NamedRead {
/// The proto input the attribute is read from.
pub input: u8,
/// The proto input holding the name's constant text.
pub name_input: u8,
/// The read's field form, every facet but the name minted from the
/// concrete value type, as for a write.
pub template: FieldWrite,
}
impl NamedRead {
/// The template for a name-generic marker's read at `level`.
pub fn of<X: 'static, V: crate::attribute::AttrValue>(input: u8, name_input: u8, level: u8) -> Self
where
V::Value<'static>: graphene_hash::CacheHash + PartialEq + 'static,
{
Self {
input,
name_input,
template: FieldWrite::of::<crate::attribute::Named<X, V>>(level),
}
}
}
/// Declarative record-io metadata for a node type, emitted by the macro into
/// its registry entry so the compiler can fold each input's layout without
/// running the node's constructor. [`fold`](LayoutMeta::fold) reproduces the
/// layout the constructor derives at wiring today; the compiler layout pass
/// calls it over the proto graph instead.
#[derive(Clone, Debug)]
pub struct LayoutMeta {
/// Input indices whose layouts union to form the base: `[]` writes a fresh
/// record, `[i]` derives from a single carrier, `[i, j, ..]` unions routing
/// sources.
pub sources: Vec<u8>,
/// Attributes read from each input. Unused by [`fold`](LayoutMeta::fold);
/// recorded for later compiler analysis (read-offset resolution, per-name
/// cache dependencies, residency).
pub reads: Vec<InputReads>,
/// The output element: a concrete write, or carried through from the base.
pub element: ElementSpec,
/// The attributes the node writes at its acting level.
pub writes: Vec<FieldWrite>,
/// The attributes the node writes under a name taken from the graph. The
/// compiler fold turns each into a [`writes`](Self::writes) entry and
/// empties this, so a folded meta is indistinguishable from a marker
/// node's; one still carrying an entry has not been folded.
pub named_writes: Vec<NamedWrite>,
/// The names the fold gave [`named_writes`](Self::named_writes), in
/// placeholder order. Empty until the fold runs.
pub folded_names: Vec<&'static str>,
/// The attributes the node reads under a name taken from the graph.
pub named_reads: Vec<NamedRead>,
/// The names the fold gave [`named_reads`](Self::named_reads), in
/// placeholder order. Empty until the fold runs.
pub folded_read_names: Vec<&'static str>,
/// The attributes removed from the base layout, as `(name, level)`.
pub removes: Vec<(&'static str, u8)>,
/// The depth change the node applies: `0` for elementwise and flip nodes,
/// `+1` for a creator, `-1` for a reducer.
pub level_delta: i8,
/// The materialized subject a reducer folds, as `(input, levels)`. The fold
/// consumes the whole subject input, so only the node's own levels remain.
pub folded: Option<(u8, u8)>,
}
/// The attributes a node reads from one input, recorded on [`LayoutMeta`] for
/// later compiler analysis. A read and a write of an attribute carry the same
/// [`FieldWrite`] descriptor; the direction is the position on the node.
#[derive(Clone, Debug)]
pub struct InputReads {
pub input: u8,
pub reads: Vec<FieldWrite>,
}
/// Where a node's output element comes from, for [`LayoutMeta`].
#[derive(Clone, Debug)]
pub enum ElementSpec {
/// The node writes this concrete element.
Concrete(ElementWrite),
/// The node carries the carrier's element through unchanged.
Carried,
}
impl LayoutMeta {
/// Keeps input 0's layout but replaces its element.
pub fn retype(element: ElementWrite) -> Self {
Self {
sources: vec![0],
reads: Vec::new(),
element: ElementSpec::Concrete(element),
writes: Vec::new(),
named_writes: Vec::new(),
folded_names: Vec::new(),
named_reads: Vec::new(),
folded_read_names: Vec::new(),
removes: Vec::new(),
level_delta: 0,
folded: None,
}
}
/// Folds the node's output layout from its inputs', reproducing what the
/// node's constructor derives at wiring. `inputs` is indexed by proto-input
/// position; [`sources`](LayoutMeta::sources) selects the base layouts, which
/// union (empty writes a fresh record).
pub fn fold(&self, inputs: &[Option<&Layout>]) -> Layout {
let sources: Vec<&Layout> = self.sources.iter().map(|&i| inputs[i as usize].expect("layout fold source input has no layout")).collect();
let base = match sources.as_slice() {
[] => Layout::default(),
sources => Layout::union(sources),
}
.without(&self.removes);
let depth = match self.folded {
// A fold consumes the whole subject input (a deeper input folds its
// total flat span), so only the node's own levels remain.
Some(_) => self.level_delta.max(0) as u8,
None => (base.depth as i8 + self.level_delta).max(0) as u8,
};
let element = match &self.element {
ElementSpec::Concrete(element) => *element,
ElementSpec::Carried => base.element,
};
base.with_writes(depth, element, &self.writes)
}
/// [`fold`](LayoutMeta::fold) with the frame size and carrier copy plan derived from it.
pub fn resolve(&self, inputs: &[Option<&Layout>]) -> RecordLayout {
let layout = self.fold(inputs);
let frame_bytes = layout.frame_bytes();
let plan = match self.sources.first() {
Some(&source) if self.level_delta >= 0 => {
let from = inputs[source as usize].expect("layout resolve source input has no layout");
let carry_element = matches!(self.element, ElementSpec::Carried);
let removes: Vec<(&str, u8)> = self.removes.clone();
copy_plan(from, &layout, carry_element, &removes)
}
// A reducer collapses its carrier's levels, so it writes a fresh record rather than copying fields down.
_ => Vec::new(),
};
// A named read resolves against the input it reads, whose layout is
// finished by the time this node folds. An absent attribute stays
// `None`, which the read serves as the name's forced default.
let named_reads: Vec<Option<usize>> = self
.named_reads
.iter()
.zip(&self.folded_read_names)
.map(|(read, name)| inputs.get(read.input as usize).copied().flatten().and_then(|layout| layout.offset_of(name, read.template.level)))
.collect();
// An absent read serves the name's own default, which for a declared
// name is the census's rather than the value type's. The census stages
// it the same way it fills any absent field: as the declared default's
// bytes. One name carries one value type, checked when the name folds,
// so the size agreement below is a guard rather than a branch.
let named_read_defaults = self
.named_reads
.iter()
.zip(&self.folded_read_names)
.zip(&named_reads)
.map(|((read, name), offset)| {
let row = offset.is_none().then(|| attribute::info(name))??;
(row.value_type == read.template.type_id && row.size == read.template.size).then(|| {
let mut bytes = vec![0u8; row.size];
(row.write_default_bytes)(&mut bytes);
bytes.into_boxed_slice()
})
})
.collect();
RecordLayout {
layout,
frame_bytes,
plan,
lane_invariant: 0,
named_writes: self.folded_names.clone(),
named_reads,
named_read_defaults,
}
}
/// Folds `name` into the name-from-input write at `index`, taking the
/// census row's descriptor where the name is declared so a known name
/// keeps its census default, and the template's otherwise. The write
/// joins [`writes`](Self::writes) in placeholder order.
pub fn fold_name(&mut self, index: usize, name: &'static str) {
let named = self.named_writes[index];
let census = attribute::info(name).map(|row| (row.field_write_at)(named.template.level));
let write = match census {
Some(write) if write.type_id == named.template.type_id => write,
_ => FieldWrite { name, ..named.template },
};
self.writes.push(write);
self.folded_names.push(name);
}
/// Records the name of the name-from-input read at `index`. The offset
/// itself waits for [`resolve`](Self::resolve), which is where the read
/// input's finished layout arrives.
pub fn fold_read_name(&mut self, name: &'static str) {
self.folded_read_names.push(name);
}
}
/// Field-by-field carry from `from`'s layout into `to`'s, computed at
/// wiring. The element copy is included when `carry_element` holds, which is
/// exactly when the node does not write a concrete element itself. `removes`
/// names the fields the node deletes, which are exactly the ones allowed to
/// be absent from `to`.
pub fn copy_plan(from: &Layout, to: &Layout, carry_element: bool, removes: &[(&str, u8)]) -> Vec<(usize, usize, usize)> {
let mut plan = Vec::new();
if carry_element {
assert_eq!(from.element.size, to.element.size, "a carried element must keep its size");
if from.element.size > 0 {
plan.push((0, 0, from.element.size));
}
}
for field in &from.fields {
if removes.contains(&(field.name, field.level)) {
continue;
}
let target = to.offset_of(field.name, field.level).expect("carried field missing from the output layout");
plan.push((field.offset, target, field.size));
}
plan
}
/// Whether elements of `T` move once into the arena and ride as references:
/// records byte-copy their contents and never run drop glue, so a type is
/// byte-carried exactly when it has none.
pub const fn element_parked<T>() -> bool {
std::mem::needs_drop::<T>()
}
/// The element (size, align) a record input of `T` carries.
pub fn element_dims<T>() -> (usize, usize) {
match element_parked::<T>() {
true => (size_of::<*const u8>(), align_of::<*const u8>()),
false => (size_of::<T>(), align_of::<T>()),
}
}
/// The element slot a record input of `T` carries, its erased glue bound at
/// the statically-known type.
pub fn element_write<T: Clone + Send + Sync + dyn_any::StaticTypeSized>() -> ElementWrite
where
T::Static: Clone + Send + Sync,
{
/// # Safety
/// `ptr` must address a live element of `T` in the form [`element_parked`] picks.
unsafe fn clone_out<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(ptr: *const u8) -> Box<dyn std::any::Any + Send + Sync>
where
T::Static: Clone + Send + Sync,
{
if let Some(deep) = deep_element_glue(std::any::TypeId::of::<T::Static>()) {
// SAFETY: the caller's contract; the glue is registered for this element type.
return unsafe { (deep.clone_out)(ptr) };
}
// SAFETY: a lifetime-carrying element type registers deep glue, so this
// shallow path only erases borrow-free values. The registration is a
// whole-program convention rather than something this call can check:
// the executor asserts the in-tree types registered before it evaluates,
// which is where a missed wasm registration export is caught.
Box::new(unsafe { erase_static(read_element::<T>(Rec::new(ptr))) })
}
/// # Safety
/// `dst` must be fresh element storage of a record whose element is `T`, and
/// `value` must be the clone-out this glue produced for that element type.
unsafe fn repark<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(value: &(dyn std::any::Any + Send + Sync), dst: *mut u8, arena: &crate::arena::Arena) -> Option<()>
where
T::Static: Clone + Send + Sync,
{
if let Some(deep) = deep_element_glue(std::any::TypeId::of::<T::Static>()) {
// SAFETY: the caller's contract; the glue is registered for this element type.
return unsafe { (deep.repark)(value, dst, arena) };
}
let retained = retained_measure(std::any::TypeId::of::<T::Static>()).map_or(0, |measure| measure(value));
let value = value.downcast_ref::<T::Static>().expect("an element replays at its own type");
// SAFETY: the caller's contract, keyed as this element's own parks are.
unsafe { write_element_keyed(dst, value.clone(), arena, retained, std::any::TypeId::of::<T::Static>()) }
}
/// Declines for a type carrying deep glue, whose value may hold interiors
/// the evaluation's arena owns and which a moved header may not reference.
///
/// # Safety
/// `parked` must address a live payload of `T`.
unsafe fn park_move<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(parked: *const u8, promotion: &Promotion<'_>) -> Option<*const u8>
where
T::Static: Clone + Send + Sync,
{
deep_element_glue(std::any::TypeId::of::<T::Static>()).is_none().then_some(())?;
// SAFETY: the caller's contract, at the type the park was written with.
let value: &(dyn std::any::Any + Send + Sync) = unsafe { &*parked.cast::<T::Static>() };
let retained = retained_measure(std::any::TypeId::of::<T::Static>()).map_or(0, |measure| measure(value));
// SAFETY: as above, and the decline above establishes that the payload
// owns all of its content.
unsafe { promotion.move_park::<T>(parked, retained) }.map(<*const T::Static>::cast)
}
let (size, align) = element_dims::<T>();
ElementWrite {
size,
align,
parked: element_parked::<T>(),
type_id: std::any::TypeId::of::<T::Static>(),
clone_out: clone_out::<T>,
repark: repark::<T>,
park_move: park_move::<T>,
content_hash: None,
content_eq: None,
}
}
/// [`element_write`] plus the content hashing and equality glue, for element
/// types that support them.
pub fn element_write_hashed<T: Clone + Send + Sync + graphene_hash::CacheHash + PartialEq + dyn_any::StaticTypeSized>() -> ElementWrite
where
T::Static: Clone + Send + Sync,
{
/// # Safety
/// `ptr` must address a live element of `T` in the form [`element_parked`] picks.
unsafe fn content_hash<T: graphene_hash::CacheHash>(ptr: *const u8, state: &mut dyn core::hash::Hasher) {
let mut state = state;
// SAFETY: the caller's contract.
unsafe { borrow_element::<T>(Rec::new(ptr)) }.cache_hash(&mut state);
}
/// # Safety
/// `a` and `b` must each address a live element of `T` in that same form.
unsafe fn content_eq<T: PartialEq>(a: *const u8, b: *const u8) -> bool {
// SAFETY: the caller's contract.
unsafe { borrow_element::<T>(Rec::new(a)) == borrow_element::<T>(Rec::new(b)) }
}
ElementWrite {
content_hash: Some(content_hash::<T>),
content_eq: Some(content_eq::<T>),
..element_write::<T>()
}
}
/// Selects [`element_write_hashed`] when the element type supports the
/// content glue and [`element_write`] otherwise, by autoref method
/// resolution: call `(&ElementWritePick::<T>(..)).element_write()` with both
/// traits in scope.
pub struct ElementWritePick<T>(pub std::marker::PhantomData<T>);
pub trait ElementWritePickHashed {
fn element_write(&self) -> ElementWrite;
}
impl<T: Clone + Send + Sync + graphene_hash::CacheHash + PartialEq + dyn_any::StaticTypeSized> ElementWritePickHashed for ElementWritePick<T>
where
T::Static: Clone + Send + Sync,
{
fn element_write(&self) -> ElementWrite {
element_write_hashed::<T>()
}
}
pub trait ElementWritePickPlain {
fn element_write(&self) -> ElementWrite;
}
impl<T: Clone + Send + Sync + dyn_any::StaticTypeSized> ElementWritePickPlain for &ElementWritePick<T>
where
T::Static: Clone + Send + Sync,
{
fn element_write(&self) -> ElementWrite {
element_write::<T>()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::record::test_support::{f64_field, sized_field};
#[test]
fn canonical_order_and_offsets() {
let layout = Layout::default().with_writes(0, element_write::<f64>(), &[sized_field("tint", 4, 4), f64_field("opacity"), sized_field("flag", 1, 1)]);
assert_eq!(layout.offset_of("opacity", 0), Some(8));
assert_eq!(layout.offset_of("tint", 0), Some(16));
assert_eq!(layout.offset_of("flag", 0), Some(20));
assert_eq!(layout.size, 21);
assert_eq!(layout.align, 8);
}
#[test]
#[should_panic(expected = "a record element aligns to at most 8 bytes")]
fn an_over_aligned_element_is_refused_at_wiring() {
Layout::default().with_writes(0, element_write::<u128>(), &[]);
}
#[test]
#[should_panic(expected = "attribute `wide` aligns to at most 8 bytes")]
fn an_over_aligned_attribute_is_refused_at_wiring() {
Layout::default().with_writes(0, element_write::<f64>(), &[sized_field("wide", 16, 16)]);
}
#[test]
#[should_panic(expected = "two different types")]
fn type_conflicts_panic() {
let mut conflicting = sized_field("opacity", 8, 8);
conflicting.type_id = std::any::TypeId::of::<u64>();
let layout = Layout::default().with_writes(0, element_write::<f64>(), &[f64_field("opacity")]);
layout.with_writes(0, element_write::<f64>(), &[conflicting]);
}
#[test]
fn a_token_resolves_only_in_the_layout_it_was_minted_against() {
use crate::attribute::{Attribute, Opacity, Transform};
let layout = Layout::default().with_writes(0, element_write::<f64>(), &[FieldWrite::of::<Opacity>(0)]);
let token = FieldOffset::<Opacity>::of(&layout, 0).expect("the layout carries the marker");
assert_eq!(token.resolve(&layout), layout.offset_of(Opacity::NAME, 0));
let shifted = Layout::default().with_writes(0, element_write::<f64>(), &[FieldWrite::of::<Transform>(0), FieldWrite::of::<Opacity>(0)]);
assert_eq!(FieldOffset::<Opacity>::of(&shifted, 0).and_then(|token| token.resolve(&layout)), None);
assert!(FieldOffset::<Opacity>::of(&Layout::default(), 0).is_none());
}
#[test]
fn union_is_order_independent() {
let a = Layout::default().with_writes(0, element_write::<f64>(), &[f64_field("opacity")]);
let b = Layout::default().with_writes(0, element_write::<f64>(), &[f64_field("length")]);
assert_eq!(Layout::union(&[&a, &b]), Layout::union(&[&b, &a]));
assert!(Layout::union(&[&a, &b]).offset_of("length", 0).is_some());
}
#[test]
fn the_element_write_pick_selects_the_content_glue_by_type() {
use super::{ElementWritePickHashed as _, ElementWritePickPlain as _};
#[derive(Clone, dyn_any::DynAny)]
struct Opaque;
let hashed = ElementWritePick::<String>(std::marker::PhantomData).element_write();
assert!(hashed.content_hash.is_some() && hashed.content_eq.is_some());
let plain = (&ElementWritePick::<Opaque>(std::marker::PhantomData)).element_write();
assert!(plain.content_hash.is_none() && plain.content_eq.is_none());
}
#[test]
fn elements_ride_as_bytes_exactly_without_drop_glue() {
assert!(!element_parked::<f64>());
assert!(!element_parked::<[f64; 4]>());
assert!(element_parked::<String>());
assert!(element_parked::<std::sync::Arc<str>>());
assert_eq!(element_dims::<[f64; 4]>(), (32, 8));
assert_eq!(element_dims::<String>(), (8, 8));
}
#[test]
fn layouts_resolve_spilled_values() {
let small = Layout::default().with_writes(0, element_write::<f64>(), &[f64_field("opacity")]);
assert_eq!(small.frame_bytes(), 16);
let backing = [4f64, 0.5];
let value = RecordValue::spilled(unsafe { Rec::new(backing.as_ptr().cast()) });
assert_eq!(unsafe { small.rec(&value).element::<f64>() }, 4.);
assert_eq!(unsafe { small.rec(&value).read::<f64>(small.offset_of("opacity", 0).unwrap()) }, 0.5);
let spilled = Layout::default().with_writes(0, element_write::<f64>(), &[f64_field("opacity"), f64_field("length")]);
assert_eq!(spilled.frame_bytes(), 24);
let record = [1f64, 2., 3.];
let value = RecordValue::spilled(unsafe { Rec::new(record.as_ptr().cast()) });
assert_eq!(unsafe { spilled.rec(&value).element::<f64>() }, 1.);
assert_eq!(unsafe { spilled.rec(&value).read::<f64>(spilled.offset_of("length", 0).unwrap()) }, 2.);
assert_eq!(unsafe { spilled.rec(&value).read::<f64>(spilled.offset_of("opacity", 0).unwrap()) }, 3.);
}
}
@@ -0,0 +1,36 @@
//! The packed-record tier at rank 0. A record is the element at offset 0
//! plus one field per written attribute; its [`Layout`] is computed at
//! wiring from the upstream write set and never serialized. Records of
//! inline layouts live in the [`RecordValue`] itself; larger ones live as
//! per-lane views on the evaluation's [`Frames`], which the root owns and
//! every node claims its own frame out of. Kernels route them as opaque
//! [`RecordValue`]s that carry
//! their provenance. Only generated or wiring code touches offsets, so a
//! safe kernel cannot misalign a field.
mod access;
mod frames;
mod input;
mod layout;
mod owned;
mod promote;
mod route;
mod run;
mod serve;
#[cfg(test)]
mod test_support;
mod testkit;
pub use access::{Rec, RecordValue, apply_plan, borrow_element, erase_static, read_at, read_at_defaulting, read_element, token_only, write_element, write_element_sized, write_field};
pub use frames::{FrameArena, FrameScope, Frames};
pub use input::{DerivedLazyInput, DerivedRecordInput, ElementInput, ElementLazyInput, LevelStatus, RecordExtract, RecordInput, RecordLazyInput, fill_frames, materialize_batch, materialize_level};
pub use layout::{
ElToken, ElementSpec, ElementWrite, ElementWritePick, ElementWritePickHashed, ElementWritePickPlain, FieldDesc, FieldOffset, FieldWrite, InputReads, Layout, LayoutMeta, NamedRead, NamedWrite,
RecordLayout, copy_plan, element_dims, element_parked, element_write, element_write_hashed, empty_layout,
};
pub use owned::{OwnedRecord, deepen_field_value, has_deep_element_glue, register_deep_element_clone, register_deep_field_value, replay_field_value};
pub use promote::{Promotion, assert_promoted, register_element_promote, register_field_promote, register_retained_heap};
pub use route::{RecordSource, SourcePlan};
pub use run::{Group, GroupItem, RunBuilder, RunColumn, RunView};
pub use serve::{FrameClaim, MaterializedSpan, Served, SlotRun, serve_input};
pub use testkit::{LiftedSource, ServedRecord, capture, test_frames};
@@ -0,0 +1,233 @@
//! The owned crossing: deep copies that outlive the evaluation their content borrowed.
use super::access::Rec;
use super::layout::Layout;
use super::serve::FrameClaim;
/// Deep-copy overrides for element types whose plain clone borrows the
/// evaluation's arena (a `Graphic` holding a group interior). The generic
/// element glue consults this registry, so every layout carrying such an
/// element deep-copies at memo and capture seams regardless of which
/// constructor built the glue. The clone-out must produce a value of the
/// element's own type that owns all of its content; the re-park restores that
/// value's arena-resident form before parking it.
#[derive(Clone, Copy)]
pub(in crate::record) struct DeepElementGlue {
pub(in crate::record) clone_out: unsafe fn(*const u8) -> Box<dyn std::any::Any + Send + Sync>,
pub(in crate::record) repark: unsafe fn(&(dyn std::any::Any + Send + Sync), *mut u8, &crate::arena::Arena) -> Option<()>,
}
static DEEP_ELEMENT_CLONES: std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<std::any::TypeId, DeepElementGlue>>> = std::sync::LazyLock::new(Default::default);
/// Registers the deep copy-out and re-park pair for elements of `T`. Called
/// at startup from the crate that owns the type.
pub fn register_deep_element_clone<T: dyn_any::StaticTypeSized>(
clone_out: unsafe fn(*const u8) -> Box<dyn std::any::Any + Send + Sync>,
repark: unsafe fn(&(dyn std::any::Any + Send + Sync), *mut u8, &crate::arena::Arena) -> Option<()>,
) {
DEEP_ELEMENT_CLONES.lock().unwrap().insert(std::any::TypeId::of::<T::Static>(), DeepElementGlue { clone_out, repark });
}
pub(in crate::record) fn deep_element_glue(type_id: std::any::TypeId) -> Option<DeepElementGlue> {
DEEP_ELEMENT_CLONES.lock().unwrap().get(&type_id).copied()
}
/// Whether elements of a type registered deep glue. The shallow clone path is
/// only sound for types that did not need to, so a host that drives the
/// registration itself checks the types it owes before it evaluates anything.
pub fn has_deep_element_glue(type_id: std::any::TypeId) -> bool {
DEEP_ELEMENT_CLONES.lock().unwrap().contains_key(&type_id)
}
/// Deep-copy overrides for field values whose content borrows the
/// evaluation's arena (a graphic list holding native groups), keyed by the
/// field's owned value form. Consulted at the persistence seams only:
/// `read_erased` itself stays shallow, since introspection reads captures in
/// generation. Both halves decline when the value already owns all of its
/// content, so group-free values pay no extra clone: `copy_out` returns
/// `None` for unchanged, `replay` returns `Some(None)` for unchanged and
/// `None` for arena exhaustion.
#[derive(Clone, Copy)]
pub(in crate::record) struct DeepFieldGlue {
pub(in crate::record) copy_out: fn(&dyn crate::list::AnyAttributeValue) -> Option<Box<dyn crate::list::AnyAttributeValue>>,
pub(in crate::record) replay: crate::list::FieldReplayFn,
}
static DEEP_FIELD_VALUES: std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<std::any::TypeId, DeepFieldGlue>>> = std::sync::LazyLock::new(Default::default);
/// Registers the deep copy-out and replay pair for field values of `T`.
/// Called at startup from the crate that owns the type.
pub fn register_deep_field_value<T: 'static>(copy_out: fn(&dyn crate::list::AnyAttributeValue) -> Option<Box<dyn crate::list::AnyAttributeValue>>, replay: crate::list::FieldReplayFn) {
DEEP_FIELD_VALUES.lock().unwrap().insert(std::any::TypeId::of::<T>(), DeepFieldGlue { copy_out, replay });
}
pub(in crate::record) fn deep_field_glue(type_id: std::any::TypeId) -> Option<DeepFieldGlue> {
DEEP_FIELD_VALUES.lock().unwrap().get(&type_id).copied()
}
/// The copy-out half over an erased field value: the owned form a value takes
/// when it crosses out of the evaluation whose arena its content borrows. A
/// value with no registered glue already owns everything and passes through.
pub fn deepen_field_value(value: Box<dyn crate::list::AnyAttributeValue>) -> Box<dyn crate::list::AnyAttributeValue> {
match deep_field_glue(value.as_any().type_id()) {
Some(glue) => (glue.copy_out)(&*value).unwrap_or(value),
None => value,
}
}
/// The replay half over an erased field value: `Some(None)` where the value
/// already owns its content, `None` on arena exhaustion.
pub fn replay_field_value(value: &dyn crate::list::AnyAttributeValue, arena: &crate::arena::Arena) -> Option<Option<Box<dyn crate::list::AnyAttributeValue>>> {
match deep_field_glue(value.as_any().type_id()) {
Some(glue) => (glue.replay)(value, arena),
None => Some(None),
}
}
/// A record deep-copied out of its evaluation: the packed bytes plus owned
/// clones of every parked payload, replayable into a later evaluation's
/// storage through the layout's erased glue. The layout stays with the
/// holder, which proved it at wiring.
pub struct OwnedRecord {
pub(in crate::record) bytes: Box<[u8]>,
pub(in crate::record) element: Option<Box<dyn std::any::Any + Send + Sync>>,
/// Each copied field's index in the copy's layout, that field's declared
/// value type, and the owned value. The type rides along so a replay can
/// re-check the field it resolves rather than trusting the caller's claim.
fields: Vec<(usize, std::any::TypeId, Box<dyn crate::list::AnyAttributeValue>)>,
}
impl std::fmt::Debug for OwnedRecord {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("OwnedRecord(..)")
}
}
impl OwnedRecord {
/// # Safety
/// `rec` must be a live record of `layout`.
pub unsafe fn copy_out(layout: &Layout, rec: Rec<'_>) -> OwnedRecord {
// The element-to-field seam is never written, so the copy stays untyped:
// a `&[u8]` over the frame would read those bytes.
let mut staged = Vec::<u8>::with_capacity(layout.size);
// SAFETY: the caller's contract sizes the record at `layout.size`, which
// is the capacity just reserved, so the copy fills exactly the staging.
let bytes = unsafe {
std::ptr::copy_nonoverlapping(rec.ptr(), staged.as_mut_ptr(), layout.size);
staged.set_len(layout.size);
staged.into_boxed_slice()
};
// SAFETY: the caller's contract; a parked element sits at offset 0.
let element = layout.element.parked.then(|| unsafe { (layout.element.clone_out)(rec.ptr()) });
let fields = layout
.fields
.iter()
.enumerate()
.filter(|(_, field)| field.repark.is_some())
// SAFETY: the caller's contract; each field reads its own descriptor's offset.
.map(|(index, field)| (index, field.type_id, deepen_field_value(unsafe { (field.read_erased)(rec.ptr().add(field.offset)) })))
.collect();
OwnedRecord { bytes, element, fields }
}
/// Replays the copy into a caller's claim, re-parking droppable payloads
/// against `arena`; `None` reports arena exhaustion. The claim's layout must
/// be the one the copy was taken at, which the checks below establish rather
/// than assume: the copy carries no layout of its own, so a mismatched claim
/// would otherwise write past the frame or re-park a field through another
/// field's glue.
pub fn replay_into(&self, slot: &mut FrameClaim<'_, '_>, arena: &crate::arena::Arena) -> Option<()> {
let layout = slot.layout;
assert_eq!(self.bytes.len(), layout.size, "a replay lands in the layout the copy was taken at");
assert_eq!(self.element.is_some(), layout.element.parked, "a replay lands in the layout the copy was taken at");
for &(index, type_id, _) in &self.fields {
let field = layout.fields.get(index).expect("a replay lands in the layout the copy was taken at");
assert_eq!(field.type_id, type_id, "a replay lands in the layout the copy was taken at");
}
self.write_into(layout, slot.dst(), arena)
}
/// `dst` is a claimed frame of `layout`, and `replay_into`'s asserts have
/// established that `layout` is the one the copy was taken at.
fn write_into(&self, layout: &Layout, dst: *mut u8, arena: &crate::arena::Arena) -> Option<()> {
// SAFETY: the copy is `layout.size` bytes and the claim is a frame of it.
unsafe { std::ptr::copy_nonoverlapping(self.bytes.as_ptr(), dst, self.bytes.len()) };
if let Some(element) = &self.element {
// SAFETY: the element was cloned out of this layout's own slot at offset 0.
unsafe { (layout.element.repark)(&**element, dst, arena) }?;
}
for (index, _, value) in &self.fields {
let field = &layout.fields[*index];
let repark = field.repark.expect("copied fields carry re-park glue");
let resident = replay_field_value(&**value, arena)?;
// SAFETY: the asserts matched this index's field type, so the glue and
// the value agree; the write lands in that field's own region.
unsafe { repark(resident.as_deref().unwrap_or(&**value), dst.add(field.offset), arena) }?;
}
Some(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::record::access::{read_element, write_element, write_field};
use crate::record::frames::FrameArena;
use crate::record::layout::{FieldWrite, element_write};
#[test]
fn a_padded_layout_copies_out_without_reading_its_seam() {
// A 4-byte element before an 8-aligned field leaves [4, 8) unwritten.
let layout = Layout::default().with_writes(0, element_write::<u32>(), &[FieldWrite::of::<crate::attribute::Opacity>(0)]);
let offset = layout.offset_of("opacity", 0).unwrap();
assert_eq!((layout.element.size, offset), (4, 8), "the fixture needs the element-to-field seam");
let arena = crate::arena::Arena::new(1024).unwrap();
let scratch = arena.alloc_scratch::<u64>(layout.frame_bytes().div_ceil(8)).unwrap();
let base: *mut u8 = scratch.as_mut_ptr().cast();
unsafe { write_element(base, 7u32, &arena) }.unwrap();
unsafe { write_field::<f64>(base, offset, 0.5) };
let copy = unsafe { OwnedRecord::copy_out(&layout, Rec::new(base.cast_const())) };
let replay_arena = crate::arena::Arena::new(1024).unwrap();
let mut frame_arena = FrameArena::new();
frame_arena.reserve(layout.frame_bytes());
let frames = frame_arena.frames();
let mut slot = frames.claim(&layout);
copy.replay_into(&mut slot, &replay_arena).unwrap();
// SAFETY: the replay completes the record in the claimed frame.
let value = unsafe { slot.finish() };
let rec = layout.rec(&value);
assert_eq!(unsafe { read_element::<u32>(rec) }, 7);
assert_eq!(unsafe { rec.read::<f64>(offset) }, 0.5);
}
#[test]
fn owned_records_replay_re_parked_payloads_after_the_source_dies() {
let layout = Layout::default().with_writes(0, element_write::<String>(), &[FieldWrite::of::<crate::attribute::Name>(0)]);
let mut buffer = vec![0u64; layout.size.div_ceil(8)];
let base: *mut u8 = buffer.as_mut_ptr().cast();
let copy = {
let arena = crate::arena::Arena::new(1024).unwrap();
unsafe { write_element(base, String::from("element"), &arena) }.unwrap();
let (name, _) = arena.alloc(String::from("field")).unwrap();
unsafe { write_field::<&str>(base, layout.offset_of("name", 0).unwrap(), name.as_str()) };
unsafe { OwnedRecord::copy_out(&layout, Rec::new(base)) }
};
buffer.fill(u64::MAX);
let replay_arena = crate::arena::Arena::new(1024).unwrap();
let mut frame_arena = FrameArena::new();
frame_arena.reserve(layout.frame_bytes());
let frames = frame_arena.frames();
let mut slot = frames.claim(&layout);
copy.replay_into(&mut slot, &replay_arena).unwrap();
// SAFETY: the replay completes the record in the claimed frame.
let value = unsafe { slot.finish() };
let rec = layout.rec(&value);
assert_eq!(unsafe { read_element::<String>(rec) }, "element");
assert_eq!(unsafe { rec.read::<&str>(layout.offset_of("name", 0).unwrap()) }, "field");
}
}
@@ -0,0 +1,433 @@
//! Transient-to-persistent promotion of records and their parked payloads.
use super::layout::Layout;
use super::owned::{deepen_field_value, replay_field_value};
use super::serve::MaterializedSpan;
/// The regions a promote dispatches on. A payload already living in the
/// persistent region outlives every entry promoted into it and is shared; a
/// payload in the transient arena or the frame buffer dies at the next reset
/// and is cloned.
///
/// The dispatch is decidable only where the reference addresses the payload
/// itself, which holds for parked elements and for a group interior's frames.
/// A reference-valued attribute instead names storage whose owner the address
/// alone does not identify, so those are never provenance-shared; they clone,
/// or move where [`Arena::move_park`](crate::arena::Arena::move_park) confirms
/// the reference is the transient arena's own park.
///
/// THE SHARING LAW: sharing a payload between persistent entries is sound
/// because persistent invalidation is epochal, so every entry dies at one
/// flush and no entry can outlive a payload another still names. Per-entry
/// eviction would have to refcount the shared payloads before it could
/// reclaim one entry's storage.
#[derive(Clone, Copy)]
pub struct Promotion<'a> {
transient: &'a crate::arena::Arena,
frames: (usize, usize),
persistent: &'a crate::arena::Arena,
}
impl<'a> Promotion<'a> {
/// `frames` is the whole frame buffer as (address, bytes), from
/// [`Frames::bounds`].
pub fn new(transient: &'a crate::arena::Arena, frames: (usize, usize), persistent: &'a crate::arena::Arena) -> Self {
Promotion { transient, frames, persistent }
}
pub fn persistent(&self) -> &'a crate::arena::Arena {
self.persistent
}
/// Whether the reference dies with the evaluation, which is the promote's
/// clone-or-share question. A null or byte-carried slot reads as neither
/// region's and shares.
pub fn evaluation_lived(&self, ptr: *const u8) -> bool {
self.transient.contains(ptr) || (ptr as usize).wrapping_sub(self.frames.0) < self.frames.1
}
/// Moves a transient payload's header into the persistent region instead of
/// cloning the heap it owns: the heap travels with the drop obligation and
/// is freed at the persistent flush, never at the transient reset. `None`
/// where the header is not the transient arena's own park keyed to `T`'s
/// static type or the region refused it, which leaves the caller its clone
/// path.
///
/// The forwarding is the evaluation's, so a payload two records share moves
/// once and both reach the one persistent header. The source header stays
/// readable to the evaluation's remaining sharers, which are the only reads
/// the move keeps sound: no read of it may outlive the persistent flush.
///
/// # Safety
/// `parked` must address a live `T`, and `T` must own all of its content, a
/// persistent header being allowed to reference no transient storage, which
/// is also what lets it be republished at `T::Static`. The park's key
/// settles the type, so the caller owes no identity argument.
pub unsafe fn move_park<T: dyn_any::StaticTypeSized>(&self, parked: *const u8, retained: usize) -> Option<*const T::Static>
where
T::Static: Send + Sync,
{
// SAFETY: the caller's contract, forwarded to the parking arena.
unsafe { self.transient.move_park::<T>(parked, self.persistent, retained) }
}
}
/// Rewrites one promoted record's parked references in place: the lane bytes
/// are already the persistent region's, and each reference whose payload dies
/// with the evaluation is replaced by a clone parked there.
///
/// A parked element rides the arena slot its payload was written into, so the
/// region holding it decides share against clone. A parked field's reference
/// names storage the promote cannot attribute from the address alone, so it is
/// never provenance-shared: it clones, or takes the route a registered
/// [`FieldPromote`] states under the two-level sharing law.
///
/// # Safety
/// `dst` must be a persistent image of a live record of `layout`.
pub(in crate::record) unsafe fn promote_record(layout: &Layout, dst: *mut u8, promotion: &Promotion<'_>) -> Option<()> {
if layout.element.parked {
// SAFETY: a parked element slot holds one reference at offset 0.
let parked = unsafe { dst.cast::<*const u8>().read() };
if !promotion.persistent.contains(parked) {
match element_promote_glue(layout.element.type_id) {
// SAFETY: the slot images a parked element of this type.
Some(promote) => unsafe { promote(dst.cast_const(), dst, promotion) }?,
// SAFETY: as above; the header is the payload's own.
None => match unsafe { (layout.element.park_move)(parked, promotion) } {
// SAFETY: a parked element slot holds one reference at offset 0.
Some(moved) => unsafe { dst.cast::<*const u8>().write(moved) },
None => {
// SAFETY: as above, and the clone owns its content.
let owned = unsafe { (layout.element.clone_out)(dst.cast_const()) };
// SAFETY: the clone is this element's own type, back into its slot.
unsafe { (layout.element.repark)(&*owned, dst, promotion.persistent) }?;
}
},
}
}
}
for field in &layout.fields {
let Some(repark) = field.repark else { continue };
// SAFETY: a parked field slot holds one reference at its offset.
let slot = unsafe { dst.add(field.offset) };
if let Some(promote) = field_promote_glue(field.type_id) {
// SAFETY: the slot images a parked field of this descriptor, and the
// promoted reference is written back into that same slot.
unsafe { promote(slot.cast_const(), slot, promotion) }?;
continue;
}
// SAFETY: the slot images a parked field of this descriptor.
let value = deepen_field_value(unsafe { (field.read_erased)(slot.cast_const()) });
let resident = replay_field_value(&*value, promotion.persistent)?;
// SAFETY: the replay produced this field's own value type.
unsafe { repark(resident.as_deref().unwrap_or(&*value), slot, promotion.persistent) }?;
}
Some(())
}
/// Re-walks a promoted record and asserts no reference into the evaluation's
/// storage survived, which is the postcondition every later hit and every
/// shared interior relies on. The element's payload must sit in the persistent
/// region itself; a field's payload is heap its owner holds, so the weaker
/// range check is all that is decidable there.
///
/// # Safety
/// `ptr` must be a live record of `layout`.
pub unsafe fn assert_promoted(layout: &Layout, ptr: *const u8, promotion: &Promotion<'_>) {
if layout.element.parked {
// SAFETY: a parked element slot holds one reference at offset 0.
let parked = unsafe { ptr.cast::<*const u8>().read() };
assert!(promotion.persistent.contains(parked), "a promoted element kept a reference outside the persistent region");
}
for field in &layout.fields {
if field.repark.is_none() {
continue;
}
// SAFETY: a parked field slot holds one reference at its offset.
let parked = unsafe { ptr.add(field.offset).cast::<*const u8>().read() };
assert!(!promotion.evaluation_lived(parked), "a promoted field kept a reference into the evaluation");
}
}
/// The promote override for element types whose payload holds arena-resident
/// interiors: the generic path clones through an owned intermediate, while a
/// registered promote shares the interiors already living in the persistent
/// region and copies only the rest.
type ElementPromote = unsafe fn(*const u8, *mut u8, &Promotion<'_>) -> Option<()>;
static ELEMENT_PROMOTES: std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<std::any::TypeId, ElementPromote>>> = std::sync::LazyLock::new(Default::default);
/// Registers the promote for elements of `T`. Called at startup from the crate
/// that owns the type. The promote must leave no reference the promotion calls
/// evaluation-lived.
pub fn register_element_promote<T: dyn_any::StaticTypeSized>(promote: ElementPromote) {
ELEMENT_PROMOTES.lock().unwrap().insert(std::any::TypeId::of::<T::Static>(), promote);
}
fn element_promote_glue(type_id: std::any::TypeId) -> Option<ElementPromote> {
ELEMENT_PROMOTES.lock().unwrap().get(&type_id).copied()
}
/// The deep field glue's third half, opt-in beside [`register_deep_field_value`]'s
/// pair: a registered promote routes the field payload transient-to-persistent
/// at the slot itself, so the promote never builds the owned form the other two
/// halves round-trip through. Keyed by the field's stored type rather than its
/// owned one, since the route runs before any erased read. The owned halves keep
/// serving every other seam, [`OwnedRecord::copy_out`] and [`GroupItem::copy_out`]
/// included.
///
/// THE TWO-LEVEL SHARING LAW, which a registrant must hold to: the field's own
/// header is not provenance-shared, since a stored reference names storage whose
/// owner the promote cannot attribute from the address alone; it clones, or moves
/// where the payload owns all of its content and the transient arena confirms the
/// reference is its own park. One level inside the payload, an interior that is
/// arena-resident has decidable provenance and takes the Cow dispatch: an interior
/// the persistent region already holds is shared pointer for pointer, and one that
/// dies with the evaluation is copied or moved.
type FieldPromote = unsafe fn(*const u8, *mut u8, &Promotion<'_>) -> Option<()>;
static FIELD_PROMOTES: std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<std::any::TypeId, FieldPromote>>> = std::sync::LazyLock::new(Default::default);
/// Registers the promote for fields stored as `T`. Called at startup from the
/// crate that owns the type. The promote must leave no reference the promotion
/// calls evaluation-lived.
pub fn register_field_promote<T: 'static>(promote: FieldPromote) {
FIELD_PROMOTES.lock().unwrap().insert(std::any::TypeId::of::<T>(), promote);
}
fn field_promote_glue(type_id: std::any::TypeId) -> Option<FieldPromote> {
FIELD_PROMOTES.lock().unwrap().get(&type_id).copied()
}
/// The park glue's heap estimate for values of a type, keyed as the deep glue
/// is. Consulted where a payload parks, so a region's retained heap is known
/// without walking it.
type RetainedMeasure = fn(&(dyn std::any::Any + Send + Sync)) -> usize;
static RETAINED_MEASURES: std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<std::any::TypeId, RetainedMeasure>>> = std::sync::LazyLock::new(Default::default);
/// Registers the retained-heap estimate for values of `T`. Called at startup
/// from the crate that owns the type. The estimate is a hint: an unregistered
/// type contributes 0, so a region's counter is a lower bound.
pub fn register_retained_heap<T: dyn_any::StaticTypeSized>(measure: RetainedMeasure) {
RETAINED_MEASURES.lock().unwrap().insert(std::any::TypeId::of::<T::Static>(), measure);
}
pub(in crate::record) fn retained_measure(type_id: std::any::TypeId) -> Option<RetainedMeasure> {
RETAINED_MEASURES.lock().unwrap().get(&type_id).copied()
}
impl MaterializedSpan {
/// Copies the batch into the persistent region as a copy-on-write over
/// provenance: the frame bytes memcpy, and each parked reference is cloned
/// only where it dies with the evaluation, so a layout carrying no parked
/// slot reduces to the memcpy and a level whose payloads an upstream memo
/// already published costs nothing beyond it. `None` where the region
/// could not hold the copy, which leaves the caller with nothing to cache.
///
/// # Safety
/// The batch's lanes must be live records of its layout.
pub unsafe fn to_persistent(batch: &crate::node::RecordBatch<'_>, promotion: &Promotion<'_>) -> Option<MaterializedSpan> {
let layout = batch.layout();
let stride = layout.lane_stride();
let len = batch.len();
if len == 0 {
return Some(MaterializedSpan {
base: crate::arena::ArenaWeak::NULL,
len: 0,
});
}
let persistent = promotion.persistent();
let slab = persistent.alloc_scratch::<u64>((len * stride).div_ceil(8))?;
let base: *mut u8 = slab.as_mut_ptr().cast();
for lane in 0..len {
// SAFETY: the caller's contract on the lane, into the lane's own
// region of the freshly reserved slab.
let dst = unsafe { base.add(lane * stride) };
// SAFETY: as above; `layout.size` bytes of a lane fit its own stride.
unsafe { std::ptr::copy_nonoverlapping(batch.get(lane).rec().ptr(), dst, layout.size) };
// SAFETY: the copy images a record of this layout.
unsafe { promote_record(layout, dst, promotion) }?;
}
#[cfg(debug_assertions)]
for lane in 0..len {
// SAFETY: every lane was imaged and promoted above.
unsafe { assert_promoted(layout, base.add(lane * stride).cast_const(), promotion) };
}
Some(MaterializedSpan {
base: persistent.handle_at(base.cast_const())?,
len,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::record::access::{borrow_element, write_element, write_element_sized};
use crate::record::layout::element_write;
use crate::record::test_support::f64_field;
#[test]
fn a_pod_level_promotes_as_a_bare_memcpy() {
let transient = crate::arena::Arena::new(4096).unwrap();
let persistent = crate::arena::Arena::new(4096).unwrap();
let layout = Layout::default().with_writes(1, element_write::<f64>(), &[f64_field("opacity")]);
let stride = layout.lane_stride();
let mut buffer = vec![0u64; (4 * stride).div_ceil(8)];
let base = buffer.as_mut_ptr().cast::<u8>();
let bounds = (base as usize, buffer.len() * 8);
for lane in 0..4usize {
unsafe { base.add(lane * stride).cast::<f64>().write(lane as f64) };
}
let batch = unsafe { crate::node::RecordBatch::new(base.cast_const(), 4, &layout) };
let promotion = Promotion::new(&transient, bounds, &persistent);
let span = unsafe { MaterializedSpan::to_persistent(&batch, &promotion) }.unwrap();
let slab = (4 * stride).div_ceil(8) * 8;
assert_eq!(persistent.occupancy(), slab, "a layout with no parked slot allocates the slab and nothing else");
assert_eq!(persistent.retained_heap(), 0, "no payload parked, so nothing is retained");
let published = span.batch(&persistent, &layout).unwrap();
for lane in 0..4usize {
assert_eq!(unsafe { published.get(lane).rec().element::<f64>() }, lane as f64, "lane {lane}");
}
}
#[test]
fn a_promoted_element_lands_in_the_persistent_region() {
let transient = crate::arena::Arena::new(4096).unwrap();
let persistent = crate::arena::Arena::new(4096).unwrap();
let layout = Layout::default().with_writes(0, element_write::<String>(), &[]);
let mut buffer = vec![0u64; layout.frame_bytes().div_ceil(8)];
let base = buffer.as_mut_ptr().cast::<u8>();
let bounds = (base as usize, buffer.len() * 8);
unsafe { write_element(base, String::from("parked in the evaluation"), &transient) }.unwrap();
let source = unsafe { base.cast::<*const u8>().read() };
assert!(transient.contains(source));
let batch = unsafe { crate::node::RecordBatch::new(base.cast_const(), 1, &layout) };
let promotion = Promotion::new(&transient, bounds, &persistent);
let span = unsafe { MaterializedSpan::to_persistent(&batch, &promotion) }.unwrap();
let published = span.batch(&persistent, &layout).unwrap();
let promoted = unsafe { published.get(0).rec().ptr().cast::<*const u8>().read() };
assert!(persistent.contains(promoted), "the promote re-parked the payload into the persistent region");
assert_ne!(source, promoted, "an evaluation-lived payload gets its own persistent header");
assert_eq!(unsafe { borrow_element::<String>(published.get(0).rec()) }, "parked in the evaluation");
}
/// The measure production registers for `String`, without which a promote
/// credits the region 0 and the counters cannot be observed to transfer.
fn measure_strings() {
register_retained_heap::<String>(|value| value.downcast_ref::<String>().map_or(0, String::len));
}
#[test]
fn a_promoted_payload_moves_its_heap_rather_than_cloning_it() {
measure_strings();
let mut transient = crate::arena::Arena::new(4096).unwrap();
let persistent = crate::arena::Arena::new(4096).unwrap();
let layout = Layout::default().with_writes(0, element_write::<String>(), &[]);
let mut buffer = vec![0u64; layout.frame_bytes().div_ceil(8)];
let base = buffer.as_mut_ptr().cast::<u8>();
let bounds = (base as usize, buffer.len() * 8);
let owned = String::from("the obligation travels with the header");
let (heap, length) = (owned.as_ptr(), owned.len());
unsafe { write_element_sized(base, owned, &transient, length) }.unwrap();
assert_eq!(transient.retained_heap(), length);
let batch = unsafe { crate::node::RecordBatch::new(base.cast_const(), 1, &layout) };
let promotion = Promotion::new(&transient, bounds, &persistent);
let span = unsafe { MaterializedSpan::to_persistent(&batch, &promotion) }.unwrap();
let published = span.batch(&persistent, &layout).unwrap();
let served = unsafe { borrow_element::<String>(published.get(0).rec()) };
assert_eq!(served.as_ptr(), heap, "the promote moved the header, so the served view names the pre-promote heap");
assert_eq!(transient.retained_heap(), 0, "the transient counter gave the hint up");
assert_eq!(persistent.retained_heap(), length, "and the persistent counter took it");
transient.reset();
let published = span.batch(&persistent, &layout).unwrap();
assert_eq!(
unsafe { borrow_element::<String>(published.get(0).rec()) },
"the obligation travels with the header",
"the moved payload survives the transient reset"
);
}
#[test]
fn a_payload_two_records_share_promotes_to_one_persistent_header() {
measure_strings();
let transient = crate::arena::Arena::new(4096).unwrap();
let mut persistent = crate::arena::Arena::new(4096).unwrap();
let layout = Layout::default().with_writes(0, element_write::<String>(), &[]);
let stride = layout.lane_stride();
let mut buffer = vec![0u64; (2 * stride).div_ceil(8)];
let base = buffer.as_mut_ptr().cast::<u8>();
let bounds = (base as usize, buffer.len() * 8);
let length = "shared across lanes".len();
unsafe { write_element_sized(base, String::from("shared across lanes"), &transient, length) }.unwrap();
// A carried element byte-copies its park reference, so both lanes name the one park.
let shared = unsafe { base.cast::<*const u8>().read() };
unsafe { base.add(stride).cast::<*const u8>().write(shared) };
let batch = unsafe { crate::node::RecordBatch::new(base.cast_const(), 2, &layout) };
let promotion = Promotion::new(&transient, bounds, &persistent);
let span = unsafe { MaterializedSpan::to_persistent(&batch, &promotion) }.unwrap();
let published = span.batch(&persistent, &layout).unwrap();
let first = unsafe { published.get(0).rec().ptr().cast::<*const u8>().read() };
let second = unsafe { published.get(1).rec().ptr().cast::<*const u8>().read() };
assert_eq!(first, second, "a payload two records share moves once");
assert_eq!(persistent.retained_heap(), length, "and its hint transfers once");
persistent.reset();
assert_eq!(persistent.retained_heap(), 0, "the flush frees the one header exactly once");
}
#[test]
fn a_persistent_element_is_shared_by_the_promote() {
let transient = crate::arena::Arena::new(4096).unwrap();
let persistent = crate::arena::Arena::new(4096).unwrap();
let layout = Layout::default().with_writes(0, element_write::<String>(), &[]);
let mut buffer = vec![0u64; layout.frame_bytes().div_ceil(8)];
let base = buffer.as_mut_ptr().cast::<u8>();
let bounds = (base as usize, buffer.len() * 8);
// The payload an upstream memo already published: the promote must
// name it rather than copy it.
unsafe { write_element(base, String::from("published upstream"), &persistent) }.unwrap();
let upstream = unsafe { base.cast::<*const u8>().read() };
let occupied = persistent.occupancy();
let batch = unsafe { crate::node::RecordBatch::new(base.cast_const(), 1, &layout) };
let promotion = Promotion::new(&transient, bounds, &persistent);
let span = unsafe { MaterializedSpan::to_persistent(&batch, &promotion) }.unwrap();
let published = span.batch(&persistent, &layout).unwrap();
let promoted = unsafe { published.get(0).rec().ptr().cast::<*const u8>().read() };
assert_eq!(upstream, promoted, "an already persistent payload is shared, pointer for pointer");
assert_eq!(persistent.occupancy() - occupied, layout.frame_bytes(), "only the lane slab was allocated");
}
#[test]
#[should_panic(expected = "a promoted element kept a reference outside the persistent region")]
fn the_rewalk_catches_a_reference_the_promote_left_behind() {
let transient = crate::arena::Arena::new(4096).unwrap();
let persistent = crate::arena::Arena::new(4096).unwrap();
let layout = Layout::default().with_writes(0, element_write::<String>(), &[]);
let mut buffer = vec![0u64; layout.frame_bytes().div_ceil(8)];
let base = buffer.as_mut_ptr().cast::<u8>();
let bounds = (base as usize, buffer.len() * 8);
unsafe { write_element(base, String::from("never promoted"), &transient) }.unwrap();
let promotion = Promotion::new(&transient, bounds, &persistent);
unsafe { assert_promoted(&layout, base.cast_const(), &promotion) };
}
}
@@ -0,0 +1,165 @@
//! Producer-side routing: a source's translation into the union layout.
use super::access::{Rec, apply_plan};
use super::frames::Frames;
use super::layout::{Layout, copy_plan};
use super::serve::{FrameClaim, Served, serve_input};
use crate::attribute;
use crate::gpoll::GPoll;
use crate::node::Node;
/// The default bytes for a union field the source does not carry: the census
/// default for declared names, zeroes otherwise.
fn default_fill_bytes(name: &str, size: usize) -> Box<[u8]> {
let mut bytes = vec![0u8; size].into_boxed_slice();
if let Some(info) = attribute::info(name)
&& info.size == size
{
(info.write_default_bytes)(&mut bytes);
}
bytes
}
/// A routing source's wiring-resolved translation: field moves into the
/// union layout plus census default fill for union fields the source lacks.
/// Absent when the source's layout already equals the union, in which case
/// the record pointer forwards untouched.
#[derive(Debug)]
pub struct SourcePlan {
moves: Vec<(usize, usize, usize)>,
fills: Vec<(usize, Box<[u8]>)>,
source: Layout,
}
impl SourcePlan {
pub fn new(source: &Layout, union: &Layout) -> Option<SourcePlan> {
if source == union {
return None;
}
let moves = copy_plan(source, union, true, &[]);
let fills = union
.fields
.iter()
.filter(|field| source.offset_of(field.name, field.level).is_none())
.map(|field| (field.offset, default_fill_bytes(field.name, field.size)))
.collect();
Some(SourcePlan { moves, fills, source: source.clone() })
}
/// # Safety
/// `src` must be a record of this plan's source layout and `dst` a
/// buffer of the plan's union layout that does not overlap `src`. The
/// returned view borrows `dst`, so `'d` must not outlive it.
pub unsafe fn translate<'d>(&self, src: Rec<'_>, dst: *mut u8) -> Rec<'d> {
// SAFETY: the caller's contract; the plan's moves and fills name only
// offsets of the layouts it was built from.
unsafe {
apply_plan(src, dst, &self.moves);
for (offset, bytes) in &self.fills {
std::ptr::copy_nonoverlapping(bytes.as_ptr(), dst.add(*offset), bytes.len());
}
Rec::new(dst)
}
}
}
/// A routing input's claimed source plus its wiring-resolved [`SourcePlan`].
/// Evaluating it yields the source's record translated to the union layout
/// (or forwarded untouched when the layouts already agree), so the kernel
/// holds and returns record values without ever seeing the representation.
/// A translation lands in the claim the caller minted, so the value survives
/// sibling evaluations and its region is free again with that claim, which
/// bounds claims at one per source evaluation the kernel performs.
pub struct RecordSource<N> {
edge: N,
plan: Option<SourcePlan>,
union: Layout,
}
impl<N> RecordSource<N> {
pub fn new(edge: N, source: &Layout, union: &Layout) -> Self {
Self {
edge,
plan: SourcePlan::new(source, union),
union: union.clone(),
}
}
}
impl<C, N> Node<C> for RecordSource<N>
where
N: Node<C>,
{
fn serve<'e, 'l>(&self, input: &C, mut slot: FrameClaim<'e, 'l>) -> GPoll<Served<'e>>
where
C: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
// The source's frame is claimed beyond this one and dies with the
// claim; the translated union record stays.
let Some(plan) = &self.plan else {
return self.edge.serve(input, slot);
};
match serve_input(&self.edge, input, &slot.frames().reborrow()) {
GPoll::Final(value) => {
// SAFETY: the value came from this source, so it carries the
// plan's source layout.
unsafe { slot.translate(plan.source.rec(&value), plan) };
// SAFETY: the translation completes the union record.
GPoll::Final(unsafe { slot.finish_served() })
}
GPoll::Partial(value) => {
// SAFETY: as for the final arm.
unsafe { slot.translate(plan.source.rec(&value), plan) };
// SAFETY: as for the final arm.
GPoll::Partial(unsafe { slot.finish_served() })
}
GPoll::Fallback(boxed) => {
let (value, error) = *boxed;
// SAFETY: as for the final arm.
unsafe { slot.translate(plan.source.rec(&value), plan) };
// SAFETY: as for the final arm.
GPoll::Fallback(Box::new((unsafe { slot.finish_served() }, error)))
}
GPoll::Pending => GPoll::Pending,
GPoll::Error(error) => GPoll::Error(error),
}
}
fn extent_at<'x>(&self, input: &C, level: u8, frames: &Frames<'x>) -> GPoll<crate::gpoll::Extent>
where
C: crate::context::ExtractArena<ArenaRef = &'x crate::arena::Arena>,
{
self.edge.extent_at(input, level, frames)
}
fn layout(&self) -> &Layout {
&self.union
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::record::layout::element_write;
use crate::record::test_support::f64_field;
#[test]
fn translation_moves_fields_and_fills_census_defaults() {
let source = Layout::default().with_writes(0, element_write::<f64>(), &[f64_field("length")]);
let union = Layout::union(&[&source, &Layout::default().with_writes(0, element_write::<f64>(), &[f64_field("opacity")])]);
let plan = SourcePlan::new(&source, &union).unwrap();
let record = [5f64, 7f64];
let mut buffer = vec![0u64; union.size.div_ceil(8)];
let translated = unsafe { plan.translate(Rec::new(record.as_ptr().cast()), buffer.as_mut_ptr().cast()) };
assert_eq!(unsafe { translated.element::<f64>() }, 5.);
assert_eq!(unsafe { translated.read::<f64>(union.offset_of("length", 0).unwrap()) }, 7.);
assert_eq!(unsafe { translated.read::<f64>(union.offset_of("opacity", 0).unwrap()) }, 1.);
}
#[test]
fn identity_layouts_forward() {
let layout = Layout::default().with_writes(0, element_write::<f64>(), &[f64_field("opacity")]);
assert!(SourcePlan::new(&layout, &layout.clone()).is_none());
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,389 @@
//! The serving protocol: a node's own frame claim and the proof it closes with.
use super::access::{Rec, RecordValue, apply_plan, lift_poll_into, write_element, write_field};
use super::frames::Frames;
use super::layout::{Layout, element_dims, element_parked};
use super::route::SourcePlan;
use crate::gpoll::GPoll;
use crate::node::Node;
/// A claimed run of same-layout slots over the caller's scratch: [`Self::slot`]
/// backs an ordinary claim's own region by the lane's region of the slab, so a
/// lane serves in place with no staging copy, and [`Self::served`] records the
/// proof. The filled prefix is the only readable part, which is what makes
/// [`Self::finish`] safe.
pub struct SlotRun<'a> {
scratch: &'a mut [std::mem::MaybeUninit<u64>],
layout: &'a Layout,
len: usize,
filled: usize,
}
impl<'a> SlotRun<'a> {
/// `None` where the scratch cannot hold `len` lanes. The products are
/// checked: the stride is a multiple of 8, so a wrapped one would pass the
/// capacity test vacuously.
pub(in crate::record) fn new(scratch: &'a mut [std::mem::MaybeUninit<u64>], len: usize, layout: &'a Layout) -> Option<SlotRun<'a>> {
let need = len.checked_mul(layout.lane_stride())?;
let capacity = scratch.len().checked_mul(8)?;
(capacity >= need).then_some(SlotRun { scratch, layout, len, filled: 0 })
}
pub fn layout(&self) -> &'a Layout {
self.layout
}
/// Lane `lane`'s claim: its own frame is the lane's region of the slab and
/// its free space is `frames`, so the lane's inputs claim beyond it.
pub fn slot<'e>(&mut self, lane: usize, frames: &Frames<'e>) -> FrameClaim<'e, 'a> {
assert!(lane < self.len, "lane {lane} out of bounds for a run of {}", self.len);
let stride = self.layout.lane_stride();
// SAFETY: in-bounds by the assert against the capacity check `new` made.
let frame = unsafe { self.scratch.as_mut_ptr().cast::<u8>().add(lane * stride) };
FrameClaim {
layout: self.layout,
inline: RecordValue::zeroed(),
frame: (self.layout.frame_bytes() != 0).then_some(frame),
free: frames.reborrow(),
filled_fields: false,
}
}
/// Records lane `lane` as served; the proof came from that lane's slot. An
/// inline record rides the value's own storage, so it takes the one copy
/// the run makes. Lanes serve in ascending order with no gaps, so the
/// filled count is an initialized prefix rather than a high-water mark.
pub fn served(&mut self, lane: usize, proof: &Served<'_>) {
assert!(lane < self.len, "lane {lane} out of bounds for a run of {}", self.len);
assert_eq!(lane, self.filled, "lane {lane} serves out of order after {} filled lanes", self.filled);
if self.layout.size == 0 {
let stride = self.layout.lane_stride();
// SAFETY: in-bounds by the assert against the capacity check `new`
// made, and the lane takes the whole inline record.
unsafe { std::ptr::copy_nonoverlapping(self.layout.rec(proof.record()).ptr(), self.scratch.as_mut_ptr().cast::<u8>().add(lane * stride), stride) };
}
self.filled = lane + 1;
}
/// The served lanes as the caller's exclusive batch.
pub fn finish(self) -> crate::node::RecordBatchMut<'a> {
crate::node::RecordBatchMut::new(self.scratch, self.filled, self.layout)
}
}
/// A node's own output frame, minted by its caller from the caller's frame
/// space: the one closing surface for every exit. Writes land through it,
/// [`Self::lift`] and [`Self::finish`] serve the record, and it carries the
/// free space beyond the frame, so a node's inputs claim past it and their
/// space is free again when the claim dies, on value, error, and pending exits
/// alike with no per-exit ritual.
pub struct FrameClaim<'e, 'l> {
pub(in crate::record) layout: &'l Layout,
pub(in crate::record) inline: RecordValue<'static>,
pub(in crate::record) frame: Option<*mut u8>,
pub(in crate::record) free: Frames<'e>,
/// Set by the writes that fill the declared fields, so the safe closers can
/// refuse a field-bearing frame that was never filled.
pub(in crate::record) filled_fields: bool,
}
impl<'e, 'l> FrameClaim<'e, 'l> {
/// The free space beyond this claim's frame, which the node's own inputs
/// claim from.
pub fn frames(&mut self) -> &Frames<'e> {
&mut self.free
}
pub(in crate::record) fn dst(&mut self) -> *mut u8 {
match self.frame {
Some(frame) => frame,
None => (&raw mut self.inline).cast(),
}
}
/// Asserts the served element matches the wired layout, so a node whose
/// layout never resolved (or resolved at another type) panics here
/// instead of writing past its frame.
fn check_element<T: dyn_any::StaticTypeSized>(&self) {
let (size, _) = element_dims::<T>();
assert!(
self.layout.element.size == size && self.layout.element.parked == element_parked::<T>() && self.layout.element.type_id == std::any::TypeId::of::<T::Static>(),
"the served element `{}` ({size} bytes) must match the wired layout ({} bytes)",
std::any::type_name::<T>(),
self.layout.element.size,
);
}
/// Carries the plan's fields from a source record into the frame.
///
/// # Safety
/// `src` must be a live record of the plan's source layout, and the plan
/// must be the wiring-resolved plan of this frame's layout. `src` must not
/// overlap this frame; an input's frame is split off beyond the claim, so
/// serving the source through [`Self::frames`] establishes it.
pub unsafe fn carry(&mut self, src: Rec<'_>, plan: &[(usize, usize, usize)]) {
unsafe { apply_plan(src, self.dst(), plan) };
self.filled_fields = true;
}
/// Writes a field at its wiring-resolved offset.
///
/// # Safety
/// `offset` must be this layout's resolved offset for a field of `T`. A
/// generated write offset defaults to 0 until `set_layout` installs it, so
/// the debug assertion catches a serve that ran before the install.
pub unsafe fn attr_at<T>(&mut self, offset: usize, value: T) {
debug_assert!(
self.layout.fields.iter().any(|field| field.offset == offset),
"attribute write at an offset this layout does not carry; the layout must install before serving"
);
unsafe { write_field(self.dst(), offset, value) };
self.filled_fields = true;
}
/// Writes the element; `None` reports arena exhaustion for a parked
/// element. Panics where the element does not match the wired layout.
pub fn element<T: Send + Sync + dyn_any::StaticTypeSized>(&mut self, value: T, arena: &crate::arena::Arena) -> Option<()> {
self.check_element::<T>();
// SAFETY: the frame is this layout's fresh claim and the element
// check pinned `T` to the layout's element slot.
unsafe { write_element(self.dst(), value, arena) }
}
/// Lifts a kernel's poll into the frame and closes it: the element
/// writes on value polls, every poll keeps the frame claimed, and arena
/// exhaustion of a parked element reports as an error poll. Panics where
/// the element does not match the wired layout, or where a field-bearing
/// layout closes on a frame no carry or field write ever filled, since the
/// [`Served`] proof certifies the whole record and the fields would be the
/// prior frame's bytes.
pub fn lift<T: Send + Sync + dyn_any::StaticTypeSized>(mut self, poll: GPoll<T>, arena: &'e crate::arena::Arena) -> GPoll<RecordValue<'e>> {
self.check_element::<T>();
assert!(
self.layout.fields.is_empty() || self.filled_fields,
"a layout with {} fields must carry or write them before lifting",
self.layout.fields.len()
);
let frame_bytes = self.layout.frame_bytes();
let dst = self.dst();
// SAFETY: the frame is this layout's fresh claim, the element check
// pinned `T`, and the drop keeps the frame contract on every poll.
unsafe { lift_poll_into(poll, dst, frame_bytes, arena) }
}
/// Copies a complete record of this layout into the frame, for serving
/// cached or published bytes.
///
/// # Safety
/// `src` must point at a live record of this layout whose parked
/// references outlive the serving evaluation.
pub unsafe fn fill_copy(&mut self, src: *const u8) {
unsafe { std::ptr::copy_nonoverlapping(src, self.dst(), self.layout.size) };
self.filled_fields = true;
}
/// The served record. The frame stays claimed for the consumer; the drop
/// releases only what was claimed above it.
///
/// # Safety
/// The frame must hold a complete record of the layout, written through
/// the carry, element, and field writes.
pub unsafe fn finish(mut self) -> RecordValue<'e> {
match self.frame {
Some(frame) => RecordValue::spilled(unsafe { Rec::new(frame.cast_const()) }),
// SAFETY: the inline record is the value's own bytes.
None => unsafe { (&raw mut self.inline).cast::<RecordValue<'e>>().read() },
}
}
/// [`Self::lift`] with the proof-bearing return for [`Node::serve`].
pub fn lift_served<T: Send + Sync + dyn_any::StaticTypeSized>(self, poll: GPoll<T>, arena: &'e crate::arena::Arena) -> GPoll<Served<'e>> {
self.lift(poll, arena).map(|value| Served { value })
}
/// [`Self::finish`] with the proof-bearing return for [`Node::serve`].
///
/// # Safety
/// As [`Self::finish`].
pub unsafe fn finish_served(self) -> Served<'e> {
Served { value: unsafe { self.finish() } }
}
/// Fills the frame from a record a forwarded input already served, and
/// closes it: the source's frame sits above this claim and dies with its
/// drop, so the served record is this claim's own.
///
/// # Safety
/// `value` must be a live record of this frame's layout.
pub unsafe fn forward(mut self, value: &RecordValue<'_>) -> Served<'e> {
let src = self.layout.rec(value).ptr();
unsafe {
self.fill_copy(src);
self.finish_served()
}
}
/// Translates a source record into the frame through a wiring-resolved plan.
///
/// # Safety
/// `src` must be a live record of `plan`'s source layout, `plan` must
/// translate into this frame's layout, and `src` must not overlap this
/// frame, as [`Self::carry`] requires.
pub unsafe fn translate(&mut self, src: Rec<'_>, plan: &SourcePlan) {
unsafe { plan.translate(src, self.dst()) };
self.filled_fields = true;
}
}
/// A materialized run of lanes as the arena region its frames live in: the
/// handle keeps the provenance the region was allocated with and carries the
/// generation, so resolving it re-checks liveness where an address would have
/// been trusted. The layout stays with the holder, which proved it at wiring.
#[derive(Clone, Copy)]
pub struct MaterializedSpan {
pub(in crate::record) base: crate::arena::ArenaWeak<u8>,
pub(in crate::record) len: usize,
}
impl std::fmt::Debug for MaterializedSpan {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("MaterializedSpan").field("len", &self.len).finish()
}
}
impl MaterializedSpan {
/// `None` where the batch's frames are not this arena's, which is the
/// caller's cue to re-materialize rather than cache.
pub fn of(batch: &crate::node::RecordBatch<'_>, arena: &crate::arena::Arena) -> Option<MaterializedSpan> {
match batch.len() {
0 => Some(MaterializedSpan {
base: crate::arena::ArenaWeak::NULL,
len: 0,
}),
len => Some(MaterializedSpan {
base: arena.handle_at(batch.get(0).rec().ptr())?,
len,
}),
}
}
/// The span's lanes at `layout`, or `None` once the generation moved on.
pub fn batch<'a>(&self, arena: &'a crate::arena::Arena, layout: &'a Layout) -> Option<crate::node::RecordBatch<'a>> {
let base: *const u8 = match self.len {
0 => std::ptr::NonNull::<u8>::dangling().as_ptr(),
_ => self.base.upgrade(arena)?,
};
// SAFETY: the handle resolved in generation, so the region still holds
// the lanes it was published with, packed at the layout's stride; an
// empty span reads no lane.
Some(unsafe { crate::node::RecordBatch::new(base, self.len, layout) })
}
/// Lane `lane`'s record, or `None` past the span or once the generation
/// moved on.
pub fn lane(&self, arena: &crate::arena::Arena, lane: usize, layout: &Layout) -> Option<*const u8> {
(lane < self.len).then_some(())?;
let base: *const u8 = self.base.upgrade(arena)?;
// SAFETY: in-bounds by the length check, at the layout the span was
// published under.
Some(unsafe { base.add(lane * layout.lane_stride()) })
}
}
/// The proof a record was served through a frame claim: mintable only by the
/// claim's closing methods, so holding one means the record is of the
/// claimed layout.
pub struct Served<'e> {
value: RecordValue<'e>,
}
impl<'e> Served<'e> {
pub fn value(self) -> RecordValue<'e> {
self.value
}
/// The served record in place, for producers that read it before passing
/// the proof on.
pub fn record(&self) -> &RecordValue<'e> {
&self.value
}
}
/// Claims `node`'s own frame from `frames` and serves through it: the
/// caller-side half of [`Node::serve`], for drivers that want the record
/// rather than the proof.
pub fn serve_input<'e, C, N>(node: &N, input: &C, frames: &Frames<'e>) -> GPoll<RecordValue<'e>>
where
N: Node<C> + ?Sized,
C: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
let slot = frames.claim(node.layout());
node.serve(input, slot).map(Served::value)
}
/// A claim shortens onto a derived context's arena lifetime.
#[cfg(test)]
fn claim_shortens<'long: 'short, 'short, 'l>(claim: FrameClaim<'long, 'l>) -> FrameClaim<'short, 'l> {
claim
}
#[cfg(test)]
mod tests {
use super::*;
use crate::record::frames::FrameArena;
use crate::record::layout::element_write;
#[test]
#[should_panic(expected = "must match the wired layout")]
fn a_mistyped_element_is_rejected_at_the_write() {
let arena = crate::arena::Arena::new(256).unwrap();
let layout = Layout::default().with_writes(0, element_write::<f64>(), &[]);
let mut frame_arena = FrameArena::new();
frame_arena.reserve(1 << 10);
let frames = frame_arena.frames();
frames.claim(&layout).element(1u32, &arena);
}
#[test]
fn a_run_refuses_a_lane_count_whose_stride_product_overflows() {
let layout = Layout::default().with_writes(0, element_write::<f64>(), &[]);
let mut scratch = [std::mem::MaybeUninit::<u64>::uninit(); 4];
let mut frame_arena = FrameArena::new();
frame_arena.reserve(64);
let frames = frame_arena.frames();
let wrapping = usize::MAX / layout.lane_stride() + 1;
assert!(frames.run(&mut scratch, wrapping, &layout).is_none(), "a wrapped capacity product must not pass the check");
}
#[test]
#[should_panic(expected = "serves out of order")]
fn a_run_refuses_a_gapped_serve() {
let arena = crate::arena::Arena::new(1024).unwrap();
let layout = Layout::default().with_writes(0, element_write::<f64>(), &[]);
let mut scratch = [std::mem::MaybeUninit::<u64>::uninit(); 8];
let mut frame_arena = FrameArena::new();
frame_arena.reserve(1 << 10);
let frames = frame_arena.frames();
let mut run = frames.run(&mut scratch, 3, &layout).unwrap();
let lane_frames = frames.scope();
let slot = run.slot(2, &lane_frames);
let GPoll::Final(proof) = slot.lift_served(GPoll::Final(1.0f64), &arena) else {
panic!("expected a final record");
};
run.served(2, &proof);
}
#[test]
fn a_claim_shortens_onto_a_derived_lifetime() {
fn shorten<'long: 'short, 'short, 'l>(claim: FrameClaim<'long, 'l>) -> FrameClaim<'short, 'l> {
claim_shortens(claim)
}
let layout = Layout::default().with_writes(0, element_write::<f64>(), &[]);
let mut frame_arena = FrameArena::new();
frame_arena.reserve(64);
let frames = frame_arena.frames();
let claim = shorten(frames.claim(&layout));
assert_eq!(claim.layout, &layout);
}
}
@@ -0,0 +1,25 @@
//! Shared fixtures for the record module family's tests.
use super::layout::FieldWrite;
unsafe fn unread(_: *const u8) -> Box<dyn crate::list::AnyAttributeValue> {
unreachable!("layout-only test field")
}
pub(super) fn sized_field(name: &'static str, size: usize, align: usize) -> FieldWrite {
FieldWrite {
name,
level: 0,
size,
align,
type_id: std::any::TypeId::of::<()>(),
read_erased: unread,
repark: None,
content_hash: None,
content_eq: None,
}
}
pub(super) fn f64_field(name: &'static str) -> FieldWrite {
sized_field(name, 8, 8)
}
@@ -0,0 +1,182 @@
//! Law-test scaffolding over the record tier.
use super::frames::{FrameArena, Frames};
use super::layout::{Layout, element_write};
use super::owned::OwnedRecord;
use super::serve::{FrameClaim, Served, serve_input};
use crate::gpoll::GPoll;
use crate::node::Node;
/// Law-test scaffolding: a frame space of `bytes`, leaked so a fixture holds
/// it for the whole test without threading the buffer's own borrow. Production
/// roots own their buffer and lend it by `&mut`.
#[doc(hidden)]
pub fn test_frames(bytes: usize) -> Frames<'static> {
let arena: &'static mut FrameArena = Box::leak(Box::new(FrameArena::new()));
arena.reserve(bytes);
arena.frames()
}
/// One record captured out of a poll: the deep copy plus the layout it was
/// served at, so assertions read owned storage with no tie to the record
/// stack. [`capture`] is the only constructor.
pub struct ServedRecord {
layout: Layout,
record: OwnedRecord,
}
impl ServedRecord {
pub fn layout(&self) -> &Layout {
&self.layout
}
/// The element, cloned out of the capture. Panics unless `T` is the
/// layout's element type.
pub fn element<T: Clone + 'static>(&self) -> T {
assert_eq!(std::any::TypeId::of::<T>(), self.layout.element.type_id, "the read type must match the layout's element type");
match &self.record.element {
Some(parked) => parked.downcast_ref::<T>().expect("the element parked at its own type").clone(),
// SAFETY: the captured bytes image a record of this layout; a
// byte-carried element is a `T` with no drop glue.
None => unsafe { self.record.bytes.as_ptr().cast::<T>().read_unaligned() },
}
}
/// The marker's level-0 field value. Panics unless the layout declares
/// the marker at its value type.
pub fn attr<A: crate::attribute::Attribute>(&self) -> A::Value<'static>
where
A::Value<'static>: Copy + 'static,
{
self.field(A::NAME, 0)
}
/// A field by name and level, for layouts whose fields are not census
/// markers. Panics unless the field is declared at `T` and byte-carried;
/// a parked field reads through replay, not the captured bytes.
pub fn field<T: Copy + 'static>(&self, name: &str, level: u8) -> T {
let field = self
.layout
.fields
.iter()
.find(|field| field.name == name && field.level == level)
.expect("the layout carries the read field");
assert_eq!(field.type_id, std::any::TypeId::of::<T>(), "the field was declared at this value type");
assert!(field.repark.is_none(), "a parked field reads through replay, not the captured bytes");
// SAFETY: the captured bytes image a record of this layout and the
// field is byte-carried at `T`.
unsafe { self.record.bytes.as_ptr().add(field.offset).cast::<T>().read_unaligned() }
}
}
/// Polls `node` once and captures any served record: the record is
/// deep-copied at the node's own declared layout inside a frame scope, so the
/// result is owned and every claimed frame is free again. Assertion
/// scaffolding for law tests; production consumers read served records in
/// place.
pub fn capture<'e, C, N>(node: &N, ctx: &C, frames: &Frames<'e>) -> GPoll<ServedRecord>
where
N: Node<C> + ?Sized,
C: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
let scope = frames.scope();
let layout = node.layout().clone();
serve_input(node, ctx, &scope).map(|value| ServedRecord {
// SAFETY: the poll served `value` at the node's declared layout and
// nothing has claimed frames since.
record: unsafe { OwnedRecord::copy_out(&layout, layout.rec(&value)) },
layout: layout.clone(),
})
}
/// Law-test scaffolding: a kernel closure served onto an element-only record
/// input (the element lands at offset 0, parked when it carries drop glue). No
/// production path constructs one; value sources are
/// [`crate::value::ValueSource`].
pub struct LiftedSource<El, F> {
kernel: F,
layout: Layout,
_marker: std::marker::PhantomData<fn() -> El>,
}
impl<El: Clone + Send + Sync + dyn_any::StaticTypeSized, F> LiftedSource<El, F>
where
El::Static: Clone + Send + Sync,
{
pub fn new(kernel: F) -> Self {
Self {
kernel,
layout: Layout::default().with_writes(0, element_write::<El>(), &[]),
_marker: std::marker::PhantomData,
}
}
}
impl<C, El, F> Node<C> for LiftedSource<El, F>
where
El: Send + Sync + dyn_any::StaticTypeSized,
F: Fn(&C) -> GPoll<El>,
{
fn serve<'e, 'l>(&self, input: &C, slot: FrameClaim<'e, 'l>) -> GPoll<Served<'e>>
where
C: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
slot.lift_served((self.kernel)(input), input.arena())
}
fn layout(&self) -> &Layout {
&self.layout
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::record::layout::FieldWrite;
#[test]
fn a_captured_frame_serves_its_writes() {
use crate::attribute::{Attribute, Transform};
use glam::{DAffine2, DVec2};
struct Fixture {
layout: Layout,
}
impl<C> Node<C> for Fixture {
fn serve<'e, 'l>(&self, input: &C, mut slot: FrameClaim<'e, 'l>) -> GPoll<Served<'e>>
where
C: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
let offset = self.layout.offset_of(Transform::NAME, 0).expect("the fixture's layout carries the transform");
if slot.element(String::from("parked"), crate::context::ExtractArena::arena(input)).is_none() {
return GPoll::error("arena exhausted");
}
// SAFETY: the offset is this layout's own, at the marker's value type.
unsafe { slot.attr_at(offset, DAffine2::from_translation(DVec2::new(3., 4.))) };
// SAFETY: the writes above complete the record.
GPoll::Final(unsafe { slot.finish_served() })
}
fn layout(&self) -> &Layout {
&self.layout
}
}
let layout = Layout::default().with_writes(0, element_write::<String>(), &[FieldWrite::of::<Transform>(0)]);
let mut frame_arena = FrameArena::new();
frame_arena.reserve(1 << 10);
let frames = frame_arena.frames();
let arena = crate::arena::Arena::new(1024).unwrap();
let generations = [];
let scope = crate::context::EvalScope::new(None, None, None, &generations, &arena);
let ctx = crate::context::ContextImpl::root(&scope);
let free = frames.free_words();
let GPoll::Final(served) = capture(&Fixture { layout }, &ctx, &frames) else {
panic!("the fixture serves finally");
};
assert_eq!(frames.free_words(), free, "capture returns every claimed slot");
assert_eq!(served.element::<String>(), "parked");
assert_eq!(served.attr::<Transform>(), DAffine2::from_translation(DVec2::new(3., 4.)));
}
}
+531 -204
View File
@@ -1,10 +1,12 @@
use crate::{Color, ContextFeature, Node, NodeIO, NodeIOTypes, ProtoNodeIdentifier, Type, WasmNotSend}; use crate::concrete;
use dyn_any::{DynAny, StaticType}; use crate::context::{Context, ContextImpl};
use crate::node::Node;
use crate::{Color, ContextFeature, ProtoNodeIdentifier, Type, WasmNotSend, WasmNotSync};
use dyn_any::DynAny;
use graphene_hash::CacheHash;
pub use no_std_types::registry::types; pub use no_std_types::registry::types;
use std::collections::HashMap; use std::collections::HashMap;
use std::marker::PhantomData; use std::hash::Hasher;
use std::ops::Deref;
use std::pin::Pin;
use std::sync::{LazyLock, Mutex}; use std::sync::{LazyLock, Mutex};
// Translation struct between macro and definition // Translation struct between macro and definition
@@ -18,6 +20,8 @@ pub struct NodeMetadata {
pub context_features: Vec<ContextFeature>, pub context_features: Vec<ContextFeature>,
pub memoize: bool, pub memoize: bool,
pub inject_scope: bool, pub inject_scope: bool,
/// Set where `_runtime` and `_source` are the last two entries of `fields`.
pub async_source_fields: bool,
} }
// Translation struct between macro and definition // Translation struct between macro and definition
@@ -25,6 +29,8 @@ pub struct NodeMetadata {
pub struct FieldMetadata { pub struct FieldMetadata {
pub name: &'static str, pub name: &'static str,
pub description: &'static str, pub description: &'static str,
/// Index levels the node pushes when evaluating this input.
pub pushed_levels: u8,
pub hidden: bool, pub hidden: bool,
pub exposed: bool, pub exposed: bool,
pub widget_override: RegistryWidgetOverride, pub widget_override: RegistryWidgetOverride,
@@ -57,239 +63,560 @@ pub enum RegistryValueSource {
None, None,
Default(&'static str), Default(&'static str),
Scope(&'static str), Scope(&'static str),
SourceId,
} }
type NodeRegistry = LazyLock<Mutex<HashMap<ProtoNodeIdentifier, Vec<(NodeConstructor, NodeIOTypes)>>>>; type NodeRegistry = LazyLock<Mutex<HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>>>>;
pub static NODE_REGISTRY: NodeRegistry = LazyLock::new(|| Mutex::new(HashMap::new())); pub static NODE_REGISTRY: NodeRegistry = LazyLock::new(|| Mutex::new(HashMap::new()));
pub static NODE_METADATA: LazyLock<Mutex<HashMap<ProtoNodeIdentifier, NodeMetadata>>> = LazyLock::new(|| Mutex::new(HashMap::new())); pub static NODE_METADATA: LazyLock<Mutex<HashMap<ProtoNodeIdentifier, NodeMetadata>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
pub use crate::NodeIOTypes;
/// Element-independent by erasure; the input's `Type::Record(El)` keeps element reads proven at wiring.
#[cfg(not(target_family = "wasm"))] #[cfg(not(target_family = "wasm"))]
pub type DynFuture<'n, T> = Pin<Box<dyn Future<Output = T> + 'n + Send>>; pub type ErasedRecordNode = dyn for<'c> Node<ContextImpl<'c>> + Send + Sync;
#[cfg(target_family = "wasm")] #[cfg(target_family = "wasm")]
pub type DynFuture<'n, T> = Pin<Box<dyn std::future::Future<Output = T> + 'n>>; pub type ErasedRecordNode = dyn for<'c> Node<ContextImpl<'c>>;
pub type LocalFuture<'n, T> = Pin<Box<dyn Future<Output = T> + 'n>>;
#[cfg(not(target_family = "wasm"))]
type DynSource = dyn std::any::Any + Send + Sync;
#[cfg(target_family = "wasm")]
type DynSource = dyn std::any::Any;
pub fn record_type<T: 'static>() -> Type {
Type::Record(Box::new(concrete!(T)))
}
pub fn record_source_type<T: 'static>() -> Type {
Type::Fn(Box::new(concrete!(Context)), Box::new(record_type::<T>()))
}
/// The record source type of a token row, generic over the element.
pub fn generic_record_source_type(name: &'static str) -> Type {
Type::Fn(Box::new(concrete!(Context)), Box::new(Type::Record(Box::new(Type::Generic(std::borrow::Cow::Borrowed(name))))))
}
pub fn cache_key<C: CacheHash + ?Sized>(ctx: &C) -> u64 {
let mut hasher = graphene_hash::FxHasher64::new();
ctx.cache_hash(&mut hasher);
hasher.finish()
}
#[derive(Debug, PartialEq)]
pub enum ConstructionError {
Arity { expected: usize, got: usize },
Type { expected: Box<Type>, found: Box<Type> },
}
pub struct SharedSource<N: ?Sized> {
ptr: std::ptr::NonNull<N>,
own: std::sync::Arc<N>,
}
impl<N: ?Sized> SharedSource<N> {
pub fn new(own: std::sync::Arc<N>) -> Self {
Self {
ptr: std::ptr::NonNull::from(&*own),
own,
}
}
pub fn share(&self) -> Self {
Self { ptr: self.ptr, own: self.own.clone() }
}
/// Re-derives the cached pointer from the owned payload. An exclusive
/// re-borrow of the payload invalidates the pointer taken before it, so
/// every mutation through `own` ends here, an unwinding one included.
pub fn rederive(&mut self) {
self.ptr = std::ptr::NonNull::from(&*self.own);
}
}
/// Re-derives on the way out of an exclusive re-borrow, so a mutation that
/// panics cannot leave the cached pointer retired for a caller that catches.
struct Rederive<'a, N: ?Sized>(&'a mut SharedSource<N>);
impl<N: ?Sized> Drop for Rederive<'_, N> {
fn drop(&mut self) {
self.0.rederive();
}
}
// SAFETY: `ptr` is derived from the owned Arc and never mutated through, so the source is exactly as
// thread safe as the payload it shares.
unsafe impl<N: ?Sized + Send + Sync> Send for SharedSource<N> {}
// SAFETY: as in Send.
unsafe impl<N: ?Sized + Send + Sync> Sync for SharedSource<N> {}
impl<Input, N> Node<Input> for SharedSource<N>
where
N: Node<Input> + ?Sized,
{
fn serve<'e, 'l>(&self, input: &Input, slot: crate::record::FrameClaim<'e, 'l>) -> crate::gpoll::GPoll<crate::record::Served<'e>>
where
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
// SAFETY: `own` keeps the payload alive for `self`'s lifetime and Arc
// payloads are address stable.
unsafe { self.ptr.as_ref() }.serve(input, slot)
}
fn extent_at<'x>(&self, input: &Input, level: u8, frames: &crate::record::Frames<'x>) -> crate::gpoll::GPoll<crate::gpoll::Extent>
where
Input: crate::context::ExtractArena<ArenaRef = &'x crate::arena::Arena>,
{
// SAFETY: as in serve.
unsafe { self.ptr.as_ref() }.extent_at(input, level, frames)
}
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
// SAFETY: as in serve.
unsafe { self.ptr.as_ref() }.serialize()
}
fn layout(&self) -> &crate::record::Layout {
// SAFETY: as in serve.
unsafe { self.ptr.as_ref() }.layout()
}
fn eval_batch<'a, 'x>(
&'a self,
input: &'a Input,
range: std::ops::Range<u64>,
scratch: Option<&'a mut [std::mem::MaybeUninit<u64>]>,
frames: &crate::record::Frames<'x>,
) -> crate::node::BatchStatus<'a>
where
Input: crate::context::InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'x crate::arena::Arena>,
{
// SAFETY: as in serve.
unsafe { self.ptr.as_ref() }.eval_batch(input, range, scratch, frames)
}
}
pub struct SourceHandle {
node: Box<DynSource>,
share: fn(&DynSource) -> Box<DynSource>,
serialize: fn(&DynSource) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>>,
layout: fn(&DynSource) -> &crate::record::Layout,
set_layout: fn(&mut DynSource, crate::record::RecordLayout),
ty: Type,
}
impl std::fmt::Debug for SourceHandle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SourceHandle").field("ty", &self.ty).finish_non_exhaustive()
}
}
// SAFETY: wasm is single threaded, so the marker-free payload never actually crosses a thread.
#[cfg(target_family = "wasm")]
unsafe impl Send for SourceHandle {}
// SAFETY: as in Send.
#[cfg(target_family = "wasm")]
unsafe impl Sync for SourceHandle {}
#[cfg(all(target_family = "wasm", target_feature = "atomics"))]
compile_error!("SourceHandle's wasm Send/Sync rest on a single-threaded build; a +atomics target needs the stored node bounded instead");
impl SourceHandle {
pub fn new_record<T: 'static>(node: std::sync::Arc<ErasedRecordNode>) -> Self {
Self::new_erased(node, record_source_type::<T>())
}
pub fn new_erased<N>(node: std::sync::Arc<N>, ty: Type) -> Self
where
N: ?Sized + 'static + for<'c> Node<ContextImpl<'c>>,
SharedSource<N>: WasmNotSend + WasmNotSync,
{
Self {
node: Box::new(SharedSource::new(node)),
share: |edge| Box::new(edge.downcast_ref::<SharedSource<N>>().expect("share hook matches the stored edge type").share()),
serialize: |edge| Node::<ContextImpl>::serialize(edge.downcast_ref::<SharedSource<N>>().expect("serialize hook matches the stored edge type")),
layout: |edge| Node::<ContextImpl>::layout(edge.downcast_ref::<SharedSource<N>>().expect("layout hook matches the stored edge type")),
set_layout: |edge, layout| {
let shared = edge.downcast_mut::<SharedSource<N>>().expect("set_layout hook matches the stored edge type");
// The re-borrow below retires the cached pointer, so the rederive
// is a guard: a panicking `set_layout` must not leave it stale.
let guard = Rederive(shared);
let node = std::sync::Arc::get_mut(&mut guard.0.own).expect("layout is installed before the node is shared");
Node::<ContextImpl>::set_layout(node, layout);
},
ty,
}
}
pub fn ty(&self) -> &Type {
&self.ty
}
pub fn duplicate(&self) -> Self {
Self {
node: (self.share)(&*self.node),
share: self.share,
serialize: self.serialize,
layout: self.layout,
set_layout: self.set_layout,
ty: self.ty.clone(),
}
}
pub fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
(self.serialize)(&*self.node)
}
pub fn layout(&self) -> &crate::record::Layout {
(self.layout)(&*self.node)
}
pub fn set_layout(&mut self, layout: crate::record::RecordLayout) {
(self.set_layout)(&mut *self.node, layout);
}
pub fn downcast_record<T: 'static>(self) -> Result<SharedSource<ErasedRecordNode>, ConstructionError> {
self.downcast_erased(record_source_type::<T>())
}
/// The erased record source, for callers that dispatch on the layout rather
/// than a static element type. `None` for a source erased to another node type.
pub fn record_source(self) -> Option<SharedSource<ErasedRecordNode>> {
self.node.downcast::<SharedSource<ErasedRecordNode>>().ok().map(|edge| *edge)
}
pub fn downcast_erased<N: ?Sized + 'static>(self, expected: Type) -> Result<SharedSource<N>, ConstructionError> {
let found = self.ty;
self.node.downcast::<SharedSource<N>>().map(|edge| *edge).map_err(|_| ConstructionError::Type {
expected: Box::new(expected),
found: Box::new(found),
})
}
}
pub type NodeConstructor = fn(Vec<SourceHandle>) -> Result<SourceHandle, ConstructionError>;
#[derive(Clone)]
pub struct RegistryEntry {
pub io: NodeIOTypes,
pub constructor: NodeConstructor,
/// Declarative record-io metadata for the compiler layout pass; `None` for
/// nodes whose layout the pass does not fold (routing/opaque, hand-written
/// rows), which keep the construction-time path.
pub layout_meta: Option<crate::record::LayoutMeta>,
}
pub fn construct(entry: &RegistryEntry, inputs: Vec<SourceHandle>) -> Result<SourceHandle, ConstructionError> {
if inputs.len() != entry.io.inputs.len() {
return Err(ConstructionError::Arity {
expected: entry.io.inputs.len(),
got: inputs.len(),
});
}
for (handle, expected) in inputs.iter().zip(&entry.io.inputs) {
if handle.ty() != expected {
return Err(ConstructionError::Type {
expected: Box::new(expected.clone()),
found: Box::new(handle.ty().clone()),
});
}
}
(entry.constructor)(inputs)
}
#[cfg(not(target_family = "wasm"))] #[cfg(not(target_family = "wasm"))]
pub type Any<'n> = Box<dyn DynAny<'n> + 'n + Send>; pub type Any<'n> = Box<dyn DynAny<'n> + 'n + Send>;
#[cfg(target_family = "wasm")] #[cfg(target_family = "wasm")]
pub type Any<'n> = Box<dyn DynAny<'n> + 'n>; pub type Any<'n> = Box<dyn DynAny<'n> + 'n>;
pub type FutureAny<'n> = DynFuture<'n, Any<'n>>;
// TODO: is this safe? This is assumed to be send+sync.
#[cfg(not(target_family = "wasm"))]
pub type TypeErasedNode<'n> = dyn for<'i> NodeIO<'i, Any<'i>, Output = FutureAny<'i>> + 'n + Send + Sync;
#[cfg(target_family = "wasm")]
pub type TypeErasedNode<'n> = dyn for<'i> NodeIO<'i, Any<'i>, Output = FutureAny<'i>> + 'n;
pub type TypeErasedPinnedRef<'n> = Pin<&'n TypeErasedNode<'n>>;
pub type TypeErasedRef<'n> = &'n TypeErasedNode<'n>;
pub type TypeErasedBox<'n> = Box<TypeErasedNode<'n>>;
pub type TypeErasedPinned<'n> = Pin<Box<TypeErasedNode<'n>>>;
pub type SharedNodeContainer = std::sync::Arc<NodeContainer>; #[cfg(test)]
mod tests {
use super::*;
use crate::SourceId;
use crate::arena::Arena;
use crate::context::{Ctx, EvalScope, ExtractArena, ExtractIndices};
use crate::gpoll::GPoll;
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};
pub type NodeConstructor = fn(Vec<SharedNodeContainer>) -> DynFuture<'static, TypeErasedBox<'static>>; use crate::record::{FrameClaim, Layout, LiftedSource, Served, element_write, read_element, serve_input};
#[derive(Clone)] fn counting() -> LiftedSource<u32, impl for<'c> Fn(&ContextImpl<'c>) -> GPoll<u32>> {
pub struct NodeContainer { let count = AtomicU32::new(0);
#[cfg(feature = "dealloc_nodes")] LiftedSource::new(move |_: &ContextImpl<'_>| GPoll::Final(count.fetch_add(1, Ordering::Relaxed) + 1))
pub node: *const TypeErasedNode<'static>,
#[cfg(not(feature = "dealloc_nodes"))]
pub node: TypeErasedRef<'static>,
}
impl Deref for NodeContainer {
type Target = TypeErasedNode<'static>;
#[cfg(feature = "dealloc_nodes")]
fn deref(&self) -> &Self::Target {
unsafe { &*(self.node) }
#[cfg(not(feature = "dealloc_nodes"))]
self.node
}
#[cfg(not(feature = "dealloc_nodes"))]
fn deref(&self) -> &Self::Target {
self.node
}
}
/// # Safety
/// Marks NodeContainer as Sync. This dissallows the use of threadlocal storage for nodes as this would invalidate references to them.
// TODO: implement this on a higher level wrapper to avoid missuse
#[cfg(feature = "dealloc_nodes")]
unsafe impl Send for NodeContainer {}
#[cfg(feature = "dealloc_nodes")]
unsafe impl Sync for NodeContainer {}
#[cfg(feature = "dealloc_nodes")]
impl Drop for NodeContainer {
fn drop(&mut self) {
unsafe { self.dealloc_unchecked() }
}
}
impl std::fmt::Debug for NodeContainer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("NodeContainer").finish()
}
}
impl NodeContainer {
pub fn new(node: TypeErasedBox<'static>) -> SharedNodeContainer {
let node = Box::leak(node);
Self { node }.into()
} }
#[cfg(feature = "dealloc_nodes")] fn scope_fixture<'a>(generations: &'a [(SourceId, u64)], arena: &'a Arena) -> EvalScope<'a> {
unsafe fn dealloc_unchecked(&mut self) { EvalScope::new(Some(0.5), None, None, generations, arena)
unsafe { }
drop(Box::from_raw(self.node as *mut TypeErasedNode));
/// Serves a parked borrow of its own value: the element is a reference into
/// the evaluation's arena, so its lifetime is the serving one.
struct LendNode {
value: String,
layout: Layout,
}
impl LendNode {
fn new(value: &str) -> Self {
Self {
value: value.to_string(),
layout: Layout::default().with_writes(0, element_write::<&'static String>(), &[]),
}
} }
} }
}
/// Boxes the input and downcasts the output. impl<Input: Ctx> Node<Input> for LendNode {
/// Wraps around a node taking Box<dyn DynAny> and returning Box<dyn DynAny> fn serve<'e, 'l>(&self, input: &Input, slot: FrameClaim<'e, 'l>) -> GPoll<Served<'e>>
#[derive(Clone)] where
pub struct DowncastBothNode<I, O> { Input: ExtractArena<ArenaRef = &'e Arena>,
node: SharedNodeContainer,
_i: PhantomData<I>,
_o: PhantomData<O>,
}
impl<'input, O, I> Node<'input, I> for DowncastBothNode<I, O>
where
O: 'input + StaticType + WasmNotSend,
I: 'input + StaticType + WasmNotSend,
{
type Output = DynFuture<'input, O>;
#[inline]
#[track_caller]
fn eval(&'input self, input: I) -> Self::Output {
{ {
let node_name = self.node.node_name(); match input.arena().alloc(self.value.clone()) {
let input = Box::new(input); Some((parked, _)) => slot.lift_served(GPoll::Final(parked), input.arena()),
let future = self.node.eval(input); None => GPoll::arena_exhausted(),
Box::pin(async move { }
let out = dyn_any::downcast(future.await).unwrap_or_else(|e| panic!("DowncastBothNode wrong output type: {e} in: \n{node_name}")); }
*out
}) fn layout(&self) -> &Layout {
&self.layout
} }
} }
fn reset(&self) {
self.node.reset();
}
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> { #[test]
self.node.serialize() fn borrow_carrying_value_types_wire_through_the_general_constructor() {
} let arena = Arena::new(4096).unwrap();
} let generations = [];
impl<I, O> DowncastBothNode<I, O> { let scope = scope_fixture(&generations, &arena);
pub const fn new(node: SharedNodeContainer) -> Self { let ctx = ContextImpl::root(&scope);
Self { let frames = crate::record::test_frames(1 << 12);
node,
_i: PhantomData,
_o: PhantomData,
}
}
}
pub struct FutureWrapperNode<Node> {
node: Node,
}
impl<'i, T: 'i + WasmNotSend, N> Node<'i, T> for FutureWrapperNode<N> let node = LendNode::new("held");
where let layout = Node::<ContextImpl>::layout(&node).clone();
N: Node<'i, T, Output: WasmNotSend> + WasmNotSend, let handle = SourceHandle::new_erased(Arc::new(node) as Arc<ErasedRecordNode>, concrete!(String));
{ assert_eq!(*handle.ty(), concrete!(String));
type Output = DynFuture<'i, N::Output>;
#[inline(always)]
fn eval(&'i self, input: T) -> Self::Output {
let result = self.node.eval(input);
Box::pin(async move { result })
}
#[inline(always)]
fn reset(&self) {
self.node.reset();
}
#[inline(always)] let wired = handle.downcast_erased::<ErasedRecordNode>(concrete!(String)).unwrap();
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> { let GPoll::Final(value) = serve_input(&wired, &ctx, &frames) else {
self.node.serialize() panic!("borrow-carrying output must serve through the erased edge");
}
}
impl<N> FutureWrapperNode<N> {
pub const fn new(node: N) -> Self {
Self { node }
}
}
pub struct DynAnyNode<I, O, Node> {
node: Node,
_i: PhantomData<I>,
_o: PhantomData<O>,
}
impl<'input, I, O, N> Node<'input, Any<'input>> for DynAnyNode<I, O, N>
where
I: 'input + StaticType + WasmNotSend,
O: 'input + StaticType + WasmNotSend,
N: 'input + Node<'input, I, Output = DynFuture<'input, O>>,
{
type Output = FutureAny<'input>;
#[inline]
fn eval(&'input self, input: Any<'input>) -> Self::Output {
let node_name = std::any::type_name::<N>();
let output = |input| {
let result = self.node.eval(input);
async move { Box::new(result.await) as Any<'input> }
}; };
match dyn_any::downcast(input) { // SAFETY: the record was served at `layout`, whose element is the borrow.
Ok(input) => Box::pin(output(*input)), let held = unsafe { read_element::<&String>(layout.rec(&value)) };
Err(e) => panic!("DynAnyNode Input, {e} in:\n{node_name}"), assert_eq!(held, "held");
assert_eq!(held.len(), 4);
}
/// Evaluates its content at three indices of one promoted level and serves
/// the collected elements.
struct RepeatNode<Node0, T> {
content: Node0,
inner: Layout,
layout: Layout,
_marker: std::marker::PhantomData<fn() -> T>,
}
impl<Node0, T: Clone + Send + Sync + dyn_any::StaticTypeSized> RepeatNode<Node0, T>
where
Vec<T>: Clone + Send + Sync + dyn_any::StaticTypeSized,
<Vec<T> as dyn_any::StaticTypeSized>::Static: Clone + Send + Sync,
{
fn new(content: Node0, inner: Layout) -> Self {
Self {
content,
inner,
layout: Layout::default().with_writes(0, element_write::<Vec<T>>(), &[]),
_marker: std::marker::PhantomData,
}
} }
} }
fn reset(&self) { impl<C, T, Node0> Node<C> for RepeatNode<Node0, T>
self.node.reset(); where
} C: Ctx + crate::context::DeriveCtx,
T: Clone + 'static,
Vec<T>: Send + Sync + dyn_any::StaticTypeSized,
Node0: for<'x> crate::record::DerivedRecordInput<'x, crate::context::Derived<'x, C>>,
{
fn serve<'e, 'l>(&self, input: &C, mut slot: FrameClaim<'e, 'l>) -> GPoll<Served<'e>>
where
C: ExtractArena<ArenaRef = &'e Arena>,
{
let cell = crate::node::StatusCell::new();
let spilled = input.index_head();
let mut result = Vec::new();
for index in 0..3 {
// The element copies out by value, so the content's frame is
// dead when the scope ends.
let scope = slot.frames().scope();
let derived = input.promoted(&spilled, index);
match self.content.eval_derived(&cell, 0, &derived, &scope) {
// SAFETY: the content served at its own layout, whose
// element is `T`.
Ok(value) => result.push(unsafe { read_element::<T>(self.inner.rec(&value)) }),
Err(interrupt) => return interrupt.into(),
}
}
slot.lift_served(cell.finish(result), input.arena())
}
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> { fn layout(&self) -> &Layout {
self.node.serialize() &self.layout
}
}
impl<'input, I, O, N> DynAnyNode<I, O, N>
where
I: 'input + StaticType,
O: 'input + StaticType,
N: 'input + Node<'input, I, Output = DynFuture<'input, O>>,
{
pub const fn new(node: N) -> Self {
Self {
node,
_i: PhantomData,
_o: PhantomData,
} }
} }
}
pub struct PanicNode<I: WasmNotSend, O: WasmNotSend>(PhantomData<I>, PhantomData<O>);
impl<'i, I: 'i + WasmNotSend, O: 'i + WasmNotSend> Node<'i, I> for PanicNode<I, O> { #[test]
type Output = O; fn derive_ctx_repeat_pushes_index_levels_through_the_erased_edge() {
fn eval(&'i self, _: I) -> Self::Output { let arena = Arena::new(1024).unwrap();
unimplemented!("This node should never be evaluated") let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let levels = LiftedSource::<Vec<usize>, _>::new(|input: &ContextImpl| GPoll::Final(input.try_index().map(|levels| levels.collect()).unwrap_or_default()));
let levels_layout = Node::<ContextImpl>::layout(&levels).clone();
let inner = RepeatNode::<_, Vec<usize>>::new(levels, levels_layout);
let inner_layout = Node::<ContextImpl>::layout(&inner).clone();
let nested = RepeatNode::<_, Vec<Vec<usize>>>::new(inner, inner_layout);
let layout = Node::<ContextImpl>::layout(&nested).clone();
let erased: Box<ErasedRecordNode> = Box::new(nested);
let frames = crate::record::test_frames(1 << 12);
let GPoll::Final(value) = serve_input(&*erased, &ctx, &frames) else {
panic!("nested repeat must evaluate");
};
// SAFETY: the record was served at `layout`, whose element is the output.
let outer = unsafe { read_element::<Vec<Vec<Vec<usize>>>>(layout.rec(&value)) };
assert_eq!(outer.len(), 3);
assert_eq!(outer[2][1], vec![1, 2, 0]);
assert_eq!(outer[0][0], vec![0, 0, 0]);
}
/// Shifts the footprint's resolution and serves its content's element under
/// the derived context.
struct ShiftFootprintNode<Node0> {
content: Node0,
inner: Layout,
layout: Layout,
}
impl<Node0> ShiftFootprintNode<Node0> {
fn new(content: Node0, inner: Layout) -> Self {
Self {
content,
inner,
layout: Layout::default().with_writes(0, element_write::<u32>(), &[]),
}
}
}
impl<C, Node0> Node<C> for ShiftFootprintNode<Node0>
where
C: Ctx + crate::context::DeriveCtx + crate::context::ExtractFootprint,
Node0: for<'x> crate::record::DerivedRecordInput<'x, crate::context::Derived<'x, C>>,
{
fn serve<'e, 'l>(&self, input: &C, mut slot: FrameClaim<'e, 'l>) -> GPoll<Served<'e>>
where
C: ExtractArena<ArenaRef = &'e Arena>,
{
use crate::transform::Footprint;
let cell = crate::node::StatusCell::new();
let mut footprint = input.try_footprint().copied().unwrap_or(Footprint::DEFAULT);
footprint.resolution.x += 7;
// The element copies out by value, so the content's frame is dead
// when the scope ends.
let value = {
let scope = slot.frames().scope();
let derived = input.with_footprint(&footprint);
match self.content.eval_derived(&cell, 0, &derived, &scope) {
// SAFETY: the content served at its own layout, whose
// element is the resolution.
Ok(value) => unsafe { read_element::<u32>(self.inner.rec(&value)) },
Err(interrupt) => return interrupt.into(),
}
};
slot.lift_served(cell.finish(value), input.arena())
}
fn layout(&self) -> &Layout {
&self.layout
}
}
#[test]
fn derive_ctx_footprint_replace_reaches_the_content() {
use crate::context::ExtractFootprint;
use crate::transform::Footprint;
let arena = Arena::new(1024).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let frames = crate::record::test_frames(1 << 12);
let resolution = LiftedSource::<u32, _>::new(|input: &ContextImpl| GPoll::Final(input.try_footprint().map(|footprint| footprint.resolution.x).unwrap_or(0)));
let resolution_layout = Node::<ContextImpl>::layout(&resolution).clone();
let shifted = ShiftFootprintNode::new(resolution, resolution_layout);
let shifted_layout = Node::<ContextImpl>::layout(&shifted).clone();
let graph = ShiftFootprintNode::new(shifted, shifted_layout);
let layout = Node::<ContextImpl>::layout(&graph).clone();
let GPoll::Final(value) = serve_input(&graph, &ctx, &frames) else {
panic!("the footprint shift must reach the content");
};
// SAFETY: the record was served at `layout`, whose element is the resolution.
assert_eq!(unsafe { read_element::<u32>(layout.rec(&value)) }, Footprint::DEFAULT.resolution.x + 14);
}
#[test]
fn construct_checks_arity_and_types() {
fn construct_strlen(args: Vec<SourceHandle>) -> Result<SourceHandle, ConstructionError> {
let mut args = args.into_iter();
let value = args.next().ok_or(ConstructionError::Arity { expected: 1, got: 0 })?.downcast_record::<String>()?;
drop(value);
Ok(crate::value::record_value_source(0u32))
}
let entry = RegistryEntry {
layout_meta: None,
io: NodeIOTypes::new(concrete!(Context), record_type::<u32>(), vec![record_source_type::<String>()]),
constructor: construct_strlen,
};
let owned = crate::value::record_value_source("typed".to_string());
assert!(construct(&entry, vec![owned]).is_ok());
assert_eq!(construct(&entry, vec![]).unwrap_err(), ConstructionError::Arity { expected: 1, got: 0 });
let mistyped = crate::value::record_value_source(1.0f64);
assert_eq!(
construct(&entry, vec![mistyped]).unwrap_err(),
ConstructionError::Type {
expected: Box::new(record_source_type::<String>()),
found: Box::new(record_source_type::<f64>()),
}
);
}
#[test]
fn duplicated_edges_share_one_instance_and_outlive_each_other() {
let arena = Arena::new(1024).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let counting = counting();
let layout = Node::<ContextImpl>::layout(&counting).clone();
let handle = SourceHandle::new_record::<u32>(Arc::new(counting) as Arc<ErasedRecordNode>);
let duplicate = handle.duplicate();
assert_eq!(*duplicate.ty(), record_source_type::<u32>());
let frames = crate::record::test_frames(1 << 12);
let first = handle.downcast_record::<u32>().unwrap();
let second = duplicate.downcast_record::<u32>().unwrap();
// SAFETY: each record was served at `layout`, whose element is the count.
let count = |value| unsafe { layout.rec(&value).element::<u32>() };
assert_eq!(serve_input(&first, &ctx, &frames).map(count), GPoll::Final(1));
assert_eq!(serve_input(&second, &ctx, &frames).map(count), GPoll::Final(2));
drop(first);
assert_eq!(serve_input(&second, &ctx, &frames).map(count), GPoll::Final(3));
} }
} }
impl<I: WasmNotSend, O: WasmNotSend> PanicNode<I, O> {
pub const fn new() -> Self {
Self(PhantomData, PhantomData)
}
}
impl<I: WasmNotSend, O: WasmNotSend> Default for PanicNode<I, O> {
fn default() -> Self {
Self::new()
}
}
// TODO: Evaluate safety
unsafe impl<I: WasmNotSend, O: WasmNotSend> Sync for PanicNode<I, O> {}
@@ -0,0 +1,682 @@
use crate::SourceId;
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
#[cfg(not(target_family = "wasm"))]
pub type SourceFuture<T = ()> = Pin<Box<dyn Future<Output = T> + Send + 'static>>;
#[cfg(target_family = "wasm")]
pub type SourceFuture<T = ()> = Pin<Box<dyn Future<Output = T> + 'static>>;
#[cfg(not(target_family = "wasm"))]
pub type DynRuntime = dyn Runtime + Send + Sync;
#[cfg(target_family = "wasm")]
pub type DynRuntime = dyn Runtime;
pub trait Runtime {
/// Returns true when the future completed during the call, so its result is already observable.
fn spawn(&self, source: SourceId, future: SourceFuture) -> bool;
}
#[derive(Clone, dyn_any::DynAny)]
pub struct RuntimeHandle(pub Arc<DynRuntime>);
// SAFETY: wasm is single threaded, so the handle never actually crosses a thread.
#[cfg(target_family = "wasm")]
unsafe impl Send for RuntimeHandle {}
// SAFETY: as in Send.
#[cfg(target_family = "wasm")]
unsafe impl Sync for RuntimeHandle {}
#[cfg(all(target_family = "wasm", target_feature = "atomics"))]
compile_error!("RuntimeHandle's wasm Send/Sync rest on a single-threaded build; a +atomics target needs the payload bounded instead");
impl std::fmt::Debug for RuntimeHandle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RuntimeHandle").finish_non_exhaustive()
}
}
impl graphene_hash::CacheHash for RuntimeHandle {
fn cache_hash<H: std::hash::Hasher>(&self, _state: &mut H) {}
}
pub trait Spawner {
/// Returns true when the task completed during the call, so its result is already observable.
fn spawn(&self, task: SourceFuture) -> bool;
}
/// Polls `task` once with a no-op waker, returning true if it completed.
pub fn poll_once(task: &mut SourceFuture) -> bool {
let mut context = std::task::Context::from_waker(std::task::Waker::noop());
task.as_mut().poll(&mut context).is_ready()
}
#[cfg(not(target_family = "wasm"))]
pub type DynSpawner = dyn Spawner + Send + Sync;
#[cfg(target_family = "wasm")]
pub type DynSpawner = dyn Spawner;
#[cfg(not(target_family = "wasm"))]
pub type DynNotifier = dyn Fn() + Send + Sync;
#[cfg(target_family = "wasm")]
pub type DynNotifier = dyn Fn();
impl<S: Spawner + ?Sized> Spawner for Box<S> {
fn spawn(&self, task: SourceFuture) -> bool {
(**self).spawn(task)
}
}
/// Polls each task once inline. Tasks that are not immediately ready never complete.
pub struct NoopSpawner;
impl Spawner for NoopSpawner {
fn spawn(&self, mut task: SourceFuture) -> bool {
if poll_once(&mut task) {
return true;
}
log::warn!("async source is not immediately ready and no host spawner is wired; the task is dropped");
false
}
}
pub type DynGraphRuntime = GraphRuntime<Box<DynSpawner>>;
impl Default for RuntimeHandle {
fn default() -> Self {
Self(Arc::new(GraphRuntime::new(Box::new(NoopSpawner) as Box<DynSpawner>)))
}
}
pub struct GraphRuntime<S> {
generations: Arc<Mutex<HashMap<SourceId, u64>>>,
dirty: Arc<AtomicBool>,
notifier: Arc<Mutex<Arc<DynNotifier>>>,
spawner: S,
}
// SAFETY: wasm is single threaded, so the runtime never actually crosses a thread.
#[cfg(target_family = "wasm")]
unsafe impl<S> Send for GraphRuntime<S> {}
// SAFETY: as in Send.
#[cfg(target_family = "wasm")]
unsafe impl<S> Sync for GraphRuntime<S> {}
#[cfg(all(target_family = "wasm", target_feature = "atomics"))]
compile_error!("GraphRuntime's wasm Send/Sync are unbounded in S and rest on a single-threaded build; a +atomics target needs S bounded instead");
impl<S> GraphRuntime<S> {
pub fn new(spawner: S) -> Self {
Self {
generations: Arc::default(),
dirty: Arc::default(),
notifier: Arc::new(Mutex::new(Arc::new(|| {}))),
spawner,
}
}
pub fn set_notifier(&self, notifier: Arc<DynNotifier>) {
*self.notifier.lock().unwrap_or_else(PoisonError::into_inner) = notifier;
}
pub fn retain_sources(&self, live: &[SourceId]) {
let mut generations = self.generations.lock().unwrap_or_else(PoisonError::into_inner);
generations.retain(|source, _| live.contains(source));
for source in live {
generations.entry(*source).or_insert(0);
}
}
pub fn snapshot(&self) -> Vec<(SourceId, u64)> {
let generations = self.generations.lock().unwrap_or_else(PoisonError::into_inner);
let mut snapshot: Vec<_> = generations.iter().map(|(source, generation)| (*source, *generation)).collect();
snapshot.sort_unstable();
snapshot
}
pub fn take_dirty(&self) -> bool {
self.dirty.swap(false, Ordering::Acquire)
}
pub fn spawner(&self) -> &S {
&self.spawner
}
}
impl<S: Spawner> Runtime for GraphRuntime<S> {
fn spawn(&self, source: SourceId, mut future: SourceFuture) -> bool {
let generations = Arc::clone(&self.generations);
let dirty = Arc::clone(&self.dirty);
let notifier = Arc::clone(&self.notifier);
let mut first = true;
self.spawner.spawn(Box::pin(std::future::poll_fn(move |task_context| {
let poll = future.as_mut().poll(task_context);
if poll.is_ready() && !first {
let mut generations = generations.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(generation) = generations.get_mut(&source) {
*generation += 1;
dirty.store(true, Ordering::Release);
drop(generations);
let notifier = Arc::clone(&notifier.lock().unwrap_or_else(PoisonError::into_inner));
notifier();
}
}
first = false;
poll
})))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::arena::Arena;
use crate::context::{ContextImpl, Ctx, EvalScope, ExtractFootprint, ExtractVarArgs, VarArgLink, VarArgSlots};
use crate::gpoll::GPoll;
use crate::node::Node;
use crate::record::{Layout, LiftedSource, RecordExtract, element_write};
use crate::transform::Footprint;
use std::sync::Mutex;
use std::sync::atomic::{AtomicU32, Ordering};
#[derive(Default)]
struct MockRuntime {
futures: Mutex<Vec<(SourceId, SourceFuture)>>,
}
impl Runtime for MockRuntime {
fn spawn(&self, source: SourceId, future: SourceFuture) -> bool {
self.futures.lock().unwrap().push((source, future));
false
}
}
impl MockRuntime {
fn drain(&self) -> Vec<SourceId> {
let futures = std::mem::take(&mut *self.futures.lock().unwrap());
let mut task_ctx = std::task::Context::from_waker(std::task::Waker::noop());
futures
.into_iter()
.map(|(source, mut future)| {
assert!(future.as_mut().poll(&mut task_ctx).is_ready());
source
})
.collect()
}
}
#[derive(Default)]
struct CollectSpawner {
tasks: Mutex<Vec<SourceFuture>>,
}
impl Spawner for CollectSpawner {
fn spawn(&self, mut task: SourceFuture) -> bool {
if poll_once(&mut task) {
return true;
}
self.tasks.lock().unwrap().push(task);
false
}
}
struct YieldOnce(bool);
impl Future for YieldOnce {
type Output = ();
fn poll(mut self: Pin<&mut Self>, task_context: &mut std::task::Context<'_>) -> std::task::Poll<()> {
if self.0 {
return std::task::Poll::Ready(());
}
self.0 = true;
task_context.waker().wake_by_ref();
std::task::Poll::Pending
}
}
fn yield_once() -> YieldOnce {
YieldOnce(false)
}
impl CollectSpawner {
fn drain(&self) -> usize {
let tasks = std::mem::take(&mut *self.tasks.lock().unwrap());
let mut task_ctx = std::task::Context::from_waker(std::task::Waker::noop());
let count = tasks.len();
for mut task in tasks {
assert!(task.as_mut().poll(&mut task_ctx).is_ready());
}
count
}
}
fn element_layout<T: Clone + Send + Sync + dyn_any::StaticTypeSized>() -> Layout
where
T::Static: Clone + Send + Sync,
{
Layout::default().with_writes(0, element_write::<T>(), &[])
}
fn lifted<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(value: T) -> LiftedSource<T, impl for<'c> Fn(&ContextImpl<'c>) -> GPoll<T>>
where
T::Static: Clone + Send + Sync,
{
LiftedSource::new(move |_: &ContextImpl<'_>| GPoll::Final(value.clone()))
}
fn extract<El: Clone + Send + Sync + dyn_any::StaticTypeSized, N: Node<ContextImpl<'static>>>(mut graph: N) -> RecordExtract<El, N>
where
El::Static: Clone + Send + Sync,
{
let layout = element_layout::<El>();
graph.set_layout(crate::record::RecordLayout {
frame_bytes: layout.frame_bytes(),
plan: Vec::new(),
layout: layout.clone(),
lane_invariant: u32::MAX,
named_writes: Vec::new(),
named_reads: Vec::new(),
named_read_defaults: Vec::new(),
});
RecordExtract::new(graph, &layout)
}
static SLOW_DOUBLE_RUNS: AtomicU32 = AtomicU32::new(0);
#[node_macro::node(category(""))]
async fn slow_double(_: impl Ctx, value: f64) -> f64 {
SLOW_DOUBLE_RUNS.fetch_add(1, Ordering::Relaxed);
value * 2.
}
fn stand_in(_value: &f64) -> f64 {
-1.
}
#[node_macro::node(category(""), placeholder(stand_in))]
async fn preview_double(_: impl Ctx, value: f64) -> f64 {
value * 2.
}
#[node_macro::node(category(""), placeholder(stand_in), no_partial)]
async fn strict_double(_: impl Ctx, value: f64) -> f64 {
value * 2.
}
#[node_macro::node(category(""))]
async fn snapshot_resolution(ctx: CtxSnapshot, _primary: ()) -> u32 {
ctx.try_footprint().map(|footprint| footprint.resolution.x).unwrap_or(0)
}
#[node_macro::node(category(""))]
async fn snapshot_vararg(ctx: CtxSnapshot, _primary: ()) -> f64 {
ctx.vararg(0).ok().and_then(|slot| slot.downcast_ref::<f64>()).copied().unwrap_or(0.)
}
static STAGED_RUNS: AtomicU32 = AtomicU32::new(0);
#[node_macro::node(category(""))]
fn staged_double(_: impl Ctx, value: f64) -> SourceFuture<f64> {
STAGED_RUNS.fetch_add(1, Ordering::Relaxed);
Box::pin(async move { value * 2. })
}
#[node_macro::node(category(""))]
fn staged_sum(ctx: impl Ctx, value: f64, addend: impl Node<Context<'_>, Output = f64>) -> Result<SourceFuture<f64>, crate::gpoll::Interrupt> {
let addend = addend.eval(ctx)?;
Ok(Box::pin(async move { value + addend }))
}
fn gated(gate: Arc<std::sync::atomic::AtomicBool>, value: f64) -> LiftedSource<f64, impl for<'c> Fn(&ContextImpl<'c>) -> GPoll<f64>> {
LiftedSource::new(move |_: &ContextImpl<'_>| match gate.load(Ordering::Relaxed) {
true => GPoll::Final(value),
false => GPoll::Pending,
})
}
fn scope_fixture<'a>(generations: &'a [(SourceId, u64)], arena: &'a Arena) -> EvalScope<'a> {
EvalScope::new(None, None, None, generations, arena)
}
#[test]
fn async_source_spawns_once_and_lands_via_the_slot() {
let frames = crate::record::test_frames(1 << 16);
let arena = Arena::new(64).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let runtime = Arc::new(MockRuntime::default());
let graph = extract::<f64, _>(SlowDoubleNode::new(
lifted(21.0f64),
lifted(RuntimeHandle(runtime.clone())),
lifted(7u64),
&element_layout::<f64>(),
&element_layout::<RuntimeHandle>(),
&element_layout::<u64>(),
));
assert_eq!(graph.eval(&ctx, &frames), GPoll::Pending);
assert_eq!(graph.eval(&ctx, &frames), GPoll::Pending);
assert_eq!(SLOW_DOUBLE_RUNS.load(Ordering::Relaxed), 0);
assert_eq!(runtime.drain(), vec![7]);
assert_eq!(SLOW_DOUBLE_RUNS.load(Ordering::Relaxed), 1);
assert_eq!(graph.eval(&ctx, &frames), GPoll::Final(42.0));
assert_eq!(graph.eval(&ctx, &frames), GPoll::Final(42.0));
assert_eq!(SLOW_DOUBLE_RUNS.load(Ordering::Relaxed), 1);
}
#[test]
fn async_source_reports_the_placeholder_while_in_flight() {
let frames = crate::record::test_frames(1 << 16);
let arena = Arena::new(64).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let runtime = Arc::new(MockRuntime::default());
let graph = extract::<f64, _>(PreviewDoubleNode::new(
lifted(21.0f64),
lifted(RuntimeHandle(runtime.clone())),
lifted(1u64),
&element_layout::<f64>(),
&element_layout::<RuntimeHandle>(),
&element_layout::<u64>(),
));
assert_eq!(graph.eval(&ctx, &frames), GPoll::Partial(-1.0));
runtime.drain();
assert_eq!(graph.eval(&ctx, &frames), GPoll::Final(42.0));
}
#[test]
fn no_partial_maps_the_placeholder_frame_to_pending() {
let frames = crate::record::test_frames(1 << 16);
let arena = Arena::new(64).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let runtime = Arc::new(MockRuntime::default());
let graph = extract::<f64, _>(StrictDoubleNode::new(
lifted(21.0f64),
lifted(RuntimeHandle(runtime.clone())),
lifted(2u64),
&element_layout::<f64>(),
&element_layout::<RuntimeHandle>(),
&element_layout::<u64>(),
));
assert_eq!(graph.eval(&ctx, &frames), GPoll::Pending);
runtime.drain();
assert_eq!(graph.eval(&ctx, &frames), GPoll::Final(42.0));
}
#[test]
fn prologue_runs_sync_and_spawns_once() {
let frames = crate::record::test_frames(1 << 16);
let arena = Arena::new(64).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let runtime = Arc::new(MockRuntime::default());
let graph = extract::<f64, _>(StagedDoubleNode::new(
lifted(21.0f64),
lifted(RuntimeHandle(runtime.clone())),
lifted(8u64),
&element_layout::<f64>(),
&element_layout::<RuntimeHandle>(),
&element_layout::<u64>(),
));
assert_eq!(graph.eval(&ctx, &frames), GPoll::Pending);
assert_eq!(STAGED_RUNS.load(Ordering::Relaxed), 1, "the prologue runs synchronously on the miss");
assert_eq!(graph.eval(&ctx, &frames), GPoll::Pending);
assert_eq!(STAGED_RUNS.load(Ordering::Relaxed), 1, "in flight must not rerun the prologue");
assert_eq!(runtime.drain(), vec![8]);
assert_eq!(graph.eval(&ctx, &frames), GPoll::Final(42.0));
assert_eq!(STAGED_RUNS.load(Ordering::Relaxed), 1);
}
#[test]
fn prologue_interrupt_defers_the_spawn() {
let frames = crate::record::test_frames(1 << 16);
let arena = Arena::new(64).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let gate = Arc::new(std::sync::atomic::AtomicBool::new(false));
let runtime = Arc::new(MockRuntime::default());
let graph = extract::<f64, _>(StagedSumNode::new(
lifted(40.0f64),
gated(gate.clone(), 2.0),
lifted(RuntimeHandle(runtime.clone())),
lifted(9u64),
&element_layout::<f64>(),
&element_layout::<f64>(),
&element_layout::<RuntimeHandle>(),
&element_layout::<u64>(),
));
assert_eq!(graph.eval(&ctx, &frames), GPoll::Pending);
assert_eq!(runtime.drain(), Vec::<SourceId>::new(), "an interrupted prologue must not spawn or claim the slot");
gate.store(true, Ordering::Relaxed);
assert_eq!(graph.eval(&ctx, &frames), GPoll::Pending);
assert_eq!(runtime.drain(), vec![9]);
assert_eq!(graph.eval(&ctx, &frames), GPoll::Final(42.0));
}
#[test]
fn async_kernels_read_captured_varargs() {
let frames = crate::record::test_frames(1 << 16);
let arena = Arena::new(64).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let root = ContextImpl::root(&scope);
let payload = 21.5f64;
let link = VarArgLink {
args: VarArgSlots::Single(&payload),
outer: None,
};
let ctx = root.with_varargs(&link);
let runtime = Arc::new(MockRuntime::default());
let graph = extract::<f64, _>(SnapshotVarargNode::new(
lifted(()),
lifted(RuntimeHandle(runtime.clone())),
lifted(5u64),
&element_layout::<()>(),
&element_layout::<RuntimeHandle>(),
&element_layout::<u64>(),
));
assert_eq!(graph.eval(&ctx, &frames), GPoll::Pending);
runtime.drain();
assert_eq!(graph.eval(&ctx, &frames), GPoll::Final(21.5));
}
#[test]
fn async_kernels_read_the_captured_context_snapshot() {
let frames = crate::record::test_frames(1 << 16);
let arena = Arena::new(64).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let root = ContextImpl::root(&scope);
let footprint = Footprint::DEFAULT;
let ctx = root.with_footprint(&footprint);
let runtime = Arc::new(MockRuntime::default());
let graph = extract::<u32, _>(SnapshotResolutionNode::new(
lifted(()),
lifted(RuntimeHandle(runtime.clone())),
lifted(3u64),
&element_layout::<()>(),
&element_layout::<RuntimeHandle>(),
&element_layout::<u64>(),
));
assert_eq!(graph.eval(&ctx, &frames), GPoll::Pending);
runtime.drain();
assert_eq!(graph.eval(&ctx, &frames), GPoll::Final(Footprint::DEFAULT.resolution.x));
}
#[test]
fn the_epilogue_bumps_the_generation_and_sets_dirty() {
let runtime = GraphRuntime::new(CollectSpawner::default());
runtime.retain_sources(&[7]);
Runtime::spawn(&runtime, 7, Box::pin(yield_once()));
assert_eq!(runtime.snapshot(), vec![(7, 0)], "no bump before the future completes");
assert!(!runtime.take_dirty());
assert_eq!(runtime.spawner().drain(), 1);
assert_eq!(runtime.snapshot(), vec![(7, 1)]);
assert!(runtime.take_dirty());
assert!(!runtime.take_dirty(), "take_dirty drains the flag");
}
#[test]
fn the_epilogue_notifies_after_setting_dirty() {
let runtime = GraphRuntime::new(CollectSpawner::default());
runtime.retain_sources(&[7]);
let observed_dirty = Arc::new(AtomicBool::new(false));
let dirty_at_notify = Arc::clone(&runtime.dirty);
let observed = Arc::clone(&observed_dirty);
runtime.set_notifier(Arc::new(move || {
observed.store(dirty_at_notify.load(Ordering::Acquire), Ordering::Relaxed);
}));
Runtime::spawn(&runtime, 7, Box::pin(yield_once()));
assert_eq!(runtime.spawner().drain(), 1);
assert!(observed_dirty.load(Ordering::Relaxed), "the notifier must observe the dirty flag already set");
}
#[test]
fn the_epilogue_of_a_removed_source_does_not_notify() {
let runtime = GraphRuntime::new(CollectSpawner::default());
runtime.retain_sources(&[7]);
let notified = Arc::new(AtomicBool::new(false));
let flag = Arc::clone(&notified);
runtime.set_notifier(Arc::new(move || flag.store(true, Ordering::Relaxed)));
Runtime::spawn(&runtime, 7, Box::pin(yield_once()));
runtime.retain_sources(&[]);
assert_eq!(runtime.spawner().drain(), 1);
assert!(!notified.load(Ordering::Relaxed));
}
#[test]
fn the_epilogue_of_a_removed_source_is_inert() {
let runtime = GraphRuntime::new(CollectSpawner::default());
runtime.retain_sources(&[7]);
Runtime::spawn(&runtime, 7, Box::pin(yield_once()));
runtime.retain_sources(&[]);
assert_eq!(runtime.spawner().drain(), 1);
assert_eq!(runtime.snapshot(), Vec::<(SourceId, u64)>::new());
assert!(!runtime.take_dirty(), "a removed source must not invalidate");
}
#[test]
fn retain_sources_preserves_live_generations() {
let runtime = GraphRuntime::new(CollectSpawner::default());
runtime.retain_sources(&[7]);
Runtime::spawn(&runtime, 7, Box::pin(yield_once()));
runtime.spawner().drain();
runtime.retain_sources(&[7, 9]);
assert_eq!(runtime.snapshot(), vec![(7, 1), (9, 0)]);
runtime.retain_sources(&[9]);
assert_eq!(runtime.snapshot(), vec![(9, 0)]);
}
#[node_macro::node(category(""))]
async fn epilogue_double(_: impl Ctx, value: f64) -> f64 {
yield_once().await;
value * 2.
}
#[node_macro::node(category(""))]
async fn inline_double(_: impl Ctx, value: f64) -> f64 {
value * 2.
}
#[test]
fn an_immediately_ready_task_completes_inline_without_invalidating() {
let runtime = GraphRuntime::new(CollectSpawner::default());
runtime.retain_sources(&[7]);
assert!(Runtime::spawn(&runtime, 7, Box::pin(async {})));
assert_eq!(runtime.spawner().drain(), 0);
assert_eq!(runtime.snapshot(), vec![(7, 0)], "inline completion must not bump the generation");
assert!(!runtime.take_dirty());
}
#[test]
fn an_immediately_ready_kernel_returns_final_on_the_first_eval() {
let frames = crate::record::test_frames(1 << 16);
let arena = Arena::new(64).unwrap();
let runtime = Arc::new(GraphRuntime::new(CollectSpawner::default()));
runtime.retain_sources(&[13]);
let graph = extract::<f64, _>(InlineDoubleNode::new(
lifted(21.0f64),
lifted(RuntimeHandle(runtime.clone())),
lifted(13u64),
&element_layout::<f64>(),
&element_layout::<RuntimeHandle>(),
&element_layout::<u64>(),
));
let snapshot = runtime.snapshot();
let scope = EvalScope::new(None, None, None, &snapshot, &arena);
let ctx = ContextImpl::root(&scope);
assert_eq!(graph.eval(&ctx, &frames), GPoll::Final(42.0));
assert!(!runtime.take_dirty());
assert_eq!(runtime.snapshot(), vec![(13, 0)]);
assert_eq!(runtime.spawner().drain(), 0);
}
#[test]
fn a_source_slot_lands_through_the_runtime_while_downstream_keys_invalidate() {
let frames = crate::record::test_frames(1 << 16);
let arena = Arena::new(64).unwrap();
let runtime = Arc::new(GraphRuntime::new(CollectSpawner::default()));
runtime.retain_sources(&[11]);
let graph = extract::<f64, _>(EpilogueDoubleNode::new(
lifted(21.0f64),
lifted(RuntimeHandle(runtime.clone())),
lifted(11u64),
&element_layout::<f64>(),
&element_layout::<RuntimeHandle>(),
&element_layout::<u64>(),
));
let snapshot = runtime.snapshot();
let scope = EvalScope::new(None, None, None, &snapshot, &arena);
let ctx = ContextImpl::root(&scope);
assert_eq!(graph.eval(&ctx, &frames), GPoll::Pending);
assert!(!runtime.take_dirty());
assert_eq!(runtime.spawner().drain(), 1);
assert!(runtime.take_dirty());
let bumped = runtime.snapshot();
assert_eq!(bumped, vec![(11, 1)]);
let bumped_scope = EvalScope::new(None, None, None, &bumped, &arena);
let bumped_ctx = ContextImpl::root(&bumped_scope);
assert_eq!(graph.eval(&bumped_ctx, &frames), GPoll::Final(42.0), "the own-generation-excluded key replays the landed slot");
assert_eq!(runtime.spawner().drain(), 0, "a slot hit must not respawn");
let downstream_key = crate::registry::cache_key(&ContextImpl::root(&scope));
let bumped_downstream_key = crate::registry::cache_key(&ContextImpl::root(&bumped_scope));
assert_ne!(downstream_key, bumped_downstream_key, "unretained keys see the bump");
}
}
+61 -117
View File
@@ -12,12 +12,21 @@ macro_rules! concrete {
}; };
} }
/// The type's name with lifetime arguments stripped, so a lifetimed type
/// keeps its pre-lifetime registry and document name.
pub fn normalize_type_name<'a>(name: &'a str) -> std::borrow::Cow<'a, str> {
if !name.contains("<'") && !name.contains(", '") {
return std::borrow::Cow::Borrowed(name);
}
std::borrow::Cow::Owned(name.replace("<'_>", "").replace("<'_, ", "<").replace(", '_", ""))
}
#[macro_export] #[macro_export]
macro_rules! descriptor { macro_rules! descriptor {
($type:ty) => { ($type:ty) => {
$crate::TypeDescriptor { $crate::TypeDescriptor {
id: Some(std::any::TypeId::of::<$type>()), id: Some(std::any::TypeId::of::<$type>()),
name: $crate::Cow::Borrowed(std::any::type_name::<$type>()), name: $crate::normalize_type_name(std::any::type_name::<$type>()),
alias: None, alias: None,
size: std::mem::size_of::<$type>(), size: std::mem::size_of::<$type>(),
align: std::mem::align_of::<$type>(), align: std::mem::align_of::<$type>(),
@@ -26,7 +35,7 @@ macro_rules! descriptor {
($type:ty, $name:ty) => { ($type:ty, $name:ty) => {
$crate::TypeDescriptor { $crate::TypeDescriptor {
id: Some(std::any::TypeId::of::<$type>()), id: Some(std::any::TypeId::of::<$type>()),
name: $crate::Cow::Borrowed(std::any::type_name::<$type>()), name: $crate::normalize_type_name(std::any::type_name::<$type>()),
alias: Some($crate::Cow::Borrowed(stringify!($name))), alias: Some($crate::Cow::Borrowed(stringify!($name))),
size: std::mem::size_of::<$type>(), size: std::mem::size_of::<$type>(),
align: std::mem::align_of::<$type>(), align: std::mem::align_of::<$type>(),
@@ -100,36 +109,6 @@ macro_rules! future {
}; };
} }
#[macro_export]
macro_rules! fn_type {
(List<$inner:ty>) => {
$crate::Type::Fn(Box::new(concrete!(())), Box::new($crate::list!($inner)))
};
(Item<$inner:ty>) => {
$crate::Type::Fn(Box::new(concrete!(())), Box::new($crate::item!($inner)))
};
($type:ty) => {
$crate::Type::Fn(Box::new(concrete!(())), Box::new(concrete!($type)))
};
($in_type:ty, List<$inner:ty>, alias: $outname:ty) => {
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::list!($inner)))
};
($in_type:ty, List<$inner:ty>) => {
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::list!($inner)))
};
($in_type:ty, Item<$inner:ty>, alias: $outname:ty) => {
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::item!($inner, $inner)))
};
($in_type:ty, Item<$inner:ty>) => {
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::item!($inner)))
};
($in_type:ty, $type:ty, alias: $outname:ty) => {
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new(concrete!($type, $outname)))
};
($in_type:ty, $type:ty) => {
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new(concrete!($type)))
};
}
#[macro_export] #[macro_export]
macro_rules! fn_type_fut { macro_rules! fn_type_fut {
(List<$inner:ty>) => { (List<$inner:ty>) => {
@@ -175,15 +154,6 @@ impl NodeIOTypes {
Self { call_argument, return_value, inputs } Self { call_argument, return_value, inputs }
} }
/// Applies [`Type::normalize_rank`] to every type in the signature.
pub fn normalize_rank(self) -> Self {
Self {
call_argument: self.call_argument.normalize_rank(),
return_value: self.return_value.normalize_rank(),
inputs: self.inputs.into_iter().map(Type::normalize_rank).collect(),
}
}
pub const fn empty() -> Self { pub const fn empty() -> Self {
let tds1 = TypeDescriptor { let tds1 = TypeDescriptor {
id: None, id: None,
@@ -277,13 +247,13 @@ pub struct TypeDescriptor {
impl std::hash::Hash for TypeDescriptor { impl std::hash::Hash for TypeDescriptor {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) { fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.name.hash(state); normalize_type_name(&self.name).hash(state);
} }
} }
impl graphene_hash::CacheHash for TypeDescriptor { impl graphene_hash::CacheHash for TypeDescriptor {
fn cache_hash<H: ::core::hash::Hasher>(&self, state: &mut H) { fn cache_hash<H: ::core::hash::Hasher>(&self, state: &mut H) {
graphene_hash::CacheHash::cache_hash(&self.name, state); graphene_hash::CacheHash::cache_hash(&normalize_type_name(&self.name), state);
} }
} }
@@ -301,7 +271,7 @@ impl PartialEq for TypeDescriptor {
_ => { _ => {
// TODO: Add a flag to disable this warning // TODO: Add a flag to disable this warning
// warn!("TypeDescriptor::eq: comparing types without ids based on name"); // warn!("TypeDescriptor::eq: comparing types without ids based on name");
self.name == other.name normalize_type_name(&self.name) == normalize_type_name(&other.name)
} }
} }
} }
@@ -310,7 +280,8 @@ impl PartialEq for TypeDescriptor {
/// Graph runtime type information used for type inference. /// Graph runtime type information used for type inference.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] #[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, PartialEq, Eq, Hash, graphene_hash::CacheHash)] #[derive(Clone, PartialEq, Eq, Hash, graphene_hash::CacheHash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "PascalCase"))]
pub enum Type { pub enum Type {
/// A wrapper for some type variable used within the inference system. Resolved at inference time and replaced with a concrete type. /// A wrapper for some type variable used within the inference system. Resolved at inference time and replaced with a concrete type.
Generic(Cow<'static, str>), Generic(Cow<'static, str>),
@@ -320,10 +291,43 @@ pub enum Type {
Fn(Box<Type>, Box<Type>), Fn(Box<Type>, Box<Type>),
/// Represents a future which promises to return the inner type. /// Represents a future which promises to return the inner type.
Future(Box<Type>), Future(Box<Type>),
/// Represents a recursive [Type] allowing nested levels of types to represent the type of an Item<T>. /// A packed record input over the element type; the layout stays node-resident metadata.
Item(Box<Type>), Record(Box<Type>),
/// Represents a list of this recursive [Type] allowing nested levels of types to represent the type of a List<T>. }
List(Box<Type>),
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Type {
/// Documents written against the structural rank model store `Item` and `List` wire types.
/// Our one wire kind has neither, so an `Item` reduces to the element it wraps and a `List`
/// becomes the concrete `List<..>` type it names.
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
#[derive(serde::Deserialize)]
enum Stored {
Generic(Cow<'static, str>),
Concrete(TypeDescriptor),
Fn(Box<Type>, Box<Type>),
Future(Box<Type>),
Record(Box<Type>),
Item(Box<Type>),
List(Box<Type>),
}
Ok(match Stored::deserialize(deserializer)? {
Stored::Generic(name) => Type::Generic(name),
Stored::Concrete(descriptor) => Type::Concrete(descriptor),
Stored::Fn(input, output) => Type::Fn(input, output),
Stored::Future(inner) => Type::Future(inner),
Stored::Record(inner) => Type::Record(inner),
Stored::Item(element) => *element,
Stored::List(element) => Type::Concrete(TypeDescriptor {
id: None,
name: Cow::Owned(format!("core_types::list::List<{}>", element.identifier_name())),
alias: None,
size: 0,
align: 0,
}),
})
}
} }
impl Default for Type { impl Default for Type {
@@ -384,7 +388,7 @@ impl Type {
pub fn new<T: dyn_any::StaticType + Sized>() -> Self { pub fn new<T: dyn_any::StaticType + Sized>() -> Self {
Self::Concrete(TypeDescriptor { Self::Concrete(TypeDescriptor {
id: Some(TypeId::of::<T::Static>()), id: Some(TypeId::of::<T::Static>()),
name: Cow::Borrowed(std::any::type_name::<T::Static>()), name: normalize_type_name(std::any::type_name::<T::Static>()),
alias: None, alias: None,
size: size_of::<T>(), size: size_of::<T>(),
align: align_of::<T>(), align: align_of::<T>(),
@@ -397,8 +401,7 @@ impl Type {
Self::Concrete(ty) => Some(ty.size), Self::Concrete(ty) => Some(ty.size),
Self::Fn(_, _) => None, Self::Fn(_, _) => None,
Self::Future(_) => None, Self::Future(_) => None,
Self::Item(_) => None, Self::Record(_) => None,
Self::List(_) => None,
} }
} }
@@ -408,8 +411,7 @@ impl Type {
Self::Concrete(ty) => Some(ty.align), Self::Concrete(ty) => Some(ty.align),
Self::Fn(_, _) => None, Self::Fn(_, _) => None,
Self::Future(_) => None, Self::Future(_) => None,
Self::Item(_) => None, Self::Record(_) => None,
Self::List(_) => None,
} }
} }
@@ -419,8 +421,7 @@ impl Type {
Self::Concrete(_) => self, Self::Concrete(_) => self,
Self::Fn(_, output) => output.nested_type(), Self::Fn(_, output) => output.nested_type(),
Self::Future(output) => output.nested_type(), Self::Future(output) => output.nested_type(),
Self::Item(_) => self, Self::Record(inner) => inner.nested_type(),
Self::List(_) => self,
} }
} }
@@ -433,8 +434,7 @@ impl Type {
Self::Concrete(_) => None, Self::Concrete(_) => None,
Self::Fn(_, output) => output.replace_nested(f), Self::Fn(_, output) => output.replace_nested(f),
Self::Future(output) => output.replace_nested(f), Self::Future(output) => output.replace_nested(f),
Self::Item(_) => None, Self::Record(inner) => inner.replace_nested(f),
Self::List(_) => None,
} }
} }
@@ -444,62 +444,7 @@ impl Type {
Type::Concrete(ty) => simplify_identifier_name(&ty.name), Type::Concrete(ty) => simplify_identifier_name(&ty.name),
Type::Fn(call_arg, return_value) => format!("{} called with {}", return_value.identifier_name(), call_arg.identifier_name()), Type::Fn(call_arg, return_value) => format!("{} called with {}", return_value.identifier_name(), call_arg.identifier_name()),
Type::Future(ty) => ty.identifier_name(), Type::Future(ty) => ty.identifier_name(),
Type::Item(element) => element.identifier_name(), Type::Record(ty) => ty.identifier_name(),
Type::List(element) => format!("{}[]", element.identifier_name()),
}
}
/// Constructs the [`Type`] of a `List` holding elements of the given type, the expression-position counterpart of [`list!`].
pub fn list_of(element: Type) -> Type {
Type::List(Box::new(element))
}
/// The element type if this is a rank-1 `List` wire type.
pub fn list_element(&self) -> Option<&Type> {
match self {
Type::List(element) => Some(element),
_ => None,
}
}
/// The element name if this is the type of an `Item<Bundle<X>>` cell carrying a whole list, e.g. `f64` from `Item<Bundle<f64>>`.
/// The `Bundle` layer stays name-encoded inside the structural `Item` since it has no structural variant.
pub fn bundle_element_name(&self) -> Option<&str> {
let Type::Item(element) = self else { return None };
let Type::Concrete(descriptor) = element.as_ref() else { return None };
descriptor.name.strip_prefix("core_types::list::Bundle<")?.strip_suffix('>')
}
/// Converts a name-encoded `List` or `Item` concrete type into its structural form, recursively.
/// Structurally-built types pass through unchanged, so sources which cannot construct ranked types
/// (reflection and opaque macro captures) converge with macro-built ones at this single point.
pub fn normalize_rank(self) -> Type {
fn parse_element(element_name: &str) -> Type {
let element = Type::Concrete(TypeDescriptor {
id: None,
name: Cow::Owned(element_name.to_string()),
alias: None,
size: 0,
align: 0,
});
element.normalize_rank()
}
match self {
Type::Concrete(descriptor) => {
if let Some(element_name) = descriptor.name.strip_prefix("core_types::list::List<").and_then(|rest| rest.strip_suffix('>')) {
return Type::List(Box::new(parse_element(element_name)));
}
if let Some(element_name) = descriptor.name.strip_prefix("core_types::list::Item<").and_then(|rest| rest.strip_suffix('>')) {
return Type::Item(Box::new(parse_element(element_name)));
}
Type::Concrete(descriptor)
}
Type::Fn(input, output) => Type::Fn(Box::new(input.normalize_rank()), Box::new(output.normalize_rank())),
Type::Future(inner) => Type::Future(Box::new(inner.normalize_rank())),
Type::Item(element) => Type::Item(Box::new(element.normalize_rank())),
Type::List(element) => Type::List(Box::new(element.normalize_rank())),
Type::Generic(_) => self,
} }
} }
} }
@@ -514,7 +459,7 @@ pub fn simplify_identifier_name(ty: &str) -> String {
/// Converts a Rust-internal type name to its user-facing form. /// Converts a Rust-internal type name to its user-facing form.
pub fn make_type_user_readable(ty: &str) -> String { pub fn make_type_user_readable(ty: &str) -> String {
let ty = ty let ty = ty
.replace("Option<Arc<OwnedContextImpl>>", "Context") .replace("ContextImpl", "Context")
.replace("Raster<CPU>", "Raster") .replace("Raster<CPU>", "Raster")
.replace("Raster<GPU>", "Raster") .replace("Raster<GPU>", "Raster")
.replace("DAffine2", "Transform") .replace("DAffine2", "Transform")
@@ -614,8 +559,7 @@ impl std::fmt::Display for Type {
Type::Concrete(ty) => write!(f, "{ty}"), Type::Concrete(ty) => write!(f, "{ty}"),
Type::Fn(_, return_value) => write!(f, "{return_value}"), Type::Fn(_, return_value) => write!(f, "{return_value}"),
Type::Future(ty) => write!(f, "{ty}"), Type::Future(ty) => write!(f, "{ty}"),
Type::Item(element) => write!(f, "{element}"), Type::Record(ty) => write!(f, "{ty}"),
Type::List(element) => write!(f, "{element}[]"),
} }
} }
} }
+84 -218
View File
@@ -1,233 +1,99 @@
use crate::list::Item; /// The node behind every value source: clones its constant onto the record
use crate::registry::DynFuture; /// input per evaluation.
use crate::{Node, WasmNotSend}; pub struct ValueSource<T> {
use std::cell::{Cell, RefCell, RefMut}; value: T,
use std::marker::PhantomData; layout: crate::record::Layout,
}
#[derive(Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] impl<T: Clone + Send + Sync + dyn_any::StaticTypeSized> ValueSource<T>
pub struct IntNode<const N: u32>; where
T::Static: Clone + Send + Sync,
impl<'i, const N: u32, I> Node<'i, I> for IntNode<N> { {
type Output = u32; pub fn new(value: T) -> Self {
#[inline(always)] Self {
fn eval(&'i self, _input: I) -> Self::Output { value,
N layout: crate::record::Layout::default().with_writes(0, crate::record::element_write::<T>(), &[]),
}
} }
} }
#[derive(Default, Debug, Clone, Copy)] impl<C, T> crate::node::Node<C> for ValueSource<T>
pub struct ValueNode<T>(pub T); where
T: Clone + Send + Sync + dyn_any::StaticTypeSized,
{
fn serve<'e, 'l>(&self, input: &C, slot: crate::record::FrameClaim<'e, 'l>) -> crate::gpoll::GPoll<crate::record::Served<'e>>
where
C: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
slot.lift_served(crate::gpoll::GPoll::Final(self.value.clone()), input.arena())
}
impl<'i, T: 'i, I> Node<'i, I> for ValueNode<T> { fn layout(&self) -> &crate::record::Layout {
type Output = &'i T; &self.layout
#[inline(always)]
fn eval(&'i self, _input: I) -> Self::Output {
&self.0
} }
} }
impl<T> ValueNode<T> { /// The native record source of a constant.
pub const fn new(value: T) -> ValueNode<T> { pub fn record_value_source<T: Clone + Send + Sync + dyn_any::StaticTypeSized + 'static>(value: T) -> crate::registry::SourceHandle
ValueNode(value) where
T::Static: Clone + Send + Sync,
{
crate::registry::SourceHandle::new_record::<T>(std::sync::Arc::new(ValueSource::new(value)) as std::sync::Arc<crate::registry::ErasedRecordNode>)
}
/// The node behind a leveled value source: a constant list served as one level,
/// one lane per item, with the list's length as the exact extent.
pub struct LeveledValueSource<T> {
values: Vec<T>,
layout: crate::record::Layout,
}
impl<T: Clone + Send + Sync + crate::CacheHash + PartialEq + dyn_any::StaticTypeSized> LeveledValueSource<T>
where
T::Static: Clone + Send + Sync,
{
pub fn new(values: Vec<T>) -> Self {
Self {
values,
layout: crate::record::Layout::default().with_writes(1, crate::record::element_write_hashed::<T>(), &[]),
}
} }
} }
impl<T> From<T> for ValueNode<T> { impl<C, T> crate::node::Node<C> for LeveledValueSource<T>
fn from(value: T) -> Self { where
ValueNode::new(value) C: crate::context::ExtractIndex,
T: Clone + Send + Sync + dyn_any::StaticTypeSized,
{
fn serve<'e, 'l>(&self, input: &C, slot: crate::record::FrameClaim<'e, 'l>) -> crate::gpoll::GPoll<crate::record::Served<'e>>
where
C: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
let Some(value) = self.values.get(input.innermost_index() as usize) else {
return crate::gpoll::GPoll::error("value level addressed past its items");
};
slot.lift_served(crate::gpoll::GPoll::Final(value.clone()), input.arena())
}
fn extent_at<'x>(&self, _input: &C, level: u8, _frames: &crate::record::Frames<'x>) -> crate::gpoll::GPoll<crate::gpoll::Extent>
where
C: crate::context::ExtractArena<ArenaRef = &'x crate::arena::Arena>,
{
match level {
0 => crate::gpoll::GPoll::Final(crate::gpoll::Extent::Exactly(self.values.len())),
_ => crate::gpoll::GPoll::Final(crate::gpoll::Extent::Exactly(1)),
}
}
fn layout(&self) -> &crate::record::Layout {
&self.layout
} }
} }
#[derive(Default, Debug, Clone, Copy)] /// The native record source of a constant level: the source type is the element's.
pub struct AsRefNode<T: AsRef<U>, U>(pub T, PhantomData<U>); pub fn leveled_record_value_source<T: Clone + Send + Sync + crate::CacheHash + PartialEq + dyn_any::StaticTypeSized + 'static>(values: Vec<T>) -> crate::registry::SourceHandle
where
impl<'i, T: 'i + AsRef<U>, U: 'i> Node<'i, ()> for AsRefNode<T, U> { T::Static: Clone + Send + Sync,
type Output = &'i U; {
#[inline(always)] crate::registry::SourceHandle::new_record::<T>(std::sync::Arc::new(LeveledValueSource::new(values)) as std::sync::Arc<crate::registry::ErasedRecordNode>)
fn eval(&'i self, _input: ()) -> Self::Output {
self.0.as_ref()
}
}
impl<T: AsRef<U>, U> AsRefNode<T, U> {
pub const fn new(value: T) -> AsRefNode<T, U> {
AsRefNode(value, PhantomData)
}
}
#[derive(Default, Debug, Clone)]
pub struct RefCellMutNode<T>(pub RefCell<T>);
impl<'i, T: 'i> Node<'i, ()> for RefCellMutNode<T> {
type Output = RefMut<'i, T>;
#[inline(always)]
fn eval(&'i self, _input: ()) -> Self::Output {
self.0.borrow_mut()
}
}
impl<T> RefCellMutNode<T> {
pub const fn new(value: T) -> RefCellMutNode<T> {
RefCellMutNode(RefCell::new(value))
}
}
#[derive(Default)]
pub struct OnceCellNode<T>(pub Cell<T>);
impl<'i, T: Default + 'i, I> Node<'i, I> for OnceCellNode<T> {
type Output = T;
#[inline(always)]
fn eval(&'i self, _input: I) -> Self::Output {
self.0.replace(T::default())
}
}
impl<T> OnceCellNode<T> {
pub const fn new(value: T) -> OnceCellNode<T> {
OnceCellNode(Cell::new(value))
}
}
#[derive(Clone, Copy)]
pub struct ClonedNode<T: Clone>(pub T);
impl<'i, T: Clone + 'i, I> Node<'i, I> for ClonedNode<T> {
type Output = T;
#[inline(always)]
fn eval(&'i self, _input: I) -> Self::Output {
self.0.clone()
}
}
impl<T: Clone> ClonedNode<T> {
pub const fn new(value: T) -> ClonedNode<T> {
ClonedNode(value)
}
}
impl<T: Clone> From<T> for ClonedNode<T> {
fn from(value: T) -> Self {
ClonedNode::new(value)
}
}
/// Yields a precomputed `Item<T>` as a ready future, ignoring its input context.
/// Generated list-content variants feed each already-evaluated content slot through this so the kernel's own
/// context modifications become no-ops (the slot was evaluated once, up front, at the ambient footprint).
pub struct PrecomputedItemNode<T>(pub Item<T>);
impl<'i, T: Clone + WasmNotSend + 'i, I: 'i> Node<'i, I> for PrecomputedItemNode<T> {
type Output = DynFuture<'i, Item<T>>;
#[inline(always)]
fn eval(&'i self, _input: I) -> Self::Output {
let item = self.0.clone();
Box::pin(async move { item })
}
}
impl<T> PrecomputedItemNode<T> {
pub const fn new(item: Item<T>) -> Self {
Self(item)
}
}
#[derive(Clone, Copy)]
/// The DebugClonedNode logs every time it is evaluated.
/// This is useful for debugging.
pub struct DebugClonedNode<T: Clone>(pub T);
impl<'i, T: Clone + 'i> Node<'i, ()> for DebugClonedNode<T> {
type Output = T;
#[inline(always)]
fn eval(&'i self, _input: ()) -> Self::Output {
// KEEP THIS `debug!()` - It acts as the output for the debug node itself
log::debug!("DebugClonedNode::eval");
self.0.clone()
}
}
impl<T: Clone> DebugClonedNode<T> {
pub const fn new(value: T) -> DebugClonedNode<T> {
DebugClonedNode(value)
}
}
#[derive(Clone, Copy)]
pub struct CopiedNode<T: Copy>(pub T);
impl<'i, T: Copy + 'i, I> Node<'i, I> for CopiedNode<T> {
type Output = T;
#[inline(always)]
fn eval(&'i self, _input: I) -> Self::Output {
self.0
}
}
impl<T: Copy> CopiedNode<T> {
pub const fn new(value: T) -> CopiedNode<T> {
CopiedNode(value)
}
}
#[derive(Default)]
pub struct DefaultNode<T>(PhantomData<T>);
impl<'i, T: Default + 'i, I> Node<'i, I> for DefaultNode<T> {
type Output = T;
fn eval(&'i self, _input: I) -> Self::Output {
T::default()
}
}
impl<T> DefaultNode<T> {
pub fn new() -> Self {
Self(PhantomData)
}
}
#[repr(C)]
/// Return the unit value
#[derive(Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct ForgetNode;
impl<'i, T: 'i> Node<'i, T> for ForgetNode {
type Output = ();
fn eval(&'i self, _input: T) -> Self::Output {}
}
impl ForgetNode {
pub const fn new() -> Self {
ForgetNode
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_int_node() {
let node = IntNode::<5>;
assert_eq!(node.eval(()), 5);
}
#[test]
fn test_value_node() {
let node = ValueNode::new(5);
assert_eq!(node.eval(()), &5);
let type_erased = &node as &dyn for<'a> Node<'a, (), Output = &'a i32>;
assert_eq!(type_erased.eval(()), &5);
}
#[test]
fn test_default_node() {
let node = DefaultNode::<u32>::new();
assert_eq!(node.eval(42), 0);
}
#[test]
#[allow(clippy::unit_cmp)]
fn test_unit_node() {
let node = ForgetNode::new();
assert_eq!(node.eval(()), ());
}
} }
@@ -236,3 +236,141 @@ impl_tuple!(A, B, C);
impl_tuple!(A, B, C, D); impl_tuple!(A, B, C, D);
impl_tuple!(A, B, C, D, E); impl_tuple!(A, B, C, D, E);
impl_tuple!(A, B, C, D, E, F); impl_tuple!(A, B, C, D, E, F);
/// rustc-hash's polynomial hash with the state pinned to u64, so keys match across native and wasm targets.
/// The state starts at a nonzero seed, since zero-initialized fx absorbs leading zero words.
#[derive(Clone)]
pub struct FxHasher64 {
hash: u64,
}
const K: u64 = 0xf1357aea2e62a9c5;
const SEED: u64 = 0x517cc1b727220a95;
const SEED1: u64 = 0x243f6a8885a308d3;
const SEED2: u64 = 0x13198a2e03707344;
const PREVENT_TRIVIAL_ZERO_COLLAPSE: u64 = 0xa4093822299f31d0;
impl Default for FxHasher64 {
fn default() -> Self {
Self::new()
}
}
impl FxHasher64 {
pub const fn new() -> Self {
Self { hash: SEED }
}
#[inline]
fn add_to_hash(&mut self, i: u64) {
self.hash = self.hash.wrapping_add(i).wrapping_mul(K);
}
}
impl core::hash::Hasher for FxHasher64 {
#[inline]
fn write(&mut self, bytes: &[u8]) {
self.add_to_hash(hash_bytes(bytes));
}
#[inline]
fn write_u8(&mut self, i: u8) {
self.add_to_hash(i as u64);
}
#[inline]
fn write_u16(&mut self, i: u16) {
self.add_to_hash(i as u64);
}
#[inline]
fn write_u32(&mut self, i: u32) {
self.add_to_hash(i as u64);
}
#[inline]
fn write_u64(&mut self, i: u64) {
self.add_to_hash(i);
}
#[inline]
fn write_u128(&mut self, i: u128) {
self.add_to_hash(i as u64);
self.add_to_hash((i >> 64) as u64);
}
#[inline]
fn write_usize(&mut self, i: usize) {
self.add_to_hash(i as u64);
}
#[inline]
fn finish(&self) -> u64 {
self.hash.rotate_left(26)
}
}
#[inline]
fn multiply_mix(x: u64, y: u64) -> u64 {
let full = (x as u128) * (y as u128);
(full as u64) ^ ((full >> 64) as u64)
}
#[inline]
fn hash_bytes(bytes: &[u8]) -> u64 {
let len = bytes.len();
let mut s0 = SEED1;
let mut s1 = SEED2;
if len <= 16 {
if len >= 8 {
s0 ^= u64::from_le_bytes(bytes[0..8].try_into().unwrap());
s1 ^= u64::from_le_bytes(bytes[len - 8..].try_into().unwrap());
} else if len >= 4 {
s0 ^= u32::from_le_bytes(bytes[0..4].try_into().unwrap()) as u64;
s1 ^= u32::from_le_bytes(bytes[len - 4..].try_into().unwrap()) as u64;
} else if len > 0 {
let lo = bytes[0];
let mid = bytes[len / 2];
let hi = bytes[len - 1];
s0 ^= lo as u64;
s1 ^= ((hi as u64) << 8) | mid as u64;
}
} else {
let mut off = 0;
while off < len - 16 {
let x = u64::from_le_bytes(bytes[off..off + 8].try_into().unwrap());
let y = u64::from_le_bytes(bytes[off + 8..off + 16].try_into().unwrap());
let t = multiply_mix(s0 ^ x, PREVENT_TRIVIAL_ZERO_COLLAPSE ^ y);
s0 = s1;
s1 = t;
off += 16;
}
let suffix = &bytes[len - 16..];
s0 ^= u64::from_le_bytes(suffix[0..8].try_into().unwrap());
s1 ^= u64::from_le_bytes(suffix[8..16].try_into().unwrap());
}
multiply_mix(s0, s1) ^ (len as u64)
}
#[cfg(test)]
mod tests {
use super::FxHasher64;
use core::hash::Hasher;
#[test]
fn leading_zero_words_are_not_absorbed() {
let hash_words = |words: &[u64]| {
let mut hasher = FxHasher64::new();
for &word in words {
hasher.write_u64(word);
}
hasher.finish()
};
assert_ne!(hash_words(&[]), hash_words(&[0]), "a zero word must change the hash of the empty input");
assert_ne!(hash_words(&[0]), hash_words(&[0, 0]), "zero words must accumulate distinct states");
assert_ne!(hash_words(&[0, 7]), hash_words(&[7]), "a leading zero word must not be absorbed");
}
}
@@ -115,7 +115,7 @@ impl Coverage {
} }
/// Builds an appearance row, eliding the paint attribute when it is the default none-paint. /// Builds an appearance row, eliding the paint attribute when it is the default none-paint.
fn cover_row(coverage: Coverage, paint: Graphic) -> Item<Coverage> { fn cover_row(coverage: Coverage, paint: Graphic<'static>) -> Item<Coverage> {
let mut row = Item::new_from_element(coverage); let mut row = Item::new_from_element(coverage);
if paint != Graphic::default() { if paint != Graphic::default() {
row.set_attribute(ATTR_PAINT, paint); row.set_attribute(ATTR_PAINT, paint);
@@ -125,7 +125,7 @@ fn cover_row(coverage: Coverage, paint: Graphic) -> Item<Coverage> {
impl Appearance { impl Appearance {
/// Creates an appearance holding a single coverage with the given paint. /// Creates an appearance holding a single coverage with the given paint.
pub fn new_single(coverage: Coverage, paint: Graphic) -> Self { pub fn new_single(coverage: Coverage, paint: Graphic<'static>) -> Self {
Self(List::new_from_item(cover_row(coverage, paint))) Self(List::new_from_item(cover_row(coverage, paint)))
} }
@@ -161,8 +161,8 @@ impl Appearance {
} }
/// The paint of the coverage at the given index, or `None` if the paint attribute is absent. /// The paint of the coverage at the given index, or `None` if the paint attribute is absent.
pub fn paint_at(&self, index: usize) -> Option<&Graphic> { pub fn paint_at(&self, index: usize) -> Option<&Graphic<'static>> {
self.0.attribute::<Graphic>(ATTR_PAINT, index) self.0.attribute::<Graphic<'static>>(ATTR_PAINT, index)
} }
/// The index of the first coverage of the given cover in paint order. /// The index of the first coverage of the given cover in paint order.
@@ -176,12 +176,12 @@ impl Appearance {
} }
/// The paint of the first coverage of the given cover, filtered to paint that draws something. /// The paint of the first coverage of the given cover, filtered to paint that draws something.
pub fn first_paint_of(&self, cover: Cover) -> Option<&Graphic> { pub fn first_paint_of(&self, cover: Cover) -> Option<&Graphic<'static>> {
self.first_index_of(cover).and_then(|index| self.paint_at(index)).filter(|paint| !paint.is_empty()) self.first_index_of(cover).and_then(|index| self.paint_at(index)).filter(|paint| !paint.is_empty())
} }
/// Iterates the coverages in paint order together with their paint, which is `None` when absent or drawing nothing. /// Iterates the coverages in paint order together with their paint, which is `None` when absent or drawing nothing.
pub fn covers_with_paints(&self) -> impl Iterator<Item = (&Coverage, Option<&Graphic>)> { pub fn covers_with_paints(&self) -> impl Iterator<Item = (&Coverage, Option<&Graphic<'static>>)> {
self.covers().enumerate().map(|(index, coverage)| (coverage, self.paint_at(index).filter(|paint| !paint.is_empty()))) self.covers().enumerate().map(|(index, coverage)| (coverage, self.paint_at(index).filter(|paint| !paint.is_empty())))
} }
@@ -221,7 +221,7 @@ impl Appearance {
/// Replaces the first coverage of the incoming cover in place (keeping its position in the paint order), /// Replaces the first coverage of the incoming cover in place (keeping its position in the paint order),
/// or inserts a new row at the requested end of the paint order if none exists. /// or inserts a new row at the requested end of the paint order if none exists.
pub fn replace_or_insert(&mut self, coverage: Coverage, paint: Graphic, placement: CoverPlacement) { pub fn replace_or_insert(&mut self, coverage: Coverage, paint: Graphic<'static>, placement: CoverPlacement) {
if let Some(index) = self.first_index_of(coverage.cover()) { if let Some(index) = self.first_index_of(coverage.cover()) {
if let Some(element) = self.0.element_mut(index) { if let Some(element) = self.0.element_mut(index) {
*element = coverage; *element = coverage;
@@ -243,7 +243,7 @@ impl Appearance {
/// Sets the paint of the first coverage of the given cover, leaving its other parameters untouched. /// Sets the paint of the first coverage of the given cover, leaving its other parameters untouched.
/// Returns `false` without changing anything if no coverage of that cover exists. /// Returns `false` without changing anything if no coverage of that cover exists.
pub fn set_paint_of(&mut self, cover: Cover, paint: Graphic) -> bool { pub fn set_paint_of(&mut self, cover: Cover, paint: Graphic<'static>) -> bool {
let Some(index) = self.first_index_of(cover) else { return false }; let Some(index) = self.first_index_of(cover) else { return false };
self.0.set_attribute(ATTR_PAINT, index, paint); self.0.set_attribute(ATTR_PAINT, index, paint);
true true
@@ -260,15 +260,15 @@ impl Appearance {
#[derive(Debug, Default)] #[derive(Debug, Default)]
pub struct FillAndStroke<'a> { pub struct FillAndStroke<'a> {
pub stroke: Option<Stroke>, pub stroke: Option<Stroke>,
pub fill_paint: Option<&'a Graphic>, pub fill_paint: Option<&'a Graphic<'static>>,
pub stroke_paint: Option<&'a Graphic>, pub stroke_paint: Option<&'a Graphic<'static>>,
/// Whether the first stroke coverage sits before the first fill in the paint order, painting below it. /// Whether the first stroke coverage sits before the first fill in the paint order, painting below it.
pub stroke_below: bool, pub stroke_below: bool,
} }
/// Stamps a coverage into the item's `ATTR_APPEARANCE` cell, creating the attribute if absent. /// Stamps a coverage into the item's `ATTR_APPEARANCE` cell, creating the attribute if absent.
/// The coverage replaces the first same-cover one in place, or lands at the placement end of the paint order. /// The coverage replaces the first same-cover one in place, or lands at the placement end of the paint order.
pub fn stamp_coverage<T>(item: &mut Item<T>, coverage: Coverage, paint: Graphic, placement: CoverPlacement) { pub fn stamp_coverage<T>(item: &mut Item<T>, coverage: Coverage, paint: Graphic<'static>, placement: CoverPlacement) {
item.attribute_mut_or_insert_default::<Appearance>(ATTR_APPEARANCE).replace_or_insert(coverage, paint, placement); item.attribute_mut_or_insert_default::<Appearance>(ATTR_APPEARANCE).replace_or_insert(coverage, paint, placement);
} }
@@ -279,14 +279,15 @@ mod tests {
use glam::{DAffine2, DVec2}; use glam::{DAffine2, DVec2};
use vector_types::vector::style::{StrokeAlign, StrokeCap, StrokeJoin}; use vector_types::vector::style::{StrokeAlign, StrokeCap, StrokeJoin};
fn solid_paint(color: Color) -> Graphic { // Our leaf holds the element bare, so a solid paint is the color leaf itself.
Graphic::ColorList(List::new_from_element(color)) fn solid_paint(color: Color) -> Graphic<'static> {
Graphic::Color(color)
} }
fn paint_color(appearance: &Appearance, index: usize) -> Option<Color> { fn paint_color(appearance: &Appearance, index: usize) -> Option<Color> {
let paint = appearance.paint_at(index)?; let paint = appearance.paint_at(index)?;
let Graphic::ColorList(colors) = paint else { return None }; let Graphic::Color(color) = paint else { return None };
colors.element(0).copied() Some(*color)
} }
#[test] #[test]
@@ -12,39 +12,135 @@ use glam::DAffine2;
/// enclosing `List<Artboard>`, not as fields here. This keeps `Artboard` a pure type-system boundary /// enclosing `List<Artboard>`, not as fields here. This keeps `Artboard` a pure type-system boundary
/// that prevents arbitrary `List<List<...<Graphic>>>` nesting. /// that prevents arbitrary `List<List<...<Graphic>>>` nesting.
#[derive(Clone, Debug, Default, CacheHash, PartialEq, DynAny)] #[derive(Clone, Debug, Default, CacheHash, PartialEq, DynAny)]
pub struct Artboard(pub List<Graphic>); pub struct Artboard<'e>(pub List<Graphic<'e>>);
impl Artboard { impl<'e> Artboard<'e> {
pub fn new(content: List<Graphic>) -> Self { pub fn new(content: List<Graphic<'e>>) -> Self {
Self(content) Self(content)
} }
pub fn as_graphic_list(&self) -> &List<Graphic> { pub fn as_graphic_list(&self) -> &List<Graphic<'_>> {
&self.0 &self.0
} }
pub fn as_graphic_list_mut(&mut self) -> &mut List<Graphic> { pub fn as_graphic_list_mut(&mut self) -> &mut List<Graphic<'e>> {
&mut self.0 &mut self.0
} }
pub fn into_graphic_list(self) -> List<Graphic> { pub fn into_graphic_list(self) -> List<Graphic<'e>> {
self.0 self.0
} }
/// The artboard with every content group converted to its legacy form, so
/// the value owns all of its content free of arena borrows.
pub fn with_legacy_groups(&self) -> Artboard<'e> {
let mut content = self.0.clone();
for element in content.iter_element_values_mut() {
*element = crate::graphic::map_groups_to_legacy(element);
}
crate::graphic::map_paint_attrs_to_legacy(&mut content);
Artboard(content)
}
} }
impl From<List<Graphic>> for Artboard { /// The deep copy-out for `Artboard` elements: as for `Graphic`, a plain
fn from(content: List<Graphic>) -> Self { /// clone of group content would carry frame pointers into the evaluation's
/// arena, so memo and capture seams copy out the owned-group form.
///
/// # Safety
/// `ptr` must point at a live parked `Artboard` element field.
unsafe fn deep_clone_artboard(ptr: *const u8) -> Box<dyn std::any::Any + Send + Sync> {
// SAFETY: the caller's contract.
let artboard = unsafe { core_types::record::borrow_element::<Artboard>(core_types::record::Rec::new(ptr)) };
let mut content = artboard.0.clone();
for element in content.iter_element_values_mut() {
*element = crate::graphic::map_groups_to_owned(element);
}
crate::graphic::map_attribute_groups_to_owned(&mut content);
Box::new(Artboard(content))
}
/// The deep re-park for `Artboard` elements: owned content groups replay into
/// the serving arena before the artboard parks.
///
/// # Safety
/// `value` must hold an `Artboard` and `dst` must be a live `Artboard`
/// element field.
unsafe fn deep_repark_artboard(value: &(dyn std::any::Any + Send + Sync), dst: *mut u8, arena: &core_types::arena::Arena) -> Option<()> {
let artboard = value.downcast_ref::<Artboard>().expect("an element replays at its own type");
let mut content = artboard.0.clone();
for element in content.iter_element_values_mut() {
*element = crate::graphic::map_groups_to_resident(element, arena)?;
}
crate::graphic::map_attribute_groups_to_resident(&mut content, arena)?;
// SAFETY: the caller's contract on `dst`; the replayed content is an `Artboard`.
unsafe { core_types::record::write_element(dst, Artboard(content), arena) }
}
/// The promote for `Artboard` elements: as for `Graphic`, content groups the
/// persistent region already holds are shared rather than copied, and content
/// no group is reachable from moves its header instead of copying its heap.
///
/// # Safety
/// `src` must point at a live parked `Artboard` element field, and `dst` at
/// the element field the promoted reference is written to.
unsafe fn promote_artboard(src: *const u8, dst: *mut u8, promotion: &core_types::record::Promotion<'_>) -> Option<()> {
// SAFETY: the caller's contract on `src`.
let artboard = unsafe { core_types::record::borrow_element::<Artboard>(core_types::record::Rec::new(src)) };
if !crate::graphic::list_contains_groups(&artboard.0) {
// SAFETY: a parked element slot holds one reference at offset 0, and
// content no group is reachable from, elements and item attribute values
// alike, owns all of itself.
let header = unsafe { src.cast::<*const u8>().read() };
// SAFETY: as above; the group-free check establishes the own-all-content half.
if let Some(moved) = unsafe { promotion.move_park::<Artboard>(header, 0) } {
// SAFETY: as above, into the promoted image's own element slot.
unsafe { dst.cast::<*const Artboard>().write(moved) };
return Some(());
}
}
let mut content = List::new();
for item in artboard.0.clone().into_iter() {
let (element, attributes) = item.into_parts();
content.push(core_types::list::Item::from_parts(crate::graphic::map_groups_to_persistent(&element, promotion)?, attributes));
}
crate::graphic::map_attribute_groups_to_persistent(&mut content, promotion)?;
// SAFETY: the caller's contract on `dst`; the promoted content is an `Artboard`.
unsafe { core_types::record::write_element(dst, Artboard(content), promotion.persistent()) }
}
const _: () = {
fn register_all() {
core_types::record::register_deep_element_clone::<Artboard>(deep_clone_artboard, deep_repark_artboard);
core_types::record::register_element_promote::<Artboard>(promote_artboard);
}
#[cfg(not(target_family = "wasm"))]
#[core_types::ctor::ctor]
fn register() {
register_all();
}
#[cfg(target_family = "wasm")]
#[unsafe(export_name = "__node_registry_deep_element_artboard")]
extern "C" fn register() {
register_all();
}
};
impl<'e> From<List<Graphic<'e>>> for Artboard<'e> {
fn from(content: List<Graphic<'e>>) -> Self {
Self(content) Self(content)
} }
} }
impl From<Artboard> for List<Graphic> { impl<'e> From<Artboard<'e>> for List<Graphic<'e>> {
fn from(artboard: Artboard) -> Self { fn from(artboard: Artboard<'e>) -> Self {
artboard.0 artboard.0
} }
} }
impl BoundingBox for Artboard { impl BoundingBox for Artboard<'_> {
fn bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox { fn bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
self.0.bounding_box(transform, include_stroke) self.0.bounding_box(transform, include_stroke)
} }
@@ -54,7 +150,7 @@ impl BoundingBox for Artboard {
} }
} }
impl RenderComplexity for Artboard { impl RenderComplexity for Artboard<'_> {
fn render_complexity(&self) -> usize { fn render_complexity(&self) -> usize {
self.0.render_complexity() self.0.render_complexity()
} }
@@ -0,0 +1,105 @@
//! Boundary helpers between leveled wires and the legacy editor surface:
//! the renderer's flip form materializes a wire into a group, and captured
//! wires convert to the legacy values the editor's downcasts expect.
use crate::graphic::{Graphic, group_to_legacy_list, run_to_legacy_list};
use crate::raster_types::{CPU, GPU, Raster};
use crate::{Artboard, Vector};
use core_types::Color;
use core_types::arena::Arena;
use core_types::context::InjectIndex;
use core_types::gpoll::{Finality, GraphError};
use core_types::node::Node;
use core_types::record::{Group, GroupItem, LevelStatus, materialize_level};
use core_types::uuid::NodeId;
use glam::{DAffine2, DVec2};
use vector_types::Gradient;
/// The outcome of materializing a leveled wire into a group.
// The group is the render path's success payload; boxing it would add a heap allocation per materialized level.
#[allow(clippy::large_enum_variant)]
pub enum LevelGroup<'e> {
Group(Group<'e>, Finality),
Pending,
Error(GraphError),
}
/// The renderer's flip form: the wire's whole extent materialized into a
/// group over the level's records, ready for the group render bridge.
pub fn materialize_group<'a, 'e, C, N>(node: &'a N, input: &'a C, arena: &'a Arena, frames: &core_types::record::Frames<'e>) -> LevelGroup<'a>
where
C: InjectIndex + Copy + core_types::context::ExtractArena<ArenaRef = &'e Arena>,
N: Node<C>,
{
match materialize_level(node, input, arena, frames) {
LevelStatus::Batch(batch, finality) => {
// SAFETY: a materialized batch's frames are arena-resident.
let item = unsafe { GroupItem::from_resident(batch) };
LevelGroup::Group(Group { row: None, content: item }, finality)
}
LevelStatus::Pending => LevelGroup::Pending,
LevelStatus::Error(error) => LevelGroup::Error(error),
}
}
/// The resident batch as the legacy value the editor's downcasts expect: a
/// rank-0 wire is its element, a leveled `Graphic` wire becomes its legacy
/// list through the group bridge, and another element type becomes a legacy
/// list of that element. `None` for an element type outside the legacy
/// vocabulary or an empty rank-0 batch.
pub fn batch_to_legacy(layout: &core_types::record::Layout, batch: core_types::node::RecordBatch<'_>, _arena: &Arena) -> Option<Box<dyn std::any::Any + Send + Sync>> {
if layout.depth == 0 {
// The group-carrying types legacy-convert while the batch is
// resident; the deep clone-out would hand back the unreadable owned
// form.
if batch.is_empty() {
return None;
}
let element = &layout.element;
if element.type_id == std::any::TypeId::of::<Graphic>() {
// SAFETY: the layout records the element type, and a parked
// element stores its reference at offset 0.
let graphic = unsafe { core_types::record::borrow_element::<Graphic>(batch.get(0).rec()) };
return Some(Box::new(crate::graphic::map_groups_to_legacy(graphic)));
}
if element.type_id == std::any::TypeId::of::<Artboard>() {
// SAFETY: as for the graphic arm.
let artboard = unsafe { core_types::record::borrow_element::<Artboard>(batch.get(0).rec()) };
return Some(Box::new(artboard.with_legacy_groups()));
}
// SAFETY: lane 0 is a live record of `layout`.
return Some(unsafe { (element.clone_out)(batch.get(0).rec().ptr()) });
}
// SAFETY: the caller's batch is resident for the read.
let item = unsafe { GroupItem::from_resident(batch) };
fn typed<T: Clone + Send + Sync + dyn_any::StaticTypeSized + 'static>(item: &GroupItem) -> Option<Box<dyn std::any::Any + Send + Sync>> {
run_to_legacy_list::<T>(item).map(|list| Box::new(list) as Box<dyn std::any::Any + Send + Sync>)
}
if item.typed_lanes::<Graphic>().is_some() {
let group = Group { row: None, content: item };
return Some(Box::new(group_to_legacy_list(&group)));
}
fn typed_artboards(item: &GroupItem) -> Option<Box<dyn std::any::Any + Send + Sync>> {
let mut list = run_to_legacy_list::<Artboard>(item)?;
// The capture outlives the arena generation, so group content must
// leave in its owned legacy form.
for artboard in list.iter_element_values_mut() {
*artboard = artboard.with_legacy_groups();
}
Some(Box::new(list))
}
None.or_else(|| typed_artboards(&item))
.or_else(|| typed::<Vector>(&item))
.or_else(|| typed::<Raster<CPU>>(&item))
.or_else(|| typed::<Raster<GPU>>(&item))
.or_else(|| typed::<Color>(&item))
.or_else(|| typed::<Gradient>(&item))
.or_else(|| typed::<String>(&item))
.or_else(|| typed::<f64>(&item))
.or_else(|| typed::<u64>(&item))
.or_else(|| typed::<u32>(&item))
.or_else(|| typed::<bool>(&item))
.or_else(|| typed::<NodeId>(&item))
.or_else(|| typed::<DAffine2>(&item))
.or_else(|| typed::<DVec2>(&item))
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,680 @@
//! The record-crossing glue: group interiors carried between the owned, resident, and persistent regions.
use super::Graphic;
use core_types::Color;
use core_types::list::{Item, List};
use raster_types::{CPU, Raster};
use vector_types::Vector;
/// The graphic with every `Group` deep-copied to its owned form, which
/// survives the arena generation but cannot be read until
/// [`map_groups_to_resident`] re-parks it into a serving arena.
pub fn map_groups_to_owned<'out>(graphic: &Graphic<'_>) -> Graphic<'out> {
match graphic {
Graphic::Group(group) => Graphic::Group(group.copy_out()),
Graphic::GraphicList(children) => {
let mut out = List::new();
for item in children.clone().into_iter() {
let (element, attributes) = item.into_parts();
out.push(Item::from_parts(map_groups_to_owned(&element), attributes));
}
map_attribute_groups_to_owned(&mut out);
Graphic::GraphicList(out)
}
Graphic::Stroke(stroke) => Graphic::Stroke(stroke.clone()),
Graphic::StrokeList(strokes) => Graphic::StrokeList(strokes.clone()),
Graphic::Vector(vector) => Graphic::Vector(vector.clone()),
Graphic::RasterCPU(raster) => Graphic::RasterCPU(raster.clone()),
Graphic::RasterGPU(raster) => Graphic::RasterGPU(raster.clone()),
Graphic::Color(color) => Graphic::Color(*color),
Graphic::Gradient(gradient) => Graphic::Gradient(gradient.clone()),
Graphic::Text(text) => Graphic::Text(text.clone()),
}
}
/// The graphic with every owned `Group` re-parked into `arena`; `None`
/// reports arena exhaustion.
pub fn map_groups_to_resident<'a>(graphic: &Graphic<'a>, arena: &'a core_types::arena::Arena) -> Option<Graphic<'a>> {
match graphic {
Graphic::Group(group) => group.replay(arena).map(Graphic::Group),
Graphic::GraphicList(children) => {
let mut children = children.clone();
for child in children.iter_element_values_mut() {
*child = map_groups_to_resident(child, arena)?;
}
map_attribute_groups_to_resident(&mut children, arena)?;
Some(Graphic::GraphicList(children))
}
other => Some(other.clone()),
}
}
/// The deep copy-out for `Graphic` elements: a plain clone of a group
/// interior would carry frame pointers into the evaluation's arena, so memo
/// and capture seams copy out the owned-group form.
///
/// # Safety
/// `ptr` must point at a live parked `Graphic` element field.
unsafe fn deep_clone_graphic(ptr: *const u8) -> Box<dyn std::any::Any + Send + Sync> {
// SAFETY: the caller's contract.
let graphic = unsafe { core_types::record::borrow_element::<Graphic>(core_types::record::Rec::new(ptr)) };
Box::new(map_groups_to_owned(graphic))
}
/// The deep re-park for `Graphic` elements: owned groups replay into the
/// serving arena before the graphic parks.
///
/// # Safety
/// `value` must hold a `Graphic` and `dst` must be a live `Graphic` element
/// field.
unsafe fn deep_repark_graphic(value: &(dyn std::any::Any + Send + Sync), dst: *mut u8, arena: &core_types::arena::Arena) -> Option<()> {
let graphic = value.downcast_ref::<Graphic>().expect("an element replays at its own type");
let resident = map_groups_to_resident(graphic, arena)?;
let retained = graphic_retained_heap(&resident);
// SAFETY: the caller's contract; the resident form is a `Graphic` for `dst`.
unsafe { core_types::record::write_element_sized(dst, resident, arena, retained) }
}
/// The graphic with every `Group` promoted into the persistent region: an
/// interior already living there is shared rather than copied, so the cost is
/// what this level newly produced. `None` reports arena exhaustion.
pub fn map_groups_to_persistent<'p>(graphic: &Graphic<'_>, promotion: &core_types::record::Promotion<'p>) -> Option<Graphic<'p>> {
match graphic {
Graphic::Group(group) => group.to_persistent(promotion).map(Graphic::Group),
Graphic::GraphicList(children) => {
let mut out = List::new();
for item in children.clone().into_iter() {
let (element, attributes) = item.into_parts();
out.push(Item::from_parts(map_groups_to_persistent(&element, promotion)?, attributes));
}
map_attribute_groups_to_persistent(&mut out, promotion)?;
Some(Graphic::GraphicList(out))
}
Graphic::Stroke(stroke) => Some(Graphic::Stroke(stroke.clone())),
Graphic::StrokeList(strokes) => Some(Graphic::StrokeList(strokes.clone())),
Graphic::Vector(vector) => Some(Graphic::Vector(vector.clone())),
Graphic::RasterCPU(raster) => Some(Graphic::RasterCPU(raster.clone())),
Graphic::RasterGPU(raster) => Some(Graphic::RasterGPU(raster.clone())),
Graphic::Color(color) => Some(Graphic::Color(*color)),
Graphic::Gradient(gradient) => Some(Graphic::Gradient(gradient.clone())),
Graphic::Text(text) => Some(Graphic::Text(text.clone())),
}
}
/// The list's attribute keys, owned so the columns can be walked mutably.
fn attribute_keys(list: &List<Graphic>) -> Vec<String> {
list.attribute_keys().map(str::to_string).collect()
}
/// Every group held in the list's item attribute values, deep-copied to its
/// owned form. Element values are the caller's own pass; a value list's own
/// item attributes recurse here.
pub(crate) fn map_attribute_groups_to_owned(list: &mut List<Graphic<'_>>) {
for key in attribute_keys(list) {
// A column of a type that cannot hold groups is skipped whole.
let Some(values) = list.iter_attribute_values_mut::<Option<List<Graphic>>>(&key) else { continue };
for value in values.flatten() {
for element in value.iter_element_values_mut() {
*element = map_groups_to_owned(element);
}
map_attribute_groups_to_owned(value);
}
}
}
/// Every owned group held in the list's item attribute values, re-parked into
/// `arena`. `None` reports arena exhaustion.
pub(crate) fn map_attribute_groups_to_resident(list: &mut List<Graphic<'_>>, arena: &core_types::arena::Arena) -> Option<()> {
for key in attribute_keys(list) {
// A column of a type that cannot hold groups is skipped whole.
let Some(values) = list.iter_attribute_values_mut::<Option<List<Graphic>>>(&key) else { continue };
for value in values.flatten() {
for element in value.iter_element_values_mut() {
let resident = map_groups_to_resident(element, arena)?;
// SAFETY: the attribute store is erased, and the replay serves as
// long as `arena`, which the store's reader outlives.
*element = unsafe { core_types::record::erase_static(resident) };
}
map_attribute_groups_to_resident(value, arena)?;
}
}
Some(())
}
/// Every group held in the list's item attribute values, promoted into the
/// persistent region on the same Cow dispatch the elements take. `None` reports
/// arena exhaustion.
pub(crate) fn map_attribute_groups_to_persistent(list: &mut List<Graphic<'_>>, promotion: &core_types::record::Promotion<'_>) -> Option<()> {
for key in attribute_keys(list) {
// A column of a type that cannot hold groups is skipped whole.
let Some(values) = list.iter_attribute_values_mut::<Option<List<Graphic>>>(&key) else { continue };
for value in values.flatten() {
for element in value.iter_element_values_mut() {
let promoted = map_groups_to_persistent(element, promotion)?;
// SAFETY: the attribute store is erased, and persistent content
// outlives the evaluation.
*element = unsafe { core_types::record::erase_static(promoted) };
}
map_attribute_groups_to_persistent(value, promotion)?;
}
}
Some(())
}
/// The promote for `Graphic` elements: the generic path would deep-copy every
/// interior through an owned intermediate, while this shares the interiors the
/// persistent region already holds. A graphic no group is reachable from
/// references nothing the evaluation owns, so its header moves and its heap is
/// never copied.
///
/// # Safety
/// `src` must point at a live parked `Graphic` element field, and `dst` at the
/// element field the promoted reference is written to.
unsafe fn promote_graphic(src: *const u8, dst: *mut u8, promotion: &core_types::record::Promotion<'_>) -> Option<()> {
// SAFETY: the caller's contract on `src`.
let graphic = unsafe { core_types::record::borrow_element::<Graphic>(core_types::record::Rec::new(src)) };
if !graphic_contains_groups(graphic) {
// SAFETY: a parked element slot holds one reference at offset 0, and a
// graphic no group is reachable from, elements and item attribute values
// alike, owns all of its content.
let header = unsafe { src.cast::<*const u8>().read() };
// SAFETY: as above; the group-free check establishes the own-all-content half.
if let Some(moved) = unsafe { promotion.move_park::<Graphic<'static>>(header, graphic_retained_heap(graphic)) } {
// SAFETY: as above, into the promoted image's own element slot.
unsafe { dst.cast::<*const Graphic<'static>>().write(moved) };
return Some(());
}
}
let promoted = map_groups_to_persistent(graphic, promotion)?;
let retained = graphic_retained_heap(&promoted);
// SAFETY: the caller's contract on `dst`; the promoted form is a `Graphic`.
unsafe { core_types::record::write_element_sized(dst, promoted, promotion.persistent(), retained) }
}
/// The heap a graphic's own payload owns. Group interiors are excluded: their
/// lanes park through this same glue and are counted as they land.
fn graphic_retained_heap(graphic: &Graphic<'_>) -> usize {
match graphic {
Graphic::Vector(vector) => vector_retained_heap(vector),
Graphic::RasterCPU(raster) => raster.data.len() * size_of::<Color>(),
Graphic::Text(text) => text.len(),
Graphic::Gradient(gradient) => gradient.len() * size_of::<(f64, Color)>(),
Graphic::GraphicList(children) => (0..children.len()).filter_map(|index| children.element(index)).map(graphic_retained_heap).sum(),
Graphic::Stroke(stroke) => stroke.position.len() * size_of::<glam::DVec2>(),
Graphic::StrokeList(strokes) => (0..strokes.len()).filter_map(|index| strokes.element(index)).map(|stroke| stroke.position.len() * size_of::<glam::DVec2>()).sum(),
Graphic::Group(_) | Graphic::RasterGPU(_) | Graphic::Color(_) => 0,
}
}
/// The heap a vector's domain columns own, summed over the columns it
/// exposes, so the segment domain's private parallel columns are undercounted.
fn vector_retained_heap(vector: &Vector) -> usize {
size_of_val(vector.point_domain.ids())
+ size_of_val(vector.point_domain.positions())
+ size_of_val(vector.segment_domain.ids())
+ size_of_val(vector.colinear_manipulators.as_slice())
}
/// Whether any group is reachable from the graphic, so it does not own all of
/// its content.
fn graphic_contains_groups(graphic: &Graphic) -> bool {
match graphic {
Graphic::Group(_) => true,
Graphic::GraphicList(children) => list_contains_groups(children),
_ => false,
}
}
/// Whether any group is reachable from the list, so it does not own all of its
/// content. An item attribute value holds its groups exactly as an element
/// does: a cloned group there keeps a resident interior borrowing the
/// evaluation's arena, so the elements alone cannot decide ownership.
pub(crate) fn list_contains_groups(list: &List<Graphic>) -> bool {
(0..list.len()).any(|index| list.element(index).is_some_and(graphic_contains_groups)) || attribute_values_contain_groups(list)
}
/// Whether any group hides in the list's item attribute values. Only the
/// group-capable columns are scanned: those are the value types the deep field
/// glue is registered for, today `Option<List<Graphic>>` alone. A list with no
/// attribute columns costs nothing, and a column of any other type is decided
/// by its one downcast rather than per value.
fn attribute_values_contain_groups(list: &List<Graphic>) -> bool {
list.attribute_keys().any(|key| {
list.iter_attribute_values::<Option<List<Graphic>>>(key)
.is_some_and(|mut values| values.any(|value| value.as_ref().is_some_and(list_contains_groups)))
})
}
/// The heap a graphic list's elements own, group interiors excluded as
/// [`graphic_retained_heap`] excludes them.
fn list_retained_heap(list: &List<Graphic>) -> usize {
(0..list.len()).filter_map(|index| list.element(index)).map(graphic_retained_heap).sum()
}
/// The deep copy-out for graphic-list field values (the paint markers' owned
/// form): content groups leave in their owned form, whether an element or an
/// item attribute value holds them. Declines (`None`) for group-free content,
/// which already owns everything.
fn deep_clone_graphic_list(value: &dyn core_types::list::AnyAttributeValue) -> Option<Box<dyn core_types::list::AnyAttributeValue>> {
let list = value.as_any().downcast_ref::<Option<List<Graphic>>>().expect("a graphic list field deep-copies at its own type");
let list = list.as_ref().filter(|list| list_contains_groups(list))?;
let mut list = list.clone();
for element in list.iter_element_values_mut() {
*element = map_groups_to_owned(element);
}
map_attribute_groups_to_owned(&mut list);
Some(Box::new(Some(list)))
}
/// The deep replay for graphic-list field values: owned content groups replay
/// into the serving arena before the field re-parks, whether an element or an
/// item attribute value holds them. `Some(None)` declines for group-free
/// content; `None` reports arena exhaustion.
fn deep_repark_graphic_list(value: &dyn core_types::list::AnyAttributeValue, arena: &core_types::arena::Arena) -> Option<Option<Box<dyn core_types::list::AnyAttributeValue>>> {
let list = value.as_any().downcast_ref::<Option<List<Graphic>>>().expect("a graphic list field replays at its own type");
let Some(list) = list.as_ref().filter(|list| list_contains_groups(list)) else {
return Some(None);
};
let mut list = list.clone();
for element in list.iter_element_values_mut() {
*element = map_groups_to_resident(element, arena)?;
}
map_attribute_groups_to_resident(&mut list, arena)?;
// SAFETY: every group the clone carried, in an element or an item attribute
// value, now names `arena`, whose borrow the replayed field is read at.
let list = unsafe { core_types::record::erase_static(list) };
Some(Some(Box::new(Some(list))))
}
/// The promote for graphic-list fields, the deep field glue's third half: the
/// owned halves copy content groups out to the owned form and replay them back,
/// while this maps the content transient-to-persistent in one pass.
///
/// THE TWO-LEVEL SHARING LAW: the field's own header is not provenance-shared.
/// It moves where no group is reachable from the list, elements and item
/// attribute values alike, since the payload then owns all of its content and
/// the transient arena confirms the reference is its own park, and otherwise it
/// clones into a fresh persistent park. One level inside, a content group's
/// interior is arena-resident and its provenance is decidable, so it takes
/// [`map_groups_to_persistent`]'s Cow dispatch: an interior the persistent
/// region already holds is shared pointer for pointer.
///
/// # Safety
/// `src` must point at a live parked graphic-list field, and `dst` at the field
/// slot the promoted reference is written to.
unsafe fn promote_graphic_list(src: *const u8, dst: *mut u8, promotion: &core_types::record::Promotion<'_>) -> Option<()> {
// SAFETY: the caller's contract; the slot holds one optional reference.
let Some(list) = (unsafe { src.cast::<Option<&List<Graphic<'static>>>>().read() }) else {
// SAFETY: as above, into the promoted image's own field slot.
unsafe { dst.cast::<Option<&List<Graphic<'static>>>>().write(None) };
return Some(());
};
let retained = list_retained_heap(list);
if !list_contains_groups(list) {
// SAFETY: a list no group is reachable from, elements and item attribute
// values alike, owns all of its content, and the arena declines a
// reference that is not a park at the list's own address and size.
if let Some(moved) = unsafe { promotion.move_park::<List<Graphic<'static>>>(std::ptr::from_ref(list).cast(), retained) } {
// SAFETY: the move published a live list in the persistent region.
unsafe { dst.cast::<Option<&List<Graphic<'static>>>>().write(Some(&*moved)) };
return Some(());
}
}
let mut promoted = list.clone();
for element in promoted.iter_element_values_mut() {
*element = map_groups_to_persistent(element, promotion)?;
}
map_attribute_groups_to_persistent(&mut promoted, promotion)?;
// SAFETY: every borrow the clone carried, in an element or an item attribute
// value, was replaced by persistent content above, so the erased form
// outlives the evaluation.
let promoted = unsafe { core_types::record::erase_static(promoted) };
let (parked, _) = promotion.persistent().alloc_sized(promoted, retained)?;
// SAFETY: the slot holds one optional reference.
unsafe { dst.cast::<Option<&List<Graphic<'static>>>>().write(Some(parked)) };
Some(())
}
const _: () = {
fn register_all() {
core_types::record::register_deep_element_clone::<Graphic>(deep_clone_graphic, deep_repark_graphic);
core_types::record::register_deep_field_value::<Option<List<Graphic>>>(deep_clone_graphic_list, deep_repark_graphic_list);
core_types::record::register_field_promote::<Option<&'static List<Graphic<'static>>>>(promote_graphic_list);
core_types::record::register_element_promote::<Graphic>(promote_graphic);
core_types::record::register_retained_heap::<Graphic>(|value| value.downcast_ref::<Graphic>().map_or(0, graphic_retained_heap));
core_types::record::register_retained_heap::<Vector>(|value| value.downcast_ref::<Vector>().map_or(0, vector_retained_heap));
core_types::record::register_retained_heap::<Raster<CPU>>(|value| value.downcast_ref::<Raster<CPU>>().map_or(0, |raster| raster.data.len() * size_of::<Color>()));
core_types::record::register_retained_heap::<String>(|value| value.downcast_ref::<String>().map_or(0, String::len));
}
#[cfg(not(target_family = "wasm"))]
#[core_types::ctor::ctor]
fn register() {
register_all();
}
#[cfg(target_family = "wasm")]
#[unsafe(export_name = "__node_registry_deep_element_graphic")]
extern "C" fn register() {
register_all();
}
};
#[cfg(test)]
mod run_tests {
use super::*;
use crate::graphic::test_support::{native_group_paint, unit_square_at};
use crate::graphic::{group_to_legacy_list, map_groups_to_legacy};
use crate::markers::{Fill, Stroke};
use core_types::attribute::Attribute;
use core_types::lane::LaneSource;
use core_types::record::{FieldWrite, RunBuilder, RunView, element_write_hashed};
use glam::DVec2;
#[test]
fn an_owned_group_replays_content_equal_after_the_source_dies() {
let paint = List::new_from_element(Graphic::Color(Color::BLACK));
let vector = unit_square_at(DVec2::ZERO);
let source = core_types::arena::Arena::new(1 << 16).unwrap();
let mut builder = RunBuilder::new(&source, element_write_hashed::<Vector>(), &[FieldWrite::of::<Fill>(0)], 1).unwrap();
let lane = builder.push(vector.clone()).unwrap();
builder.attr::<Fill>(lane, Some(&paint));
let group = core_types::record::Group { row: None, content: builder.finish() };
let expected = group_to_legacy_list(&group);
let owned = map_groups_to_owned(&Graphic::Group(group));
drop(source);
let arena = core_types::arena::Arena::new(1 << 16).unwrap();
let resident = map_groups_to_resident(&owned, &arena).expect("the arena holds the replay");
let Graphic::Group(group) = &resident else { panic!("the replay keeps the group form") };
assert_eq!(group_to_legacy_list(group), expected);
}
#[test]
fn an_owned_group_replays_nested_groups_through_the_element_glue() {
let vector = unit_square_at(DVec2::ZERO);
let source = core_types::arena::Arena::new(1 << 16).unwrap();
let mut builder = RunBuilder::new(&source, element_write_hashed::<Vector>(), &[], 1).unwrap();
builder.push(vector.clone()).unwrap();
let nested = Graphic::Group(core_types::record::Group { row: None, content: builder.finish() });
let mut builder = RunBuilder::new(&source, element_write_hashed::<Graphic>(), &[], 1).unwrap();
builder.push(nested).unwrap();
let group = core_types::record::Group { row: None, content: builder.finish() };
let expected = group_to_legacy_list(&group);
let owned = map_groups_to_owned(&Graphic::Group(group));
drop(source);
let arena = core_types::arena::Arena::new(1 << 16).unwrap();
let resident = map_groups_to_resident(&owned, &arena).expect("the arena holds the replay");
let Graphic::Group(group) = &resident else { panic!("the replay keeps the group form") };
assert_eq!(group_to_legacy_list(group), expected);
}
#[test]
fn an_owned_run_deep_copies_graphic_list_fields() {
let inner_vector = unit_square_at(DVec2::ZERO);
let source = core_types::arena::Arena::new(1 << 16).unwrap();
// SAFETY: the erased native list serves only while `source` is live; the
// deep glue under test replaces its borrows at the copy-out seam.
let paint = unsafe { core_types::record::erase_static(native_group_paint(&inner_vector, &source)) };
let vector = unit_square_at(DVec2::new(4., 4.));
let mut builder = RunBuilder::new(&source, element_write_hashed::<Vector>(), &[FieldWrite::of::<Fill>(0)], 1).unwrap();
let lane = builder.push(vector.clone()).unwrap();
builder.attr::<Fill>(lane, Some(&paint));
let item = builder.finish();
let owned = item.copy_out();
let expected = map_groups_to_legacy(paint.element(0).unwrap());
drop(item);
drop(paint);
drop(source);
let arena = core_types::arena::Arena::new(1 << 16).unwrap();
let replayed = owned.replay(&arena).expect("the arena holds the replay");
let run = RunView::<Vector>::new(&replayed).expect("the run holds vector elements");
let served = run.attr::<Fill>(0).expect("the fill replays present");
assert_eq!(map_groups_to_legacy(served.element(0).unwrap()), expected);
}
#[test]
fn an_owned_record_deep_copies_graphic_list_fields() {
let inner_vector = unit_square_at(DVec2::ZERO);
let source = core_types::arena::Arena::new(1 << 16).unwrap();
// SAFETY: the erased native list serves only while `source` is live; the
// deep glue under test replaces its borrows at the copy-out seam.
let paint = unsafe { core_types::record::erase_static(native_group_paint(&inner_vector, &source)) };
let vector = unit_square_at(DVec2::new(4., 4.));
let mut builder = RunBuilder::new(&source, element_write_hashed::<Vector>(), &[FieldWrite::of::<Fill>(0)], 1).unwrap();
let lane = builder.push(vector.clone()).unwrap();
builder.attr::<Fill>(lane, Some(&paint));
let item = builder.finish();
let layout = item.layout().clone();
let offset = layout.offset_of(Fill::NAME, 0).unwrap();
// SAFETY: the item's lane is a live record of `layout`.
let owned = unsafe { core_types::record::OwnedRecord::copy_out(&layout, item.lanes().get(0).rec()) };
let expected = map_groups_to_legacy(paint.element(0).unwrap());
drop(item);
drop(paint);
drop(source);
let arena = core_types::arena::Arena::new(1 << 16).unwrap();
let frames = core_types::record::test_frames(layout.frame_bytes());
let mut slot = frames.claim(&layout);
owned.replay_into(&mut slot, &arena).expect("the arena holds the replay");
// SAFETY: the replay completes the record in the claimed frame.
let value = unsafe { slot.finish() };
// SAFETY: the replay wrote a record of `layout`.
let served = unsafe { layout.rec(&value).read::<Option<&List<Graphic>>>(offset) }.expect("the fill replays present");
assert_eq!(map_groups_to_legacy(served.element(0).unwrap()), expected);
}
/// A `lanes`-long frame promoted out of `transient` into `persistent`, with
/// `fill` written into the paint field of every lane. The frame buffer comes
/// back so it outlives the promote's reads.
fn promote_paint_field(
fill: Option<&List<Graphic<'static>>>,
lanes: usize,
transient: &core_types::arena::Arena,
persistent: &core_types::arena::Arena,
) -> (core_types::record::Layout, core_types::record::MaterializedSpan, Vec<u64>) {
use core_types::record::{Layout, MaterializedSpan, Promotion, element_write, write_field};
let layout = Layout::default().with_writes(0, element_write::<f64>(), &[FieldWrite::of::<Fill>(0)]);
let offset = layout.offset_of(Fill::NAME, 0).unwrap();
let stride = layout.lane_stride();
let mut buffer = vec![0u64; (lanes * stride).div_ceil(8)];
let base = buffer.as_mut_ptr().cast::<u8>();
let bounds = (base as usize, buffer.len() * 8);
for lane in 0..lanes {
// SAFETY: the frame is this layout's, written at the element slot and
// at the paint field's own offset.
unsafe {
base.add(lane * stride).cast::<f64>().write(lane as f64);
write_field::<Option<&List<Graphic<'static>>>>(base.add(lane * stride), offset, fill);
}
}
// SAFETY: the frames hold `lanes` live records of `layout`.
let batch = unsafe { core_types::node::RecordBatch::new(base.cast_const(), lanes, &layout) };
let promotion = Promotion::new(transient, bounds, persistent);
// SAFETY: as above.
let span = unsafe { MaterializedSpan::to_persistent(&batch, &promotion) }.expect("the region holds the promote");
(layout, span, buffer)
}
/// The promoted paint of one lane, at the layout the promote published.
fn promoted_paint<'p>(span: &core_types::record::MaterializedSpan, layout: &core_types::record::Layout, lane: usize, persistent: &'p core_types::arena::Arena) -> &'p List<Graphic<'p>> {
let offset = layout.offset_of(Fill::NAME, 0).unwrap();
let batch = span.batch(persistent, layout).expect("the span resolves in its own region");
// SAFETY: the promote wrote a record of `layout` into every lane.
unsafe { batch.get(lane).rec().read::<Option<&List<Graphic>>>(offset) }.expect("the paint promotes present")
}
#[test]
fn a_promoted_paint_field_shares_persistent_interiors() {
let inner_vector = unit_square_at(DVec2::ZERO);
let transient = core_types::arena::Arena::new(1 << 16).unwrap();
let persistent = core_types::arena::Arena::new(1 << 16).unwrap();
// The interior an upstream promote already published, named by a paint
// list the evaluation parked.
let published = native_group_paint(&inner_vector, &persistent);
let interior = {
let Some(Graphic::Group(group)) = published.element(0) else {
panic!("the paint carries a native group")
};
group.content.lanes().get(0).rec().ptr()
};
// SAFETY: the list serves only while `persistent` is live, and the
// promote under test replaces every borrow it carries.
let (paint, _) = transient.alloc_sized_keyed(unsafe { core_types::record::erase_static(published) }, 0).unwrap();
let occupied = persistent.occupancy();
let (layout, span, _frames) = promote_paint_field(Some(paint), 1, &transient, &persistent);
let served = promoted_paint(&span, &layout, 0, &persistent);
let Some(Graphic::Group(group)) = served.element(0) else {
panic!("the promote keeps the group form")
};
assert_eq!(group.content.lanes().get(0).rec().ptr(), interior, "a persistent interior is shared pointer for pointer");
assert!(
persistent.occupancy() - occupied <= layout.frame_bytes() + size_of::<List<Graphic>>() + align_of::<List<Graphic>>(),
"the promote allocated the lane slab and the field's own header, never the owned form of the shared interior"
);
}
#[test]
fn a_group_free_paint_field_moves_its_parked_header() {
let mut transient = core_types::arena::Arena::new(1 << 16).unwrap();
let persistent = core_types::arena::Arena::new(1 << 16).unwrap();
let paint = List::new_from_element(Graphic::Vector(unit_square_at(DVec2::ZERO)));
let heap = {
let Some(Graphic::Vector(vector)) = paint.element(0) else { panic!("the paint carries a vector") };
vector.point_domain.positions().as_ptr()
};
let (paint, _) = transient.alloc_sized_keyed(paint, 0).unwrap();
let (layout, span, _frames) = promote_paint_field(Some(paint), 2, &transient, &persistent);
let served = promoted_paint(&span, &layout, 0, &persistent);
let Some(Graphic::Vector(vector)) = served.element(0) else {
panic!("the promote keeps the vector")
};
assert_eq!(
vector.point_domain.positions().as_ptr(),
heap,
"the promote moved the header, so the served paint names the pre-promote heap"
);
assert!(std::ptr::eq(served, promoted_paint(&span, &layout, 1, &persistent)), "a paint two lanes share moves once");
transient.reset();
let served = promoted_paint(&span, &layout, 0, &persistent);
assert!(matches!(served.element(0), Some(Graphic::Vector(_))), "the moved paint survives the transient reset");
}
#[test]
fn a_paint_field_whose_attributes_hold_groups_never_moves() {
let inner_vector = unit_square_at(DVec2::ZERO);
let mut transient = core_types::arena::Arena::new(1 << 16).unwrap();
let persistent = core_types::arena::Arena::new(1 << 16).unwrap();
// Group-free elements, with the resident group hidden in an item attribute.
let native = native_group_paint(&inner_vector, &transient);
let expected = map_groups_to_legacy(native.element(0).unwrap());
let mut paint = List::new_from_element(Graphic::Vector(unit_square_at(DVec2::new(4., 4.))));
// SAFETY: the erased native list serves only while `transient` is live; the
// promote under test replaces its borrows.
paint.set_attribute::<Option<List<Graphic>>>(Stroke::NAME, 0, Some(unsafe { core_types::record::erase_static(native) }));
let (paint, _) = transient.alloc_sized_keyed(paint, 0).unwrap();
let (layout, span, _frames) = promote_paint_field(Some(paint), 1, &transient, &persistent);
let served = promoted_paint(&span, &layout, 0, &persistent);
let moved = std::ptr::eq(std::ptr::from_ref(served).cast::<u8>(), std::ptr::from_ref(paint).cast::<u8>());
assert!(!moved, "an attribute-held group denies the move, so the promote parks a header of its own");
transient.reset();
let served = promoted_paint(&span, &layout, 0, &persistent);
let held = served.attribute::<Option<List<Graphic>>>(Stroke::NAME, 0).expect("the stroke attribute rides the promoted list");
let held = held.as_ref().expect("the stroke is present");
assert_eq!(
map_groups_to_legacy(held.element(0).unwrap()),
expected,
"the attribute-held group serves from persistent storage after the reset"
);
}
#[test]
fn a_group_free_paint_field_moves_past_its_attribute_columns() {
let mut transient = core_types::arena::Arena::new(1 << 16).unwrap();
let persistent = core_types::arena::Arena::new(1 << 16).unwrap();
let mut paint = List::new_from_element(Graphic::Vector(unit_square_at(DVec2::ZERO)));
// Columns of a type that cannot hold groups, and a group-capable column
// whose value holds none: neither denies the move.
paint.set_attribute::<f64>("opacity", 0, 0.5);
paint.set_attribute::<Color>("probe:color", 0, Color::BLACK);
paint.set_attribute::<Option<List<Graphic>>>(Stroke::NAME, 0, Some(List::new_from_element(Graphic::Color(Color::WHITE))));
let heap = {
let Some(Graphic::Vector(vector)) = paint.element(0) else { panic!("the paint carries a vector") };
vector.point_domain.positions().as_ptr()
};
let (paint, _) = transient.alloc_sized_keyed(paint, 0).unwrap();
let (layout, span, _frames) = promote_paint_field(Some(paint), 1, &transient, &persistent);
let served = promoted_paint(&span, &layout, 0, &persistent);
let Some(Graphic::Vector(vector)) = served.element(0) else {
panic!("the promote keeps the vector")
};
assert_eq!(
vector.point_domain.positions().as_ptr(),
heap,
"the promote moved the header, so the served paint names the pre-promote heap"
);
transient.reset();
let served = promoted_paint(&span, &layout, 0, &persistent);
assert!(matches!(served.element(0), Some(Graphic::Vector(_))), "the moved paint survives the transient reset");
}
#[test]
fn an_owned_record_deep_copies_attribute_held_groups() {
let inner_vector = unit_square_at(DVec2::ZERO);
let source = core_types::arena::Arena::new(1 << 16).unwrap();
let native = native_group_paint(&inner_vector, &source);
let expected = map_groups_to_legacy(native.element(0).unwrap());
// The field's elements are group-free; the group rides an item attribute,
// which the shallow read alone would leave borrowing `source`.
let mut paint = List::new_from_element(Graphic::Vector(unit_square_at(DVec2::new(2., 2.))));
// SAFETY: the erased native list serves only while `source` is live; the
// deep glue under test replaces its borrows at the copy-out seam.
paint.set_attribute::<Option<List<Graphic>>>(Stroke::NAME, 0, Some(unsafe { core_types::record::erase_static(native) }));
let vector = unit_square_at(DVec2::new(4., 4.));
let mut builder = RunBuilder::new(&source, element_write_hashed::<Vector>(), &[FieldWrite::of::<Fill>(0)], 1).unwrap();
let lane = builder.push(vector.clone()).unwrap();
builder.attr::<Fill>(lane, Some(&paint));
let item = builder.finish();
let layout = item.layout().clone();
let offset = layout.offset_of(Fill::NAME, 0).unwrap();
// SAFETY: the item's lane is a live record of `layout`.
let owned = unsafe { core_types::record::OwnedRecord::copy_out(&layout, item.lanes().get(0).rec()) };
drop(item);
drop(paint);
drop(source);
let arena = core_types::arena::Arena::new(1 << 16).unwrap();
let frames = core_types::record::test_frames(layout.frame_bytes());
let mut slot = frames.claim(&layout);
owned.replay_into(&mut slot, &arena).expect("the arena holds the replay");
// SAFETY: the replay completes the record in the claimed frame.
let value = unsafe { slot.finish() };
// SAFETY: the replay wrote a record of `layout`.
let served = unsafe { layout.rec(&value).read::<Option<&List<Graphic>>>(offset) }.expect("the fill replays present");
let held = served.attribute::<Option<List<Graphic>>>(Stroke::NAME, 0).expect("the stroke attribute rides the replayed list");
let held = held.as_ref().expect("the stroke is present");
assert_eq!(map_groups_to_legacy(held.element(0).unwrap()), expected, "the attribute-held group replayed into the serving arena");
}
}
@@ -0,0 +1,161 @@
//! The legacy bridge: record-backed groups rebuilt as owned legacy lists.
use super::walk::push_lane_paint_into_interiors;
use super::{Graphic, detable_items};
use crate::markers::{ATTR_FILL, ATTR_STROKE};
use core_types::Color;
use core_types::list::{AttributeValueDyn, Item, List};
use raster_types::{CPU, GPU, Raster};
use vector_types::{Gradient, Vector};
/// One typed run as an owned list, elements cloned and every attribute copied
/// through its erased read. Content keeps its native form; the legacy
/// conversions layer their mapping on top.
pub fn run_to_list<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(item: &core_types::record::GroupItem) -> Option<List<T>> {
let lanes = item.typed_lanes::<T>()?;
let mut list = List::new();
for lane in 0..lanes.len() {
list.push(Item::new_from_element(lanes.element_ref(lane).clone()));
}
for field in &item.layout().fields {
for lane in 0..lanes.len() {
// SAFETY: the offset comes from the item's own layout.
let value = unsafe { (field.read_erased)(item.lanes().get(lane).rec().ptr().add(field.offset)) };
list.set_attribute_value_dyn(field.name, lane, AttributeValueDyn(value));
}
}
Some(list)
}
/// Converts the group content of the list's paint attribute values to legacy
/// form, so a legacy product owns everything its attributes reach.
pub fn map_paint_attrs_to_legacy<T>(list: &mut List<T>) {
for key in [ATTR_FILL, ATTR_STROKE, crate::markers::ATTR_EDITOR_MERGED_LAYERS] {
let Some(values) = list.iter_attribute_values_mut::<Option<List<Graphic>>>(key) else { continue };
for value in values.flatten() {
for element in value.iter_element_values_mut() {
*element = map_groups_to_legacy(element);
}
}
}
}
/// One typed run as a legacy list: [`run_to_list`] with the paint attribute
/// contents converted to their legacy form.
pub(crate) fn run_to_legacy_list<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(item: &core_types::record::GroupItem) -> Option<List<T>> {
let mut list = run_to_list::<T>(item)?;
map_paint_attrs_to_legacy(&mut list);
Some(list)
}
/// The graphic with every `Group` converted to its legacy form.
pub fn map_groups_to_legacy<'out>(graphic: &Graphic<'_>) -> Graphic<'out> {
match graphic {
Graphic::Group(group) => group_to_legacy_graphic(group),
Graphic::GraphicList(children) => {
let mut out = List::new();
for item in children.clone().into_iter() {
let (element, attributes) = item.into_parts();
out.push(Item::from_parts(map_groups_to_legacy(&element), attributes));
}
map_paint_attrs_to_legacy(&mut out);
Graphic::GraphicList(out)
}
Graphic::Stroke(stroke) => Graphic::Stroke(stroke.clone()),
Graphic::StrokeList(strokes) => Graphic::StrokeList(strokes.clone()),
Graphic::Vector(vector) => Graphic::Vector(vector.clone()),
Graphic::RasterCPU(raster) => Graphic::RasterCPU(raster.clone()),
Graphic::RasterGPU(raster) => Graphic::RasterGPU(raster.clone()),
Graphic::Color(color) => Graphic::Color(*color),
Graphic::Gradient(gradient) => Graphic::Gradient(gradient.clone()),
Graphic::Text(text) => Graphic::Text(text.clone()),
}
}
/// The group as one legacy graphic. A bare (row-less) wrap of a single typed
/// run keeps the run's typed variant, matching the `Into<Graphic>` the
/// pre-flip wrap applied; everything else becomes the legacy group list.
pub fn group_to_legacy_graphic(group: &core_types::record::Group) -> Graphic<'static> {
if group.row.is_none() {
let item = &group.content;
let typed = None
.or_else(|| run_to_legacy_list::<Vector>(item).map(|list| detable_items(list, Graphic::Vector)))
.or_else(|| run_to_legacy_list::<Raster<CPU>>(item).map(|list| detable_items(list, Graphic::RasterCPU)))
.or_else(|| run_to_legacy_list::<Raster<GPU>>(item).map(|list| detable_items(list, Graphic::RasterGPU)))
.or_else(|| run_to_legacy_list::<Color>(item).map(|list| detable_items(list, Graphic::Color)))
.or_else(|| run_to_legacy_list::<Gradient>(item).map(|list| detable_items(list, Graphic::Gradient)))
.or_else(|| run_to_legacy_list::<String>(item).map(|list| detable_items(list, Graphic::Text)));
if let Some(typed) = typed {
return Graphic::GraphicList(typed);
}
}
Graphic::GraphicList(group_to_legacy_list(group))
}
/// The group as a legacy `List<Graphic>`: a `Graphic` run becomes the items,
/// another typed run becomes one de-tabled leaf item per lane.
pub fn group_to_legacy_list(group: &core_types::record::Group) -> List<Graphic<'static>> {
let item = &group.content;
if let Some(mut list) = run_to_legacy_list::<Graphic>(item) {
for element in list.iter_element_values_mut() {
*element = map_groups_to_legacy(element);
}
push_lane_paint_into_interiors(&mut list);
return list;
}
None.or_else(|| run_to_legacy_list::<Vector>(item).map(|list| detable_items(list, Graphic::Vector)))
.or_else(|| run_to_legacy_list::<Raster<CPU>>(item).map(|list| detable_items(list, Graphic::RasterCPU)))
.or_else(|| run_to_legacy_list::<Raster<GPU>>(item).map(|list| detable_items(list, Graphic::RasterGPU)))
.or_else(|| run_to_legacy_list::<Color>(item).map(|list| detable_items(list, Graphic::Color)))
.or_else(|| run_to_legacy_list::<Gradient>(item).map(|list| detable_items(list, Graphic::Gradient)))
.or_else(|| run_to_legacy_list::<String>(item).map(|list| detable_items(list, Graphic::Text)))
.unwrap_or_default()
}
#[cfg(test)]
mod run_tests {
use super::*;
use crate::graphic::test_support::{native_group_paint, unit_square_at};
use crate::markers::Fill;
use core_types::attribute::Attribute;
use core_types::record::{FieldWrite, RunBuilder, element_write_hashed};
use glam::DVec2;
#[test]
fn a_legacy_list_owns_its_paint_attr_content() {
let inner_vector = unit_square_at(DVec2::ZERO);
let source = core_types::arena::Arena::new(1 << 16).unwrap();
// SAFETY: the erased native list serves only while `source` is live; the
// deep glue under test replaces its borrows at the copy-out seam.
let paint = unsafe { core_types::record::erase_static(native_group_paint(&inner_vector, &source)) };
let vector = unit_square_at(DVec2::new(4., 4.));
let mut builder = RunBuilder::new(&source, element_write_hashed::<Vector>(), &[FieldWrite::of::<Fill>(0)], 1).unwrap();
let lane = builder.push(vector.clone()).unwrap();
builder.attr::<Fill>(lane, Some(&paint));
let item = builder.finish();
let legacy = run_to_legacy_list::<Vector>(&item).expect("the run lowers to a legacy vector list");
let expected = map_groups_to_legacy(paint.element(0).unwrap());
drop(item);
drop(paint);
drop(source);
let served = legacy.attribute::<Option<List<Graphic>>>(Fill::NAME, 0).expect("the fill attribute rides the list");
let served = served.as_ref().expect("the fill is present");
assert_eq!(served.element(0).unwrap(), &expected);
}
#[test]
fn a_run_list_keeps_native_group_elements() {
let inner_vector = unit_square_at(DVec2::ZERO);
let arena = core_types::arena::Arena::new(1 << 16).unwrap();
let content = native_group_paint(&inner_vector, &arena);
let element = content.element(0).unwrap();
let mut builder = RunBuilder::new(&arena, element_write_hashed::<Graphic>(), &[], 1).unwrap();
builder.push(element.clone()).unwrap();
let item = builder.finish();
let list = run_to_list::<Graphic>(&item).expect("the run holds graphic lanes");
assert!(matches!(list.element(0), Some(Graphic::Group(_))), "the list keeps the native group form");
}
}
@@ -0,0 +1,775 @@
mod glue;
mod legacy;
mod paint;
mod walk;
pub(crate) use glue::{list_contains_groups, map_attribute_groups_to_owned, map_attribute_groups_to_persistent, map_attribute_groups_to_resident};
pub use glue::{map_groups_to_owned, map_groups_to_persistent, map_groups_to_resident};
pub(crate) use legacy::run_to_legacy_list;
pub use legacy::{group_to_legacy_graphic, group_to_legacy_list, map_groups_to_legacy, map_paint_attrs_to_legacy, run_to_list};
pub use paint::{
LanePaint, PaintColumns, PaintOverlay, PaintOverlayColumn, PaintReach, bake_paint_transforms, has_paint, is_paint_present, paint_graphics, set_paint_attribute, set_paint_attribute_at,
vector_can_reduce_to_clip_path,
};
pub use walk::{GraphicLevel, GraphicLevelColumn, RowStep, VectorRow, direct_vector_len, flatten_vector_rows, group_is_empty, lane_attributes, run_lane_attributes, walk_vector_rows};
use walk::{group_all_clipped, group_bounding_box, group_is_fully_transparent, group_is_opaque, group_render_complexity};
use brush_types::Stroke;
use core_types::bounds::{BoundingBox, RenderBoundingBox};
use core_types::graphene_hash::CacheHash;
use core_types::list::{Item, List};
use core_types::ops::{FromAnchorPosition, ListConvert};
use core_types::render_complexity::RenderComplexity;
use core_types::uuid::NodeId;
use core_types::{ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color};
use dyn_any::DynAny;
use glam::{DAffine2, DVec2};
use raster_types::{CPU, GPU, Raster};
use vector_types::Gradient;
pub use vector_types::Vector;
/// The possible forms of graphical content that can be rendered by the Render node into either an image or SVG syntax.
/// A leaf holds its element directly; its attributes ride the containing
/// lane. Multi-element content is a [`core_types::record::Group`] run, or
/// transitionally the legacy `Graphic` list.
#[derive(Clone, Debug, CacheHash, PartialEq, DynAny)]
pub enum Graphic<'e> {
GraphicList(List<Graphic<'e>>),
Vector(Vector),
RasterCPU(Raster<CPU>),
RasterGPU(Raster<GPU>),
Color(Color),
Gradient(Gradient),
Text(String),
Stroke(Stroke),
/// Transitional typed list, kept because master's brush nodes match on it directly.
StrokeList(List<Stroke>),
Group(core_types::record::Group<'e>),
}
impl Default for Graphic<'_> {
fn default() -> Self {
Self::GraphicList(List::new())
}
}
/// A typed legacy list as a legacy graphic list: each item de-tables to a
/// leaf element, keeping its attributes on the containing lane.
pub(in crate::graphic) fn detable_items<'e, T: Clone + Send + Sync + 'static>(list: List<T>, leaf: fn(T) -> Graphic<'e>) -> List<Graphic<'e>> {
let mut out = List::new();
for item in list.into_iter() {
let (element, attributes) = item.into_parts();
out.push(Item::from_parts(leaf(element), attributes));
}
out
}
/// The element-space coercion into `Graphic`: a leaf converts in place and a
/// legacy list becomes a native group built over the arena, so the coercion
/// never constructs a legacy interior.
pub trait IntoGraphicElement: Clone + Send + Sync + CacheHash + 'static {
/// `None` reports arena exhaustion.
fn into_graphic_element(self, arena: &core_types::arena::Arena) -> Option<Graphic<'_>>;
}
fn list_group<T: Clone + Send + Sync + CacheHash + PartialEq + dyn_any::StaticTypeSized>(list: List<T>, arena: &core_types::arena::Arena) -> Option<Graphic<'_>>
where
T::Static: Clone + Send + Sync,
{
Some(Graphic::Group(core_types::record::Group {
row: None,
content: core_types::record::GroupItem::from_list(list, arena)?,
}))
}
macro_rules! into_graphic_element {
($($leaf:ident: $element:ty;)*) => {
$(
impl IntoGraphicElement for $element {
fn into_graphic_element(self, _arena: &core_types::arena::Arena) -> Option<Graphic<'_>> {
Some(Graphic::$leaf(self))
}
}
impl IntoGraphicElement for List<$element> {
fn into_graphic_element(self, arena: &core_types::arena::Arena) -> Option<Graphic<'_>> {
list_group(self, arena)
}
}
)*
};
}
into_graphic_element! {
Vector: Vector;
RasterCPU: Raster<CPU>;
RasterGPU: Raster<GPU>;
Color: Color;
Gradient: Gradient;
Text: String;
Stroke: Stroke;
}
impl IntoGraphicElement for Graphic<'static> {
fn into_graphic_element(self, _arena: &core_types::arena::Arena) -> Option<Graphic<'_>> {
Some(self)
}
}
impl IntoGraphicElement for List<Graphic<'static>> {
fn into_graphic_element(self, arena: &core_types::arena::Arena) -> Option<Graphic<'_>> {
list_group(self, arena)
}
}
// Vector
impl From<Vector> for Graphic<'_> {
fn from(vector: Vector) -> Self {
Graphic::Vector(vector)
}
}
// Raster<CPU>
impl From<Raster<CPU>> for Graphic<'_> {
fn from(raster: Raster<CPU>) -> Self {
Graphic::RasterCPU(raster)
}
}
// Raster<GPU>
impl From<Raster<GPU>> for Graphic<'_> {
fn from(raster: Raster<GPU>) -> Self {
Graphic::RasterGPU(raster)
}
}
// Color
impl From<Color> for Graphic<'_> {
fn from(color: Color) -> Self {
Graphic::Color(color)
}
}
// Note: List<Color> -> Option<Color> is in gcore (Color is defined there)
// Gradient
impl From<Gradient> for Graphic<'_> {
fn from(gradient: Gradient) -> Self {
Graphic::Gradient(gradient)
}
}
// String
impl From<String> for Graphic<'_> {
fn from(text: String) -> Self {
Graphic::Text(text)
}
}
// Stroke
impl From<Stroke> for Graphic<'_> {
fn from(stroke: Stroke) -> Self {
Graphic::Stroke(stroke)
}
}
impl From<List<Stroke>> for Graphic<'_> {
fn from(strokes: List<Stroke>) -> Self {
Graphic::StrokeList(strokes)
}
}
/// Whether the list is a single bare leaf carrying no attribute of its own, so
/// wrapping it collapses no structure and rebuilding it would be busywork.
/// Master reads one `appearance` here; our paint is still the fill and stroke pair.
pub fn is_lone_anonymous_leaf(content: &List<Graphic>) -> bool {
content.len() == 1
&& !matches!(content.element(0), Some(Graphic::GraphicList(_)))
&& content.attribute::<DAffine2>(ATTR_TRANSFORM, 0).is_none()
&& content.attribute::<f64>(ATTR_OPACITY, 0).is_none()
&& content.attribute::<f64>(ATTR_OPACITY_FILL, 0).is_none()
&& content.attribute::<List<Graphic>>(crate::markers::ATTR_FILL, 0).is_none()
&& content.attribute::<List<Graphic>>(crate::markers::ATTR_STROKE, 0).is_none()
&& content.attribute::<Vec<NodeId>>(ATTR_EDITOR_LAYER_PATH, 0).is_none()
}
/// Deeply flattens a `List<Graphic>`, collecting only elements matching a specific variant (extracted by `extract_variant`)
/// and discarding all other non-matching content. Recursion through `Graphic::Graphic` sub-`List`s composes transforms and opacity.
fn flatten_graphic_list<T>(content: List<Graphic>, extract_variant: fn(Graphic) -> Option<List<T>>) -> List<T> {
fn flatten_recursive<T>(output: &mut List<T>, current_graphic_list: List<Graphic>, extract_variant: fn(Graphic) -> Option<List<T>>, parent_layer_path: Option<&[NodeId]>) {
for current_graphic_item in current_graphic_list.into_iter() {
// Whether the parent carries each attribute: a structural fact (column presence), never a value comparison.
// Flattening composes a parent attribute onto its children only when the parent has it,
// so an absent parent attribute never invents a column the children didn't already have.
let parent_has_transform = current_graphic_item.attribute::<DAffine2>(ATTR_TRANSFORM).is_some();
let parent_has_opacity = current_graphic_item.attribute::<f64>(ATTR_OPACITY).is_some();
let parent_has_fill = current_graphic_item.attribute::<f64>(ATTR_OPACITY_FILL).is_some();
let current_transform: DAffine2 = current_graphic_item.attribute_cloned_or_default(ATTR_TRANSFORM);
let current_opacity: f64 = current_graphic_item.attribute_cloned_or(ATTR_OPACITY, 1.);
let current_fill: f64 = current_graphic_item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.);
let lane_layer_path: Option<Vec<NodeId>> = current_graphic_item.attribute::<Vec<NodeId>>(ATTR_EDITOR_LAYER_PATH).cloned();
let (element, attributes) = current_graphic_item.into_parts();
match element {
// Compose the parent's transform/opacity/fill onto each child, but only for attributes the parent carries.
// A child lacking one is padded with the composition identity (`1.` for opacity/fill, identity for transform), so composing through it is a no-op.
Graphic::GraphicList(mut sub_list) => {
if parent_has_transform {
for v in sub_list.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM) {
*v = current_transform * *v;
}
}
if parent_has_opacity {
for v in sub_list.iter_attribute_values_mut_or_default::<f64>(ATTR_OPACITY) {
*v *= current_opacity;
}
}
if parent_has_fill {
for v in sub_list.iter_attribute_values_mut_or_default::<f64>(ATTR_OPACITY_FILL) {
*v *= current_fill;
}
}
flatten_recursive(output, sub_list, extract_variant, lane_layer_path.as_deref());
}
// A bridge row's native group flattens through its legacy lowering.
Graphic::Group(group) => {
let lowered = List::new_from_item(Item::from_parts(group_to_legacy_graphic(&group), attributes.clone()));
flatten_recursive(output, lowered, extract_variant, parent_layer_path);
}
// A de-tabled leaf is one attr-less element; the extracted row rides with its containing lane's full attributes, paint included.
// The enclosing group lane's own layer path overrides, one hop only, matching the native walk.
other => {
if let Some(typed_list) = extract_variant(other) {
for item in typed_list.into_iter() {
let mut row = Item::from_parts(item.into_element(), attributes.clone());
if let Some(layer_path) = parent_layer_path {
row.set_attribute(ATTR_EDITOR_LAYER_PATH, layer_path.to_vec());
}
output.push(row);
}
}
}
}
}
}
let mut output = List::new();
flatten_recursive(&mut output, content, extract_variant, None);
output
}
/// Maps from a concrete element type to its corresponding `Graphic` enum variant,
/// enabling type-directed casting of typed `List`s from a `Graphic` value.
pub trait TryFromGraphic: Clone + Sized {
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>>;
}
impl TryFromGraphic for Vector {
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
if let Graphic::Vector(t) = graphic { Some(List::new_from_element(t)) } else { None }
}
}
impl TryFromGraphic for Raster<CPU> {
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
if let Graphic::RasterCPU(t) = graphic { Some(List::new_from_element(t)) } else { None }
}
}
impl TryFromGraphic for Color {
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
if let Graphic::Color(t) = graphic { Some(List::new_from_element(t)) } else { None }
}
}
impl TryFromGraphic for Gradient {
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
if let Graphic::Gradient(t) = graphic { Some(List::new_from_element(t)) } else { None }
}
}
impl TryFromGraphic for String {
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
if let Graphic::Text(t) = graphic { Some(List::new_from_element(t)) } else { None }
}
}
// Local trait to convert types to List<Graphic> (avoids orphan rule issues)
pub trait IntoGraphicList: Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash + 'static {
fn into_graphic_list(self) -> List<Graphic<'static>>;
/// Deeply flattens any content of type `T` within a `List<Graphic>`, discarding all other content, and returning a flat `List<T>`.
fn into_flattened_list<T: TryFromGraphic>(self) -> List<T>
where
Self: std::marker::Sized,
{
flatten_graphic_list(self.into_graphic_list(), T::try_from_graphic)
}
}
impl IntoGraphicList for List<Graphic<'static>> {
fn into_graphic_list(self) -> List<Graphic<'static>> {
self
}
}
impl IntoGraphicList for List<Vector> {
fn into_graphic_list(self) -> List<Graphic<'static>> {
detable_items(self, Graphic::Vector)
}
}
impl IntoGraphicList for List<Raster<CPU>> {
fn into_graphic_list(self) -> List<Graphic<'static>> {
detable_items(self, Graphic::RasterCPU)
}
}
impl IntoGraphicList for List<Raster<GPU>> {
fn into_graphic_list(self) -> List<Graphic<'static>> {
detable_items(self, Graphic::RasterGPU)
}
}
impl IntoGraphicList for List<Color> {
fn into_graphic_list(self) -> List<Graphic<'static>> {
detable_items(self, Graphic::Color)
}
}
impl IntoGraphicList for List<Gradient> {
fn into_graphic_list(self) -> List<Graphic<'static>> {
detable_items(self, Graphic::Gradient)
}
}
impl IntoGraphicList for List<String> {
fn into_graphic_list(self) -> List<Graphic<'static>> {
detable_items(self, Graphic::Text)
}
}
impl IntoGraphicList for DAffine2 {
fn into_graphic_list(self) -> List<Graphic<'static>> {
List::new_from_element(Graphic::default())
}
}
// DAffine2
impl From<DAffine2> for Graphic<'_> {
fn from(_: DAffine2) -> Self {
Graphic::default()
}
}
// DVec2
impl From<DVec2> for Graphic<'_> {
fn from(position: DVec2) -> Self {
Graphic::Vector(Vector::from_anchor_position(position))
}
}
// Note: List conversions handled by blanket impl in gcore
impl<'e> Graphic<'e> {
pub fn as_graphic_list(&self) -> Option<&List<Graphic<'_>>> {
match self {
Graphic::GraphicList(graphic) => Some(graphic),
_ => None,
}
}
pub fn as_graphic_list_mut(&mut self) -> Option<&mut List<Graphic<'e>>> {
match self {
Graphic::GraphicList(graphic) => Some(graphic),
_ => None,
}
}
pub fn as_vector(&self) -> Option<&Vector> {
match self {
Graphic::Vector(vector) => Some(vector),
_ => None,
}
}
pub fn as_raster(&self) -> Option<&Raster<CPU>> {
match self {
Graphic::RasterCPU(raster) => Some(raster),
_ => None,
}
}
pub fn as_raster_mut(&mut self) -> Option<&mut Raster<CPU>> {
match self {
Graphic::RasterCPU(raster) => Some(raster),
_ => None,
}
}
/// A leaf carries no clipping attribute, which rides its containing lane.
pub fn had_clip_enabled(&self) -> bool {
fn all_clipped<T>(list: &List<T>) -> bool {
list.iter_attribute_values_or_default::<bool>(ATTR_CLIPPING_MASK).all(|clip| clip)
}
match self {
Graphic::GraphicList(list) => all_clipped(list),
Graphic::Group(group) => group_all_clipped(group),
_ => false,
}
}
pub fn can_reduce_to_clip_path(&self) -> bool {
match self {
Graphic::Vector(vector) => vector_can_reduce_to_clip_path(&core_types::lane::Single(vector)),
_ => false,
}
}
pub fn is_guaranteed_fully_opaque(&self) -> bool {
match self {
Graphic::GraphicList(list) => !list.is_empty() && list.iter_element_values().all(Graphic::is_guaranteed_fully_opaque),
// A bare leaf carries no paint attribute, which rides its lane, so
// nothing here claims opacity.
Graphic::Vector(_) => false,
Graphic::Color(color) => color.is_opaque(),
Graphic::Gradient(gradient) => !gradient.is_empty() && gradient.iter().all(|stop| stop.color.is_opaque()),
Graphic::RasterCPU(_) | Graphic::RasterGPU(_) | Graphic::Text(_) | Graphic::Stroke(_) | Graphic::StrokeList(_) => false,
Graphic::Group(group) => group_is_opaque(group),
}
}
pub fn is_guaranteed_fully_transparent(&self) -> bool {
match self {
Graphic::GraphicList(list) => list.iter_element_values().all(Graphic::is_guaranteed_fully_transparent),
// A bare leaf carries no paint attribute, which rides its lane, so
// nothing here can prove invisibility.
Graphic::Vector(_) => false,
Graphic::Color(color) => color.a() == 0.,
// A stopless ramp paints solid black, so it counts as transparent only once it has stops.
Graphic::Gradient(gradient) => !gradient.is_empty() && gradient.iter().all(|stop| stop.color.a() == 0.),
Graphic::RasterCPU(_) | Graphic::RasterGPU(_) | Graphic::Text(_) | Graphic::Stroke(_) | Graphic::StrokeList(_) => false,
Graphic::Group(group) => group_is_fully_transparent(group),
}
}
/// True if this paint opaquely covers the entire fill region.
/// Vector, Raster, and a nested Graphic may leave gaps, so they return false.
pub fn is_guaranteed_to_cover_opaquely(&self) -> bool {
matches!(self, Graphic::Color(_) | Graphic::Gradient(_)) && self.is_guaranteed_fully_opaque()
}
/// Whether the graphic holds no content: a leaf always holds its element.
pub fn is_empty(&self) -> bool {
match self {
Graphic::GraphicList(list) => list.is_empty(),
Graphic::Group(group) => group_is_empty(group),
_ => false,
}
}
}
impl BoundingBox for Graphic<'_> {
fn bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
match self {
Graphic::Vector(vector) => BoundingBox::bounding_box(vector, transform, include_stroke),
Graphic::RasterCPU(raster) => raster.bounding_box(transform, include_stroke),
Graphic::RasterGPU(raster) => raster.bounding_box(transform, include_stroke),
Graphic::GraphicList(list) => list.bounding_box(transform, include_stroke),
Graphic::Color(color) => color.bounding_box(transform, include_stroke),
Graphic::Gradient(gradient) => gradient.bounding_box(transform, include_stroke),
Graphic::Text(text) => text.bounding_box(transform, include_stroke),
// Brush strokes carry no vector outline; a brush node renders them to rasters.
Graphic::Stroke(_) | Graphic::StrokeList(_) => RenderBoundingBox::None,
Graphic::Group(group) => group_bounding_box(group, transform, include_stroke, false),
}
}
fn thumbnail_bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
match self {
Graphic::Vector(vector) => vector.thumbnail_bounding_box(transform, include_stroke),
Graphic::RasterCPU(raster) => raster.thumbnail_bounding_box(transform, include_stroke),
Graphic::RasterGPU(raster) => raster.thumbnail_bounding_box(transform, include_stroke),
Graphic::GraphicList(graphic) => graphic.thumbnail_bounding_box(transform, include_stroke),
Graphic::Color(color) => color.thumbnail_bounding_box(transform, include_stroke),
Graphic::Gradient(gradient) => gradient.thumbnail_bounding_box(transform, include_stroke),
Graphic::Text(list) => list.thumbnail_bounding_box(transform, include_stroke),
Graphic::Stroke(_) | Graphic::StrokeList(_) => RenderBoundingBox::None,
Graphic::Group(group) => group_bounding_box(group, transform, include_stroke, true),
}
}
}
impl<'e> ListConvert<Graphic<'e>> for Vector {
fn convert_item(self) -> Graphic<'e> {
Graphic::Vector(self)
}
}
impl<'e> ListConvert<Graphic<'e>> for Raster<CPU> {
fn convert_item(self) -> Graphic<'e> {
Graphic::RasterCPU(self)
}
}
impl<'e> ListConvert<Graphic<'e>> for Raster<GPU> {
fn convert_item(self) -> Graphic<'e> {
Graphic::RasterGPU(self)
}
}
// A leveled paint input types by its element, so the same embedding is needed one rank down.
macro_rules! convert_leaf_to_graphic {
($($element:ty),* $(,)?) => {
$(
impl<'e> core_types::ops::Convert<Graphic<'e>, ()> for $element {
fn convert(self, _: core_types::transform::Footprint, _: ()) -> Graphic<'e> {
core_types::ops::ListConvert::convert_item(self)
}
}
)*
};
}
convert_leaf_to_graphic!(Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String, Stroke);
// The paint wires accept any leaf element, the role master's `From<X> for Graphic` embedding adapters play.
impl<'e> ListConvert<Graphic<'e>> for Graphic<'e> {
fn convert_item(self) -> Graphic<'e> {
self
}
}
impl<'e> ListConvert<Graphic<'e>> for Color {
fn convert_item(self) -> Graphic<'e> {
Graphic::Color(self)
}
}
impl<'e> ListConvert<Graphic<'e>> for Gradient {
fn convert_item(self) -> Graphic<'e> {
Graphic::Gradient(self)
}
}
impl<'e> ListConvert<Graphic<'e>> for String {
fn convert_item(self) -> Graphic<'e> {
Graphic::Text(self)
}
}
impl<'e> ListConvert<Graphic<'e>> for Stroke {
fn convert_item(self) -> Graphic<'e> {
Graphic::Stroke(self)
}
}
impl RenderComplexity for Graphic<'_> {
fn render_complexity(&self) -> usize {
match self {
Self::GraphicList(list) => list.render_complexity(),
Self::Vector(list) => list.render_complexity(),
Self::RasterCPU(list) => list.render_complexity(),
Self::RasterGPU(list) => list.render_complexity(),
Self::Color(list) => list.render_complexity(),
Self::Gradient(list) => list.render_complexity(),
Self::Text(list) => list.render_complexity(),
Self::Stroke(stroke) => stroke.position.len(),
Self::StrokeList(strokes) => (0..strokes.len()).filter_map(|index| strokes.element(index)).map(|stroke| stroke.position.len()).sum(),
Self::Group(group) => group_render_complexity(group),
}
}
}
// Node definitions moved to graphic-nodes crate
pub trait AtIndex {
type Output;
fn at_index(&self, index: usize) -> Option<Self::Output>;
fn at_index_from_end(&self, index: usize) -> Option<Self::Output>;
}
impl<T: Clone> AtIndex for Vec<T> {
type Output = T;
fn at_index(&self, index: usize) -> Option<Self::Output> {
self.get(index).cloned()
}
fn at_index_from_end(&self, index: usize) -> Option<Self::Output> {
if index == 0 || index > self.len() { None } else { self.get(self.len() - index).cloned() }
}
}
impl<T: Clone> AtIndex for List<T> {
type Output = List<T>;
fn at_index(&self, index: usize) -> Option<Self::Output> {
self.clone_item(index).map(|item| {
let mut result_list = Self::default();
result_list.push(item);
result_list
})
}
fn at_index_from_end(&self, index: usize) -> Option<Self::Output> {
if index == 0 || index > self.len() { None } else { self.at_index(self.len() - index) }
}
}
pub trait OmitIndex {
fn omit_index(&self, index: usize) -> Self;
fn omit_index_from_end(&self, index: usize) -> Self;
}
impl<T: Clone> OmitIndex for Vec<T> {
fn omit_index(&self, index: usize) -> Self {
self.iter().enumerate().filter(|(i, _)| *i != index).map(|(_, v)| v.clone()).collect()
}
fn omit_index_from_end(&self, index: usize) -> Self {
if index == 0 || index > self.len() {
return self.clone();
}
self.omit_index(self.len() - index)
}
}
impl<T: Clone> OmitIndex for List<T> {
fn omit_index(&self, index: usize) -> Self {
let mut result = Self::default();
for i in 0..self.len() {
if i != index
&& let Some(item) = self.clone_item(i)
{
result.push(item);
}
}
result
}
fn omit_index_from_end(&self, index: usize) -> Self {
if index == 0 || index > self.len() {
return self.clone();
}
self.omit_index(self.len() - index)
}
}
#[cfg(test)]
mod tests {
use super::*;
use core_types::list::List;
fn vector_graphic() -> Graphic<'static> {
Graphic::Vector(Vector::default())
}
// Flattening must not invent attribute columns that neither the parent graphic nor the child carried
#[test]
fn flatten_does_not_invent_attributes() {
let graphics = List::new_from_element(vector_graphic());
let flattened: List<Vector> = graphics.into_flattened_list();
for key in [ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, ATTR_EDITOR_LAYER_PATH] {
assert!(!flattened.attribute_keys().any(|k| k == key), "flatten invented the `{key}` attribute");
}
}
// A parent attribute that is present must compose onto the flattened children
#[test]
fn flatten_propagates_present_attributes() {
let mut graphics = List::new_from_element(vector_graphic());
graphics.set_attribute(ATTR_OPACITY, 0, 0.5_f64);
let flattened: List<Vector> = graphics.into_flattened_list();
assert_eq!(flattened.attribute_cloned_or_default::<f64>(ATTR_OPACITY, 0), 0.5);
let mut group = List::new_from_element(Graphic::GraphicList(List::new_from_element(vector_graphic())));
group.set_attribute(ATTR_OPACITY, 0, 0.5_f64);
let flattened: List<Vector> = group.into_flattened_list();
assert_eq!(flattened.attribute_cloned_or_default::<f64>(ATTR_OPACITY, 0), 0.5);
}
}
#[cfg(test)]
mod graphic_is_opaque_tests {
use vector_types::GradientStop;
use super::*;
fn color_graphic(alpha: f64) -> Graphic<'static> {
let color = Color::from_rgbaf32(1., 0., 0., alpha as f32).unwrap();
Graphic::Color(color)
}
fn gradient_graphic(gradient: Gradient) -> Graphic<'static> {
Graphic::Gradient(gradient)
}
#[test]
fn opaque_color_is_opaque() {
let g = color_graphic(1.);
assert!(g.is_guaranteed_fully_opaque());
}
#[test]
fn transparent_color_is_not_opaque() {
let g = color_graphic(0.5);
assert!(!g.is_guaranteed_fully_opaque());
}
#[test]
fn vector_is_not_opaque() {
let g = Graphic::Vector(Vector::default());
assert!(!g.is_guaranteed_fully_opaque());
}
#[test]
fn gradient_with_all_opaque_stops_is_opaque() {
let color_1 = Color::from_rgbaf32(1., 0., 0., 1.).unwrap();
let color_2 = Color::from_rgbaf32(1., 0., 0., 1.).unwrap();
let gradient = Gradient::new(vec![
GradientStop {
position: 0.,
midpoint: 0.5,
color: color_1,
},
GradientStop {
position: 1.,
midpoint: 0.5,
color: color_2,
},
]);
let g = gradient_graphic(gradient);
assert!(g.is_guaranteed_fully_opaque());
}
#[test]
fn gradient_with_transparent_stop_is_not_opaque() {
let color_1 = Color::from_rgbaf32(1., 0., 0., 0.5).unwrap();
let color_2 = Color::from_rgbaf32(1., 0., 0., 1.).unwrap();
let gradient = Gradient::new(vec![
GradientStop {
position: 0.,
midpoint: 0.5,
color: color_1,
},
GradientStop {
position: 1.,
midpoint: 0.5,
color: color_2,
},
]);
let g = gradient_graphic(gradient);
assert!(!g.is_guaranteed_fully_opaque());
}
}
#[cfg(test)]
mod test_support {
use super::Graphic;
use core_types::list::List;
use core_types::record::{RunBuilder, element_write_hashed};
use glam::DVec2;
use vector_types::Vector;
use vector_types::vector::algorithms::shapes::rectangle_bezpath;
use vector_types::vector::PointId;
pub(in crate::graphic) fn unit_square_at(corner: DVec2) -> Vector {
Vector::from_bezpath(rectangle_bezpath(corner, corner + DVec2::ONE))
}
pub(in crate::graphic) fn native_group_paint<'a>(vector: &Vector, arena: &'a core_types::arena::Arena) -> List<Graphic<'a>> {
let mut builder = RunBuilder::new(arena, element_write_hashed::<Vector>(), &[], 1).unwrap();
builder.push(vector.clone()).unwrap();
List::new_from_element(Graphic::Group(core_types::record::Group { row: None, content: builder.finish() }))
}
}
@@ -0,0 +1,273 @@
//! The paint column level: fill and stroke read as lane columns and threaded down to the elements they reach.
use super::{Graphic, IntoGraphicList};
use crate::markers::{ATTR_FILL, ATTR_STROKE, Fill, Stroke};
use core_types::ATTR_TRANSFORM;
use core_types::attribute::{Attribute, Opacity};
use core_types::lane::{LaneColumn, LaneSource};
use core_types::list::{ItemAttributeValues, List};
use glam::DAffine2;
use vector_types::Vector;
/// Whether a normalized paint graphic list actually carries renderable paint.
/// A 0-item list, or a list whose first graphic is empty, is treated as no paint.
pub fn is_paint_present(graphic_list: &List<Graphic>) -> bool {
graphic_list.element(0).is_some_and(|graphic| !graphic.is_empty())
}
/// Look up the paint graphics stored under the marker `A`, in the canonical `List<Graphic>` form.
pub fn paint_graphics<'a, A, S>(source: &'a S, index: usize) -> Option<&'a List<Graphic<'static>>>
where
S: LaneSource,
A: Attribute<Value<'a> = Option<&'a List<Graphic<'static>>>>,
{
source
.attr::<A>(index)
// Treat a blank paint attribute as absent so an empty attribute doesn't count as painted
.filter(|graphic_list| is_paint_present(graphic_list))
}
/// Whether the item carries a non-blank canonical `List<Graphic>` paint under the marker `A`,
/// checked by borrowing without cloning the renderable list.
pub fn has_paint<'a, A, S>(source: &'a S, index: usize) -> bool
where
S: LaneSource,
A: Attribute<Value<'a> = Option<&'a List<Graphic<'static>>>>,
{
paint_graphics::<A, S>(source, index).is_some()
}
/// Whether every lane of a vector source draws as a plain clip path: fully
/// opaque, fill absent or opaque, stroke invisible or fully transparent.
pub fn vector_can_reduce_to_clip_path<S: LaneSource<Element = Vector>>(source: &S) -> bool {
(0..source.lane_count()).all(|index| {
let opacity: f64 = source.attr::<Opacity>(index);
let fill_opaque_or_absent = paint_graphics::<Fill, _>(source, index).is_none_or(|graphic_list| graphic_list.element(0).is_none_or(|graphic| graphic.is_guaranteed_fully_opaque()));
// The stroke weight rides the stroke paint list, the carrier that replaced the deleted `Vector::stroke` field.
let stroke_invisible_or_transparent = paint_graphics::<Stroke, _>(source, index).is_none_or(|graphic_list| {
graphic_list.attribute_cloned_or::<f64>(core_types::list::ATTR_WEIGHT, 0, 0.) <= 0. || graphic_list.element(0).is_none_or(|graphic| graphic.is_guaranteed_fully_transparent())
});
opacity > 1. - f64::EPSILON && fill_opaque_or_absent && stroke_invisible_or_transparent
})
}
/// The paint a lane carries for its interiors, in the reference form
/// [`PaintOverlay`] threads down.
#[derive(Clone, Copy, Default)]
pub struct LanePaint<'a> {
pub fill: Option<&'a List<Graphic<'static>>>,
pub stroke: Option<&'a List<Graphic<'static>>>,
}
impl<'a> LanePaint<'a> {
pub const NONE: Self = Self { fill: None, stroke: None };
pub fn is_present(&self) -> bool {
self.fill.is_some() || self.stroke.is_some()
}
}
/// A source's fill and stroke columns, resolved once for per-lane reads.
pub struct PaintColumns<'a, S: LaneSource + 'a> {
fill: S::Column<'a, Fill>,
stroke: S::Column<'a, Stroke>,
}
impl<'a, S: LaneSource> PaintColumns<'a, S> {
pub fn new(source: &'a S) -> Self {
Self {
fill: source.column::<Fill>(),
stroke: source.column::<Stroke>(),
}
}
/// The lane's present, non-blank paint.
pub fn read(&self, lane: usize) -> LanePaint<'a> {
let present = |value: Option<Option<&'a List<Graphic<'static>>>>| value.flatten().filter(|list| is_paint_present(list));
LanePaint {
fill: present(self.fill.try_get(lane)),
stroke: present(self.stroke.try_get(lane)),
}
}
}
/// How far a lane's paint reaches into the element beneath it, mirroring the
/// legacy conversion's paint push: vector interiors directly and vector
/// children of a nested graphic list, one level deep.
#[derive(Clone, Copy)]
pub struct PaintReach<'a> {
pub paint: LanePaint<'a>,
hops: u8,
}
impl<'a> PaintReach<'a> {
pub const NONE: Self = Self { paint: LanePaint::NONE, hops: 0 };
/// The lane's effective reach: an inherited paint stays authoritative
/// (lane paint below a push's origin is inert in the legacy model), an
/// absent one reads the lane's own paint.
pub fn for_lane<S: LaneSource>(self, columns: &PaintColumns<'a, S>, index: usize) -> Self {
match self.paint.is_present() {
true => self,
false => Self { paint: columns.read(index), hops: 2 },
}
}
pub fn applies(&self) -> bool {
self.hops > 0 && self.paint.is_present()
}
/// The reach one graphic nesting level further down.
pub fn nested(self) -> Self {
Self {
paint: self.paint,
hops: self.hops.saturating_sub(1),
}
}
/// The reach entering a group's own graphic run: a spent or absent reach
/// resets so the group's own lane paint applies at its own boundary.
pub fn into_group_graphics(self) -> Self {
match self.applies() {
true => self.nested(),
false => Self::NONE,
}
}
}
/// A source with a lane's paint forced over its fill and stroke columns,
/// reaching the interiors the legacy conversion's paint push reached.
pub struct PaintOverlay<'a, S> {
inner: &'a S,
paint: LanePaint<'a>,
}
impl<'a, S> PaintOverlay<'a, S> {
pub fn new(inner: &'a S, paint: LanePaint<'a>) -> Self {
Self { inner, paint }
}
}
pub struct PaintOverlayColumn<'a, S: LaneSource + 'a, A: Attribute> {
inner: S::Column<'a, A>,
forced: Option<A::Value<'a>>,
}
impl<'a, S: LaneSource, A: Attribute> LaneColumn<'a, A> for PaintOverlayColumn<'a, S, A> {
fn try_get(&self, lane: usize) -> Option<A::Value<'a>> {
match self.forced {
Some(forced) => Some(forced),
None => self.inner.try_get(lane),
}
}
}
/// The forced value for the marker `A`: the lane paint where `A` is this
/// crate's fill or stroke marker, absent otherwise.
fn forced_paint<'a, A: Attribute>(paint: LanePaint<'a>) -> Option<A::Value<'a>> {
let slot = match A::NAME {
name if name == Fill::NAME => paint.fill,
name if name == Stroke::NAME => paint.stroke,
_ => None,
}?;
assert_eq!(
std::any::TypeId::of::<A::Value<'static>>(),
std::any::TypeId::of::<Option<&'static List<Graphic<'static>>>>(),
"attribute `{}` is declared at another value type than this crate's paint form",
A::NAME
);
assert_eq!(
size_of::<A::Value<'a>>(),
size_of::<Option<&'a List<Graphic<'a>>>>(),
"the paint value form must span the marker's value"
);
// SAFETY: the census admits one value type per attribute name, so a `fill` or `stroke` marker carries this crate's `Option<&List<Graphic>>` at the asserted size.
Some(unsafe { std::mem::transmute_copy::<Option<&'a List<Graphic>>, A::Value<'a>>(&Some(slot)) })
}
impl<'a, S: LaneSource> LaneSource for PaintOverlay<'a, S> {
type Element = S::Element;
type Column<'b, A: Attribute>
= PaintOverlayColumn<'b, S, A>
where
Self: 'b;
fn lane_count(&self) -> usize {
self.inner.lane_count()
}
fn element(&self, lane: usize) -> Option<&S::Element> {
self.inner.element(lane)
}
fn column<A: Attribute>(&self) -> PaintOverlayColumn<'_, S, A> {
PaintOverlayColumn {
inner: self.inner.column::<A>(),
forced: forced_paint::<A>(self.paint),
}
}
}
/// Stores a paint attribute in the paint marker's owned form, the only representation paint readers accept.
pub fn set_paint_attribute(attributes: &mut ItemAttributeValues, key: &str, paint: impl IntoGraphicList) {
attributes.insert(key, Some(paint.into_graphic_list()));
}
/// Stores a paint attribute at a list index in the paint marker's owned form, the only representation paint readers accept.
pub fn set_paint_attribute_at<T>(list: &mut List<T>, index: usize, key: &str, paint: impl IntoGraphicList) {
list.set_attribute(key, index, Some(paint.into_graphic_list()));
}
/// Bake the provided transform into the per-item transforms of the paint graphics stored under the
/// canonical `List<Graphic>` fill and stroke attributes.
pub fn bake_paint_transforms(attributes: &mut ItemAttributeValues, transform: DAffine2) {
fn bake_graphic_paint_transform(graphics: &mut List<Graphic>, transform: DAffine2) {
for item_transform in graphics.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM) {
*item_transform = transform * *item_transform;
}
for graphic in graphics.iter_element_values_mut() {
if let Graphic::GraphicList(list) = graphic {
bake_graphic_paint_transform(list, transform);
}
}
}
for paint_key in [ATTR_FILL, ATTR_STROKE] {
if let Some(Some(graphics)) = attributes.get_mut::<Option<List<Graphic>>>(paint_key) {
bake_graphic_paint_transform(graphics, transform);
}
}
}
#[cfg(test)]
mod run_tests {
use super::*;
use crate::graphic::run_to_legacy_list;
use crate::graphic::test_support::unit_square_at;
use core_types::Color;
use core_types::record::{FieldWrite, RunBuilder, RunView, element_write_hashed};
use glam::DVec2;
#[test]
fn a_run_serves_the_parked_paint_reference() {
let paint = List::new_from_element(Graphic::Color(Color::BLACK));
let vector = unit_square_at(DVec2::ZERO);
let arena = core_types::arena::Arena::new(1 << 16).unwrap();
let mut builder = RunBuilder::new(&arena, element_write_hashed::<Vector>(), &[FieldWrite::of::<Fill>(0)], 1).unwrap();
let lane = builder.push(vector.clone()).unwrap();
builder.attr::<Fill>(lane, Some(&paint));
let item = builder.finish();
let run = RunView::<Vector>::new(&item).expect("the run holds vector elements");
assert_eq!(run.attr::<Fill>(0), Some(&paint));
assert_eq!(paint_graphics::<Fill, _>(&run, 0), Some(&paint));
assert_eq!(paint_graphics::<Stroke, _>(&run, 0), None);
let legacy = run_to_legacy_list::<Vector>(&item).expect("the run lowers to a legacy vector list");
assert_eq!(paint_graphics::<Fill, _>(&legacy, 0), paint_graphics::<Fill, _>(&run, 0));
}
}
@@ -0,0 +1,572 @@
//! The native-content walk: vector rows reached through a graphic's own storage, with no legacy conversion.
use super::Graphic;
use super::paint::{LanePaint, PaintColumns, PaintReach, is_paint_present, paint_graphics, set_paint_attribute_at};
use crate::markers::{ATTR_FILL, ATTR_STROKE, Fill};
use core_types::attribute::{Attribute, ClippingMask, EditorLayerPath, Opacity, OpacityFill, Transform};
use core_types::bounds::{BoundingBox, RenderBoundingBox};
use core_types::lane::LaneSource;
use core_types::list::{AttributeValueDyn, Item, ItemAttributeValues, List};
use core_types::record::FieldOffset;
use core_types::render_complexity::RenderComplexity;
use core_types::uuid::NodeId;
use core_types::{ATTR_EDITOR_LAYER_PATH, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color};
use glam::{DAffine2, DVec2};
use raster_types::{CPU, GPU, Raster};
use vector_types::{Gradient, Vector};
/// One run's attribute tokens, minted once so the lane loops read at an offset.
struct RunAttrs {
transform: Option<FieldOffset<Transform>>,
opacity: Option<FieldOffset<Opacity>>,
opacity_fill: Option<FieldOffset<OpacityFill>>,
clipping_mask: Option<FieldOffset<ClippingMask>>,
}
impl RunAttrs {
fn of(item: &core_types::record::GroupItem) -> Self {
let layout = item.layout();
Self {
transform: FieldOffset::of(layout, 0),
opacity: FieldOffset::of(layout, 0),
opacity_fill: FieldOffset::of(layout, 0),
clipping_mask: FieldOffset::of(layout, 0),
}
}
fn read_or<'i, A: Attribute>(item: &'i core_types::record::GroupItem, field: Option<FieldOffset<A>>, lane: usize, default: A::Value<'i>) -> A::Value<'i> {
match field.and_then(|field| item.lanes().get(lane).try_attr_at(field)) {
Some(value) => value,
None => default,
}
}
}
pub fn group_is_empty(group: &core_types::record::Group) -> bool {
group.content.is_empty()
}
pub(in crate::graphic) fn group_all_clipped(group: &core_types::record::Group) -> bool {
let item = &group.content;
let attrs = RunAttrs::of(item);
(0..item.len()).all(|lane| RunAttrs::read_or(item, attrs.clipping_mask, lane, false))
}
pub(in crate::graphic) fn group_is_opaque(group: &core_types::record::Group) -> bool {
let item = &group.content;
let attrs = RunAttrs::of(item);
let lanes = item.typed_lanes::<Graphic>();
!item.is_empty()
&& (0..item.len()).all(|lane| {
RunAttrs::read_or(item, attrs.opacity, lane, 1.) >= 1.
&& RunAttrs::read_or(item, attrs.opacity_fill, lane, 1.) >= 1.
&& lanes.as_ref().is_some_and(|lanes| lanes.element_ref(lane).is_guaranteed_fully_opaque())
})
}
pub(in crate::graphic) fn group_is_fully_transparent(group: &core_types::record::Group) -> bool {
let item = &group.content;
let attrs = RunAttrs::of(item);
let lanes = item.typed_lanes::<Graphic>();
(0..item.len()).all(|lane| RunAttrs::read_or(item, attrs.opacity, lane, 1.) <= 0. || lanes.as_ref().is_some_and(|lanes| lanes.element_ref(lane).is_guaranteed_fully_transparent()))
}
pub(in crate::graphic) fn group_bounding_box(group: &core_types::record::Group, transform: DAffine2, include_stroke: bool, thumbnail: bool) -> RenderBoundingBox {
fn combine(combined: &mut Option<[DVec2; 2]>, any_infinite: &mut bool, bounds: RenderBoundingBox, thumbnail: bool) -> Option<RenderBoundingBox> {
match bounds {
RenderBoundingBox::None => None,
RenderBoundingBox::Infinite if thumbnail => {
*any_infinite = true;
None
}
RenderBoundingBox::Infinite => Some(RenderBoundingBox::Infinite),
RenderBoundingBox::Rectangle(bounds) => {
*combined = Some(match *combined {
Some(existing) => core_types::math::quad::Quad::combine_bounds(existing, bounds),
None => bounds,
});
None
}
}
}
fn typed_run<T: dyn_any::StaticTypeSized + BoundingBox>(item: &core_types::record::GroupItem, transform: DAffine2, include_stroke: bool, thumbnail: bool) -> Option<RenderBoundingBox> {
let lanes = item.typed_lanes::<T>()?;
let transform_offset = RunAttrs::of(item).transform;
let mut combined = None;
let mut any_infinite = false;
for lane in 0..lanes.len() {
let lane_transform = transform * RunAttrs::read_or(item, transform_offset, lane, DAffine2::IDENTITY);
let element = lanes.element_ref(lane);
let bounds = match thumbnail {
true => element.thumbnail_bounding_box(lane_transform, include_stroke),
false => element.bounding_box(lane_transform, include_stroke),
};
if let Some(short_circuit) = combine(&mut combined, &mut any_infinite, bounds, thumbnail) {
return Some(short_circuit);
}
}
Some(match (combined, any_infinite) {
(Some(bounds), _) => RenderBoundingBox::Rectangle(bounds),
(None, true) => RenderBoundingBox::Infinite,
(None, false) => RenderBoundingBox::None,
})
}
fn run_bounding_box(item: &core_types::record::GroupItem, transform: DAffine2, include_stroke: bool, thumbnail: bool) -> RenderBoundingBox {
None.or_else(|| typed_run::<Graphic>(item, transform, include_stroke, thumbnail))
.or_else(|| typed_run::<Vector>(item, transform, include_stroke, thumbnail))
.or_else(|| typed_run::<Raster<CPU>>(item, transform, include_stroke, thumbnail))
.or_else(|| typed_run::<Raster<GPU>>(item, transform, include_stroke, thumbnail))
.or_else(|| typed_run::<Color>(item, transform, include_stroke, thumbnail))
.or_else(|| typed_run::<Gradient>(item, transform, include_stroke, thumbnail))
.or_else(|| typed_run::<String>(item, transform, include_stroke, thumbnail))
.unwrap_or(RenderBoundingBox::Infinite)
}
run_bounding_box(&group.content, transform, include_stroke, thumbnail)
}
/// One step of the vector-row walk: continue to the next row or stop early.
pub enum RowStep {
Continue,
Stop,
}
/// The ancestor composition a flattened row inherits: transform, opacity and
/// fill opacity multiply down, each composing only where some ancestor
/// carries the attribute, matching the legacy flatten.
#[derive(Clone, Copy)]
struct FlattenScale {
has_transform: bool,
transform: DAffine2,
has_opacity: bool,
opacity: f64,
has_fill_opacity: bool,
fill_opacity: f64,
}
impl FlattenScale {
const ROOT: Self = Self {
has_transform: false,
transform: DAffine2::IDENTITY,
has_opacity: false,
opacity: 1.,
has_fill_opacity: false,
fill_opacity: 1.,
};
fn composed<S: LaneSource>(self, source: &S, lane: usize) -> Self {
let transform = source.try_attr::<Transform>(lane);
let opacity = source.try_attr::<Opacity>(lane);
let fill_opacity = source.try_attr::<OpacityFill>(lane);
Self {
has_transform: self.has_transform || transform.is_some(),
transform: self.transform * transform.unwrap_or(DAffine2::IDENTITY),
has_opacity: self.has_opacity || opacity.is_some(),
opacity: self.opacity * opacity.unwrap_or(1.),
has_fill_opacity: self.has_fill_opacity || fill_opacity.is_some(),
fill_opacity: self.fill_opacity * fill_opacity.unwrap_or(1.),
}
}
}
/// A graphic level in either of its two storages, as one lane source.
#[derive(Clone, Copy)]
pub enum GraphicLevel<'a> {
Legacy(&'a List<Graphic<'a>>),
Run(&'a core_types::record::GroupItem<'a>),
}
pub enum GraphicLevelColumn<'a, A: Attribute> {
Legacy(core_types::list::ListColumn<'a, A>),
Run(core_types::record::RunColumn<'a, A>),
}
impl<'a, A: Attribute> core_types::lane::LaneColumn<'a, A> for GraphicLevelColumn<'a, A> {
fn try_get(&self, lane: usize) -> Option<A::Value<'a>> {
match self {
GraphicLevelColumn::Legacy(column) => column.try_get(lane),
GraphicLevelColumn::Run(column) => column.try_get(lane),
}
}
}
impl<'a> LaneSource for GraphicLevel<'a> {
type Element = Graphic<'a>;
type Column<'b, A: Attribute>
= GraphicLevelColumn<'b, A>
where
Self: 'b;
fn lane_count(&self) -> usize {
match self {
GraphicLevel::Legacy(list) => list.len(),
GraphicLevel::Run(item) => item.len(),
}
}
fn element(&self, lane: usize) -> Option<&Graphic<'a>> {
match self {
GraphicLevel::Legacy(list) => list.element(lane),
GraphicLevel::Run(item) => {
let lanes = item.typed_lanes::<Graphic>()?;
if lane >= lanes.len() {
return None;
}
// SAFETY: the layout records the element type, and a parked
// element stores its reference at offset 0.
Some(unsafe { core_types::record::borrow_element::<Graphic>(item.lanes().get(lane).rec()) })
}
}
}
fn column<A: Attribute>(&self) -> GraphicLevelColumn<'_, A> {
match self {
GraphicLevel::Legacy(list) => GraphicLevelColumn::Legacy(list.column::<A>()),
GraphicLevel::Run(item) => GraphicLevelColumn::Run(core_types::record::RunColumn::of(item)),
}
}
}
/// The lane's attributes as an owned set, read through the erased glue.
pub fn run_lane_attributes(item: &core_types::record::GroupItem, lane: usize) -> ItemAttributeValues {
let mut scratch: List<Vector> = List::new_from_element(Vector::default());
for field in &item.layout().fields {
// SAFETY: the offset comes from the item's own layout.
let value = unsafe { (field.read_erased)(item.lanes().get(lane).rec().ptr().add(field.offset)) };
scratch.set_attribute_value_dyn(field.name, 0, AttributeValueDyn(value));
}
scratch.clone_item_attributes(0)
}
/// The lane's attributes as an owned set, from either level storage.
pub fn lane_attributes(level: GraphicLevel<'_>, lane: usize) -> ItemAttributeValues {
match level {
GraphicLevel::Legacy(list) => list.clone_item_attributes(lane),
GraphicLevel::Run(item) => run_lane_attributes(item, lane),
}
}
/// One flattened vector row served by [`walk_vector_rows`]: cheap probes
/// first, the full row built on demand.
pub struct VectorRow<'w> {
source: RowSourceRef<'w>,
scale: FlattenScale,
layer_path: Option<&'w [NodeId]>,
paint: LanePaint<'w>,
}
enum RowSourceRef<'w> {
/// A de-tabled vector leaf on a graphic lane: the lane is the row.
Lane(GraphicLevel<'w>, usize),
/// A lane of a vector run.
Run(&'w core_types::record::RunView<'w, Vector>, &'w core_types::record::GroupItem<'w>, usize),
}
impl VectorRow<'_> {
/// The row's vector, borrowed.
pub fn element(&self) -> &Vector {
match &self.source {
RowSourceRef::Lane(level, index) => level.element(*index).and_then(Graphic::as_vector).expect("the walk visits vector lanes"),
RowSourceRef::Run(run, _, index) => LaneSource::element(*run, *index).expect("the walk visits held lanes"),
}
}
/// Whether the built row will carry fill paint: the reaching lane paint,
/// else the row's own.
pub fn has_fill(&self) -> bool {
if self.paint.fill.is_some() {
return true;
}
match &self.source {
RowSourceRef::Lane(level, index) => paint_graphics::<Fill, _>(level, *index).is_some(),
RowSourceRef::Run(run, _, index) => paint_graphics::<Fill, _>(*run, *index).is_some(),
}
}
/// Builds the row at the end of `out`, applying the reach paint and the
/// inherited composition.
pub fn build_into(&self, out: &mut List<Vector>) {
let index = out.len();
match &self.source {
RowSourceRef::Lane(level, lane) => {
let vector = self.element().clone();
out.push(Item::from_parts(vector, lane_attributes(*level, *lane)));
}
RowSourceRef::Run(run, item, lane) => {
let vector = LaneSource::element(*run, *lane).expect("the walk visits held lanes").clone();
out.push(Item::from_parts(vector, run_lane_attributes(item, *lane)));
}
}
for (key, slot) in [(ATTR_FILL, self.paint.fill), (ATTR_STROKE, self.paint.stroke)] {
if let Some(paint) = slot {
set_paint_attribute_at(out, index, key, paint.clone());
}
}
if self.scale.has_transform || out.attribute::<DAffine2>(ATTR_TRANSFORM, index).is_some() {
let row_transform: DAffine2 = out.attribute_cloned_or_default(ATTR_TRANSFORM, index);
out.set_attribute(ATTR_TRANSFORM, index, self.scale.transform * row_transform);
}
if self.scale.has_opacity || out.attribute::<f64>(ATTR_OPACITY, index).is_some() {
let row_opacity: f64 = out.attribute_cloned_or(ATTR_OPACITY, index, 1.);
out.set_attribute(ATTR_OPACITY, index, self.scale.opacity * row_opacity);
}
if self.scale.has_fill_opacity || out.attribute::<f64>(ATTR_OPACITY_FILL, index).is_some() {
let row_fill: f64 = out.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.);
out.set_attribute(ATTR_OPACITY_FILL, index, self.scale.fill_opacity * row_fill);
}
if let Some(layer_path) = self.layer_path {
out.set_attribute(ATTR_EDITOR_LAYER_PATH, index, layer_path.to_vec());
}
}
}
fn walk_rows_of_run(item: &core_types::record::GroupItem, scale: FlattenScale, layer_path: Option<&[NodeId]>, paint: LanePaint<'_>, visit: &mut dyn FnMut(VectorRow<'_>) -> RowStep) -> RowStep {
let Some(run) = core_types::record::RunView::<Vector>::new(item) else {
return RowStep::Continue;
};
for lane in 0..item.len() {
if let RowStep::Stop = visit(VectorRow {
source: RowSourceRef::Run(&run, item, lane),
scale,
layer_path,
paint,
}) {
return RowStep::Stop;
}
}
RowStep::Continue
}
/// Walks a graphic level into its flattened vector rows, matching the legacy
/// push-then-flatten lowering: lane paint threads with [`PaintReach`],
/// ancestor transform, opacity and fill opacity compose down, the containing
/// level's parent layer path overwrites its rows, and non-vector content is
/// discarded. A de-tabled leaf's row is its lane, attributes included.
pub fn walk_vector_rows(level: GraphicLevel<'_>, visit: &mut dyn FnMut(VectorRow<'_>) -> RowStep) {
walk_vector_rows_impl(level, FlattenScale::ROOT, None, PaintReach::NONE, visit);
}
fn walk_vector_rows_impl<'a>(
level: GraphicLevel<'a>,
scale: FlattenScale,
parent_layer_path: Option<&'a [NodeId]>,
inherited: PaintReach<'a>,
visit: &mut dyn FnMut(VectorRow<'_>) -> RowStep,
) -> RowStep {
if let GraphicLevel::Run(item) = level {
// A vector-typed run is already its rows.
if item.typed_lanes::<Vector>().is_some() {
let paint = match inherited.applies() {
true => inherited.paint,
false => LanePaint::NONE,
};
return walk_rows_of_run(item, scale, parent_layer_path, paint, visit);
}
}
let columns = PaintColumns::new(&level);
for index in 0..level.lane_count() {
let Some(element) = level.element(index) else { continue };
let reach = inherited.for_lane(&columns, index);
let row_paint = match reach.applies() {
true => reach.paint,
false => LanePaint::NONE,
};
let step = match element {
Graphic::Vector(_) => visit(VectorRow {
source: RowSourceRef::Lane(level, index),
scale,
layer_path: parent_layer_path,
paint: row_paint,
}),
Graphic::GraphicList(children) => walk_vector_rows_impl(
GraphicLevel::Legacy(children),
scale.composed(&level, index),
level.try_attr::<EditorLayerPath>(index),
reach.nested(),
visit,
),
Graphic::Group(group) => {
let item = &group.content;
if item.typed_lanes::<Vector>().is_some() {
walk_rows_of_run(item, scale.composed(&level, index), level.try_attr::<EditorLayerPath>(index), row_paint, visit)
} else if item.typed_lanes::<Graphic>().is_some() {
walk_vector_rows_impl(
GraphicLevel::Run(item),
scale.composed(&level, index),
level.try_attr::<EditorLayerPath>(index),
reach.into_group_graphics(),
visit,
)
} else {
RowStep::Continue
}
}
_ => RowStep::Continue,
};
if let RowStep::Stop = step {
return RowStep::Stop;
}
}
RowStep::Continue
}
/// The level's flattened vector rows as one owned list, the walk's collect
/// form.
pub fn flatten_vector_rows(level: GraphicLevel<'_>) -> List<Vector> {
let mut out = List::new();
walk_vector_rows(level, &mut |row| {
row.build_into(&mut out);
RowStep::Continue
});
out
}
/// The transitional paint placement: a lane-level fill or stroke paint
/// attribute moves onto the vector interiors the legacy paint readers
/// inspect, reaching as far as the pre-flip broadcast did.
pub(in crate::graphic) fn push_lane_paint_into_interiors(list: &mut List<Graphic>) {
for index in 0..list.len() {
for key in [ATTR_FILL, ATTR_STROKE] {
let stored = list.attribute::<Option<List<Graphic>>>(key, index).and_then(|optional| optional.as_ref());
let Some(paint) = stored.filter(|paint| is_paint_present(paint)).cloned() else {
continue;
};
let Some(Graphic::GraphicList(children)) = list.element_mut(index) else { continue };
for child in 0..children.len() {
if matches!(children.element(child), Some(Graphic::Vector(_))) {
set_paint_attribute_at(children, child, key, paint.clone());
}
}
}
}
}
/// The count [`map_groups_to_legacy`] would expose through [`Graphic::as_vector`],
/// read from the run's lanes instead of materializing the legacy list. Mirrors
/// [`group_to_legacy_graphic`]'s typed-run path, where `Vector` is tried first.
pub fn direct_vector_len(graphic: &Graphic) -> usize {
match graphic {
Graphic::Vector(_) => 1,
Graphic::Group(group) => match &group.row {
None => group.content.typed_lanes::<Vector>().map_or(0, |lanes| lanes.len()),
_ => 0,
},
_ => 0,
}
}
pub(in crate::graphic) fn group_render_complexity(group: &core_types::record::Group) -> usize {
fn typed_run<T: dyn_any::StaticTypeSized + RenderComplexity>(item: &core_types::record::GroupItem) -> Option<usize> {
let lanes = item.typed_lanes::<T>()?;
Some((0..lanes.len()).map(|lane| lanes.element_ref(lane).render_complexity()).sum())
}
let item = &group.content;
None.or_else(|| typed_run::<Graphic>(item))
.or_else(|| typed_run::<Vector>(item))
.or_else(|| typed_run::<Raster<CPU>>(item))
.or_else(|| typed_run::<Raster<GPU>>(item))
.or_else(|| typed_run::<Color>(item))
.or_else(|| typed_run::<Gradient>(item))
.or_else(|| typed_run::<String>(item))
.unwrap_or(item.len())
}
#[cfg(test)]
mod run_tests {
use super::*;
use crate::graphic::test_support::unit_square_at;
use crate::graphic::{IntoGraphicList, map_groups_to_legacy, run_to_legacy_list};
use core_types::record::{FieldWrite, RunBuilder, RunView, element_write_hashed};
#[test]
fn the_vector_row_walk_matches_the_legacy_flatten() {
let inner_vector = unit_square_at(DVec2::ZERO);
let arena = core_types::arena::Arena::new(1 << 16).unwrap();
let mut builder = RunBuilder::new(&arena, element_write_hashed::<Vector>(), &[], 1).unwrap();
builder.push(inner_vector.clone()).unwrap();
let inner_item = builder.finish();
let mut painted = List::new();
painted.push(Item::new_from_element(Graphic::Vector(unit_square_at(DVec2::ZERO))));
painted.push(Item::new_from_element(Graphic::Vector(unit_square_at(DVec2::ONE))));
painted.set_attribute(core_types::ATTR_TRANSFORM, 0, DAffine2::from_translation(DVec2::new(1., 0.)));
painted.set_attribute(core_types::ATTR_TRANSFORM, 1, DAffine2::from_translation(DVec2::new(0., 1.)));
set_paint_attribute_at(&mut painted, 1, ATTR_FILL, List::new_from_element(Graphic::Color(Color::WHITE)));
let mut nested = List::new_from_element(Graphic::Vector(unit_square_at(DVec2::new(2., 2.))));
nested.set_attribute(core_types::ATTR_TRANSFORM, 0, DAffine2::from_scale(DVec2::splat(2.)));
let mut top = List::new();
top.push(Item::new_from_element(Graphic::GraphicList(painted)));
top.push(Item::new_from_element(Graphic::GraphicList(nested)));
top.push(Item::new_from_element(Graphic::Group(core_types::record::Group { row: None, content: inner_item })));
top.push(Item::new_from_element(Graphic::Color(Color::BLACK)));
top.push(Item::new_from_element(Graphic::Vector(unit_square_at(DVec2::new(6., 0.)))));
top.set_attribute(core_types::ATTR_TRANSFORM, 0, DAffine2::from_translation(DVec2::new(5., 5.)));
top.set_attribute(core_types::ATTR_EDITOR_LAYER_PATH, 0, vec![core_types::uuid::NodeId(7)]);
set_paint_attribute_at(&mut top, 0, ATTR_FILL, List::new_from_element(Graphic::Color(Color::BLACK)));
top.set_attribute(core_types::ATTR_OPACITY, 1, 0.5);
top.set_attribute(core_types::ATTR_TRANSFORM, 2, DAffine2::from_scale(DVec2::splat(3.)));
top.set_attribute(core_types::ATTR_TRANSFORM, 4, DAffine2::from_translation(DVec2::new(0., 7.)));
top.set_attribute(core_types::ATTR_EDITOR_LAYER_PATH, 4, vec![core_types::uuid::NodeId(9)]);
set_paint_attribute_at(&mut top, 4, ATTR_FILL, List::new_from_element(Graphic::Color(Color::WHITE)));
let legacy = {
let mut list = List::new();
for item in top.clone().into_iter() {
let (element, attributes) = item.into_parts();
list.push(Item::from_parts(map_groups_to_legacy(&element), attributes));
}
push_lane_paint_into_interiors(&mut list);
list.into_flattened_list::<Vector>()
};
let native = flatten_vector_rows(GraphicLevel::Legacy(&top));
assert_eq!(native.len(), legacy.len());
for row in 0..native.len() {
assert_eq!(
native.attribute::<DAffine2>(core_types::ATTR_TRANSFORM, row),
legacy.attribute::<DAffine2>(core_types::ATTR_TRANSFORM, row),
"transform, row {row}"
);
assert_eq!(
native.attribute::<f64>(core_types::ATTR_OPACITY, row),
legacy.attribute::<f64>(core_types::ATTR_OPACITY, row),
"opacity, row {row}"
);
assert_eq!(
native.attribute::<Vec<core_types::uuid::NodeId>>(core_types::ATTR_EDITOR_LAYER_PATH, row),
legacy.attribute::<Vec<core_types::uuid::NodeId>>(core_types::ATTR_EDITOR_LAYER_PATH, row),
"layer path, row {row}"
);
assert_eq!(
native.attribute::<Option<List<Graphic>>>(ATTR_FILL, row),
legacy.attribute::<Option<List<Graphic>>>(ATTR_FILL, row),
"fill, row {row}"
);
}
assert_eq!(native, legacy);
}
#[test]
fn a_run_and_its_legacy_list_agree_on_bounding_boxes() {
let vectors = [unit_square_at(DVec2::ZERO), unit_square_at(DVec2::new(4., 4.))];
let transforms = [DAffine2::from_translation(DVec2::new(1., 2.)), DAffine2::from_scale(DVec2::splat(3.))];
let arena = core_types::arena::Arena::new(1 << 16).unwrap();
let mut builder = RunBuilder::new(&arena, element_write_hashed::<Vector>(), &[FieldWrite::of::<core_types::attribute::Transform>(0)], 2).unwrap();
for (vector, transform) in vectors.iter().zip(transforms) {
let lane = builder.push(vector.clone()).unwrap();
builder.attr::<core_types::attribute::Transform>(lane, transform);
}
let item = builder.finish();
let run = RunView::<Vector>::new(&item).expect("the run holds vector elements");
let legacy = run_to_legacy_list::<Vector>(&item).expect("the run lowers to a legacy vector list");
let outer = DAffine2::from_angle(0.3);
for include_stroke in [false, true] {
let bounds = run.bounding_box(outer, include_stroke);
assert_eq!(bounds, legacy.bounding_box(outer, include_stroke));
assert!(matches!(bounds, RenderBoundingBox::Rectangle(_)));
assert_eq!(run.thumbnail_bounding_box(outer, include_stroke), legacy.thumbnail_bounding_box(outer, include_stroke));
}
}
}
@@ -1,6 +1,8 @@
pub mod appearance; pub mod appearance;
pub mod artboard; pub mod artboard;
pub mod boundary;
pub mod graphic; pub mod graphic;
pub mod markers;
// Re-export all transitive dependencies so downstream crates only need to depend on graphic-types // Re-export all transitive dependencies so downstream crates only need to depend on graphic-types
pub use core_types; pub use core_types;
@@ -10,7 +12,8 @@ pub use vector_types;
// Re-export commonly used types at the crate root // Re-export commonly used types at the crate root
pub use appearance::{Appearance, Cover, CoverPlacement, Coverage, FillAndStroke, stamp_coverage}; pub use appearance::{Appearance, Cover, CoverPlacement, Coverage, FillAndStroke, stamp_coverage};
pub use artboard::Artboard; pub use artboard::Artboard;
pub use graphic::{Graphic, IntoGraphicList, TryFromGraphic, Vector}; pub use graphic::{Graphic, IntoGraphicList, TryFromGraphic, Vector, is_lone_anonymous_leaf};
pub use markers::{ATTR_EDITOR_MERGED_LAYERS, ATTR_FILL, ATTR_STROKE};
pub mod migrations { pub mod migrations {
use crate::Vector; use crate::Vector;
@@ -0,0 +1,58 @@
//! Attribute markers whose value types live in this crate, with their name
//! constants for the string-keyed legacy readers and writers.
//!
//! The list-valued markers may carry native [`Graphic::Group`] content: the
//! registered deep field glue owns it across persistence seams, and legacy
//! products convert it through [`crate::graphic::map_paint_attrs_to_legacy`].
use crate::Graphic;
use core_types::attribute::Attribute;
use core_types::list::List;
core_types::attribute! {
/// Vector graphics object's filled area paint, a graphic list in the canonical paint form.
/// An absent value means no fill.
pub Fill("fill"): Option<&List<Graphic<'static>>>;
/// Vector graphics object's stroke paint, a graphic list in the canonical paint form.
/// An absent value means no stroke paint.
pub Stroke("stroke"): Option<&List<Graphic<'static>>>;
/// Snapshot of the upstream content that fed into a destructive merge (Boolean Operation,
/// Rasterize, etc.), so the editor can still surface click targets for the original child
/// layers after their content has been collapsed.
pub EditorMergedLayers("editor:merged_layers"): Option<&List<Graphic<'static>>>;
}
pub const ATTR_FILL: &str = Fill::NAME;
pub const ATTR_STROKE: &str = Stroke::NAME;
pub const ATTR_EDITOR_MERGED_LAYERS: &str = EditorMergedLayers::NAME;
#[cfg(test)]
mod tests {
use super::*;
use core_types::attribute::info;
use std::any::TypeId;
#[test]
fn the_census_carries_this_crates_names() {
for name in ["fill", "stroke", "editor:merged_layers"] {
assert_eq!(info(name).unwrap().value_type, TypeId::of::<Option<&'static List<Graphic>>>());
}
}
#[test]
fn an_absent_paint_defaults_to_none() {
assert_eq!(<Fill as Attribute>::default(), None);
}
#[test]
fn a_paint_marker_reads_back_what_the_paint_writer_stored() {
use core_types::lane::LaneSource;
let paint = List::new_from_element(Graphic::default());
let mut list = List::new_from_element(Graphic::default());
crate::graphic::set_paint_attribute_at(&mut list, 0, ATTR_FILL, paint.clone());
assert_eq!(list.attr::<Fill>(0), Some(&paint));
assert_eq!(list.attr::<Stroke>(0), None);
}
}
@@ -7,3 +7,12 @@ impl Ctx for () {}
pub trait ArcCtx: Send + Sync {} pub trait ArcCtx: Send + Sync {}
#[cfg(feature = "std")] #[cfg(feature = "std")]
impl<T: ArcCtx> Ctx for std::sync::Arc<T> {} impl<T: ArcCtx> Ctx for std::sync::Arc<T> {}
// The cache-hash bound record kernels place on their element generics; the
// shader build compiles the same signatures without the hashing machinery.
#[cfg(feature = "std")]
pub use graphene_hash::CacheHash;
#[cfg(not(feature = "std"))]
pub trait CacheHash {}
#[cfg(not(feature = "std"))]
impl<T> CacheHash for T {}
+99 -138
View File
@@ -1,16 +1,15 @@
use crate::renderer::{ use crate::renderer::{ClearGuardPlacement, RenderParams, format_transform_matrix, gradient_placement, gradient_settings_from_lane, spread_adjusted_samples, transform_is_invertible};
ClearGuardPlacement, ItemRef, RenderParams, composite_paint_colors, faded_paint_color, format_transform_matrix, gradient_placement, gradient_settings_from_item, spread_adjusted_samples,
transform_is_invertible,
};
use crate::{Render, RenderSvgSegmentList, SvgRender}; use crate::{Render, RenderSvgSegmentList, SvgRender};
use core_types::Color;
use core_types::attribute::Transform;
use core_types::color::SRGBA8; use core_types::color::SRGBA8;
use core_types::list::List; use core_types::list::List;
use core_types::uuid::generate_uuid; use core_types::uuid::generate_uuid;
use core_types::{ATTR_GRADIENT_FORM, ATTR_TRANSFORM, Color};
use glam::{DAffine2, DVec2}; use glam::{DAffine2, DVec2};
use graphic_types::Graphic; use graphic_types::Graphic;
use graphic_types::vector_types::gradient::GradientForm; use graphic_types::vector_types::gradient::GradientForm;
use graphic_types::vector_types::vector::style::{Stroke, StrokeAlign, StrokeCap, StrokeJoin}; use graphic_types::vector_types::markers::GradientForm as GradientFormAttr;
use graphic_types::vector_types::vector::style::{PaintOrder, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
use std::fmt::Write; use std::fmt::Write;
use vector_types::Gradient; use vector_types::Gradient;
use vector_types::gradient::GradientSpread; use vector_types::gradient::GradientSpread;
@@ -53,11 +52,13 @@ pub trait RenderExt {
) -> Self::Output; ) -> Self::Output;
} }
/// The paint attribute for an already-faded solid color, or the SVG `none` keyword when the color is absent. /// The color paint attribute over any color lane source.
fn render_color_paint(color: Option<Color>, target: PaintTarget) -> String { pub fn render_color_paint<S: core_types::lane::LaneSource<Element = Color>>(source: &S, target: PaintTarget) -> String {
let Some(color) = color else { return format!(r#" {}="none""#, target.paint_attr()) }; let Some(color) = source.element(0) else {
return format!(r#" {}="none""#, target.paint_attr());
};
let mut result = format!(r##" {}="#{}""##, target.paint_attr(), SRGBA8::from(color).to_rgb_hex()); let mut result = format!(r##" {}="#{}""##, target.paint_attr(), SRGBA8::from(*color).to_rgb_hex());
if color.a() < 1. { if color.a() < 1. {
let _ = write!(result, r#" {}="{}""#, target.opacity_attr(), (color.a() * 1000.).round() / 1000.); let _ = write!(result, r#" {}="{}""#, target.opacity_attr(), (color.a() * 1000.).round() / 1000.);
} }
@@ -75,32 +76,42 @@ impl RenderExt for List<Color> {
_element_transform: DAffine2, _element_transform: DAffine2,
_stroke_transform: DAffine2, _stroke_transform: DAffine2,
_bounds: DAffine2, _bounds: DAffine2,
render_params: &RenderParams, _render_params: &RenderParams,
target: PaintTarget, target: PaintTarget,
) -> Self::Output { ) -> Self::Output {
render_color_paint(composite_paint_colors(self, render_params.for_mask), target) render_color_paint(self, target)
} }
} }
/// Adds one gradient item's def into `svg_defs` and returns the gradient ID, or `None` when the item is absent. impl RenderExt for List<Gradient> {
/// `for_mask` keeps the fill opacity at full, as [`ItemRef::paint_opacity`] explains. type Output = u64;
fn render_gradient_paint(item: Option<ItemRef<'_, Gradient>>, svg_defs: &mut String, item_transform: DAffine2, element_transform: DAffine2, for_mask: bool) -> Option<u64> {
/// Adds the gradient def through mutating the first argument, returning the gradient ID.
fn render(
&self,
svg_defs: &mut String,
item_transform: DAffine2,
element_transform: DAffine2,
_stroke_transform: DAffine2,
_bounds: DAffine2,
_render_params: &RenderParams,
_target: PaintTarget,
) -> Self::Output {
render_gradient_paint(self, svg_defs, item_transform, element_transform)
}
}
/// Adds the gradient def through mutating `svg_defs`, returning the gradient
/// ID, over any gradient lane source.
pub fn render_gradient_paint<S: core_types::lane::LaneSource<Element = Gradient>>(source: &S, svg_defs: &mut String, item_transform: DAffine2, element_transform: DAffine2) -> u64 {
let mut stop = String::new(); let mut stop = String::new();
let item = item?; let Some(stops) = source.element(0) else { return 0 };
let stops = item.element()?; let gradient_form: GradientForm = source.attr::<GradientFormAttr>(0);
let gradient_form: GradientForm = item.attribute_cloned_or_default(ATTR_GRADIENT_FORM); let local_gradient_transform: DAffine2 = source.attr::<Transform>(0);
let local_gradient_transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM); let settings = gradient_settings_from_lane(source, 0);
let settings = gradient_settings_from_item(item);
let (mut samples, _) = spread_adjusted_samples(stops, settings, gradient_form, ClearGuardPlacement::SvgStopOrder); let (samples, _) = spread_adjusted_samples(stops, settings, gradient_form, ClearGuardPlacement::SvgStopOrder);
let paint_opacity = item.paint_opacity(for_mask);
if paint_opacity < 1. {
for (_, color, _) in &mut samples {
*color = color.with_alpha(color.a() * paint_opacity);
}
}
for (position, color, original_midpoint) in samples { for (position, color, original_midpoint) in samples {
stop.push_str("<stop"); stop.push_str("<stop");
@@ -119,11 +130,7 @@ fn render_gradient_paint(item: Option<ItemRef<'_, Gradient>>, svg_defs: &mut Str
// A gradient with no stops paints as solid black, matching `Gradient::evaluate` (a stopless def would otherwise render as no paint per the SVG spec) // A gradient with no stops paints as solid black, matching `Gradient::evaluate` (a stopless def would otherwise render as no paint per the SVG spec)
if stop.is_empty() { if stop.is_empty() {
stop.push_str(r##"<stop stop-color="#000000""##); stop.push_str(r##"<stop stop-color="#000000" />"##);
if paint_opacity < 1. {
let _ = write!(stop, r#" stop-opacity="{}""#, (paint_opacity * 1000.).round() / 1000.);
}
stop.push_str(" />");
} }
// Need to cancel out the element's transform as it is already applied to the path itself. // Need to cancel out the element's transform as it is already applied to the path itself.
@@ -143,6 +150,7 @@ fn render_gradient_paint(item: Option<ItemRef<'_, Gradient>>, svg_defs: &mut Str
format!(r#" gradientTransform="{gradient_transform}""#) format!(r#" gradientTransform="{gradient_transform}""#)
}; };
// `Clear` rides pad, with the transparent guard stops from `spread_adjusted_samples` doing the clearing
let gradient_spread = if matches!(settings.spread, GradientSpread::Pad | GradientSpread::Clear) { let gradient_spread = if matches!(settings.spread, GradientSpread::Pad | GradientSpread::Clear) {
String::new() String::new()
} else { } else {
@@ -168,94 +176,60 @@ fn render_gradient_paint(item: Option<ItemRef<'_, Gradient>>, svg_defs: &mut Str
} }
} }
Some(gradient_id) gradient_id
} }
impl RenderExt for List<Gradient> { /// Provide the shape-related SVG attributes for the stroke. The paint-related attributes for the stroke are generated from `List<Graphic>.render` with `PaintTarget::Stroke`.
type Output = Option<u64>; ///
/// `paint_order` arrives separately because master deleted `Stroke::paint_order`; it rides the stroke paint list instead.
/// Adds the gradient def through mutating the first argument, returning the gradient ID, or `None` when the list is empty. pub fn render_stroke_shape(stroke: &Stroke, paint_order: PaintOrder, render_params: &RenderParams) -> String {
fn render( // Don't render a stroke at all if it would be invisible
&self, if !stroke.has_renderable_stroke() {
svg_defs: &mut String, return String::new();
item_transform: DAffine2,
element_transform: DAffine2,
_stroke_transform: DAffine2,
_bounds: DAffine2,
render_params: &RenderParams,
_target: PaintTarget,
) -> Self::Output {
render_gradient_paint(
(!self.is_empty()).then_some(ItemRef::ListItem(self, 0)),
svg_defs,
item_transform,
element_transform,
render_params.for_mask,
)
} }
}
impl RenderExt for Stroke { let default_weight = if stroke.align != StrokeAlign::Center && render_params.aligned_strokes { 1. / 2. } else { 1. };
type Output = String;
/// Provide the shape-related SVG attributes for the stroke. The paint-related attributes for the stroke are generated from `Graphic::render` with `PaintTarget::Stroke`. // Set to None if the value is the SVG default
fn render( let weight = (stroke.weight != default_weight).then_some(stroke.weight);
&self, let dash_array = (!stroke.dash_lengths.is_empty()).then_some(stroke.dash_lengths());
_svg_defs: &mut String, let dash_offset = (stroke.dash_offset != 0.).then_some(stroke.dash_offset);
_item_transform: DAffine2, let stroke_cap = (stroke.cap != StrokeCap::Butt).then_some(stroke.cap);
_element_transform: DAffine2, let stroke_join = (stroke.join != StrokeJoin::Miter).then_some(stroke.join);
_stroke_transform: DAffine2, let stroke_join_miter_limit = (stroke.join_miter_limit != 4.).then_some(stroke.join_miter_limit);
_bounds: DAffine2, let stroke_align = (stroke.align != StrokeAlign::Center).then_some(stroke.align);
render_params: &RenderParams, let paint_order = (paint_order != PaintOrder::StrokeAbove || render_params.override_paint_order).then_some(PaintOrder::StrokeBelow);
_target: PaintTarget,
) -> Self::Output {
// Don't render a stroke at all if it would be invisible
if !self.has_renderable_stroke() {
return String::new();
}
let default_weight = if self.align != StrokeAlign::Center && render_params.aligned_strokes { 1. / 2. } else { 1. }; // Render the needed stroke attributes
let mut attributes = String::new();
// Set to None if the value is the SVG default if let Some(mut weight) = weight {
let weight = (self.weight != default_weight).then_some(self.weight); if stroke_align.is_some() && render_params.aligned_strokes {
let dash_array = (!self.dash_lengths.is_empty()).then_some(self.dash_lengths()); weight *= 2.;
let dash_offset = (self.dash_offset != 0.).then_some(self.dash_offset);
let stroke_cap = (self.cap != StrokeCap::Butt).then_some(self.cap);
let stroke_join = (self.join != StrokeJoin::Miter).then_some(self.join);
let stroke_join_miter_limit = (self.join_miter_limit != 4.).then_some(self.join_miter_limit);
let stroke_align = (self.align != StrokeAlign::Center).then_some(self.align);
// Render the needed stroke attributes
let mut attributes = String::new();
if let Some(mut weight) = weight {
if stroke_align.is_some() && render_params.aligned_strokes {
weight *= 2.;
}
let _ = write!(&mut attributes, r#" stroke-width="{weight}""#);
} }
if let Some(dash_array) = dash_array { let _ = write!(&mut attributes, r#" stroke-width="{weight}""#);
let _ = write!(&mut attributes, r#" stroke-dasharray="{dash_array}""#);
}
if let Some(dash_offset) = dash_offset {
let _ = write!(&mut attributes, r#" stroke-dashoffset="{dash_offset}""#);
}
if let Some(stroke_cap) = stroke_cap {
let _ = write!(&mut attributes, r#" stroke-linecap="{}""#, stroke_cap.svg_name());
}
if let Some(stroke_join) = stroke_join {
let _ = write!(&mut attributes, r#" stroke-linejoin="{}""#, stroke_join.svg_name());
}
if let Some(stroke_join_miter_limit) = stroke_join_miter_limit {
let _ = write!(&mut attributes, r#" stroke-miterlimit="{stroke_join_miter_limit}""#);
}
if render_params.stroke_below {
let _ = write!(&mut attributes, r#" style="paint-order: stroke;" "#);
}
attributes
} }
if let Some(dash_array) = dash_array {
let _ = write!(&mut attributes, r#" stroke-dasharray="{dash_array}""#);
}
if let Some(dash_offset) = dash_offset {
let _ = write!(&mut attributes, r#" stroke-dashoffset="{dash_offset}""#);
}
if let Some(stroke_cap) = stroke_cap {
let _ = write!(&mut attributes, r#" stroke-linecap="{}""#, stroke_cap.svg_name());
}
if let Some(stroke_join) = stroke_join {
let _ = write!(&mut attributes, r#" stroke-linejoin="{}""#, stroke_join.svg_name());
}
if let Some(stroke_join_miter_limit) = stroke_join_miter_limit {
let _ = write!(&mut attributes, r#" stroke-miterlimit="{stroke_join_miter_limit}""#);
}
if paint_order.is_some() {
let _ = write!(&mut attributes, r#" style="paint-order: stroke;" "#);
}
attributes
} }
impl RenderExt for Graphic { impl RenderExt for List<Graphic<'_>> {
type Output = String; type Output = String;
fn render( fn render(
@@ -268,32 +242,18 @@ impl RenderExt for Graphic {
render_params: &RenderParams, render_params: &RenderParams,
target: PaintTarget, target: PaintTarget,
) -> Self::Output { ) -> Self::Output {
let fill_graphic = self.element(0);
let paint_attr = target.paint_attr(); let paint_attr = target.paint_attr();
match self { match fill_graphic {
Graphic::Color(item) => render_color_paint(faded_paint_color(ItemRef::Item(item), render_params.for_mask), target), Some(Graphic::Color(color)) => render_color_paint(&core_types::lane::LeafLane::new(self, 0, color), target),
Graphic::ColorList(color_list) => color_list.render(svg_defs, item_transform, element_transform, stroke_transform, bounds, render_params, target), Some(Graphic::Gradient(gradient)) => {
Graphic::Gradient(item) => render_gradient_paint(Some(ItemRef::Item(item)), svg_defs, item_transform, element_transform, render_params.for_mask) let gradient_id = render_gradient_paint(&core_types::lane::LeafLane::new(self, 0, gradient), svg_defs, item_transform, element_transform);
.map(|gradient_id| format!(r##" {paint_attr}="url(#{gradient_id})""##)) format!(r##" {paint_attr}="url(#{gradient_id})""##)
.unwrap_or_else(|| format!(r#" {paint_attr}="none""#)), }
// One gradient resolves to a paint server; stacking several needs them composited, which only the pattern below can do // Brush strokes have no vector outline, so they contribute no paint
Graphic::GradientList(gradient_list) if gradient_list.len() <= 1 => gradient_list Some(Graphic::Stroke(_)) | Some(Graphic::StrokeList(_)) => format!(r#" {paint_attr}="none""#),
.render(svg_defs, item_transform, element_transform, stroke_transform, bounds, render_params, target) Some(Graphic::Vector(_)) | Some(Graphic::RasterCPU(_)) | Some(Graphic::RasterGPU(_)) | Some(Graphic::GraphicList(_)) | Some(Graphic::Text(_)) | Some(Graphic::Group(_)) => {
.map(|gradient_id| format!(r##" {paint_attr}="url(#{gradient_id})""##))
.unwrap_or_else(|| format!(r#" {paint_attr}="none""#)),
Graphic::None(_) | Graphic::NoneList(_) => format!(r#" {paint_attr}="none""#),
Graphic::Graphic(_)
| Graphic::Vector(_)
| Graphic::RasterCPU(_)
| Graphic::RasterGPU(_)
| Graphic::Text(_)
| Graphic::VectorList(_)
| Graphic::RasterCPUList(_)
| Graphic::RasterGPUList(_)
| Graphic::GraphicList(_)
| Graphic::GradientList(_)
| Graphic::TextList(_)
| Graphic::StrokeList(_) => {
let bounds = if target == PaintTarget::Stroke { let bounds = if target == PaintTarget::Stroke {
// To prevent a wraparound artefact occurring when the tile boundary and the stroke region are perfectly aligned, the local coordinate is expanded slightly. // To prevent a wraparound artefact occurring when the tile boundary and the stroke region are perfectly aligned, the local coordinate is expanded slightly.
let inverse = |len: f64| if len > 0. { 1. / len } else { 0. }; let inverse = |len: f64| if len > 0. { 1. / len } else { 0. };
@@ -308,13 +268,14 @@ impl RenderExt for Graphic {
.map(|id| format!(r##" {paint_attr}="url(#{id})""##)) .map(|id| format!(r##" {paint_attr}="url(#{id})""##))
.unwrap_or_else(|| format!(r#" {paint_attr}="none""#)) .unwrap_or_else(|| format!(r#" {paint_attr}="none""#))
} }
None => format!(r#" {paint_attr}="none""#),
} }
} }
} }
/// Emits an SVG `<pattern>` paint server into `svg_defs` that renders the given graphic as the paint content, and returns the pattern ID. /// Emits an SVG `<pattern>` paint server into `svg_defs` that renders the given graphic list as the paint content, and returns the pattern ID.
/// Currently, this function is only used for clipping-based filling and stroking, not considering tiling yet. /// Currently, this function is only used for clipping-based filling and stroking, not considering tiling yet.
fn render_svg_pattern(svg_defs: &mut String, paint: &Graphic, stroke_transform: DAffine2, bounds: DAffine2, render_params: &RenderParams) -> Option<String> { fn render_svg_pattern(svg_defs: &mut String, fill_graphic_list: &List<Graphic>, stroke_transform: DAffine2, bounds: DAffine2, render_params: &RenderParams) -> Option<String> {
let min = bounds.transform_point2(DVec2::ZERO); let min = bounds.transform_point2(DVec2::ZERO);
let max = bounds.transform_point2(DVec2::ONE); let max = bounds.transform_point2(DVec2::ONE);
let size = max - min; let size = max - min;
@@ -324,7 +285,7 @@ fn render_svg_pattern(svg_defs: &mut String, paint: &Graphic, stroke_transform:
// Render the pattern content recursively // Render the pattern content recursively
let mut content = SvgRender::new(); let mut content = SvgRender::new();
paint.render_svg(&mut content, &render_params.for_pattern()); fill_graphic_list.render_svg(&mut content, &render_params.for_pattern());
// Unwrap the inner def element // Unwrap the inner def element
write!(svg_defs, "{}", content.svg_defs).unwrap(); write!(svg_defs, "{}", content.svg_defs).unwrap();
Loaded 100 of 166 files, more files were not shown because too many files have changed in this diff. Show more