mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
260
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d1df2abeda | ||
|
|
309c376ff0 | ||
|
|
40db86f650 | ||
|
|
db205b5153 | ||
|
|
5b61db5d5c | ||
|
|
407492b698 | ||
|
|
aa50c42930 | ||
|
|
c73976f407 | ||
|
|
cac1c47b86 | ||
|
|
1426f6401f | ||
|
|
6b951c1806 | ||
|
|
1f860aae6a | ||
|
|
e415714b04 | ||
|
|
a6016b2c03 | ||
|
|
c12f8f1115 | ||
|
|
4e7d72d4b8 | ||
|
|
41d42fe794 | ||
|
|
21dfe04bf8 | ||
|
|
0f26893ec1 | ||
|
|
0cd428f1b1 | ||
|
|
39ed962e16 | ||
|
|
6a5417ed3d | ||
|
|
29052a58db | ||
|
|
84d11b9285 | ||
|
|
5a6192bbd6 | ||
|
|
ca831c00db | ||
|
|
fe8ca88752 | ||
|
|
8fd2529e27 | ||
|
|
641fcc88c6 | ||
|
|
78e35eb6ea | ||
|
|
3302a3b0b8 | ||
|
|
41d295f140 | ||
|
|
a955d6b458 | ||
|
|
97bc10e4c3 | ||
|
|
3af6834d3c | ||
|
|
277641d27e | ||
|
|
f3e945c5d8 | ||
|
|
aef750153b | ||
|
|
f4d37524c8 | ||
|
|
e5b910f840 | ||
|
|
25f49e8750 | ||
|
|
1ef7c9c2c2 | ||
|
|
f34ec257e7 | ||
|
|
1e5b2c7f62 | ||
|
|
c6b669fc88 | ||
|
|
d814b610da | ||
|
|
5181c74205 | ||
|
|
4cb711e3f8 | ||
|
|
e8aea0728a | ||
|
|
6f809fda73 | ||
|
|
ba84e2a968 | ||
|
|
72387d17ad | ||
|
|
048a4c4b70 | ||
|
|
b262195549 | ||
|
|
68a2fb2be3 | ||
|
|
50911a6a25 | ||
|
|
79f3571b02 | ||
|
|
34ea9c59fd | ||
|
|
92ec2069ad | ||
|
|
20e70e7bc9 | ||
|
|
084f14e973 | ||
|
|
694d3d34b3 | ||
|
|
ed457093b1 | ||
|
|
7d44f6ec9e | ||
|
|
54c140e4f3 | ||
|
|
5987c449b2 | ||
|
|
c7605d12a6 | ||
|
|
d9533de9ea | ||
|
|
bc33e14c35 | ||
|
|
2b06d27729 | ||
|
|
b685ca77f2 | ||
|
|
e5b1fad675 | ||
|
|
eb11eec5bb | ||
|
|
182c2a1554 | ||
|
|
913d7093ea | ||
|
|
938fc1783a | ||
|
|
d452ac0de1 | ||
|
|
95bbeb6634 | ||
|
|
5176bfd331 | ||
|
|
db761cf8ed | ||
|
|
34e03038df | ||
|
|
bb3643541d | ||
|
|
ff99f3605c | ||
|
|
9cf037e992 | ||
|
|
888cdf17b0 | ||
|
|
9aef511891 | ||
|
|
0d88e8be9f | ||
|
|
56d38b3f61 | ||
|
|
a6c56c8655 | ||
|
|
2c84bb478f | ||
|
|
9cdaf06ca9 | ||
|
|
027218f16c | ||
|
|
f1ccb74625 | ||
|
|
cb5fabc6ad | ||
|
|
2448157af8 | ||
|
|
d718cdb225 | ||
|
|
dcc9059041 | ||
|
|
d70eae205d | ||
|
|
ed6922d7eb | ||
|
|
abb099a1c3 | ||
|
|
a4d01bfd11 | ||
|
|
d38c767312 | ||
|
|
aba941e81d | ||
|
|
8c67ad508f | ||
|
|
9ca897963f | ||
|
|
2575b94e8f | ||
|
|
b03e4fb215 | ||
|
|
c0eb2ee4ff | ||
|
|
faa5c9d3db | ||
|
|
bedb0d4159 | ||
|
|
94b9d279a2 | ||
|
|
7c4b029d76 | ||
|
|
9ba3c16e79 | ||
|
|
511b4da9f5 | ||
|
|
2c15dc838e | ||
|
|
73b2ef1d58 | ||
|
|
9d2031f7d0 | ||
|
|
7b609ea781 | ||
|
|
5e918af371 | ||
|
|
6e9cac3b32 | ||
|
|
893cbfe450 | ||
|
|
e40ee486a9 | ||
|
|
58182bc2d3 | ||
|
|
3fb8b10f80 | ||
|
|
6fe533a875 | ||
|
|
feea006fc3 | ||
|
|
73897111d0 | ||
|
|
e76dcb15aa | ||
|
|
538959ea90 | ||
|
|
c33f8ae75b | ||
|
|
3126a5b278 | ||
|
|
5f6c18893e | ||
|
|
cdc6f11d92 | ||
|
|
c4b22c03b9 | ||
|
|
6ab9d0360a | ||
|
|
01da817f61 | ||
|
|
040bd71f82 | ||
|
|
f2b0f7c533 | ||
|
|
a2918887f6 | ||
|
|
7b993c5de6 | ||
|
|
3da7f6cea3 | ||
|
|
7569bdb9cb | ||
|
|
4e8a44650e | ||
|
|
b4346fd47d | ||
|
|
e9a18a6437 | ||
|
|
77b0be5c15 | ||
|
|
4bceae26f2 | ||
|
|
c0f50d41d7 | ||
|
|
0b2aa3798a | ||
|
|
13cd718c90 | ||
|
|
39c7ba39cf | ||
|
|
6635e0aeff | ||
|
|
98dabd7ff5 | ||
|
|
a244cc13d0 | ||
|
|
fb71ea426d | ||
|
|
217f32eb88 | ||
|
|
7fb36123e9 | ||
|
|
46220ac268 | ||
|
|
887dbaca2c | ||
|
|
44369cb12b | ||
|
|
56c772de4c | ||
|
|
93e34d00e5 | ||
|
|
46f048b07c | ||
|
|
4b130b4319 | ||
|
|
da0f70bb5f | ||
|
|
5821816228 | ||
|
|
8eaa541c8c | ||
|
|
e4adf16eba | ||
|
|
a8d257e7d6 | ||
|
|
49c592013c | ||
|
|
80db9c13c8 | ||
|
|
cf87796072 | ||
|
|
8859e6b1a0 | ||
|
|
1f23991a72 | ||
|
|
2be252d7b4 | ||
|
|
2c1acbdc62 | ||
|
|
61e751f278 | ||
|
|
cdd62ed269 | ||
|
|
f12094ced6 | ||
|
|
b5c4aa4598 | ||
|
|
da8ae2be43 | ||
|
|
157c011953 | ||
|
|
ae6807f8e3 | ||
|
|
17ba74485a | ||
|
|
1f2eef5f8f | ||
|
|
1b6513b954 | ||
|
|
74fddff589 | ||
|
|
7e24f810c6 | ||
|
|
306cf1110f | ||
|
|
b610eede20 | ||
|
|
21f671555a | ||
|
|
951059aa3a | ||
|
|
e68254eff3 | ||
|
|
61cf619f4b | ||
|
|
7914a09d4b | ||
|
|
95e2cbca15 | ||
|
|
724bb0fc17 | ||
|
|
fb171cd5ac | ||
|
|
cb46be0430 | ||
|
|
7ffc9b9e3b | ||
|
|
58a65c69e9 | ||
|
|
d1d50ec469 | ||
|
|
e25e32ee8a | ||
|
|
d560a39856 | ||
|
|
00e08359a3 | ||
|
|
116ce622d4 | ||
|
|
082fb5d959 | ||
|
|
043f28cc23 | ||
|
|
b7413dd22c | ||
|
|
586737247e | ||
|
|
055b7f0055 | ||
|
|
4a042bade2 | ||
|
|
3aa018a15c | ||
|
|
8508dc6c9d | ||
|
|
fbba0cd037 | ||
|
|
ae7c51a964 | ||
|
|
0c49026c9a | ||
|
|
bc29166d4c | ||
|
|
0f3e3f7337 | ||
|
|
a03db0ac6c | ||
|
|
932ed8653e | ||
|
|
5ab3f067fe | ||
|
|
3df028cb18 | ||
|
|
e423dd96de | ||
|
|
bef58bf395 | ||
|
|
131abf5883 | ||
|
|
3859bd713e | ||
|
|
ac40f1838f | ||
|
|
9055a5f3d5 | ||
|
|
d32caeab52 | ||
|
|
15f4aa8f98 | ||
|
|
99ce2ea565 | ||
|
|
87200f3c2a | ||
|
|
214632c5ec | ||
|
|
64fb4eda61 | ||
|
|
f9e30c4c77 | ||
|
|
bfa48439c8 | ||
|
|
a717403db8 | ||
|
|
fdf13f91cb | ||
|
|
65e0969721 | ||
|
|
8f265e7660 | ||
|
|
98e6b97072 | ||
|
|
a3e9074955 | ||
|
|
04afada5b3 | ||
|
|
3e183fbd28 | ||
|
|
849d6a17be | ||
|
|
20ba069fe0 | ||
|
|
c82093f153 | ||
|
|
010785d8db | ||
|
|
69774d445c | ||
|
|
b42c632474 | ||
|
|
f195e363a5 | ||
|
|
40f99152ce | ||
|
|
3b1170b148 | ||
|
|
3a20091d3a | ||
|
|
e5206c3b50 | ||
|
|
fbc736e1cc | ||
|
|
d7da2ba9e7 | ||
|
|
a5784c8f0b | ||
|
|
83fbaca6f2 |
No files matched your search
Generated
+2
@@ -2008,6 +2008,7 @@ dependencies = [
|
||||
"graphene-hash",
|
||||
"graphic-types",
|
||||
"gungraun",
|
||||
"interpreted-executor",
|
||||
"js-sys",
|
||||
"log",
|
||||
"mmap-io",
|
||||
@@ -2936,6 +2937,7 @@ dependencies = [
|
||||
"graph-craft",
|
||||
"graphene-core",
|
||||
"graphene-std",
|
||||
"graphic-types",
|
||||
"gungraun",
|
||||
"log",
|
||||
"once_cell",
|
||||
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::graphic::Graphic>"}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[366962978353611840,{"inputs":[{"Node":{"node_id":8366826746721323000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"contextLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::graphic::Graphic>"}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[366962978353611840,{"inputs":[{"Node":{"node_id":8366826746721323000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1789832635968548900,{"inputs":[{"Node":{"node_id":1924303400883620400,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.9822506,"green":0.2050787Line truncated
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1268.999999999999,634.9999999999992]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183952488591282082,{"inputs":[{"Node":{"node_id":17965270694495451178,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,-6.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exportsLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1268.999999999999,634.9999999999992]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[183952488591282082,{"inputs":[{"Node":{"node_id":17965270694495451178,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,-6.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"impleLine truncated
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5],"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4388711862172196665,{"inputs":[],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"U32":0},"exposed":false}},{"Value":{"tagged_value":{"F64":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"U32":3},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"CellularDistanceFunction":"Hybrid"},"exposed":false}},{"Value":{"tagged_valLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5],"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[4388711862172196665,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":"","sources":[]}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"U32":0},"exposed":false}},{"Value":{"tagged_value":{"F64":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"U32":3},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"CellularDistanceFunction":"Hybrid"},"exposed":false}},{"Value":{"tagged_value":{"CellularReturnType":"CellValue"},"exposed":false}},{"ValueLine truncated
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[140396870212231820,{"inputs":[{"Node":{"node_id":18095952297474762348,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Intersect"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[20.0,0.0,0.0,20.0,-10.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::artboard::Artboard>"}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8549927,"green":0.71569365,"blue":0.48514998,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":4}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphiLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[140396870212231820,{"inputs":[{"Node":{"node_id":18095952297474762348,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Intersect"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[20.0,0.0,0.0,20.0,-10.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::artboard::Artboard>"}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8549927,"green":0.71569365,"blue":0.48514998,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Node":{"node_id":6,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":4}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[2,{"inputs":Line truncated
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::graphic::Graphic>"}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"F64":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"F64":63.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"F64":4000.0},"exposed":false}},{"Value":{"tagged_value":{"F64":500.0},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.9911022,"green":0.6514057,"blue":0.39157256,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":null},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2288754089236120499,{"inputs":[{"Node":{"node_id":14158287945315818946,"output_index":0}}],"call_argument":{"Concrete":Line truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::graphic::Graphic>"}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"F64":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"F64":63.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"F64":4000.0},"exposed":false}},{"Value":{"tagged_value":{"F64":500.0},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.9911022,"green":0.6514057,"blue":0.39157256,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":null},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2288754089236120499,{"inputs":[{"Node":{"node_id":14158287945315818946,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"core_types::vector::SplineNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":Line truncated
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":6559102076450693000,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[31.556350940025634,-2.7755575615628914e-17,2.7755575615628914e-17,31.556350940025634,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0Line truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":6559102076450693000,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[31.55635094002563,-2.7755575615628914e-17,2.7755575615628914e-17,31.55635094002563,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"stroke":[[1,0],[2,0],[3,0],[4,0],[5,0],[6,0],[7,0],[8,0],[9,0],[10,0]]},"regions":{"add":[],"remove":[],"segLine truncated
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]],"stroke":[[1,0],[2,0],[3,0],[4,0],[5,0]]},"regions":{"add":[0],"remove":[],"segment_range":[[0,{"start":1,"end":5}]],"fill":[[0,0]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Concrete":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"StrinLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]],"stroke":[[1,0],[2,0],[3,0],[4,0],[5,0]]},"regions":{"add":[0],"remove":[],"segment_range":[[0,{"start":1,"end":5}]],"fill":[[0,0]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Concrete":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implemeLine truncated
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[74,{"inputs":[{"Node":{"node_id":75,"output_index":0}},{"Node":{"node_id":81,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[75,{"inputs":[{"Node":{"node_id":76,"output_index":0}},{"Node":{"node_id":161,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scLine truncated
|
||||
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[74,{"inputs":[{"Node":{"node_id":75,"output_index":0}},{"Node":{"node_id":81,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[75,{"inputs":[{"Node":{"node_id":76,"output_index":0}},{"Node":{"node_id":161,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[76,{"inputs":[{"Node":{"node_id":77,"output_index":0}},{"Node":{"node_id":16164610528699022118,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodesLine truncated
|
||||
@@ -1,6 +1,5 @@
|
||||
pub mod node {
|
||||
pub const CALL_ARGUMENT: &str = "call_argument";
|
||||
pub const CONTEXT_FEATURES: &str = "context_features";
|
||||
pub const VISIBLE: &str = "visible";
|
||||
pub const SKIP_DEDUPLICATION: &str = "skip_deduplication";
|
||||
pub const REFLECTION_METADATA: &str = "reflection_metadata";
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use core_types::Context;
|
||||
use core_types::context::ContextDependencies;
|
||||
use core_types::uuid::NodeId as RuntimeNodeId;
|
||||
use graph_craft::concrete;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
@@ -390,9 +389,6 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(doc_node: &DocumentNode, locatio
|
||||
attributes
|
||||
.set_if_not_default(node::CALL_ARGUMENT, &doc_node.call_argument, &concrete!(Context), timestamp)
|
||||
.map_err(map_serialization_error(node::CALL_ARGUMENT))?;
|
||||
attributes
|
||||
.set_if_not_default(node::CONTEXT_FEATURES, &doc_node.context_features, &ContextDependencies::default(), timestamp)
|
||||
.map_err(map_serialization_error(node::CONTEXT_FEATURES))?;
|
||||
attributes
|
||||
.set_if_not_default(node::VISIBLE, &doc_node.visible, &true, timestamp)
|
||||
.map_err(map_serialization_error(node::VISIBLE))?;
|
||||
|
||||
@@ -14,7 +14,9 @@ use crate::{NetworkId, NodeMetadataSource, PeerId, Position, Registry};
|
||||
/// Test networks with Import inputs will fail compilation (which is expected).
|
||||
fn verify_network_compiles(network: &NodeNetwork) -> Result<(), String> {
|
||||
let compiler = Compiler {};
|
||||
compiler.compile_single(network.clone()).map_err(|e| format!("Compilation failed: {:?}", e))?;
|
||||
compiler
|
||||
.compile_single(network.clone(), &graph_craft::proto::Registry::new())
|
||||
.map_err(|e| format!("Compilation failed: {:?}", e))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -246,11 +248,6 @@ fn test_nested_network_flattening() {
|
||||
#[test]
|
||||
fn test_metadata_preservation() {
|
||||
// Create a network with nodes that have non-default metadata
|
||||
let context_features = ContextDependencies::new(
|
||||
core_types::context::ContextFeatures::FOOTPRINT | core_types::context::ContextFeatures::REAL_TIME,
|
||||
core_types::context::ContextFeatures::empty(),
|
||||
);
|
||||
|
||||
let network = NodeNetwork {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [
|
||||
@@ -260,7 +257,6 @@ fn test_metadata_preservation() {
|
||||
inputs: vec![NodeInput::import(concrete!(f64), 0), NodeInput::import(Type::Generic(Cow::Borrowed("T")), 1)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("test::NodeWithMetadata")),
|
||||
call_argument: concrete!(String),
|
||||
context_features,
|
||||
visible: false, // Non-default value
|
||||
skip_deduplication: true, // Non-default value
|
||||
..Default::default()
|
||||
@@ -294,8 +290,12 @@ fn test_metadata_preservation() {
|
||||
let conv_node_1 = converted.nodes.get(&NodeId(1)).unwrap();
|
||||
assert_eq!(orig_node_1.call_argument, conv_node_1.call_argument, "call_argument for node 1 should be preserved");
|
||||
|
||||
// Verify context_features is preserved
|
||||
assert_eq!(orig_node_0.context_features, conv_node_0.context_features, "context_features should be preserved");
|
||||
// Verify context_features is not stored
|
||||
assert_eq!(
|
||||
conv_node_0.context_features,
|
||||
ContextDependencies::default(),
|
||||
"context_features should resolve at compile, not round-trip"
|
||||
);
|
||||
|
||||
// Verify visible is preserved
|
||||
assert_eq!(orig_node_0.visible, conv_node_0.visible, "visible should be preserved");
|
||||
|
||||
@@ -310,8 +310,8 @@ fn convert_node(
|
||||
implementation: convert_implementation(context, &node.implementation, metadata_path, runtime_node_id, node_collector, network_collector)?,
|
||||
visible: node.attributes.get_or(node::VISIBLE, true),
|
||||
skip_deduplication: node.attributes.get_or(node::SKIP_DEDUPLICATION, false),
|
||||
context_features: node.attributes.get_or_default(node::CONTEXT_FEATURES),
|
||||
// Regenerated during compilation; not stored.
|
||||
context_features: Default::default(),
|
||||
original_location: Default::default(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -180,6 +180,11 @@ fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'st
|
||||
if let Some(list) = introspected_data.downcast_ref::<List<NodeId>>() {
|
||||
return Some(table_node_id_path_layout_with_breadcrumb(list, data));
|
||||
}
|
||||
// The path's plain value form, produced by `path_of_subgraph` on leveled wires.
|
||||
if let Some(path) = introspected_data.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));
|
||||
}
|
||||
generate_layout_downcast!(introspected_data, data, [
|
||||
List<Artboard>,
|
||||
List<Graphic>,
|
||||
@@ -307,7 +312,7 @@ impl<T: TableItemLayout> TableItemLayout for List<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for Artboard {
|
||||
impl TableItemLayout for Artboard<'_> {
|
||||
fn type_name() -> &'static str {
|
||||
"Artboard"
|
||||
}
|
||||
@@ -323,7 +328,7 @@ impl TableItemLayout for Artboard {
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for Graphic {
|
||||
impl TableItemLayout for Graphic<'_> {
|
||||
fn type_name() -> &'static str {
|
||||
"Graphic"
|
||||
}
|
||||
@@ -336,6 +341,7 @@ impl TableItemLayout for Graphic {
|
||||
Self::Color(list) => list.identifier(),
|
||||
Self::Gradient(list) => list.identifier(),
|
||||
Self::Text(list) => list.identifier(),
|
||||
Self::Group(_) => "Group".to_string(),
|
||||
}
|
||||
}
|
||||
// Don't put a breadcrumb for Graphic
|
||||
@@ -351,6 +357,7 @@ impl TableItemLayout for Graphic {
|
||||
Self::Color(list) => list.layout_with_breadcrumb(data),
|
||||
Self::Gradient(list) => list.layout_with_breadcrumb(data),
|
||||
Self::Text(list) => list.layout_with_breadcrumb(data),
|
||||
Self::Group(_) => Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1009,6 +1016,11 @@ fn drilldown_attribute_layout(any: &dyn Any, data: &mut LayoutData) -> Option<Ve
|
||||
if let Some(path) = any.downcast_ref::<List<NodeId>>() {
|
||||
return Some(table_node_id_path_layout_with_breadcrumb(path, 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 {
|
||||
( $($ty:ty),* $(,)? ) => {
|
||||
$(
|
||||
|
||||
@@ -248,11 +248,11 @@ pub enum DocumentMessage {
|
||||
// `UpdateFillAttributes` and `UpdateStrokeAttributes` are produced inside `editor.handle_message` by `node_graph_executor.rs` and consumed in the same dispatch loop, so it never reaches that serialization point.
|
||||
#[serde(skip)]
|
||||
UpdateFillAttributes {
|
||||
fill_attributes: HashMap<NodeId, Arc<List<Graphic>>>,
|
||||
fill_attributes: HashMap<NodeId, Arc<List<Graphic<'static>>>>,
|
||||
},
|
||||
#[serde(skip)]
|
||||
UpdateStrokeAttributes {
|
||||
stroke_attributes: HashMap<NodeId, Arc<List<Graphic>>>,
|
||||
stroke_attributes: HashMap<NodeId, Arc<List<Graphic<'static>>>>,
|
||||
},
|
||||
Undo,
|
||||
UngroupSelectedLayers,
|
||||
|
||||
@@ -457,7 +457,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
let Some(fill_node_id) = self.existing_proto_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, true) else {
|
||||
return;
|
||||
};
|
||||
let input_connector = InputConnector::node(fill_node_id, graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX);
|
||||
let input_connector = InputConnector::node(fill_node_id, graphene_std::vector::fill::FillInput::INDEX);
|
||||
let backup_input_connector = InputConnector::node(fill_node_id, graphene_std::vector::fill::BackupColorInput::INDEX);
|
||||
|
||||
self.set_input_with_refresh(backup_input_connector, NodeInput::value(TaggedValue::Color(color), false), true);
|
||||
@@ -474,7 +474,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
|
||||
// Skip the rerender on all but the last input so the whole update triggers a single graph run
|
||||
self.set_input_with_refresh(
|
||||
InputConnector::node(fill_node_id, graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX),
|
||||
InputConnector::node(fill_node_id, graphene_std::vector::fill::FillInput::INDEX),
|
||||
NodeInput::value(TaggedValue::Gradient(gradient), false),
|
||||
true,
|
||||
);
|
||||
@@ -715,7 +715,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
return;
|
||||
};
|
||||
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintInput::<List<Graphic>>::INDEX);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintInput::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Color(color), false), true);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::WeightInput::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.weight), false), true);
|
||||
@@ -729,7 +729,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.join_miter_limit), false), false);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintOrderInput::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::PaintOrder(stroke.paint_order), false), false);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashLengthsInput::<graphene_std::list::List<f64>>::INDEX);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashLengthsInput::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64Array(stroke.dash_lengths), false), true);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashOffsetInput::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.dash_offset), false), true);
|
||||
|
||||
@@ -159,7 +159,8 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphic::to_graphic::IDENTIFIER),
|
||||
..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.
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::import(generic!(T), 1)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphic::wrap_graphic::IDENTIFIER),
|
||||
@@ -174,12 +175,8 @@ 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,
|
||||
// so editor tools (e.g. selection, click target routing) can trace data back to its owning layer.
|
||||
DocumentNode {
|
||||
inputs: vec![
|
||||
NodeInput::node(NodeId(1), 0),
|
||||
NodeInput::value(TaggedValue::String(graphene_std::ATTR_EDITOR_LAYER_PATH.to_string()), false),
|
||||
NodeInput::node(NodeId(2), 0),
|
||||
],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphic::write_attribute::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(1), 0), NodeInput::node(NodeId(2), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphic::stamp_layer_path::IDENTIFIER),
|
||||
..Default::default()
|
||||
},
|
||||
// The monitor node is used to display a thumbnail in the UI
|
||||
@@ -236,7 +233,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
// 3: write_attribute
|
||||
// 3: stamp_layer_path
|
||||
DocumentNodeMetadata {
|
||||
persistent_metadata: DocumentNodePersistentMetadata {
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-14, -1)),
|
||||
@@ -287,7 +284,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
call_argument: generic!(T),
|
||||
implementation: DocumentNodeImplementation::ProtoNode(artboard::create_artboard::IDENTIFIER),
|
||||
inputs: vec![
|
||||
NodeInput::import(concrete!(TaggedValue), 1),
|
||||
NodeInput::node(NodeId(6), 0),
|
||||
NodeInput::import(concrete!(TaggedValue), 2),
|
||||
NodeInput::import(concrete!(TaggedValue), 3),
|
||||
NodeInput::import(concrete!(TaggedValue), 4),
|
||||
@@ -304,17 +301,13 @@ 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,
|
||||
// so editor tools (e.g. selection, click target routing) can trace data back to its owning layer.
|
||||
DocumentNode {
|
||||
inputs: vec![
|
||||
NodeInput::node(NodeId(0), 0),
|
||||
NodeInput::value(TaggedValue::String(graphene_std::ATTR_EDITOR_LAYER_PATH.to_string()), false),
|
||||
NodeInput::node(NodeId(1), 0),
|
||||
],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphic::write_attribute::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::node(NodeId(1), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphic::stamp_layer_path::IDENTIFIER),
|
||||
..Default::default()
|
||||
},
|
||||
// The monitor node is used to display a thumbnail in the UI.
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::node(NodeId(2), 0)],
|
||||
inputs: vec![NodeInput::node(NodeId(7), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(memo::monitor::IDENTIFIER),
|
||||
call_argument: generic!(T),
|
||||
skip_deduplication: true,
|
||||
@@ -328,6 +321,27 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphic::extend::IDENTIFIER),
|
||||
..Default::default()
|
||||
},
|
||||
// Content coercion into a graphic level, evaluated within the artboard's footprint
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::import(generic!(T), 1)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphic::to_graphic::IDENTIFIER),
|
||||
..Default::default()
|
||||
},
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::node(NodeId(5), 0), NodeInput::import(concrete!(TaggedValue), 2)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(artboard::translate_footprint::IDENTIFIER),
|
||||
..Default::default()
|
||||
},
|
||||
// Lifts the artboard element onto a one-lane level so it concatenates with the base stack
|
||||
DocumentNode {
|
||||
inputs: vec![
|
||||
NodeInput::node(NodeId(2), 0),
|
||||
NodeInput::value(TaggedValue::U32(1), false),
|
||||
NodeInput::value(TaggedValue::Bool(false), false),
|
||||
],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(repeat_nodes::repeat::IDENTIFIER),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
@@ -395,7 +409,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
// 2: write_attribute
|
||||
// 2: stamp_layer_path
|
||||
DocumentNodeMetadata {
|
||||
persistent_metadata: DocumentNodePersistentMetadata {
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-14, -3)),
|
||||
@@ -419,6 +433,30 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
// 5: to_graphic
|
||||
DocumentNodeMetadata {
|
||||
persistent_metadata: DocumentNodePersistentMetadata {
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-35, -3)),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
// 6: translate_footprint
|
||||
DocumentNodeMetadata {
|
||||
persistent_metadata: DocumentNodePersistentMetadata {
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-28, -3)),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
// 7: repeat (the one-lane lift)
|
||||
DocumentNodeMetadata {
|
||||
persistent_metadata: DocumentNodePersistentMetadata {
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-10, -3)),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
|
||||
+1
-2
@@ -42,7 +42,6 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
|
||||
fields,
|
||||
description,
|
||||
properties,
|
||||
context_features,
|
||||
..
|
||||
} = metadata;
|
||||
|
||||
@@ -78,7 +77,7 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
|
||||
implementation: DocumentNodeImplementation::ProtoNode(id.clone()),
|
||||
visible: true,
|
||||
skip_deduplication: false,
|
||||
context_features: ContextDependencies::from(context_features.as_slice()),
|
||||
context_features: ContextDependencies::default(),
|
||||
..Default::default()
|
||||
},
|
||||
persistent_node_metadata: DocumentNodePersistentMetadata {
|
||||
|
||||
@@ -1769,7 +1769,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
let is_text_node = reference.as_ref().is_some_and(|r| *r == DefinitionIdentifier::ProtoNode(graphene_std::text::text::IDENTIFIER));
|
||||
let is_stroke_node = reference.as_ref().is_some_and(|r| *r == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER));
|
||||
let is_fill_node = reference.as_ref().is_some_and(|r| *r == DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER));
|
||||
let is_fill_input = is_fill_node && input_index == graphene_std::vector::fill::FillInput::<graphene_std::list::List<Graphic>>::INDEX;
|
||||
let is_fill_input = is_fill_node && input_index == graphene_std::vector::fill::FillInput::INDEX;
|
||||
let is_shape_generator_node = reference.as_ref().is_some_and(|r| {
|
||||
[regular_polygon::IDENTIFIER, star::IDENTIFIER, arc::IDENTIFIER, spiral::IDENTIFIER, grid::IDENTIFIER, arrow::IDENTIFIER]
|
||||
.into_iter()
|
||||
|
||||
@@ -16,7 +16,6 @@ use graph_craft::application_io::resource::ResourceId;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput};
|
||||
use graph_craft::{Type, concrete};
|
||||
use graphene_std::Graphic;
|
||||
use graphene_std::NodeInputDecleration;
|
||||
use graphene_std::animation::RealTimeMode;
|
||||
use graphene_std::brush::brush_stroke::BrushStroke;
|
||||
@@ -252,6 +251,10 @@ pub(crate) fn property_from_type(
|
||||
Some(x) if x == TypeId::of::<List<Color>>() => color_widget(default_info, ColorInput::default().allow_none(true)),
|
||||
Some(x) if x == TypeId::of::<List<GradientStops>>() => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
Some(x) if x == TypeId::of::<List<BrushStroke>>() => brush_strokes_widget(default_info).into(),
|
||||
// Leveled wires type by their element; each element keeps its list form's widget.
|
||||
Some(x) if x == TypeId::of::<Color>() => color_widget(default_info, ColorInput::default().allow_none(true)),
|
||||
Some(x) if x == TypeId::of::<GradientStops>() => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
Some(x) if x == TypeId::of::<BrushStroke>() => brush_strokes_widget(default_info).into(),
|
||||
// ============
|
||||
// STRUCT TYPES
|
||||
// ============
|
||||
@@ -2168,7 +2171,7 @@ pub(crate) fn rectangle_properties(node_id: NodeId, context: &mut NodeProperties
|
||||
use graphene_std::vector::generator_nodes::rectangle::*;
|
||||
|
||||
// Corner Radius
|
||||
let mut corner_radius_row_1 = start_widgets(ParameterWidgetsInfo::new(node_id, CornerRadiusInput::<f64>::INDEX, true, context));
|
||||
let mut corner_radius_row_1 = start_widgets(ParameterWidgetsInfo::new(node_id, CornerRadiusInput::INDEX, true, context));
|
||||
corner_radius_row_1.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
|
||||
let mut corner_radius_row_2 = vec![Separator::new(SeparatorStyle::Unrelated).widget_instance()];
|
||||
@@ -2188,7 +2191,7 @@ pub(crate) fn rectangle_properties(node_id: NodeId, context: &mut NodeProperties
|
||||
};
|
||||
if let Some(&TaggedValue::Bool(is_individual)) = input.as_non_exposed_value() {
|
||||
// Values
|
||||
let Some(input) = document_node.inputs.get(CornerRadiusInput::<f64>::INDEX) else {
|
||||
let Some(input) = document_node.inputs.get(CornerRadiusInput::INDEX) else {
|
||||
log::warn!("A widget failed to be built because its node's input index is invalid.");
|
||||
return vec![];
|
||||
};
|
||||
@@ -2216,7 +2219,7 @@ pub(crate) fn rectangle_properties(node_id: NodeId, context: &mut NodeProperties
|
||||
.into(),
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: CornerRadiusInput::<f64>::INDEX,
|
||||
input_index: CornerRadiusInput::INDEX,
|
||||
value: TaggedValue::F64(uniform_val),
|
||||
}
|
||||
.into(),
|
||||
@@ -2236,7 +2239,7 @@ pub(crate) fn rectangle_properties(node_id: NodeId, context: &mut NodeProperties
|
||||
.into(),
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: CornerRadiusInput::<f64>::INDEX,
|
||||
input_index: CornerRadiusInput::INDEX,
|
||||
value: TaggedValue::F64Array(individual_val_for_switch.clone()),
|
||||
}
|
||||
.into(),
|
||||
@@ -2259,13 +2262,13 @@ pub(crate) fn rectangle_properties(node_id: NodeId, context: &mut NodeProperties
|
||||
};
|
||||
TextInput::default()
|
||||
.value(individual_val.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(", "))
|
||||
.on_update(optionally_update_value(move |x: &TextInput| from_string(&x.value), node_id, CornerRadiusInput::<f64>::INDEX))
|
||||
.on_update(optionally_update_value(move |x: &TextInput| from_string(&x.value), node_id, CornerRadiusInput::INDEX))
|
||||
.widget_instance()
|
||||
} else {
|
||||
NumberInput::default()
|
||||
.value(Some(uniform_val))
|
||||
.unit(" px")
|
||||
.on_update(update_value(move |x: &NumberInput| TaggedValue::F64(x.value.unwrap()), node_id, CornerRadiusInput::<f64>::INDEX))
|
||||
.on_update(update_value(move |x: &NumberInput| TaggedValue::F64(x.value.unwrap()), node_id, CornerRadiusInput::INDEX))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance()
|
||||
};
|
||||
@@ -2453,13 +2456,13 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
|
||||
Other,
|
||||
}
|
||||
|
||||
let connector = InputConnector::node(node_id, FillInput::<List<Graphic>>::INDEX);
|
||||
let connector = InputConnector::node(node_id, FillInput::INDEX);
|
||||
let input_type = context.network_interface.input_type(&connector, context.selection_network_path);
|
||||
|
||||
// Pass blank_assist=false because the assist slot is filled below ("Reverse Stops" button when in gradient mode)
|
||||
let mut widgets_first_row = start_widgets(ParameterWidgetsInfo::new(node_id, FillInput::<List<Graphic>>::INDEX, false, context));
|
||||
let mut widgets_first_row = start_widgets(ParameterWidgetsInfo::new(node_id, FillInput::INDEX, false, context));
|
||||
|
||||
if get_document_node(node_id, context).is_ok_and(|node| node.inputs.get(FillInput::<List<Graphic>>::INDEX).is_some_and(|input| input.is_exposed())) {
|
||||
if get_document_node(node_id, context).is_ok_and(|node| node.inputs.get(FillInput::INDEX).is_some_and(|input| input.is_exposed())) {
|
||||
return vec![LayoutGroup::row(widgets_first_row)];
|
||||
}
|
||||
|
||||
@@ -2470,7 +2473,7 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
|
||||
let fill = match input_type.compiled_nested_type() {
|
||||
Some(ty) if ty == &concrete!(List<Color>) => {
|
||||
if let Ok(document_node) = get_document_node(node_id, context) {
|
||||
let color = match document_node.inputs[FillInput::<List<Graphic>>::INDEX].as_value() {
|
||||
let color = match document_node.inputs[FillInput::INDEX].as_value() {
|
||||
Some(&TaggedValue::Color(c)) => c,
|
||||
_ => None,
|
||||
};
|
||||
@@ -2521,7 +2524,7 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
|
||||
let reverse_button = IconButton::new("Reverse", 24)
|
||||
.tooltip_label("Reverse Stops")
|
||||
.tooltip_description("Reverse the gradient color stops.")
|
||||
.on_update(update_value(move |_| TaggedValue::Gradient(stops.reversed()), node_id, FillInput::<List<Graphic>>::INDEX))
|
||||
.on_update(update_value(move |_| TaggedValue::Gradient(stops.reversed()), node_id, FillInput::INDEX))
|
||||
.widget_instance();
|
||||
widgets_first_row.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
widgets_first_row.push(reverse_button);
|
||||
@@ -2545,7 +2548,7 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
|
||||
messages: Box::new([
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: FillInput::<List<Graphic>>::INDEX,
|
||||
input_index: FillInput::INDEX,
|
||||
value: TaggedValue::Color(color),
|
||||
}
|
||||
.into(),
|
||||
@@ -2562,7 +2565,7 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
|
||||
messages: Box::new([
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: FillInput::<List<Graphic>>::INDEX,
|
||||
input_index: FillInput::INDEX,
|
||||
value: TaggedValue::Gradient(gradient.clone()),
|
||||
}
|
||||
.into(),
|
||||
@@ -2603,11 +2606,11 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
|
||||
let entries = vec![
|
||||
RadioEntryData::new("solid")
|
||||
.label("Solid")
|
||||
.on_update(update_value(move |_| TaggedValue::Color(backup_color), node_id, FillInput::<List<Graphic>>::INDEX))
|
||||
.on_update(update_value(move |_| TaggedValue::Color(backup_color), node_id, FillInput::INDEX))
|
||||
.on_commit(commit_value),
|
||||
RadioEntryData::new("gradient")
|
||||
.label("Gradient")
|
||||
.on_update(update_value(move |_| TaggedValue::Gradient(backup_gradient.clone()), node_id, FillInput::<List<Graphic>>::INDEX))
|
||||
.on_update(update_value(move |_| TaggedValue::Gradient(backup_gradient.clone()), node_id, FillInput::INDEX))
|
||||
.on_commit(commit_value),
|
||||
];
|
||||
|
||||
@@ -2713,14 +2716,14 @@ pub fn stroke_properties(node_id: NodeId, context: &mut NodePropertiesContext) -
|
||||
_ => &StrokeJoin::Miter,
|
||||
};
|
||||
|
||||
let has_dash_lengths = match &document_node.inputs[DashLengthsInput::<List<f64>>::INDEX].as_value() {
|
||||
let has_dash_lengths = match &document_node.inputs[DashLengthsInput::INDEX].as_value() {
|
||||
Some(TaggedValue::F64Array(values)) => values.is_empty(),
|
||||
_ => true,
|
||||
};
|
||||
let miter_limit_disabled = join_value != &StrokeJoin::Miter;
|
||||
|
||||
let color = color_widget(
|
||||
ParameterWidgetsInfo::new(node_id, PaintInput::<List<Graphic>>::INDEX, true, context),
|
||||
ParameterWidgetsInfo::new(node_id, PaintInput::INDEX, true, context),
|
||||
crate::messages::layout::utility_types::widgets::button_widgets::ColorInput::default(),
|
||||
);
|
||||
let weight = number_widget(ParameterWidgetsInfo::new(node_id, WeightInput::INDEX, true, context), NumberInput::default().unit(" px").min(0.));
|
||||
@@ -2740,10 +2743,7 @@ pub fn stroke_properties(node_id: NodeId, context: &mut NodePropertiesContext) -
|
||||
.for_socket(ParameterWidgetsInfo::new(node_id, PaintOrderInput::INDEX, true, context))
|
||||
.property_row();
|
||||
let disabled_number_input = NumberInput::default().unit(" px").disabled(has_dash_lengths);
|
||||
let dash_lengths = array_of_number_widget(
|
||||
ParameterWidgetsInfo::new(node_id, DashLengthsInput::<List<f64>>::INDEX, true, context),
|
||||
TextInput::default().centered(true),
|
||||
);
|
||||
let dash_lengths = array_of_number_widget(ParameterWidgetsInfo::new(node_id, DashLengthsInput::INDEX, true, context), TextInput::default().centered(true));
|
||||
let number_input = disabled_number_input;
|
||||
let dash_offset = number_widget(ParameterWidgetsInfo::new(node_id, DashOffsetInput::INDEX, true, context), number_input);
|
||||
|
||||
|
||||
@@ -31,11 +31,11 @@ impl FrontendGraphDataType {
|
||||
TaggedValue::String(_) => Self::Typography,
|
||||
// Types whose `TaggedValue` variant has been removed are routed through `TypeDefault` and identified by the descriptor's type name.
|
||||
TaggedValue::TypeDefault(td) => match td.name.as_ref() {
|
||||
n if n == std::any::type_name::<List<Graphic>>() => Self::Graphic,
|
||||
n if n == std::any::type_name::<List<Artboard>>() => Self::Artboard,
|
||||
n if n == std::any::type_name::<List<Raster<CPU>>>() => Self::Raster,
|
||||
n if n == std::any::type_name::<List<Vector>>() => Self::Vector,
|
||||
n if n == std::any::type_name::<List<String>>() => Self::Typography,
|
||||
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Graphic>>()) => Self::Graphic,
|
||||
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Artboard>>()) => Self::Artboard,
|
||||
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Raster<CPU>>>()) => Self::Raster,
|
||||
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Vector>>()) => Self::Vector,
|
||||
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<String>>()) => Self::Typography,
|
||||
_ => Self::General,
|
||||
},
|
||||
_ => Self::General,
|
||||
|
||||
@@ -20,6 +20,29 @@ pub fn load_demo(file_name: &str) -> DocumentMessageHandler {
|
||||
DocumentMessageHandler::deserialize_document(&content).unwrap_or_else(|e| panic!("Failed to deserialize {path}: {e:?}"))
|
||||
}
|
||||
|
||||
/// Dev tool for the flip: runs each demo through the full open-time migration and writes the
|
||||
/// re-saved form into the directory named by `DEMO_OUT`, so the CLI can render migrated copies
|
||||
/// while the checked-in originals stay pristine until the flip's re-save.
|
||||
#[test]
|
||||
#[ignore = "dev tool: set DEMO_OUT and run explicitly"]
|
||||
fn migrate_demo_artwork_into_demo_out() {
|
||||
use crate::messages::portfolio::document_migration::{document_migration_reset_node_definition, document_migration_string_preprocessing, document_migration_upgrades};
|
||||
let out_dir = std::env::var("DEMO_OUT").expect("set DEMO_OUT to the output directory");
|
||||
for entry in std::fs::read_dir("../demo-artwork").unwrap() {
|
||||
let path = entry.unwrap().path();
|
||||
if path.extension().and_then(|extension| extension.to_str()) != Some("graphite") {
|
||||
continue;
|
||||
}
|
||||
let content = std::fs::read_to_string(&path).unwrap();
|
||||
let content = document_migration_string_preprocessing(content);
|
||||
let reset = document_migration_reset_node_definition(&content);
|
||||
let mut document = DocumentMessageHandler::deserialize_document(&content).unwrap_or_else(|e| panic!("Failed to deserialize {}: {e:?}", path.display()));
|
||||
document_migration_upgrades(&mut document, reset);
|
||||
let out = format!("{out_dir}/{}", path.file_name().unwrap().to_string_lossy());
|
||||
std::fs::write(out, document.serialize_document()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// Walk every node in every nested network and collect `(network_path, local_id)` pairs, so a test can
|
||||
/// iterate every node addressable from the metadata side.
|
||||
pub fn node_paths(interface: &NodeNetworkInterface) -> Vec<(Vec<NodeId>, NodeId)> {
|
||||
|
||||
@@ -43,10 +43,10 @@ pub struct DocumentMetadata {
|
||||
pub layer_vector_data: HashMap<LayerNodeIdentifier, Arc<Vector>>,
|
||||
/// Per-layer `ATTR_FILL` attribute, exposed so message handlers can read paint
|
||||
/// information that lives on the list.
|
||||
pub layer_fill_attributes: HashMap<LayerNodeIdentifier, Arc<List<Graphic>>>,
|
||||
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>>>,
|
||||
pub layer_stroke_attributes: HashMap<LayerNodeIdentifier, Arc<List<Graphic<'static>>>>,
|
||||
/// Transform from document space to viewport space.
|
||||
pub document_to_viewport: DAffine2,
|
||||
}
|
||||
|
||||
@@ -24,7 +24,6 @@ use graph_craft::Type;
|
||||
use graph_craft::application_io::resource::ResourceId;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork, OldDocumentNodeImplementation, OldNodeNetwork};
|
||||
use graphene_std::ContextDependencies;
|
||||
use graphene_std::Graphic;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::math::quad::Quad;
|
||||
@@ -3441,12 +3440,12 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
/// Update the per-layer `ATTR_FILL` snapshot.
|
||||
pub fn update_fill_attributes(&mut self, new_layer_fill_attributes: HashMap<LayerNodeIdentifier, Arc<List<Graphic>>>) {
|
||||
pub fn update_fill_attributes(&mut self, new_layer_fill_attributes: HashMap<LayerNodeIdentifier, Arc<List<Graphic<'static>>>>) {
|
||||
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>>>) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -4090,18 +4089,6 @@ impl NodeNetworkInterface {
|
||||
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.
|
||||
/// Directly sets the input without `is_acyclic` checks, `load_structure`, position conversions,
|
||||
/// or per-node cache invalidation. Call `load_structure`, `unload_all_nodes_click_targets`, and
|
||||
|
||||
+5
-5
@@ -65,11 +65,11 @@ impl TypeSource {
|
||||
TaggedValue::String(_) => FrontendGraphDataType::Typography,
|
||||
// Types whose `TaggedValue` variant has been removed are routed through `TypeDefault` and identified by the descriptor's type name.
|
||||
TaggedValue::TypeDefault(td) => match td.name.as_ref() {
|
||||
n if n == std::any::type_name::<List<Graphic>>() => FrontendGraphDataType::Graphic,
|
||||
n if n == std::any::type_name::<List<Artboard>>() => FrontendGraphDataType::Artboard,
|
||||
n if n == std::any::type_name::<List<Raster<CPU>>>() => FrontendGraphDataType::Raster,
|
||||
n if n == std::any::type_name::<List<Vector>>() => FrontendGraphDataType::Vector,
|
||||
n if n == std::any::type_name::<List<String>>() => FrontendGraphDataType::Typography,
|
||||
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Graphic>>()) => FrontendGraphDataType::Graphic,
|
||||
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Artboard>>()) => FrontendGraphDataType::Artboard,
|
||||
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Raster<CPU>>>()) => FrontendGraphDataType::Raster,
|
||||
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Vector>>()) => FrontendGraphDataType::Vector,
|
||||
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<String>>()) => FrontendGraphDataType::Typography,
|
||||
_ => FrontendGraphDataType::General,
|
||||
},
|
||||
_ => FrontendGraphDataType::General,
|
||||
|
||||
@@ -1024,6 +1024,12 @@ fn replace_optional_f64_null(input: &str) -> String {
|
||||
result
|
||||
}
|
||||
|
||||
/// Serialized proto identifiers of the pre-flip Merge and Artboard layer internals.
|
||||
/// A document containing any of them predates the leveled-records flip and rebuilds its
|
||||
/// layer definitions through the same reset mechanism as the `SourceNodeIdNode` entry in
|
||||
/// `document_migration_reset_node_definition`.
|
||||
pub const FLIP_RESET_NODE_MARKERS: &[&str] = &["graphic_nodes::graphic::WriteAttributeNode"];
|
||||
|
||||
pub fn document_migration_reset_node_definition(document_serialized_content: &str) -> bool {
|
||||
// Upgrade a document being opened to use fresh copies of all nodes
|
||||
if document_serialized_content.contains("node_output_index") {
|
||||
@@ -1045,6 +1051,12 @@ pub fn document_migration_reset_node_definition(document_serialized_content: &st
|
||||
return true;
|
||||
}
|
||||
|
||||
// The leveled-records flip replaced the layer internals; documents from before it rebuild
|
||||
// their layer definitions.
|
||||
if FLIP_RESET_NODE_MARKERS.iter().any(|marker| document_serialized_content.contains(marker)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
@@ -1379,6 +1391,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) {
|
||||
let node_definition = resolve_document_node_type(&reference)?;
|
||||
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(*node_id, 0), old_inputs[1].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*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(*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(*node_id, 0), old_inputs[1].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*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(*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
|
||||
@@ -2401,15 +2441,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.document_node.context_features.clone();
|
||||
document.network_interface.set_context_features(node_id, network_path, context_features);
|
||||
}
|
||||
|
||||
// Add the "Scale Type" parameter to the "Decompose Scale" node
|
||||
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();
|
||||
@@ -2572,6 +2603,13 @@ fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, ne
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_flip_reset_markers_keep_the_historical_merge_internals_spelling() {
|
||||
// The node itself is removed; the marker matches its spelling in
|
||||
// documents saved before the flip, which must stay stable.
|
||||
assert_eq!(FLIP_RESET_NODE_MARKERS, &["graphic_nodes::graphic::WriteAttributeNode"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_no_duplicate_node_replacements() {
|
||||
let mut hashmap = HashMap::<ProtoNodeIdentifier, u32>::new();
|
||||
|
||||
@@ -7,8 +7,8 @@ use glam::{DAffine2, DVec2};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNode, NodeId, NodeInput};
|
||||
use graph_craft::{ProtoNodeIdentifier, concrete};
|
||||
use graphene_std::Color;
|
||||
use graphene_std::NodeInputDecleration;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::raster::BlendMode;
|
||||
use graphene_std::raster_types::{CPU, GPU, Image, Raster};
|
||||
use graphene_std::subpath::Subpath;
|
||||
@@ -16,7 +16,6 @@ use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::misc::ManipulatorPointId;
|
||||
use graphene_std::vector::style::{FillChoice, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin, initial_gradient_transform_for_bounding_box};
|
||||
use graphene_std::vector::{GradientSpreadMethod, GradientStops, GradientType, PointId, SegmentId, VectorModificationType};
|
||||
use graphene_std::{Color, Graphic};
|
||||
use std::collections::VecDeque;
|
||||
|
||||
/// Returns the ID of the first Spline node in the horizontal flow which is not followed by a `Path` node, or `None` if none exists.
|
||||
@@ -275,14 +274,14 @@ pub fn get_viewport_center(layer: LayerNodeIdentifier, network_interface: &NodeN
|
||||
pub fn get_fill_node_id_with_direct_fill_input(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<NodeId> {
|
||||
let fill_node_id = NodeGraphLayer::new(layer, network_interface).upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER))?;
|
||||
let fill_node = network_interface.document_network().nodes.get(&fill_node_id)?;
|
||||
matches!(fill_node.inputs.get(graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX)?, NodeInput::Value { .. }).then_some(fill_node_id)
|
||||
matches!(fill_node.inputs.get(graphene_std::vector::fill::FillInput::INDEX)?, NodeInput::Value { .. }).then_some(fill_node_id)
|
||||
}
|
||||
|
||||
/// Determine the input connector where the gradient chain enters the layer.
|
||||
/// Returns Fill's fill input if the layer has a "Fill" node, otherwise returns the layer's content input.
|
||||
pub fn gradient_chain_target_input(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> InputConnector {
|
||||
if let Some(fill_node_id) = NodeGraphLayer::new(layer, network_interface).upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER)) {
|
||||
InputConnector::node(fill_node_id, graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX)
|
||||
InputConnector::node(fill_node_id, graphene_std::vector::fill::FillInput::INDEX)
|
||||
} else {
|
||||
InputConnector::node(layer.to_node(), 1)
|
||||
}
|
||||
@@ -303,7 +302,7 @@ pub fn get_upstream_gradient_value_node_id(layer: LayerNodeIdentifier, network_i
|
||||
pub fn get_fill_input_node_id(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<NodeId> {
|
||||
let fill_node_id = NodeGraphLayer::new(layer, network_interface).upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER))?;
|
||||
let fill_node = network_interface.document_network().nodes.get(&fill_node_id)?;
|
||||
let NodeInput::Node { node_id, .. } = fill_node.inputs.get(graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX)? else {
|
||||
let NodeInput::Node { node_id, .. } = fill_node.inputs.get(graphene_std::vector::fill::FillInput::INDEX)? else {
|
||||
return None;
|
||||
};
|
||||
Some(*node_id)
|
||||
@@ -317,7 +316,7 @@ pub fn get_gradient_stops(layer: LayerNodeIdentifier, network_interface: &NodeNe
|
||||
.document_network()
|
||||
.nodes
|
||||
.get(&fill_node_id)
|
||||
.and_then(|node| node.inputs.get(graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX))
|
||||
.and_then(|node| node.inputs.get(graphene_std::vector::fill::FillInput::INDEX))
|
||||
.and_then(|input| input.as_value())
|
||||
.and_then(|value| if let TaggedValue::Gradient(gradient) = value { Some(gradient.clone()) } else { None });
|
||||
}
|
||||
@@ -363,7 +362,7 @@ pub fn gradient_orientation_rightward(transform: glam::DAffine2) -> bool {
|
||||
/// Get the current fill of a layer from the closest "Fill" node.
|
||||
pub fn get_fill_color(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Color> {
|
||||
let inputs = NodeGraphLayer::new(layer, network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER))?;
|
||||
let &TaggedValue::Color(color) = inputs.get(graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX)?.as_value()? else {
|
||||
let &TaggedValue::Color(color) = inputs.get(graphene_std::vector::fill::FillInput::INDEX)?.as_value()? else {
|
||||
return None;
|
||||
};
|
||||
color
|
||||
@@ -570,7 +569,7 @@ pub fn get_stroke_options(layer: LayerNodeIdentifier, network_interface: &NodeNe
|
||||
Some(TaggedValue::PaintOrder(value)) => *value,
|
||||
_ => PaintOrder::default(),
|
||||
};
|
||||
let dash_lengths = match read(graphene_std::vector::stroke::DashLengthsInput::<List<f64>>::INDEX) {
|
||||
let dash_lengths = match read(graphene_std::vector::stroke::DashLengthsInput::INDEX) {
|
||||
Some(TaggedValue::F64Array(value)) => value.clone(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
@@ -638,7 +637,7 @@ pub struct FillNodeGradient {
|
||||
pub fn read_fill_node_gradient(fill_node: &DocumentNode, bounding_box: impl FnOnce() -> [DVec2; 2]) -> Option<FillNodeGradient> {
|
||||
use graphene_std::vector::fill;
|
||||
|
||||
let TaggedValue::Gradient(stops) = fill_node.inputs.get(fill::FillInput::<List<Graphic>>::INDEX)?.as_value()? else {
|
||||
let TaggedValue::Gradient(stops) = fill_node.inputs.get(fill::FillInput::INDEX)?.as_value()? else {
|
||||
return None;
|
||||
};
|
||||
let gradient_type = match fill_node.inputs.get(fill::GradientTypeInput::INDEX).and_then(|input| input.as_value()) {
|
||||
@@ -665,7 +664,7 @@ pub fn read_fill_node_gradient(fill_node: &DocumentNode, bounding_box: impl FnOn
|
||||
}
|
||||
/// Returns the stroke color from a layer's upstream Stroke node.
|
||||
pub fn get_stroke_color(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Option<Color>> {
|
||||
let color_index = graphene_std::vector::stroke::PaintInput::<List<Graphic>>::INDEX;
|
||||
let color_index = graphene_std::vector::stroke::PaintInput::INDEX;
|
||||
let tagged = NodeGraphLayer::new(layer, network_interface).find_input(&DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER), color_index)?;
|
||||
if let TaggedValue::Color(color) = tagged { Some(*color) } else { None }
|
||||
}
|
||||
@@ -699,7 +698,7 @@ pub fn selected_fill_state(document: &DocumentMessageHandler) -> Option<Selected
|
||||
let fill_choice = (|| {
|
||||
let fill_node = document.network_interface.document_network().nodes.get(&fill_node_id)?;
|
||||
|
||||
match fill_node.inputs.get(graphene_std::vector::fill::FillInput::<List<Graphic>>::INDEX)?.as_value()? {
|
||||
match fill_node.inputs.get(graphene_std::vector::fill::FillInput::INDEX)?.as_value()? {
|
||||
&TaggedValue::Color(color) => Some(color.map_or(FillChoice::None, FillChoice::Solid)),
|
||||
TaggedValue::Gradient(stops) => Some(FillChoice::Gradient(stops.clone())),
|
||||
_ => None,
|
||||
@@ -825,7 +824,7 @@ pub fn set_stroke_color_for_selected_layers(color: Option<Color>, weight: f64, d
|
||||
let layers: Vec<_> = document.network_interface.selected_nodes().selected_layers_except_artboards(&document.network_interface).collect();
|
||||
for layer in layers {
|
||||
if let Some(node_id) = get_stroke_id(layer, &document.network_interface) {
|
||||
let input_index = graphene_std::vector::stroke::PaintInput::<List<Graphic>>::INDEX;
|
||||
let input_index = graphene_std::vector::stroke::PaintInput::INDEX;
|
||||
let value = TaggedValue::Color(color);
|
||||
responses.add(NodeGraphMessage::SetInputValue { node_id, input_index, value });
|
||||
} else {
|
||||
@@ -977,6 +976,8 @@ impl<'a> NodeGraphLayer<'a> {
|
||||
pub fn is_raster_layer(layer: LayerNodeIdentifier, network_interface: &mut NodeNetworkInterface) -> bool {
|
||||
let layer_input_type = network_interface.input_type(&InputConnector::node(layer.to_node(), 1), &[]);
|
||||
|
||||
layer_input_type.compiled_nested_type() == Some(&concrete!(List<Raster<CPU>>)) || layer_input_type.compiled_nested_type() == Some(&concrete!(List<Raster<GPU>>))
|
||||
// A leveled wire is typed by its element; depth rides the layout.
|
||||
let compiled = layer_input_type.compiled_nested_type();
|
||||
compiled == Some(&concrete!(Raster<CPU>)) || compiled == Some(&concrete!(Raster<GPU>))
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,6 @@ use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::NodeInputDecleration;
|
||||
use graphene_std::choice_type::ChoiceTypeStatic;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::vector::style::{PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
|
||||
/// All non-color stroke-related options surfaced in the control bar popover.
|
||||
@@ -215,7 +214,7 @@ pub fn apply_paint_order(drawing: &mut DrawingToolState, order: PaintOrder, docu
|
||||
|
||||
pub fn apply_dash_lengths(drawing: &mut DrawingToolState, lengths: Vec<f64>, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
drawing.dash_lengths = Some(lengths.clone());
|
||||
set_stroke_input_for_selected(document, graphene_std::vector::stroke::DashLengthsInput::<List<f64>>::INDEX, TaggedValue::F64Array(lengths), responses);
|
||||
set_stroke_input_for_selected(document, graphene_std::vector::stroke::DashLengthsInput::INDEX, TaggedValue::F64Array(lengths), responses);
|
||||
}
|
||||
|
||||
pub fn apply_dash_offset(drawing: &mut DrawingToolState, offset: f64, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
|
||||
@@ -574,12 +574,22 @@ mod test_artboard {
|
||||
use graphene_std::Artboard;
|
||||
use graphene_std::list::List;
|
||||
|
||||
/// A leveled wire introspects as its whole legacy list, so each `extend`
|
||||
/// occurrence yields one list rather than one element.
|
||||
async fn get_artboards(editor: &mut EditorTestUtils) -> List<Artboard> {
|
||||
let instrumented = match editor.eval_graph().await {
|
||||
Ok(instrumented) => instrumented,
|
||||
Err(e) => panic!("Failed to evaluate graph: {e}"),
|
||||
};
|
||||
instrumented.grab_all_input::<graphene_std::graphic::extend::NewInput<Artboard>>(&editor.runtime).flatten().collect()
|
||||
let mut artboards = List::new();
|
||||
for list in instrumented.grab_all_input_level::<graphene_std::graphic::extend::NewInput<Artboard>, Artboard>(&editor.runtime) {
|
||||
for index in 0..list.len() {
|
||||
if let Some(item) = list.clone_item(index) {
|
||||
artboards.push(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
artboards
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
|
||||
@@ -206,16 +206,20 @@ impl Fsm for FillToolFsmState {
|
||||
mod test_fill {
|
||||
pub use crate::test_utils::test_prelude::*;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::vector::fill;
|
||||
|
||||
async fn get_fills(editor: &mut EditorTestUtils) -> Vec<List<Color>> {
|
||||
/// Paint inputs are single-typed now, so the monitored wire carries the
|
||||
/// colors themselves and the `Graphic` conversion sits downstream of it.
|
||||
async fn get_fills(editor: &mut EditorTestUtils) -> Vec<Color> {
|
||||
let instrumented = match editor.eval_graph().await {
|
||||
Ok(instrumented) => instrumented,
|
||||
Err(e) => panic!("Failed to evaluate graph: {e}"),
|
||||
};
|
||||
|
||||
instrumented.grab_all_input::<fill::FillInput<List<Color>>>(&editor.runtime).collect()
|
||||
instrumented
|
||||
.grab_all_input_level::<fill::FillInput, Color>(&editor.runtime)
|
||||
.flat_map(|list| list.iter_element_values().cloned().collect::<Vec<_>>())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -245,8 +249,7 @@ mod test_fill {
|
||||
editor.click_tool(ToolType::Fill, MouseKeys::LEFT, DVec2::new(2., 2.), ModifierKeys::empty()).await;
|
||||
let fills = get_fills(&mut editor).await;
|
||||
assert_eq!(fills.len(), 1);
|
||||
let color = fills.first().unwrap().element(0).expect("Color is stored in the list");
|
||||
assert_eq!(SRGBA8::from(*color), SRGBA8::from(Color::GREEN));
|
||||
assert_eq!(SRGBA8::from(fills[0]), SRGBA8::from(Color::GREEN));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -258,7 +261,6 @@ mod test_fill {
|
||||
editor.click_tool(ToolType::Fill, MouseKeys::LEFT, DVec2::new(2., 2.), ModifierKeys::SHIFT).await;
|
||||
let fills = get_fills(&mut editor).await;
|
||||
assert_eq!(fills.len(), 1);
|
||||
let color = fills.first().unwrap().element(0).expect("Color is stored in the list");
|
||||
assert_eq!(SRGBA8::from(*color), SRGBA8::from(Color::YELLOW));
|
||||
assert_eq!(SRGBA8::from(fills[0]), SRGBA8::from(Color::YELLOW));
|
||||
}
|
||||
}
|
||||
@@ -2012,11 +2012,10 @@ mod test_gradient {
|
||||
pub use crate::test_utils::test_prelude::*;
|
||||
use glam::DAffine2;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::NodeInputDecleration;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::vector::style::{GradientSpreadMethod, build_transform_with_y_preservation};
|
||||
use graphene_std::vector::{GradientStop, GradientStops, fill};
|
||||
use graphene_std::{Graphic, NodeInputDecleration};
|
||||
|
||||
use super::gradient_space_transform;
|
||||
|
||||
@@ -2058,7 +2057,7 @@ mod test_gradient {
|
||||
let fill_node_id = get_fill_node_id_with_direct_fill_input(layer, &document.network_interface)?;
|
||||
let fill_node = document.network_interface.document_network().nodes.get(&fill_node_id)?;
|
||||
|
||||
let stops = match fill_node.inputs.get(fill::FillInput::<List<Graphic>>::INDEX)?.as_value()? {
|
||||
let stops = match fill_node.inputs.get(fill::FillInput::INDEX)?.as_value()? {
|
||||
TaggedValue::Gradient(stops) => stops.clone(),
|
||||
_ => return None,
|
||||
};
|
||||
@@ -2176,7 +2175,7 @@ mod test_gradient {
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::CreateWire {
|
||||
output_connector: OutputConnector::node(gradient_node_id, 0),
|
||||
input_connector: InputConnector::node(fill_node_id, fill::FillInput::<List<Graphic>>::INDEX),
|
||||
input_connector: InputConnector::node(fill_node_id, fill::FillInput::INDEX),
|
||||
})
|
||||
.await;
|
||||
|
||||
|
||||
@@ -985,18 +985,18 @@ mod test {
|
||||
element
|
||||
}
|
||||
|
||||
/// Grab all of the values of the input every time it occurs in the graph.
|
||||
pub fn grab_all_input<'a, Input: NodeInputDecleration + 'a>(&'a self, runtime: &'a NodeRuntime) -> impl Iterator<Item = Input::Result> + 'a
|
||||
where
|
||||
Input::Result: Send + Sync + Clone + 'static,
|
||||
{
|
||||
/// Grab all of the values of a LEVELED input, which introspects as its
|
||||
/// whole legacy list rather than as one element. `T` is the introspected
|
||||
/// element type, which differs from the declared one where a conversion
|
||||
/// sits downstream of the monitor.
|
||||
pub fn grab_all_input_level<'a, Input: NodeInputDecleration + 'a, T: Send + Sync + Clone + 'static>(&'a self, runtime: &'a NodeRuntime) -> impl Iterator<Item = List<T>> + 'a {
|
||||
self.protonodes_by_name
|
||||
.get(&Input::identifier())
|
||||
.map_or([].as_slice(), |x| x.as_slice())
|
||||
.iter()
|
||||
.filter_map(|inputs| inputs.get(Input::INDEX))
|
||||
.filter_map(|input_monitor_node| runtime.executor.introspect(input_monitor_node).ok())
|
||||
.filter_map(Instrumented::downcast::<Input>) // Some might not resolve (e.g. generics that don't work properly)
|
||||
.filter_map(|dynamic| dynamic.downcast_ref::<List<T>>().cloned())
|
||||
}
|
||||
|
||||
pub fn grab_protonode_input<Input: NodeInputDecleration>(&self, path: &Vec<NodeId>, runtime: &NodeRuntime) -> Option<Input::Result>
|
||||
|
||||
@@ -10,7 +10,6 @@ use graph_craft::proto::GraphErrors;
|
||||
use graphene_std::application_io::{ApplicationIo, ExportFormat, NodeGraphUpdateMessage, NodeGraphUpdateSender, RenderConfig, Texture};
|
||||
use graphene_std::bounds::RenderBoundingBox;
|
||||
use graphene_std::core_types::gpoll::GPoll;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::ops::ConvertAsync;
|
||||
#[cfg(all(target_family = "wasm", feature = "gpu", feature = "wasm"))]
|
||||
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasSurface, CanvasSurfaceHandle};
|
||||
@@ -438,7 +437,7 @@ impl NodeRuntime {
|
||||
assert_eq!(scoped_network.exports.len(), 1, "Graph with multiple outputs not yet handled");
|
||||
|
||||
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,
|
||||
Err(e) => return Err((ResolvedDocumentNodeTypesDelta::default(), e)),
|
||||
};
|
||||
@@ -492,44 +491,63 @@ impl NodeRuntime {
|
||||
continue;
|
||||
};
|
||||
|
||||
// Extract the monitor node's stored `Graphic` data
|
||||
let Ok(introspected_data) = self.executor.introspect(monitor_node_path) else {
|
||||
// Read the monitored run directly, inside the introspection window
|
||||
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: the batch is resident for the read.
|
||||
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: the batch is resident for the read.
|
||||
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: the batch is resident for the read.
|
||||
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: the batch is resident for the read.
|
||||
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 result.is_err() {
|
||||
// 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)]
|
||||
warn!("Failed to introspect monitor node {}", self.executor.introspect(monitor_node_path).unwrap_err());
|
||||
continue;
|
||||
};
|
||||
|
||||
// Graphic list: thumbnail (text-aware bounds, since the `BoundingBox` trait can't lay out `Graphic::Text` content)
|
||||
if let Some(list) = introspected_data.downcast_ref::<List<Graphic>>() {
|
||||
if update_thumbnails {
|
||||
let bounds = graphene_std::renderer::graphic_list_bounding_box(list, DAffine2::IDENTITY);
|
||||
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, list, 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(list) = introspected_data.downcast_ref::<List<Artboard>>() {
|
||||
if update_thumbnails {
|
||||
let bounds = artboard_clip_bounds(list);
|
||||
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, list, bounds, responses)
|
||||
}
|
||||
}
|
||||
// Vector list: vector modifications
|
||||
else if let Some(list) = introspected_data.downcast_ref::<List<Vector>>() {
|
||||
// Insert the vector modify
|
||||
self.vector_modify.insert(parent_network_node_id, list.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(list) = introspected_data.downcast_ref::<List<String>>() {
|
||||
if update_thumbnails {
|
||||
let bounds = graphene_std::renderer::text_list_bounding_box(list, DAffine2::IDENTITY);
|
||||
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, list, bounds, responses)
|
||||
}
|
||||
}
|
||||
// Other
|
||||
else {
|
||||
log::warn!("Failed to downcast monitor node output {parent_network_node_id:?}");
|
||||
warn!("Failed to introspect monitor node {}", result.unwrap_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -597,11 +615,12 @@ impl NodeRuntime {
|
||||
|
||||
/// 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.
|
||||
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;
|
||||
for index in 0..artboards.len() {
|
||||
let location: DVec2 = artboards.attribute_cloned_or_default(graphene_std::ATTR_LOCATION, index);
|
||||
let dimensions: DVec2 = artboards.attribute_cloned_or_default(graphene_std::ATTR_DIMENSIONS, index);
|
||||
for index in 0..artboards.lane_count() {
|
||||
let location: DVec2 = artboards.attr::<Location>(index);
|
||||
let dimensions: DVec2 = artboards.attr::<Dimensions>(index);
|
||||
let bounds = [location, location + dimensions];
|
||||
combined = Some(match combined {
|
||||
Some(existing) => [existing[0].min(bounds[0]), existing[1].max(bounds[1])],
|
||||
|
||||
@@ -5,7 +5,7 @@ extern crate proc_macro;
|
||||
use proc_macro::TokenStream;
|
||||
use proc_macro2::Span;
|
||||
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.
|
||||
///
|
||||
@@ -40,37 +40,45 @@ pub fn system_desc_derive(input: TokenStream) -> TokenStream {
|
||||
let struct_name = &ast.ident;
|
||||
let generics = &ast.generics;
|
||||
|
||||
let static_params = replace_lifetimes(generics, "'static");
|
||||
let dyn_params = replace_lifetimes(generics, "'dyn_any");
|
||||
let static_params = generic_arguments(generics, "'static");
|
||||
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! {
|
||||
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,)*>;
|
||||
}
|
||||
}
|
||||
.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
|
||||
.params
|
||||
.iter()
|
||||
.map(|param| {
|
||||
let param = match param {
|
||||
GenericParam::Lifetime(_) => GenericParam::Lifetime(LifetimeParam::new(Lifetime::new(replacement, Span::call_site()))),
|
||||
GenericParam::Type(t) => {
|
||||
let mut t = t.clone();
|
||||
t.bounds.iter_mut().for_each(|bond| {
|
||||
if let TypeParamBound::Lifetime(t) = bond {
|
||||
*t = Lifetime::new(replacement, Span::call_site())
|
||||
}
|
||||
});
|
||||
GenericParam::Type(t.clone())
|
||||
}
|
||||
c => c.clone(),
|
||||
};
|
||||
quote! {#param}
|
||||
.map(|param| match param {
|
||||
GenericParam::Lifetime(_) => {
|
||||
let lifetime = Lifetime::new(replacement, Span::call_site());
|
||||
quote! {#lifetime}
|
||||
}
|
||||
GenericParam::Type(t) => {
|
||||
let ident = &t.ident;
|
||||
quote! {#ident}
|
||||
}
|
||||
GenericParam::Const(c) => {
|
||||
let ident = &c.ident;
|
||||
quote! {#ident}
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
}
|
||||
@@ -74,6 +74,7 @@ mmap-io = { workspace = true }
|
||||
[dev-dependencies]
|
||||
# Workspace dependencies
|
||||
graph-craft = { workspace = true, features = ["loading"] }
|
||||
interpreted-executor = { workspace = true }
|
||||
pretty_assertions = { workspace = true }
|
||||
criterion = { workspace = true }
|
||||
gungraun = { workspace = true }
|
||||
|
||||
@@ -6,10 +6,13 @@ use graph_craft::util::DEMO_ART;
|
||||
fn compile_to_proto(c: &mut Criterion) {
|
||||
use graph_craft::util::{compile, load_from_name};
|
||||
let mut c = c.benchmark_group("Compile Network cold");
|
||||
let registry = &interpreted_executor::node_registry::NODE_REGISTRY;
|
||||
|
||||
for name in DEMO_ART {
|
||||
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]
|
||||
#[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) {
|
||||
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);
|
||||
|
||||
@@ -57,7 +57,8 @@ pub struct DocumentNode {
|
||||
#[serde(default)]
|
||||
pub skip_deduplication: bool,
|
||||
/// 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,
|
||||
/// The path to this node and its inputs and outputs as of when [`NodeNetwork::generate_node_paths`] was called.
|
||||
#[serde(skip)]
|
||||
@@ -166,6 +167,8 @@ impl DocumentNode {
|
||||
original_location: self.original_location,
|
||||
skip_deduplication: self.skip_deduplication,
|
||||
context_features: self.context_features,
|
||||
lane_invariant_inputs: 0,
|
||||
resolved: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -220,7 +223,7 @@ pub enum DocumentNodeMetadata {
|
||||
impl DocumentNodeMetadata {
|
||||
pub fn ty(&self) -> Type {
|
||||
match self {
|
||||
DocumentNodeMetadata::DocumentNodePath => concrete!(core_types::list::List<NodeId>),
|
||||
DocumentNodeMetadata::DocumentNodePath => concrete!(Vec<NodeId>),
|
||||
DocumentNodeMetadata::SourceId => concrete!(u64),
|
||||
}
|
||||
}
|
||||
@@ -1162,6 +1165,7 @@ impl NodeNetwork {
|
||||
inputs: Vec::new(),
|
||||
output: node_id,
|
||||
nodes,
|
||||
..Default::default()
|
||||
}]
|
||||
.into_iter();
|
||||
}
|
||||
@@ -1178,6 +1182,7 @@ impl NodeNetwork {
|
||||
// inputs: self.imports.clone(),
|
||||
output: node_id,
|
||||
nodes: nodes.clone(),
|
||||
..Default::default()
|
||||
})
|
||||
} else {
|
||||
None
|
||||
@@ -1442,6 +1447,7 @@ mod test {
|
||||
]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let network = flat_network();
|
||||
let mut resolved_network = network.into_proto_networks().collect::<Vec<_>>();
|
||||
|
||||
@@ -7,11 +7,10 @@ use core_types::color::SRGBA8;
|
||||
use core_types::context::Context;
|
||||
use core_types::gpoll::GPoll;
|
||||
use core_types::list::List;
|
||||
use core_types::node::Node;
|
||||
use core_types::registry::{EdgeHandle, edge_type};
|
||||
use core_types::registry::EdgeHandle;
|
||||
use core_types::transform::Footprint;
|
||||
use core_types::uuid::NodeId;
|
||||
use core_types::value::record_value_edge;
|
||||
use core_types::value::{leveled_record_value_edge, record_value_edge};
|
||||
use core_types::{CacheHash, Color, ContextModification, MemoHash, Type, TypeDescriptor};
|
||||
use dyn_any::DynAny;
|
||||
pub use dyn_any::StaticType;
|
||||
@@ -147,7 +146,7 @@ macro_rules! tagged_value {
|
||||
let name = td.name.as_ref();
|
||||
macro_rules! check {
|
||||
($type_default:ty) => {
|
||||
if name == std::any::type_name::<$type_default>() { return Box::new(<$type_default>::default()); }
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<$type_default>()) { return Box::new(<$type_default>::default()); }
|
||||
};
|
||||
}
|
||||
for_each_type_default!(check);
|
||||
@@ -174,10 +173,7 @@ macro_rules! tagged_value {
|
||||
// NON-SERIALIZED VARIANTS
|
||||
// =======================
|
||||
Self::RenderOutput(x) => Box::new(x),
|
||||
Self::NodeIdPath(path) => {
|
||||
let list: List<NodeId> = path.into_iter().map(core_types::list::Item::new_from_element).collect();
|
||||
Box::new(list)
|
||||
}
|
||||
Self::NodeIdPath(path) => Box::new(path),
|
||||
Self::DocumentNode(node) => Box::new(node),
|
||||
Self::ContextModification(modification) => Box::new(modification),
|
||||
Self::EditorApi(x) => Box::new(x),
|
||||
@@ -197,7 +193,7 @@ macro_rules! tagged_value {
|
||||
let name = td.name.as_ref();
|
||||
macro_rules! check {
|
||||
($type_default:ty) => {
|
||||
if name == std::any::type_name::<$type_default>() { return Arc::new(<$type_default>::default()); }
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<$type_default>()) { return Arc::new(<$type_default>::default()); }
|
||||
};
|
||||
}
|
||||
for_each_type_default!(check);
|
||||
@@ -224,10 +220,7 @@ macro_rules! tagged_value {
|
||||
// NON-SERIALIZED VARIANTS
|
||||
// =======================
|
||||
Self::RenderOutput(x) => Arc::new(x),
|
||||
Self::NodeIdPath(path) => {
|
||||
let list: List<NodeId> = path.into_iter().map(core_types::list::Item::new_from_element).collect();
|
||||
Arc::new(list)
|
||||
}
|
||||
Self::NodeIdPath(path) => Arc::new(path),
|
||||
Self::DocumentNode(node) => Arc::new(node),
|
||||
Self::ContextModification(modification) => Arc::new(modification),
|
||||
Self::EditorApi(x) => Arc::new(x),
|
||||
@@ -242,11 +235,21 @@ macro_rules! tagged_value {
|
||||
// MANUAL VARIANTS
|
||||
// ===============
|
||||
Self::None => concrete!(()),
|
||||
Self::TypeDefault(td) => Type::Concrete(td.clone()),
|
||||
Self::F64Array(_) => concrete!(List<f64>),
|
||||
Self::Color(_) => concrete!(List<Color>),
|
||||
Self::Gradient(_) => concrete!(List<GradientStops>),
|
||||
Self::BrushStrokes(_) => concrete!(List<BrushStroke>),
|
||||
// The list-typed defaults type by their element: depth is not a
|
||||
// `Type` axis, it rides the layout proven at wiring.
|
||||
Self::TypeDefault(td) => {
|
||||
let name = td.name.as_ref();
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<List<Graphic>>()) { return concrete!(Graphic); }
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<List<Artboard>>()) { return concrete!(Artboard); }
|
||||
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::Gradient(_) => concrete!(GradientStops),
|
||||
Self::BrushStrokes(_) => concrete!(BrushStroke),
|
||||
// =======================
|
||||
// AUTO-GENERATED VARIANTS
|
||||
// =======================
|
||||
@@ -255,7 +258,7 @@ macro_rules! tagged_value {
|
||||
// NON-SERIALIZED VARIANTS
|
||||
// =======================
|
||||
Self::RenderOutput(_) => concrete!(RenderOutput),
|
||||
Self::NodeIdPath(_) => concrete!(List<NodeId>),
|
||||
Self::NodeIdPath(_) => concrete!(Vec<NodeId>),
|
||||
Self::DocumentNode(_) => concrete!(DocumentNode),
|
||||
Self::ContextModification(_) => concrete!(ContextModification),
|
||||
Self::EditorApi(_) => concrete!(Arc<PlatformEditorApi>),
|
||||
@@ -263,7 +266,50 @@ macro_rules! tagged_value {
|
||||
}
|
||||
}
|
||||
|
||||
/// Materializes the value as [`Self::to_dynany`] does, wrapped in a `ClonedNode` edge typed by [`Self::ty`].
|
||||
/// The record layout of this value's edge: leveled for the list-carrying
|
||||
/// 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::Gradient(_) => leveled::<GradientStops>(),
|
||||
Self::BrushStrokes(_) => leveled::<BrushStroke>(),
|
||||
$( 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 edge typed by [`Self::ty`].
|
||||
pub fn to_edge(self) -> Result<EdgeHandle, String> {
|
||||
match self {
|
||||
// ===============
|
||||
@@ -271,29 +317,31 @@ macro_rules! tagged_value {
|
||||
// ===============
|
||||
Self::None => Ok(record_value_edge(())),
|
||||
Self::TypeDefault(td) => {
|
||||
// Same direct-construction path as `to_dynany` for the same reason as in `to_dynany`.
|
||||
let name = td.name.as_ref();
|
||||
macro_rules! check {
|
||||
($type_default:ty) => {
|
||||
if name == std::any::type_name::<$type_default>() { return Ok(record_value_edge(<$type_default>::default())); }
|
||||
// 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_edge(Vec::<$element>::new()));
|
||||
}
|
||||
};
|
||||
}
|
||||
for_each_type_default!(check);
|
||||
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_edge(vec![Vector::default()])); }
|
||||
check_level!(List<String>, String);
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<DocumentNode>()) { return Ok(record_value_edge(DocumentNode::default())); }
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<Resource>()) { return Ok(record_value_edge(Resource::default())); }
|
||||
Self::from_type_or_none(&Type::Concrete(td)).to_edge()
|
||||
}
|
||||
Self::F64Array(values) => {
|
||||
let list: List<f64> = values.into_iter().map(core_types::list::Item::new_from_element).collect();
|
||||
Ok(record_value_edge(list))
|
||||
}
|
||||
Self::Color(color) => {
|
||||
let list: List<Color> = color.into_iter().map(core_types::list::Item::new_from_element).collect();
|
||||
Ok(record_value_edge(list))
|
||||
}
|
||||
Self::Gradient(stops) => Ok(record_value_edge(List::<GradientStops>::new_from_element(stops))),
|
||||
Self::BrushStrokes(strokes) => {
|
||||
let list: List<BrushStroke> = strokes.into_iter().map(core_types::list::Item::new_from_element).collect();
|
||||
Ok(record_value_edge(list))
|
||||
}
|
||||
Self::F64Array(values) => Ok(leveled_record_value_edge(values)),
|
||||
Self::Color(color) => Ok(leveled_record_value_edge(color.into_iter().collect::<Vec<_>>())),
|
||||
Self::Gradient(stops) => Ok(leveled_record_value_edge(vec![stops])),
|
||||
Self::BrushStrokes(strokes) => Ok(leveled_record_value_edge(strokes)),
|
||||
// =======================
|
||||
// AUTO-GENERATED VARIANTS
|
||||
// =======================
|
||||
@@ -302,10 +350,7 @@ macro_rules! tagged_value {
|
||||
// NON-SERIALIZED VARIANTS
|
||||
// =======================
|
||||
Self::RenderOutput(x) => Ok(record_value_edge(x)),
|
||||
Self::NodeIdPath(path) => {
|
||||
let list: List<NodeId> = path.into_iter().map(core_types::list::Item::new_from_element).collect();
|
||||
Ok(record_value_edge(list))
|
||||
}
|
||||
Self::NodeIdPath(path) => Ok(record_value_edge(path)),
|
||||
Self::DocumentNode(node) => Ok(record_value_edge(node)),
|
||||
Self::ContextModification(modification) => Ok(record_value_edge(modification)),
|
||||
Self::EditorApi(x) => Ok(record_value_edge(x)),
|
||||
@@ -314,50 +359,27 @@ macro_rules! tagged_value {
|
||||
}
|
||||
|
||||
/// Evaluates a typed edge and converts the landed value into a tagged value, with the coverage of [`Self::try_from_any`].
|
||||
pub fn from_edge(handle: EdgeHandle, ctx: &Context) -> Result<GPoll<Self>, String> {
|
||||
pub fn from_edge<'f>(handle: EdgeHandle, ctx: &Context<'f>, frames: &core_types::record::Frames<'f>) -> Result<GPoll<Self>, String> {
|
||||
let ty = handle.ty().clone();
|
||||
// ===============
|
||||
// MANUAL VARIANTS
|
||||
// ===============
|
||||
if ty == edge_type::<()>() {
|
||||
return Ok(handle.downcast::<()>().map_err(|e| format!("{e:?}"))?.eval(ctx).map(|_| TaggedValue::None));
|
||||
}
|
||||
// =======================
|
||||
// AUTO-GENERATED VARIANTS
|
||||
// =======================
|
||||
$(
|
||||
if ty == edge_type::<$ty>() {
|
||||
return Ok(handle.downcast::<$ty>().map_err(|e| format!("{e:?}"))?.eval(ctx).map(TaggedValue::$identifier));
|
||||
}
|
||||
)*
|
||||
// =======================
|
||||
// NON-SERIALIZED VARIANTS
|
||||
// =======================
|
||||
if ty == edge_type::<RenderOutput>() {
|
||||
return Ok(handle.downcast::<RenderOutput>().map_err(|e| format!("{e:?}"))?.eval(ctx).map(TaggedValue::RenderOutput));
|
||||
}
|
||||
// =======================
|
||||
// RECORD WIRES, WHICH LAND AS THEIR ELEMENT
|
||||
// =======================
|
||||
if ty == core_types::registry::record_edge_type::<()>() {
|
||||
return Ok(handle.downcast_record::<()>().map_err(|e| format!("{e:?}"))?.eval(ctx).map(|_| TaggedValue::None));
|
||||
let edge = handle.downcast_record::<()>().map_err(|e| format!("{e:?}"))?;
|
||||
return Ok(core_types::record::serve_edge(&edge, ctx, frames).map(|_| TaggedValue::None));
|
||||
}
|
||||
$(
|
||||
if ty == core_types::registry::record_edge_type::<$ty>() {
|
||||
let layout = handle.layout().ok_or_else(|| "a record edge must carry its layout".to_string())?.clone();
|
||||
return Ok(handle
|
||||
.downcast_record::<$ty>()
|
||||
.map_err(|e| format!("{e:?}"))?
|
||||
.eval(ctx)
|
||||
let layout = handle.layout().clone();
|
||||
let edge = handle.downcast_record::<$ty>().map_err(|e| format!("{e:?}"))?;
|
||||
return Ok(core_types::record::serve_edge(&edge, ctx, frames)
|
||||
.map(|value| TaggedValue::$identifier(unsafe { core_types::record::read_element::<$ty>(layout.rec(&value)) })));
|
||||
}
|
||||
)*
|
||||
if ty == core_types::registry::record_edge_type::<RenderOutput>() {
|
||||
let layout = handle.layout().ok_or_else(|| "a record edge must carry its layout".to_string())?.clone();
|
||||
return Ok(handle
|
||||
.downcast_record::<RenderOutput>()
|
||||
.map_err(|e| format!("{e:?}"))?
|
||||
.eval(ctx)
|
||||
let layout = handle.layout().clone();
|
||||
let edge = handle.downcast_record::<RenderOutput>().map_err(|e| format!("{e:?}"))?;
|
||||
return Ok(core_types::record::serve_edge(&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"))
|
||||
@@ -418,17 +440,26 @@ macro_rules! tagged_value {
|
||||
let name = concrete_type.name.as_ref();
|
||||
// TODO: Add default implementations for types such as TaggedValue::Subpaths, and use the defaults here and in document_node_types
|
||||
// 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) }
|
||||
// List-wrapped types need a single-item default with the element's default, not an empty list
|
||||
if name == std::any::type_name::<List<Color>>() { return Some(TaggedValue::Color(Some(Color::default()))) }
|
||||
if name == std::any::type_name::<List<GradientStops>>() { return Some(TaggedValue::Gradient(GradientStops::default())) }
|
||||
$( if name == std::any::type_name::<$ty>() { return Some(TaggedValue::$identifier(Default::default())) } )*
|
||||
if name == std::any::type_name::<List<f64>>() { return Some(TaggedValue::F64Array(Vec::new())) }
|
||||
if name == std::any::type_name::<List<BrushStroke>>() { return Some(TaggedValue::BrushStrokes(Vec::new())) }
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<List<Color>>()) { return Some(TaggedValue::Color(Some(Color::default()))) }
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<List<GradientStops>>()) { return Some(TaggedValue::Gradient(GradientStops::default())) }
|
||||
$( if name == core_types::normalize_type_name(std::any::type_name::<$ty>()) { return Some(TaggedValue::$identifier(Default::default())) } )*
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<List<f64>>()) { return Some(TaggedValue::F64Array(Vec::new())) }
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<List<BrushStroke>>()) { return Some(TaggedValue::BrushStrokes(Vec::new())) }
|
||||
// Leveled wires 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(Some(Color::default()))) }
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<GradientStops>()) { return Some(TaggedValue::Gradient(GradientStops::default())) }
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<BrushStroke>()) { return Some(TaggedValue::BrushStrokes(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) => {
|
||||
if name == std::any::type_name::<$type_default>() { return Some(TaggedValue::TypeDefault(concrete_type.clone())); }
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<$type_default>()) { return Some(TaggedValue::TypeDefault(concrete_type.clone())); }
|
||||
};
|
||||
}
|
||||
for_each_type_default!(check);
|
||||
@@ -674,7 +705,8 @@ impl TaggedValue {
|
||||
|
||||
match ty {
|
||||
Type::Generic(_) => None,
|
||||
Type::Record(_) => None,
|
||||
// A leveled wire's default is its element's default, as in `from_type`.
|
||||
Type::Record(inner) => TaggedValue::from_primitive_string(string, inner),
|
||||
Type::Concrete(concrete_type) => {
|
||||
let ty = concrete_type.id?;
|
||||
use std::any::TypeId;
|
||||
@@ -867,7 +899,7 @@ mod typedefault_dispatch {
|
||||
DynAny::type_id(&*dyn_value),
|
||||
expected_type_id,
|
||||
"`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(descriptor).to_any();
|
||||
@@ -875,10 +907,69 @@ mod typedefault_dispatch {
|
||||
(*arc_value).type_id(),
|
||||
expected_type_id,
|
||||
"`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>()),
|
||||
);
|
||||
}};
|
||||
}
|
||||
for_each_type_default!(check);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod leveled_edges {
|
||||
use super::*;
|
||||
use core_types::descriptor;
|
||||
use core_types::registry::record_edge_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_edge_type::<f64>());
|
||||
assert_eq!(edge.layout().depth, 1);
|
||||
|
||||
let edge = TaggedValue::Color(Some(Color::default())).to_edge().unwrap();
|
||||
assert_eq!(edge.ty(), &record_edge_type::<Color>());
|
||||
assert_eq!(edge.layout().depth, 1);
|
||||
|
||||
let edge = TaggedValue::TypeDefault(descriptor!(List<Graphic>)).to_edge().unwrap();
|
||||
assert_eq!(edge.ty(), &record_edge_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_edge_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::Gradient(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_edge_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_edge_type::<u32>()), Some(TaggedValue::U32(5)));
|
||||
assert_eq!(TaggedValue::from_primitive_string("true", &record_edge_type::<bool>()), Some(TaggedValue::Bool(true)));
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
use crate::document::NodeNetwork;
|
||||
use crate::proto::ProtoNetwork;
|
||||
use crate::proto::{ProtoNetwork, Registry};
|
||||
use std::error::Error;
|
||||
|
||||
pub struct 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.generate_node_paths(&[]);
|
||||
let node_ids = network.nodes.keys().copied().collect::<Vec<_>>();
|
||||
@@ -19,13 +19,15 @@ impl Compiler {
|
||||
|
||||
proto_networks.map(move |mut proto_network| {
|
||||
proto_network.insert_context_nullification_nodes()?;
|
||||
let _ = proto_network.resolve_types(registry);
|
||||
proto_network.compute_layouts();
|
||||
proto_network.generate_stable_node_ids();
|
||||
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");
|
||||
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());
|
||||
};
|
||||
proto_network
|
||||
|
||||
+339
-120
@@ -19,6 +19,9 @@ pub struct ProtoNetwork {
|
||||
pub output: NodeId,
|
||||
/// A list of nodes stored in a Vec to allow for sorting.
|
||||
pub nodes: Vec<(NodeId, ProtoNode)>,
|
||||
/// Peak record-stack bytes for an evaluation, folded from the resolved layouts by [`compute_layouts`](ProtoNetwork::compute_layouts).
|
||||
#[serde(default)]
|
||||
pub stack_need: usize,
|
||||
}
|
||||
|
||||
impl core::fmt::Display for ProtoNetwork {
|
||||
@@ -124,6 +127,20 @@ impl ConstructionArgs {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub(crate) struct Resolved {
|
||||
pub io: Option<NodeIOTypes>,
|
||||
pub layout_meta: Option<core_types::record::LayoutMeta>,
|
||||
pub layout: Option<core_types::record::RecordLayout>,
|
||||
}
|
||||
|
||||
impl PartialEq for Resolved {
|
||||
fn eq(&self, _: &Self) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
impl Eq for Resolved {}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
/// A proto node is an intermediate step between the `DocumentNode` and the boxed struct that actually runs the node (found in the [`BorrowTree`]).
|
||||
/// At different stages in the compilation process, this struct will be transformed into a reduced (more restricted) form acting as a subset of its original form, but that restricted form is still valid in the earlier stage in the compilation process before it was transformed.
|
||||
@@ -134,6 +151,12 @@ pub struct ProtoNode {
|
||||
pub original_location: OriginalLocation,
|
||||
pub skip_deduplication: bool,
|
||||
pub(crate) context_features: ContextDependencies,
|
||||
/// Bit `i` marks input `i` as invariant under the innermost index. Inputs at
|
||||
/// position 32 and above never set a bit, so they read as varying.
|
||||
#[serde(skip)]
|
||||
pub(crate) lane_invariant_inputs: u32,
|
||||
#[serde(skip)]
|
||||
pub(crate) resolved: Resolved,
|
||||
}
|
||||
|
||||
impl Default for ProtoNode {
|
||||
@@ -145,6 +168,8 @@ impl Default for ProtoNode {
|
||||
original_location: OriginalLocation::default(),
|
||||
skip_deduplication: false,
|
||||
context_features: Default::default(),
|
||||
lane_invariant_inputs: 0,
|
||||
resolved: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -185,6 +210,8 @@ impl ProtoNode {
|
||||
},
|
||||
skip_deduplication: false,
|
||||
context_features: Default::default(),
|
||||
lane_invariant_inputs: 0,
|
||||
resolved: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -202,6 +229,10 @@ impl ProtoNode {
|
||||
_ => panic!("tried to unwrap nodes from non node construction args \n node: {self:#?}"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn resolved_layout(&self) -> Option<&core_types::record::RecordLayout> {
|
||||
self.resolved.layout.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
@@ -227,6 +258,7 @@ impl ProtoNetwork {
|
||||
inputs: vec![node_id],
|
||||
output: node_id,
|
||||
nodes: vec![(node_id, proto_node.clone())],
|
||||
..Default::default()
|
||||
};
|
||||
(proto_network, node_id, proto_node)
|
||||
}
|
||||
@@ -303,6 +335,111 @@ impl ProtoNetwork {
|
||||
self.nodes.iter().flat_map(|(_, node)| node.context_features.sources().iter().copied()).collect()
|
||||
}
|
||||
|
||||
pub fn resolve_types(&mut self, registry: &Registry) -> Result<(), String> {
|
||||
self.reorder_ids()?;
|
||||
for index in 0..self.nodes.len() {
|
||||
let resolved = {
|
||||
let node = &self.nodes[index].1;
|
||||
match &node.construction_args {
|
||||
ConstructionArgs::Value(value) => Resolved {
|
||||
io: Some(NodeIOTypes::new(concrete!(Context), Type::Record(Box::new(value.ty())), vec![])),
|
||||
..Default::default()
|
||||
},
|
||||
_ => {
|
||||
let inputs: Vec<Type> = match &node.construction_args {
|
||||
ConstructionArgs::Nodes(nodes) => nodes
|
||||
.iter()
|
||||
.map(|input| {
|
||||
self.nodes[input.0 as usize]
|
||||
.1
|
||||
.resolved
|
||||
.io
|
||||
.as_ref()
|
||||
.map(|io| io.ty())
|
||||
.ok_or_else(|| format!("input {input:?} of {} is not yet typed", node.identifier.as_str()))
|
||||
})
|
||||
.collect::<Result<_, _>>()?,
|
||||
ConstructionArgs::Inline(inline) => vec![inline.ty.clone()],
|
||||
ConstructionArgs::Value(_) => unreachable!(),
|
||||
};
|
||||
let impls = registry.get(&node.identifier).ok_or_else(|| format!("no implementations for {}", node.identifier.as_str()))?;
|
||||
let (io, entry) = resolve_entry(node, &inputs, impls).map_err(|errors| format!("{errors:?}"))?;
|
||||
Resolved {
|
||||
io: Some(io),
|
||||
layout_meta: entry.layout_meta.clone(),
|
||||
layout: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
self.nodes[index].1.resolved = resolved;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn compute_layouts(&mut self) {
|
||||
for index in 0..self.nodes.len() {
|
||||
let lane_invariant = self.nodes[index].1.lane_invariant_inputs;
|
||||
let layout = {
|
||||
let node = &self.nodes[index].1;
|
||||
match &node.construction_args {
|
||||
ConstructionArgs::Value(value) => value.value_layout().map(|layout| core_types::record::RecordLayout {
|
||||
frame_bytes: layout.frame_bytes(),
|
||||
plan: Vec::new(),
|
||||
lane_invariant,
|
||||
layout,
|
||||
}),
|
||||
ConstructionArgs::Nodes(inputs) => node.resolved.layout_meta.as_ref().and_then(|meta| {
|
||||
let input_layouts: Vec<Option<&core_types::record::Layout>> = inputs
|
||||
.iter()
|
||||
.map(|input| self.nodes[input.0 as usize].1.resolved.layout.as_ref().map(|resolved| &resolved.layout))
|
||||
.collect();
|
||||
meta.sources.iter().all(|&source| input_layouts[source as usize].is_some()).then(|| core_types::record::RecordLayout {
|
||||
lane_invariant,
|
||||
..meta.resolve(&input_layouts)
|
||||
})
|
||||
}),
|
||||
ConstructionArgs::Inline(_) => None,
|
||||
}
|
||||
};
|
||||
// Set GRAPHENE_LAYOUT_DEBUG to dump each node's resolved record depth.
|
||||
if let Some(resolved) = &layout
|
||||
&& std::env::var("GRAPHENE_LAYOUT_DEBUG").is_ok()
|
||||
{
|
||||
eprintln!("layout {} depth {}", self.nodes[index].1.identifier, resolved.layout.depth);
|
||||
}
|
||||
self.nodes[index].1.resolved.layout = layout;
|
||||
}
|
||||
self.stack_need = self.fold_stack_peak();
|
||||
}
|
||||
|
||||
/// Peak record-stack bytes for evaluating [`output`](Self::output)'s cone. A node holds its
|
||||
/// inputs' frames until it returns, so its need is its own frame plus every input's frame plus
|
||||
/// the deepest input's peak. Memoized over shared cones. Runs while node IDs are still indices.
|
||||
fn fold_stack_peak(&self) -> usize {
|
||||
fn peak(index: usize, network: &ProtoNetwork, memo: &mut [Option<usize>]) -> usize {
|
||||
if let Some(cached) = memo[index] {
|
||||
return cached;
|
||||
}
|
||||
let frame = |i: usize| network.nodes[i].1.resolved.layout.as_ref().map_or(0, |resolved| resolved.frame_bytes);
|
||||
let mut held = 0;
|
||||
let mut deepest = 0;
|
||||
if let ConstructionArgs::Nodes(inputs) = &network.nodes[index].1.construction_args {
|
||||
for input in inputs {
|
||||
let child = input.0 as usize;
|
||||
let child_frame = frame(child);
|
||||
held += child_frame;
|
||||
deepest = deepest.max(peak(child, network, memo).saturating_sub(child_frame));
|
||||
}
|
||||
}
|
||||
let need = frame(index) + held + deepest;
|
||||
memo[index] = Some(need);
|
||||
need
|
||||
}
|
||||
let mut memo = vec![None; self.nodes.len()];
|
||||
peak(self.output.0 as usize, self, &mut memo)
|
||||
}
|
||||
|
||||
/// Inserts context nullification nodes to optimize caching.
|
||||
/// This analysis is performed after topological sorting to ensure proper dependency tracking.
|
||||
pub fn insert_context_nullification_nodes(&mut self) -> Result<(), String> {
|
||||
@@ -333,7 +470,7 @@ impl ProtoNetwork {
|
||||
ProtoNode {
|
||||
construction_args: ConstructionArgs::Nodes(vec![node_id]),
|
||||
call_argument: concrete!(Context),
|
||||
identifier: graphene_core::memo::memoize::IDENTIFIER,
|
||||
identifier: graphene_core::memo::frame_memo::IDENTIFIER,
|
||||
original_location: OriginalLocation {
|
||||
path: path.clone(),
|
||||
..Default::default()
|
||||
@@ -374,31 +511,78 @@ impl ProtoNetwork {
|
||||
nullification_node_id
|
||||
}
|
||||
|
||||
/// The node's declared dependencies and per-input pushed levels, both read
|
||||
/// from the registry since they follow the node's signature. A node with no
|
||||
/// registry entry declares nothing and pushes nothing.
|
||||
fn registry_dependencies(&self, node_index: usize) -> (ContextDependencies, Vec<u8>) {
|
||||
let identifier = &self.nodes[node_index].1.identifier;
|
||||
let metadata = core_types::registry::NODE_METADATA.lock().unwrap();
|
||||
match metadata.get(identifier) {
|
||||
Some(entry) => (
|
||||
ContextDependencies::from(entry.context_features.as_slice()),
|
||||
entry.fields.iter().map(|field| field.pushed_levels).collect(),
|
||||
),
|
||||
None => (ContextDependencies::default(), Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
fn find_context_dependencies(&mut self, id: NodeId) -> (ContextModification, Option<NodeId>) {
|
||||
let mut branch_dependencies = Vec::new();
|
||||
let mut combined_deps = ContextModification::default();
|
||||
let node_index = id.0 as usize;
|
||||
|
||||
let (registry_deps, pushed_levels) = self.registry_dependencies(node_index);
|
||||
let (extract, inject, own_deps) = {
|
||||
let dependencies = &self.nodes[node_index].1.context_features;
|
||||
let own_deps = ContextModification::from_sources(dependencies.extract, dependencies.sources());
|
||||
let carried = &self.nodes[node_index].1.context_features;
|
||||
// A code-built wrapper node declares dependencies its signature cannot
|
||||
// express; everything else resolves from the registry. Sources are
|
||||
// input wiring, not declarations, so they merge either way.
|
||||
let mut dependencies = match carried.extract.is_empty() && carried.inject.is_empty() {
|
||||
false => carried.clone(),
|
||||
true => registry_deps,
|
||||
};
|
||||
dependencies.add_sources(carried.sources());
|
||||
let index_levels = match dependencies.extract.contains(core_types::context::ContextFeatures::INDEX) {
|
||||
// A hand-declared `INDEX` names no level and addresses the innermost.
|
||||
true if dependencies.index_levels.is_empty() => core_types::context::IndexLevels::innermost(),
|
||||
true => dependencies.index_levels,
|
||||
false => core_types::context::IndexLevels::empty(),
|
||||
};
|
||||
let own_deps = ContextModification::from_sources(dependencies.extract, dependencies.sources()).with_index_levels(index_levels);
|
||||
(dependencies.extract, dependencies.inject, own_deps)
|
||||
};
|
||||
|
||||
let mut inputs = match &self.nodes[node_index].1.construction_args {
|
||||
// We pretend like we have already placed context modification nodes after ourselves because value nodes don't need to be cached
|
||||
ConstructionArgs::Value(_) => return (own_deps, Some(id)),
|
||||
ConstructionArgs::Value(value) => {
|
||||
let mut deps = own_deps;
|
||||
// A leveled value serves its lanes by the innermost index.
|
||||
if value.value_layout().is_some_and(|layout| layout.depth > 0) {
|
||||
deps |= core_types::context::ContextFeatures::INDEX;
|
||||
deps.index_levels |= core_types::context::IndexLevels::innermost();
|
||||
}
|
||||
return (deps, Some(id));
|
||||
}
|
||||
ConstructionArgs::Nodes(items) => items.clone(),
|
||||
ConstructionArgs::Inline(_) => return (own_deps, Some(id)),
|
||||
};
|
||||
|
||||
// Compute the dependencies for each branch and combine all of them
|
||||
for &node in &inputs {
|
||||
let mut lane_invariant_inputs = 0u32;
|
||||
for (input, &node) in inputs.iter().enumerate() {
|
||||
let branch = self.find_context_dependencies(node);
|
||||
|
||||
combined_deps |= &branch.0;
|
||||
let reads_innermost = branch.0.features.contains(core_types::context::ContextFeatures::INDEX) && branch.0.index_levels.contains_level(0);
|
||||
if !reads_innermost && input < 32 {
|
||||
lane_invariant_inputs |= 1 << input;
|
||||
}
|
||||
|
||||
let mut lifted = branch.0.clone();
|
||||
lifted.index_levels = lifted.index_levels.lifted(0, pushed_levels.get(input).copied().unwrap_or(0));
|
||||
combined_deps |= &lifted;
|
||||
branch_dependencies.push(branch);
|
||||
}
|
||||
self.nodes[node_index].1.lane_invariant_inputs = lane_invariant_inputs;
|
||||
let mut new_deps = combined_deps.clone();
|
||||
|
||||
// Remove requirements which this node provides
|
||||
@@ -420,6 +604,9 @@ impl ProtoNetwork {
|
||||
self.nodes[node_index].1.construction_args = ConstructionArgs::Nodes(inputs);
|
||||
|
||||
// Which dependencies do we supply (and don't need ourselves)?
|
||||
// TODO: a shrinking index-level mask does not count as supplying a
|
||||
// dependency, so a fold that consumes its subtree's only level inserts
|
||||
// no boundary here.
|
||||
let net_injections = inject.difference(extract);
|
||||
|
||||
// Which dependencies still need to be met after this node?
|
||||
@@ -643,23 +830,29 @@ impl Debug for GraphError {
|
||||
}
|
||||
pub type GraphErrors = Vec<GraphError>;
|
||||
|
||||
pub type Registry = HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>>;
|
||||
|
||||
/// The `TypingContext` is used to store the types of the nodes indexed by their stable node id.
|
||||
#[derive(Default, Clone, dyn_any::DynAny)]
|
||||
pub struct TypingContext {
|
||||
lookup: Cow<'static, HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>>>,
|
||||
lookup: Cow<'static, Registry>,
|
||||
inferred: HashMap<NodeId, NodeIOTypes>,
|
||||
constructor: HashMap<NodeId, NodeConstructor>,
|
||||
}
|
||||
|
||||
impl TypingContext {
|
||||
/// Creates a new `TypingContext` with the given lookup table.
|
||||
pub fn new(lookup: &'static HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>>) -> Self {
|
||||
pub fn new(lookup: &'static Registry) -> Self {
|
||||
Self {
|
||||
lookup: Cow::Borrowed(lookup),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn registry(&self) -> &Registry {
|
||||
&self.lookup
|
||||
}
|
||||
|
||||
/// Updates the `TypingContext` with a given proto network. This will infer the types of the nodes
|
||||
/// and store them in the `inferred` field. The proto network has to be topologically sorted
|
||||
/// and contain fully resolved stable node ids.
|
||||
@@ -715,115 +908,116 @@ impl TypingContext {
|
||||
};
|
||||
|
||||
// Get the node input type from the proto node declaration
|
||||
let call_argument = &node.call_argument;
|
||||
let impls = self.lookup.get(&node.identifier).ok_or_else(|| vec![GraphError::new(node, GraphErrorType::NoImplementations)])?;
|
||||
let candidates: Vec<(NodeIOTypes, NodeConstructor)> = impls.iter().map(|entry| (entry.io.clone(), entry.constructor)).collect();
|
||||
let (node_io, entry) = resolve_entry(node, &inputs, impls)?;
|
||||
if std::env::var("GRAPHENE_TYPE_DEBUG").is_ok() {
|
||||
eprintln!("type {} {} -> {}", node_id, node.identifier, node_io.ty());
|
||||
}
|
||||
self.inferred.insert(node_id, node_io.clone());
|
||||
self.constructor.insert(node_id, entry.constructor);
|
||||
Ok(node_io)
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(index) = inputs.iter().position(|p| {
|
||||
matches!(p,
|
||||
Type::Fn(_, b) if matches!(b.as_ref(), Type::Generic(_)))
|
||||
}) {
|
||||
return Err(vec![GraphError::new(node, GraphErrorType::UnexpectedGenerics { index, inputs })]);
|
||||
/// Selects the single registry entry matching the node's resolved input types,
|
||||
/// substituting generics. Stateless and stable-id-free.
|
||||
fn resolve_entry<'a>(node: &ProtoNode, inputs: &[Type], impls: &'a [RegistryEntry]) -> Result<(NodeIOTypes, &'a RegistryEntry), GraphErrors> {
|
||||
let call_argument = &node.call_argument;
|
||||
let candidates: Vec<(NodeIOTypes, &RegistryEntry)> = impls.iter().map(|entry| (entry.io.clone(), entry)).collect();
|
||||
|
||||
if let Some(index) = inputs.iter().position(|p| {
|
||||
matches!(p,
|
||||
Type::Fn(_, b) if matches!(b.as_ref(), Type::Generic(_)))
|
||||
}) {
|
||||
return Err(vec![GraphError::new(node, GraphErrorType::UnexpectedGenerics { index, inputs: inputs.to_vec() })]);
|
||||
}
|
||||
|
||||
// List of all implementations that match the input types
|
||||
let valid_output_types = candidates
|
||||
.iter()
|
||||
.filter(|(node_io, _)| valid_type(&node_io.call_argument, call_argument) && inputs.iter().zip(node_io.inputs.iter()).all(|(p1, p2)| valid_type(p1, p2)))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// Attempt to substitute generic types with concrete types and save the list of results
|
||||
let substitution_results = valid_output_types
|
||||
.iter()
|
||||
.map(|(node_io, entry)| {
|
||||
let generics_lookup: Result<HashMap<_, _>, _> = collect_generics(node_io)
|
||||
.iter()
|
||||
.map(|generic| check_generic(node_io, call_argument, inputs, generic).map(|x| (generic.to_string(), x)))
|
||||
.collect();
|
||||
|
||||
generics_lookup.map(|generics_lookup| {
|
||||
let mut new_node_io = node_io.clone();
|
||||
replace_generics(&mut new_node_io, &generics_lookup);
|
||||
(new_node_io, *entry)
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// Collect all substitutions that are valid
|
||||
let valid_impls = substitution_results.iter().filter_map(|result| result.as_ref().ok()).collect::<Vec<_>>();
|
||||
|
||||
match valid_impls.as_slice() {
|
||||
[] => {
|
||||
let convert_node_index_offset = node.original_location.auto_convert_index.unwrap_or(0);
|
||||
let mut best_errors = usize::MAX;
|
||||
let mut error_inputs = Vec::new();
|
||||
for (node_io, _) in &candidates {
|
||||
// For errors on Convert nodes, offset the input index so it correctly corresponds to the node it is connected to.
|
||||
let current_errors = [call_argument]
|
||||
.into_iter()
|
||||
.chain(inputs)
|
||||
.cloned()
|
||||
.zip([&node_io.call_argument].into_iter().chain(&node_io.inputs).cloned())
|
||||
.enumerate()
|
||||
.filter(|(_, (p1, p2))| !valid_type(p1, p2))
|
||||
.map(|(index, expected)| (index - 1 + convert_node_index_offset, expected))
|
||||
.collect::<Vec<_>>();
|
||||
if current_errors.len() < best_errors {
|
||||
best_errors = current_errors.len();
|
||||
error_inputs.clear();
|
||||
}
|
||||
if current_errors.len() <= best_errors {
|
||||
error_inputs.push(current_errors);
|
||||
}
|
||||
}
|
||||
let inputs = [call_argument]
|
||||
.into_iter()
|
||||
.chain(inputs)
|
||||
.enumerate()
|
||||
.filter_map(|(i, t)| {
|
||||
if i == 0 {
|
||||
None
|
||||
} else {
|
||||
let number = i + convert_node_index_offset;
|
||||
Some(format!("• Input {number}: {t}"))
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
Err(vec![GraphError::new(node, GraphErrorType::InvalidImplementations { inputs, error_inputs })])
|
||||
}
|
||||
[(node_io, entry)] => Ok((node_io.clone(), *entry)),
|
||||
// If two types are available and one of them accepts () an input, always choose that one
|
||||
[first, second] => {
|
||||
if first.0.call_argument != second.0.call_argument {
|
||||
for (node_io, entry) in [first, second] {
|
||||
if node_io.call_argument != concrete!(()) {
|
||||
continue;
|
||||
}
|
||||
return Ok((node_io.clone(), *entry));
|
||||
}
|
||||
}
|
||||
let inputs = [call_argument].into_iter().chain(inputs).map(ToString::to_string).collect::<Vec<_>>().join(", ");
|
||||
let valid = valid_output_types.into_iter().map(|(node_io, _)| node_io.clone()).collect();
|
||||
Err(vec![GraphError::new(node, GraphErrorType::MultipleImplementations { inputs, valid })])
|
||||
}
|
||||
|
||||
// List of all implementations that match the input types
|
||||
let valid_output_types = candidates
|
||||
.iter()
|
||||
.filter(|(node_io, _)| valid_type(&node_io.call_argument, call_argument) && inputs.iter().zip(node_io.inputs.iter()).all(|(p1, p2)| valid_type(p1, p2)))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// Attempt to substitute generic types with concrete types and save the list of results
|
||||
let substitution_results = valid_output_types
|
||||
.iter()
|
||||
.map(|(node_io, constructor)| {
|
||||
let generics_lookup: Result<HashMap<_, _>, _> = collect_generics(node_io)
|
||||
.iter()
|
||||
.map(|generic| check_generic(node_io, call_argument, &inputs, generic).map(|x| (generic.to_string(), x)))
|
||||
.collect();
|
||||
|
||||
generics_lookup.map(|generics_lookup| {
|
||||
let mut new_node_io = node_io.clone();
|
||||
replace_generics(&mut new_node_io, &generics_lookup);
|
||||
(new_node_io, *constructor)
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// Collect all substitutions that are valid
|
||||
let valid_impls = substitution_results.iter().filter_map(|result| result.as_ref().ok()).collect::<Vec<_>>();
|
||||
|
||||
match valid_impls.as_slice() {
|
||||
[] => {
|
||||
let convert_node_index_offset = node.original_location.auto_convert_index.unwrap_or(0);
|
||||
let mut best_errors = usize::MAX;
|
||||
let mut error_inputs = Vec::new();
|
||||
for (node_io, _) in &candidates {
|
||||
// For errors on Convert nodes, offset the input index so it correctly corresponds to the node it is connected to.
|
||||
let current_errors = [call_argument]
|
||||
.into_iter()
|
||||
.chain(&inputs)
|
||||
.cloned()
|
||||
.zip([&node_io.call_argument].into_iter().chain(&node_io.inputs).cloned())
|
||||
.enumerate()
|
||||
.filter(|(_, (p1, p2))| !valid_type(p1, p2))
|
||||
.map(|(index, expected)| (index - 1 + convert_node_index_offset, expected))
|
||||
.collect::<Vec<_>>();
|
||||
if current_errors.len() < best_errors {
|
||||
best_errors = current_errors.len();
|
||||
error_inputs.clear();
|
||||
}
|
||||
if current_errors.len() <= best_errors {
|
||||
error_inputs.push(current_errors);
|
||||
}
|
||||
}
|
||||
let inputs = [call_argument]
|
||||
.into_iter()
|
||||
.chain(&inputs)
|
||||
.enumerate()
|
||||
.filter_map(|(i, t)| {
|
||||
if i == 0 {
|
||||
None
|
||||
} else {
|
||||
let number = i + convert_node_index_offset;
|
||||
Some(format!("• Input {number}: {t}"))
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
Err(vec![GraphError::new(node, GraphErrorType::InvalidImplementations { inputs, error_inputs })])
|
||||
}
|
||||
[(node_io, constructor)] => {
|
||||
let node_io = node_io.clone();
|
||||
|
||||
// Save the inferred type
|
||||
self.inferred.insert(node_id, node_io.clone());
|
||||
self.constructor.insert(node_id, *constructor);
|
||||
Ok(node_io)
|
||||
}
|
||||
// If two types are available and one of them accepts () an input, always choose that one
|
||||
[first, second] => {
|
||||
if first.0.call_argument != second.0.call_argument {
|
||||
for (node_io, constructor) in [first, second] {
|
||||
if node_io.call_argument != concrete!(()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Save the inferred type
|
||||
self.inferred.insert(node_id, node_io.clone());
|
||||
self.constructor.insert(node_id, *constructor);
|
||||
return Ok(node_io.clone());
|
||||
}
|
||||
}
|
||||
let inputs = [call_argument].into_iter().chain(&inputs).map(ToString::to_string).collect::<Vec<_>>().join(", ");
|
||||
let valid = valid_output_types.into_iter().map(|(node_io, _)| node_io.clone()).collect();
|
||||
Err(vec![GraphError::new(node, GraphErrorType::MultipleImplementations { inputs, valid })])
|
||||
}
|
||||
|
||||
_ => {
|
||||
let inputs = [call_argument].into_iter().chain(&inputs).map(ToString::to_string).collect::<Vec<_>>().join(", ");
|
||||
let valid = valid_output_types.into_iter().map(|(node_io, _)| node_io.clone()).collect();
|
||||
Err(vec![GraphError::new(node, GraphErrorType::MultipleImplementations { inputs, valid })])
|
||||
}
|
||||
_ => {
|
||||
let inputs = [call_argument].into_iter().chain(inputs).map(ToString::to_string).collect::<Vec<_>>().join(", ");
|
||||
let valid = valid_output_types.into_iter().map(|(node_io, _)| node_io.clone()).collect();
|
||||
Err(vec![GraphError::new(node, GraphErrorType::MultipleImplementations { inputs, valid })])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -886,13 +1080,7 @@ fn check_generic(types: &NodeIOTypes, input: &Type, parameters: &[Type], generic
|
||||
.into_iter()
|
||||
.chain(types.inputs.iter().map(|x| x.fn_input()).zip(parameters.iter().map(|x| x.fn_input())))
|
||||
.chain(types.inputs.iter().map(|x| x.fn_output()).zip(parameters.iter().map(|x| x.fn_output())))
|
||||
.chain(
|
||||
types
|
||||
.inputs
|
||||
.iter()
|
||||
.map(|x| record_element(x.fn_output()))
|
||||
.zip(parameters.iter().map(|x| record_element(x.fn_output()))),
|
||||
);
|
||||
.chain(types.inputs.iter().map(|x| record_element(x.fn_output())).zip(parameters.iter().map(|x| record_element(x.fn_output()))));
|
||||
let concrete_inputs = inputs.filter(|(ni, _)| matches!(ni, Some(Type::Generic(input)) if generic == input));
|
||||
let mut outputs = concrete_inputs.flat_map(|(_, out)| out);
|
||||
let out_ty = outputs
|
||||
@@ -922,6 +1110,34 @@ mod test {
|
||||
use super::*;
|
||||
use crate::proto::{ConstructionArgs, ProtoNetwork, ProtoNode};
|
||||
|
||||
#[test]
|
||||
fn stack_peak_folds_a_diamond_chain() {
|
||||
// S3 <- S2 <- S1 <- S0, each consuming the node below on both inputs; every frame is one byte.
|
||||
let node = |index: u64| {
|
||||
let args = if index == 0 {
|
||||
ConstructionArgs::Value(value::TaggedValue::U32(0).into())
|
||||
} else {
|
||||
ConstructionArgs::Nodes(vec![NodeId(index - 1), NodeId(index - 1)])
|
||||
};
|
||||
ProtoNode {
|
||||
construction_args: args,
|
||||
resolved: Resolved {
|
||||
layout: Some(core_types::record::RecordLayout { frame_bytes: 1, ..Default::default() }),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
}
|
||||
};
|
||||
let mut network = ProtoNetwork {
|
||||
output: NodeId(3),
|
||||
nodes: (0..4).map(|index| (NodeId(index), node(index))).collect(),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(network.fold_stack_peak(), 7);
|
||||
network.output = NodeId(0);
|
||||
assert_eq!(network.fold_stack_peak(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn topological_sort() {
|
||||
let construction_network = test_network();
|
||||
@@ -1112,6 +1328,7 @@ mod test {
|
||||
]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1150,6 +1367,7 @@ mod test {
|
||||
]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1179,6 +1397,7 @@ mod test {
|
||||
]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::document::NodeNetwork;
|
||||
use crate::graphene_compiler::Compiler;
|
||||
use crate::proto::ProtoNetwork;
|
||||
use crate::proto::{ProtoNetwork, Registry};
|
||||
|
||||
pub fn load_network(document_string: &str) -> NodeNetwork {
|
||||
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")
|
||||
}
|
||||
|
||||
pub fn compile(network: NodeNetwork) -> ProtoNetwork {
|
||||
pub fn compile(network: NodeNetwork, registry: &Registry) -> ProtoNetwork {
|
||||
let compiler = Compiler {};
|
||||
compiler.compile_single(network).unwrap()
|
||||
compiler.compile_single(network, registry).unwrap()
|
||||
}
|
||||
|
||||
pub fn load_from_name(name: &str) -> NodeNetwork {
|
||||
|
||||
@@ -314,7 +314,7 @@ fn compile_graph(network: NodeNetwork, editor_api: Arc<PlatformEditorApi>, gdd:
|
||||
}
|
||||
|
||||
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, runtime: Arc<DynGraphRuntime>) -> Result<DynamicExecutor, Box<dyn Error>> {
|
||||
|
||||
@@ -15,6 +15,7 @@ wasm = ["graphene-std/wasm"]
|
||||
graphene-std = { workspace = true }
|
||||
graph-craft = { workspace = true }
|
||||
graphene-core = { workspace = true }
|
||||
graphic-types = { workspace = true }
|
||||
wgpu-executor = { workspace = true }
|
||||
core-types = { workspace = true }
|
||||
dyn-any = { workspace = true }
|
||||
|
||||
@@ -12,7 +12,7 @@ pub fn setup_network(name: &str) -> (DynamicExecutor, ProtoNetwork) {
|
||||
let mut network = wrap_network_in_scope(network, editor_api);
|
||||
let preprocessor = preprocessor::Preprocessor::new();
|
||||
preprocessor.preprocess(&mut network, &|_| None).unwrap();
|
||||
let proto_network = compile(network);
|
||||
let proto_network = compile(network, &interpreted_executor::node_registry::NODE_REGISTRY);
|
||||
let executor = DynamicExecutor::new(proto_network.clone()).unwrap();
|
||||
(executor, proto_network)
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ fn setup_run_cached(name: &str) -> DynamicExecutor {
|
||||
}
|
||||
|
||||
#[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 {
|
||||
let context = RenderConfig::default();
|
||||
black_box(Executor::execute(&&executor, black_box(context)).unwrap());
|
||||
|
||||
@@ -8,7 +8,7 @@ use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
|
||||
fn update_executor<M: Measurement>(name: &str, c: &mut BenchmarkGroup<M>) {
|
||||
let network = load_from_name(name);
|
||||
let proto_network = compile(network);
|
||||
let proto_network = compile(network, &interpreted_executor::node_registry::NODE_REGISTRY);
|
||||
|
||||
c.bench_function(name, |b| {
|
||||
b.iter_batched(
|
||||
@@ -28,7 +28,7 @@ fn update_executor_demo(c: &mut Criterion) {
|
||||
|
||||
fn run_once<M: Measurement>(name: &str, c: &mut BenchmarkGroup<M>) {
|
||||
let network = load_from_name(name);
|
||||
let proto_network = compile(network);
|
||||
let proto_network = compile(network, &interpreted_executor::node_registry::NODE_REGISTRY);
|
||||
|
||||
let executor = DynamicExecutor::new(proto_network).unwrap();
|
||||
let footprint = Footprint::default();
|
||||
|
||||
@@ -4,16 +4,18 @@ use benchmark_util::{bench_for_each_demo, setup_network};
|
||||
use criterion::{Criterion, criterion_group, criterion_main};
|
||||
use graph_craft::graphene_compiler::Executor;
|
||||
use graphene_std::application_io::RenderConfig;
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
|
||||
fn run_once(c: &mut Criterion) {
|
||||
let mut group = c.benchmark_group("Run Once");
|
||||
let context = RenderConfig::default();
|
||||
bench_for_each_demo(&mut group, |name, g| {
|
||||
let (_, network) = setup_network(name);
|
||||
g.bench_function(name, |b| {
|
||||
b.iter_batched(
|
||||
|| setup_network(name),
|
||||
|(executor, _)| Executor::execute(&&executor, std::hint::black_box(context)).unwrap(),
|
||||
criterion::BatchSize::SmallInput,
|
||||
b.iter_batched_ref(
|
||||
|| DynamicExecutor::new(network.clone()).unwrap(),
|
||||
|executor| Executor::execute(&&*executor, std::hint::black_box(context)).unwrap(),
|
||||
criterion::BatchSize::LargeInput,
|
||||
)
|
||||
});
|
||||
});
|
||||
|
||||
@@ -13,13 +13,13 @@ fn setup_run_once(name: &str) -> DynamicExecutor {
|
||||
}
|
||||
|
||||
#[library_benchmark]
|
||||
#[benches::with_setup(args = ["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 {
|
||||
#[benches::with_setup(args = ["changing-seasons", "isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_run_once)]
|
||||
pub fn run_once(executor: DynamicExecutor) -> (DynamicExecutor, core_types::gpoll::GPoll<graph_craft::document::value::TaggedValue>) {
|
||||
let context = application_io::RenderConfig::default();
|
||||
black_box(Executor::execute(&&executor, 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
|
||||
executor
|
||||
// Return the executor and result so their teardown happens outside the measured section
|
||||
(executor, result)
|
||||
}
|
||||
|
||||
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");
|
||||
bench_for_each_demo(&mut group, |name, g| {
|
||||
g.bench_function(name, |b| {
|
||||
b.iter_batched(
|
||||
b.iter_batched_ref(
|
||||
|| {
|
||||
let (_, proto_network) = setup_network(name);
|
||||
let empty = ProtoNetwork::default();
|
||||
let executor = DynamicExecutor::new(empty).unwrap();
|
||||
(executor, proto_network)
|
||||
},
|
||||
|(mut executor, network)| executor.update(std::hint::black_box(network)),
|
||||
|(executor, network)| executor.update(std::hint::black_box(std::mem::take(network))),
|
||||
criterion::BatchSize::SmallInput,
|
||||
)
|
||||
});
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
use crate::node_registry;
|
||||
use core_types::arena::Arena;
|
||||
use core_types::context::{ContextImpl, DynSlot, EvalScope, VarArg, VarArgLink, VarArgSlots};
|
||||
use core_types::context::{ContextImpl, DynSlot, EvalScope, ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime, VarArg, VarArgLink, VarArgSlots};
|
||||
use core_types::gpoll::GPoll;
|
||||
use core_types::node::Node;
|
||||
use core_types::registry::{EdgeHandle, ErasedNode};
|
||||
use core_types::registry::EdgeHandle;
|
||||
use core_types::runtime::{DynGraphRuntime, DynSpawner, GraphRuntime, NoopSpawner};
|
||||
use graph_craft::Type;
|
||||
use graph_craft::document::NodeId;
|
||||
@@ -15,10 +14,27 @@ use std::collections::{HashMap, HashSet};
|
||||
use std::error::Error;
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
const ARENA_CAPACITY: usize = 1 << 20;
|
||||
const ARENA_CAPACITY: usize = 1 << 27;
|
||||
|
||||
fn new_arena() -> Arena {
|
||||
Arena::new(ARENA_CAPACITY).unwrap_or_else(|| {
|
||||
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
|
||||
}
|
||||
|
||||
fn new_arena(capacity: usize) -> Arena {
|
||||
Arena::new(capacity).unwrap_or_else(|| {
|
||||
log::error!("arena generations exhausted; continuing without frame caching");
|
||||
Arena::parked()
|
||||
})
|
||||
@@ -34,6 +50,12 @@ pub struct DynamicExecutor {
|
||||
// This allows us to keep the nodes around for one more frame which is used for introspection
|
||||
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>,
|
||||
}
|
||||
@@ -49,7 +71,9 @@ impl Default for DynamicExecutor {
|
||||
tree: Default::default(),
|
||||
typing_context: TypingContext::new(&node_registry::NODE_REGISTRY),
|
||||
orphaned_nodes: HashSet::new(),
|
||||
arena: Mutex::new(new_arena()),
|
||||
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(),
|
||||
}
|
||||
@@ -85,7 +109,9 @@ impl DynamicExecutor {
|
||||
output,
|
||||
typing_context,
|
||||
orphaned_nodes: HashSet::new(),
|
||||
arena: Mutex::new(new_arena()),
|
||||
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,
|
||||
})
|
||||
@@ -144,20 +170,75 @@ impl DynamicExecutor {
|
||||
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.
|
||||
/// A monitor's record capture materializes its element here against the
|
||||
/// arena, inside the introspection window, so consumers downcast the
|
||||
/// element type directly. The captured input context stays on the
|
||||
/// serialized io record for consumers that need it.
|
||||
/// 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 wire yields its element and a leveled wire its legacy list.
|
||||
pub fn introspect(&self, node_path: &[NodeId]) -> Result<Arc<dyn std::any::Any + Send + Sync + 'static>, IntrospectError> {
|
||||
let result = self.tree.introspect(node_path)?;
|
||||
if let Some(io) = result.downcast_ref::<core_types::memo::IORecord<core_types::context::CtxSnapshot, core_types::record::RecordCapture>>() {
|
||||
let arena = self.arena.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
return io.output.materialize_element(&arena).map(Arc::from).ok_or(IntrospectError::NoData);
|
||||
if result.downcast_ref::<core_types::context::CtxSnapshot>().is_some() {
|
||||
return self
|
||||
.introspect_with(node_path, |layout, batch, arena| graphic_types::boundary::batch_to_legacy(layout, batch, arena))
|
||||
.map(Arc::from);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Re-evaluates the monitored edge 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(EdgeHandle::record_edge)
|
||||
.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_edge(&edge, &ctx, &frames) {
|
||||
GPoll::Final(value) | GPoll::Partial(value) => {
|
||||
let rec = layout.rec(&value);
|
||||
// SAFETY: the serve produced one live record of the edge'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> {
|
||||
self.typing_context.type_of(self.output).map(|node_io| node_io.call_argument.clone())
|
||||
}
|
||||
@@ -190,10 +271,21 @@ where
|
||||
return Err("Output node not found in executor".into());
|
||||
};
|
||||
let mut arena = self.arena.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
core_types::record::stack::reserve(self.tree.stack_need());
|
||||
let result = eval_root(&mut arena, &self.runtime, &input, |ctx| match TaggedValue::from_edge(handle.duplicate(), ctx) {
|
||||
Ok(poll) => poll.map(Ok),
|
||||
Err(error) => GPoll::Final(Err(error)),
|
||||
let mut persistent = self.persistent.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
// The region is flushed whole between evaluations and the memos
|
||||
// re-promote: on a refusal, which leaves no room for the next promote,
|
||||
// and ahead of one where either the region itself or the heap its
|
||||
// parked payloads own is close to full.
|
||||
if persistent.exhausted() || over_budget(persistent.occupancy(), persistent.capacity()) || over_budget(persistent.retained_heap(), PERSISTENT_HEAP_BUDGET) {
|
||||
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?)),
|
||||
@@ -207,17 +299,30 @@ where
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn eval_root<S, T>(arena: &mut Arena, runtime: &GraphRuntime<S>, call_argument: DynSlot, eval: impl FnOnce(&ContextImpl) -> GPoll<T>) -> GPoll<T> {
|
||||
/// 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);
|
||||
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);
|
||||
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| eval(&ctx))) {
|
||||
let frames = buffer.frames();
|
||||
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| eval(&ctx, &frames))) {
|
||||
Ok(result) => result,
|
||||
Err(_) => {
|
||||
arena.reset();
|
||||
@@ -278,29 +383,21 @@ pub struct BorrowTree {
|
||||
impl BorrowTree {
|
||||
pub fn new(proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<BorrowTree, GraphErrors> {
|
||||
let mut nodes = BorrowTree::default();
|
||||
let output = proto_network.output;
|
||||
let mut deps = HashMap::new();
|
||||
let stack_need = proto_network.stack_need;
|
||||
for (id, node) in proto_network.nodes {
|
||||
if let ConstructionArgs::Nodes(ids) = &node.construction_args {
|
||||
deps.insert(id, ids.clone());
|
||||
}
|
||||
nodes.push_node(id, node, typing_context)?
|
||||
}
|
||||
nodes.stack_need = stack_peak(output, &deps, &|id| nodes.frame_bytes(id));
|
||||
nodes.stack_need = stack_need;
|
||||
Ok(nodes)
|
||||
}
|
||||
|
||||
/// Pushes new nodes into the tree and return orphaned nodes
|
||||
pub fn update(&mut self, proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<(Vec<Path>, HashSet<NodeId>), GraphErrors> {
|
||||
let output = proto_network.output;
|
||||
let stack_need = proto_network.stack_need;
|
||||
let mut old_nodes: HashSet<_> = self.nodes.keys().copied().collect();
|
||||
let mut new_nodes: Vec<_> = Vec::new();
|
||||
let mut deps = HashMap::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.
|
||||
for (id, node) in proto_network.nodes {
|
||||
if let ConstructionArgs::Nodes(ids) = &node.construction_args {
|
||||
deps.insert(id, ids.clone());
|
||||
}
|
||||
if !self.nodes.contains_key(&id) {
|
||||
new_nodes.push(node.original_location.path.clone().unwrap_or_default().into());
|
||||
self.push_node(id, node, typing_context)?;
|
||||
@@ -309,7 +406,7 @@ impl BorrowTree {
|
||||
}
|
||||
old_nodes.remove(&id);
|
||||
}
|
||||
self.stack_need = stack_peak(output, &deps, &|id| self.frame_bytes(id));
|
||||
self.stack_need = stack_need;
|
||||
Ok((new_nodes, old_nodes))
|
||||
}
|
||||
|
||||
@@ -332,14 +429,10 @@ impl BorrowTree {
|
||||
self.nodes.get(&id).map(|(node, _)| node.duplicate())
|
||||
}
|
||||
|
||||
/// Evaluate a node of the [`BorrowTree`], downcasting its edge to the expected output type.
|
||||
pub fn eval<I, T: 'static>(&self, id: NodeId, input: &I) -> Option<GPoll<T>>
|
||||
where
|
||||
ErasedNode<T>: Node<I, Output = T>,
|
||||
{
|
||||
let (node, _path) = self.nodes.get(&id)?;
|
||||
let edge = node.duplicate().downcast::<T>().ok()?;
|
||||
Some(edge.eval(input))
|
||||
/// The edge handle for the node at a document path.
|
||||
pub fn get_by_path(&self, node_path: &[NodeId]) -> Option<EdgeHandle> {
|
||||
let (id, _) = self.source_map.get(node_path)?;
|
||||
self.get(*id)
|
||||
}
|
||||
|
||||
/// Removes a node from the [`BorrowTree`] and returns its associated path.
|
||||
@@ -482,7 +575,10 @@ impl BorrowTree {
|
||||
ConstructionArgs::Nodes(ids) => {
|
||||
let construction_nodes = self.node_deps(ids);
|
||||
let constructor = typing_context.constructor(id).ok_or_else(|| vec![GraphError::new(&proto_node, GraphErrorType::NoConstructor)])?;
|
||||
let node = constructor(construction_nodes).map_err(|error| vec![GraphError::new(&proto_node, GraphErrorType::ConstructionFailed(format!("{error:?}")))])?;
|
||||
let mut node = constructor(construction_nodes).map_err(|error| vec![GraphError::new(&proto_node, GraphErrorType::ConstructionFailed(format!("{error:?}")))])?;
|
||||
if let Some(layout) = proto_node.resolved_layout() {
|
||||
node.set_layout(layout.clone());
|
||||
}
|
||||
self.store_node(node, id, path.into());
|
||||
}
|
||||
};
|
||||
@@ -494,37 +590,10 @@ impl BorrowTree {
|
||||
&self.source_map
|
||||
}
|
||||
|
||||
/// The record-stack reserve of an evaluation, folded from the graph at
|
||||
/// construction (see [`stack_peak`]).
|
||||
/// 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
|
||||
}
|
||||
|
||||
fn frame_bytes(&self, id: NodeId) -> usize {
|
||||
self.nodes.get(&id).and_then(|(handle, _)| handle.layout()).map_or(0, |layout| layout.frame_bytes())
|
||||
}
|
||||
}
|
||||
|
||||
/// Peak record-stack bytes for evaluating `output`'s cone. A node holds its
|
||||
/// inputs' frames until it returns, so its need is its own frame plus every
|
||||
/// input's frame plus the deepest input's peak. Memoized over shared cones.
|
||||
fn stack_peak(output: NodeId, deps: &HashMap<NodeId, Vec<NodeId>>, frame_bytes: &dyn Fn(NodeId) -> usize) -> usize {
|
||||
fn peak(id: NodeId, deps: &HashMap<NodeId, Vec<NodeId>>, frame_bytes: &dyn Fn(NodeId) -> usize, memo: &mut HashMap<NodeId, usize>) -> usize {
|
||||
if let Some(&cached) = memo.get(&id) {
|
||||
return cached;
|
||||
}
|
||||
let mut held = 0;
|
||||
let mut deepest = 0;
|
||||
for &child in deps.get(&id).map_or(&[][..], Vec::as_slice) {
|
||||
let child_frame = frame_bytes(child);
|
||||
held += child_frame;
|
||||
deepest = deepest.max(peak(child, deps, frame_bytes, memo).saturating_sub(child_frame));
|
||||
}
|
||||
let need = frame_bytes(id) + held + deepest;
|
||||
memo.insert(id, need);
|
||||
need
|
||||
}
|
||||
peak(output, deps, frame_bytes, &mut HashMap::new())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -544,24 +613,33 @@ mod test {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stack_peak_folds_a_diamond_chain() {
|
||||
// S3 <- S2 <- S1 <- S0, each consuming the node below on both inputs.
|
||||
let deps = HashMap::from([
|
||||
(NodeId(1), vec![NodeId(0), NodeId(0)]),
|
||||
(NodeId(2), vec![NodeId(1), NodeId(1)]),
|
||||
(NodeId(3), vec![NodeId(2), NodeId(2)]),
|
||||
]);
|
||||
let frame = |_: NodeId| 1;
|
||||
assert_eq!(stack_peak(NodeId(0), &deps, &frame), 1);
|
||||
assert_eq!(stack_peak(NodeId(3), &deps, &frame), 7);
|
||||
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, &runtime, &argument, |ctx| {
|
||||
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.))
|
||||
});
|
||||
@@ -571,15 +649,17 @@ mod test {
|
||||
#[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, &runtime, &(), |ctx| {
|
||||
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, &runtime, &(), |ctx| {
|
||||
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(())
|
||||
});
|
||||
@@ -588,16 +668,18 @@ mod test {
|
||||
#[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, &runtime, &(), |ctx| {
|
||||
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, &runtime, &(), |_| GPoll::Final(7u32)), GPoll::Final(7));
|
||||
assert_eq!(eval_root(&mut arena, &persistent, &mut buffer, &runtime, &(), |_, _| GPoll::Final(7u32)), GPoll::Final(7));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -607,19 +689,26 @@ mod test {
|
||||
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().unwrap().clone();
|
||||
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 GPoll::Final(value) = edge.eval(&ctx) else {
|
||||
let frames = core_types::record::test_frames(layout.frame_bytes());
|
||||
let GPoll::Final(value) = core_types::record::serve_edge(&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();
|
||||
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);
|
||||
@@ -634,35 +723,36 @@ mod test {
|
||||
|
||||
#[test]
|
||||
fn the_clone_node_clones_the_element_out_of_its_record_wire() {
|
||||
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(1),
|
||||
nodes: vec![
|
||||
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(raster_list.into()), 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 = DynamicExecutor::new(network).unwrap();
|
||||
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 edge = executor
|
||||
.tree()
|
||||
.get(NodeId(1))
|
||||
.unwrap()
|
||||
.downcast_record::<graphene_std::list::List<graphene_std::raster_types::Raster<graphene_std::raster_types::CPU>>>()
|
||||
.unwrap();
|
||||
let result = edge.eval(&ctx);
|
||||
assert!(matches!(result, GPoll::Final(_)), "the flipped clone must evaluate over record wires, got a non-final poll");
|
||||
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_edge(&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 a_flipped_ref_parameter_reads_the_borrow_from_its_record_wire() {
|
||||
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![
|
||||
@@ -672,33 +762,34 @@ mod test {
|
||||
],
|
||||
};
|
||||
|
||||
let executor = DynamicExecutor::new(network).unwrap();
|
||||
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::list::List<graphene_std::raster::color::Color>>()
|
||||
.unwrap();
|
||||
let result = edge.eval(&ctx);
|
||||
assert!(matches!(result, GPoll::Final(_)), "the palette must evaluate through its record wires, got a non-final poll");
|
||||
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_edge(&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 = DynamicExecutor::new(network).unwrap();
|
||||
let executor = build_executor(network);
|
||||
let value = executor.tree().get(NodeId(0)).unwrap();
|
||||
assert_eq!(value.ty(), &core_types::registry::record_edge_type::<f64>());
|
||||
assert!(value.layout().is_some());
|
||||
assert_eq!(value.layout().depth, 0);
|
||||
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::F64(7.)));
|
||||
}
|
||||
|
||||
@@ -707,12 +798,13 @@ mod test {
|
||||
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 = DynamicExecutor::new(network).unwrap();
|
||||
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");
|
||||
@@ -722,6 +814,7 @@ mod test {
|
||||
#[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![
|
||||
@@ -730,7 +823,7 @@ mod test {
|
||||
],
|
||||
};
|
||||
|
||||
let executor = DynamicExecutor::new(network).unwrap();
|
||||
let executor = build_executor(network);
|
||||
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::String(String::from("cached"))));
|
||||
assert_eq!(
|
||||
(&executor).execute(()).unwrap(),
|
||||
@@ -747,6 +840,7 @@ mod test {
|
||||
#[test]
|
||||
fn a_context_modification_row_wires_over_a_value_wire() {
|
||||
let network = ProtoNetwork {
|
||||
stack_need: 0,
|
||||
inputs: vec![],
|
||||
output: NodeId(2),
|
||||
nodes: vec![
|
||||
@@ -756,13 +850,14 @@ mod test {
|
||||
],
|
||||
};
|
||||
|
||||
let executor = DynamicExecutor::new(network).unwrap();
|
||||
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![
|
||||
@@ -774,13 +869,14 @@ mod test {
|
||||
],
|
||||
};
|
||||
|
||||
let executor = DynamicExecutor::new(network).unwrap();
|
||||
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![
|
||||
@@ -790,7 +886,7 @@ mod test {
|
||||
],
|
||||
};
|
||||
|
||||
let executor = DynamicExecutor::new(network).unwrap();
|
||||
let executor = build_executor(network);
|
||||
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::String("memoized".to_string())));
|
||||
assert_eq!(
|
||||
(&executor).execute(()).unwrap(),
|
||||
|
||||
@@ -44,7 +44,7 @@ mod tests {
|
||||
use graph_craft::graphene_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 = DynamicExecutor::new(protograph).map(|_e| panic!("The network should not type check ")).unwrap_err();
|
||||
}
|
||||
|
||||
@@ -1,22 +1,18 @@
|
||||
use glam::{DAffine2, DVec2, IVec2};
|
||||
use graph_craft::application_io::PlatformEditorApi;
|
||||
use graph_craft::document::value::RenderOutput;
|
||||
use graphene_std::gradient::GradientStops;
|
||||
use graphene_std::list::{AttributeDyn, AttributeValueDyn, List, ListDyn};
|
||||
#[cfg(target_family = "wasm")]
|
||||
use graphene_std::platform_application_io::canvas_utils::CanvasHandle;
|
||||
|
||||
use graphene_std::list::List;
|
||||
#[cfg(feature = "gpu")]
|
||||
use graphene_std::raster::GPU;
|
||||
use graphene_std::raster::color::Color;
|
||||
use graphene_std::raster::*;
|
||||
|
||||
#[cfg(feature = "gpu")]
|
||||
use graphene_std::SourceId;
|
||||
use graphene_std::raster::{CPU, Raster};
|
||||
use graphene_std::registry::{ConstructionError, EdgeHandle, ErasedNode, NodeIOTypes, RegistryEntry};
|
||||
use graphene_std::render_node::RenderIntermediate;
|
||||
use graphene_std::registry::{ConstructionError, EdgeHandle, NodeIOTypes, RegistryEntry};
|
||||
#[cfg(feature = "gpu")]
|
||||
use graphene_std::runtime::RuntimeHandle;
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphene_std::uuid::NodeId;
|
||||
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::{Artboard, Context, Graphic, ProtoNodeIdentifier, SourceId, concrete, fn_type};
|
||||
use graphene_std::{Context, Graphic, ProtoNodeIdentifier, concrete};
|
||||
use node_registry_macros::{convert_node, into_node};
|
||||
use std::collections::HashMap;
|
||||
#[cfg(feature = "gpu")]
|
||||
@@ -35,57 +31,6 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>> {
|
||||
convert_node!(from: List<Raster<CPU>>, to: List<Graphic>),
|
||||
#[cfg(feature = "gpu")]
|
||||
convert_node!(from: List<Raster<GPU>>, to: List<Graphic>),
|
||||
// Type-erased attribute conversions for the `Attach Attribute` node, so it monomorphizes only over the destination `List` type.
|
||||
convert_node!(from: List<Artboard>, to: AttributeDyn),
|
||||
convert_node!(from: List<Graphic>, to: AttributeDyn),
|
||||
convert_node!(from: List<Vector>, to: AttributeDyn),
|
||||
convert_node!(from: List<Raster<CPU>>, to: AttributeDyn),
|
||||
convert_node!(from: List<Color>, to: AttributeDyn),
|
||||
convert_node!(from: List<GradientStops>, to: AttributeDyn),
|
||||
convert_node!(from: List<f64>, to: AttributeDyn),
|
||||
convert_node!(from: List<bool>, to: AttributeDyn),
|
||||
convert_node!(from: List<String>, to: AttributeDyn),
|
||||
convert_node!(from: List<DAffine2>, to: AttributeDyn),
|
||||
convert_node!(from: List<BlendMode>, to: AttributeDyn),
|
||||
convert_node!(from: List<graphene_std::vector::style::GradientType>, to: AttributeDyn),
|
||||
convert_node!(from: List<graphene_std::vector::style::GradientSpreadMethod>, to: AttributeDyn),
|
||||
convert_node!(from: List<Artboard>, to: ListDyn),
|
||||
convert_node!(from: List<Graphic>, to: ListDyn),
|
||||
convert_node!(from: List<Vector>, to: ListDyn),
|
||||
convert_node!(from: List<Raster<CPU>>, to: ListDyn),
|
||||
#[cfg(feature = "gpu")]
|
||||
convert_node!(from: List<Raster<GPU>>, to: ListDyn),
|
||||
convert_node!(from: List<Color>, to: ListDyn),
|
||||
convert_node!(from: List<GradientStops>, to: ListDyn),
|
||||
convert_node!(from: List<f64>, to: ListDyn),
|
||||
convert_node!(from: List<bool>, to: ListDyn),
|
||||
convert_node!(from: List<String>, to: ListDyn),
|
||||
convert_node!(from: List<u8>, to: ListDyn),
|
||||
convert_node!(from: List<NodeId>, to: ListDyn),
|
||||
convert_node!(from: List<DAffine2>, to: ListDyn),
|
||||
convert_node!(from: List<BlendMode>, to: ListDyn),
|
||||
convert_node!(from: List<graphene_std::vector::style::GradientType>, to: ListDyn),
|
||||
convert_node!(from: List<graphene_std::vector::style::GradientSpreadMethod>, to: ListDyn),
|
||||
// Type-erased attribute value conversions for the `Write Attribute` node, so it monomorphizes only over the destination `List` type.
|
||||
convert_node!(from: f64, to: AttributeValueDyn),
|
||||
convert_node!(from: u32, to: AttributeValueDyn),
|
||||
convert_node!(from: u64, to: AttributeValueDyn),
|
||||
convert_node!(from: bool, to: AttributeValueDyn),
|
||||
convert_node!(from: String, to: AttributeValueDyn),
|
||||
convert_node!(from: DVec2, to: AttributeValueDyn),
|
||||
convert_node!(from: DAffine2, to: AttributeValueDyn),
|
||||
convert_node!(from: Color, to: AttributeValueDyn),
|
||||
convert_node!(from: BlendMode, to: AttributeValueDyn),
|
||||
convert_node!(from: graphene_std::vector::style::GradientType, to: AttributeValueDyn),
|
||||
convert_node!(from: graphene_std::vector::style::GradientSpreadMethod, to: AttributeValueDyn),
|
||||
convert_node!(from: List<String>, to: AttributeValueDyn),
|
||||
convert_node!(from: List<NodeId>, to: AttributeValueDyn),
|
||||
convert_node!(from: List<Color>, to: AttributeValueDyn),
|
||||
convert_node!(from: List<GradientStops>, to: AttributeValueDyn),
|
||||
convert_node!(from: List<Vector>, to: AttributeValueDyn),
|
||||
convert_node!(from: List<Raster<CPU>>, to: AttributeValueDyn),
|
||||
convert_node!(from: List<Raster<GPU>>, to: AttributeValueDyn),
|
||||
convert_node!(from: List<Graphic>, to: AttributeValueDyn),
|
||||
// into_node!(from: List<Raster<CPU>>, to: List<Raster<SRGBA8>>),
|
||||
convert_node!(from: DVec2, to: DVec2),
|
||||
convert_node!(from: List<Vector>, to: List<Vector>),
|
||||
@@ -110,6 +55,96 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>> {
|
||||
// MEMO NODES
|
||||
// ==========
|
||||
];
|
||||
// The transform's value-typed rows, served by `transform_value` under the
|
||||
// leveled transform's identifier.
|
||||
node_types.extend(
|
||||
graphene_std::transform_nodes::transform_nodes::transform_value_entries()
|
||||
.into_iter()
|
||||
.map(|entry| (graphene_std::transform_nodes::transform_nodes::transform::IDENTIFIER.clone(), entry)),
|
||||
);
|
||||
// The graphic-lane fill and stroke rows, served under their identifiers.
|
||||
node_types.extend(
|
||||
graphene_std::vector::fill_graphic_leveled_entries()
|
||||
.into_iter()
|
||||
.map(|entry| (graphene_std::vector::fill::IDENTIFIER.clone(), entry)),
|
||||
);
|
||||
node_types.extend(
|
||||
graphene_std::vector::stroke_graphic_leveled_entries()
|
||||
.into_iter()
|
||||
.map(|entry| (graphene_std::vector::stroke::IDENTIFIER.clone(), entry)),
|
||||
);
|
||||
// The boolean operation's plain vector rows, served under its identifier.
|
||||
node_types.extend(
|
||||
graphene_std::path_bool_nodes::boolean_operation_vector_entries()
|
||||
.into_iter()
|
||||
.map(|entry| (graphene_std::path_bool_nodes::boolean_operation::IDENTIFIER.clone(), entry)),
|
||||
);
|
||||
// The path flattening's plain vector rows, served under its identifier.
|
||||
node_types.extend(
|
||||
graphene_std::vector::flatten_path_vector_entries()
|
||||
.into_iter()
|
||||
.map(|entry| (graphene_std::vector::flatten_path::IDENTIFIER.clone(), entry)),
|
||||
);
|
||||
// The solidify's plain vector rows, served under its identifier.
|
||||
node_types.extend(
|
||||
graphene_std::vector::solidify_stroke_vector_entries()
|
||||
.into_iter()
|
||||
.map(|entry| (graphene_std::vector::solidify_stroke::IDENTIFIER.clone(), entry)),
|
||||
);
|
||||
// The color assignment's graphic-lane rows, served under its identifier.
|
||||
node_types.extend(
|
||||
graphene_std::vector::assign_colors_graphic_entries()
|
||||
.into_iter()
|
||||
.map(|entry| (graphene_std::vector::assign_colors::IDENTIFIER.clone(), entry)),
|
||||
);
|
||||
// The mirror's plain vector rows, served under its identifier.
|
||||
node_types.extend(
|
||||
graphene_std::graphic::mirror_vector_entries()
|
||||
.into_iter()
|
||||
.map(|entry| (graphene_std::graphic::mirror::IDENTIFIER.clone(), entry)),
|
||||
);
|
||||
// The morph's plain vector rows, served under its identifier.
|
||||
node_types.extend(
|
||||
graphene_std::vector::morph_vector_entries()
|
||||
.into_iter()
|
||||
.map(|entry| (graphene_std::vector::morph::IDENTIFIER.clone(), entry)),
|
||||
);
|
||||
// Element-wise coercion into `Graphic` for single-typed leveled inputs,
|
||||
// served by the hidden elementwise rows.
|
||||
node_types.extend(
|
||||
graphene_std::graphic::to_graphic_element_entries()
|
||||
.into_iter()
|
||||
.map(|entry| (ProtoNodeIdentifier::new("graphene_core::ops::IntoNode<Graphic>"), entry)),
|
||||
);
|
||||
// The typed-level collapse rows of To Graphic, served under its identifier.
|
||||
node_types.extend(
|
||||
graphene_std::graphic::to_graphic_typed_entries()
|
||||
.into_iter()
|
||||
.map(|entry| (graphene_std::graphic::to_graphic::IDENTIFIER.clone(), entry)),
|
||||
);
|
||||
// The unit row of To Graphic: an unconnected content input renders as nothing.
|
||||
node_types.extend(
|
||||
graphene_std::graphic::to_graphic_unit_entries()
|
||||
.into_iter()
|
||||
.map(|entry| (graphene_std::graphic::to_graphic::IDENTIFIER.clone(), entry)),
|
||||
);
|
||||
// The transitional level bridge: a leveled wire materializes into the legacy
|
||||
// list an unconverted consumer expects. The rows are keyed under the legacy
|
||||
// convert identifiers and die with the last legacy consumer.
|
||||
node_types.extend(
|
||||
graphene_std::graphic::level_to_list_entries()
|
||||
.into_iter()
|
||||
.zip([
|
||||
"List<Graphic>",
|
||||
"List<Vector>",
|
||||
"List<Raster<CPU>>",
|
||||
"List<Raster<GPU>>",
|
||||
"List<Color>",
|
||||
"List<GradientStops>",
|
||||
"List<String>",
|
||||
])
|
||||
.map(|(entry, target)| (ProtoNodeIdentifier::with_owned_string(format!("graphene_core::ops::ConvertNode<{target}>")), entry)),
|
||||
);
|
||||
// =============
|
||||
// CONVERT NODES
|
||||
// =============
|
||||
@@ -136,7 +171,6 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>> {
|
||||
.flatten(),
|
||||
);
|
||||
|
||||
|
||||
let mut map: HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>> = HashMap::new();
|
||||
let insert = |map: &mut HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>>, id: ProtoNodeIdentifier, entry: RegistryEntry| {
|
||||
let rows = map.entry(id).or_default();
|
||||
@@ -179,7 +213,7 @@ mod node_registry_macros {
|
||||
(
|
||||
ProtoNodeIdentifier::new(concat!["graphene_core::ops::IntoNode<", stringify!($to), ">"]),
|
||||
RegistryEntry {
|
||||
layout_meta: None,
|
||||
layout_meta: Some(core_types::record::LayoutMeta::retype(core_types::record::element_write::<$to>())),
|
||||
io: NodeIOTypes::new(
|
||||
concrete!(Context),
|
||||
core_types::registry::record_type::<$to>(),
|
||||
@@ -191,9 +225,7 @@ mod node_registry_macros {
|
||||
}
|
||||
let mut inputs = inputs.into_iter();
|
||||
let handle = inputs.next().unwrap();
|
||||
let Some(layout) = handle.layout().cloned() else {
|
||||
return Err(ConstructionError::MissingLayout);
|
||||
};
|
||||
let layout = handle.layout().clone();
|
||||
let node = graphene_std::ops::IntoNode::<$to, _, $from>::new(handle.downcast_record::<$from>()?, &layout);
|
||||
Ok(EdgeHandle::new_record::<$to>(std::sync::Arc::new(node) as std::sync::Arc<core_types::registry::ErasedRecordNode>))
|
||||
},
|
||||
@@ -247,7 +279,7 @@ mod node_registry_macros {
|
||||
(
|
||||
ProtoNodeIdentifier::new(concat!["graphene_core::ops::ConvertNode<", stringify!($to), ">"]),
|
||||
RegistryEntry {
|
||||
layout_meta: None,
|
||||
layout_meta: Some(core_types::record::LayoutMeta::retype(core_types::record::element_write::<$to>())),
|
||||
io: NodeIOTypes::new(
|
||||
concrete!(Context),
|
||||
core_types::registry::record_type::<$to>(),
|
||||
@@ -265,10 +297,8 @@ mod node_registry_macros {
|
||||
let mut inputs = inputs.into_iter();
|
||||
let mut claim = || {
|
||||
let handle = inputs.next().unwrap();
|
||||
let Some(layout) = handle.layout().cloned() else {
|
||||
return Err(ConstructionError::MissingLayout);
|
||||
};
|
||||
Ok((handle, layout))
|
||||
let layout = handle.layout().clone();
|
||||
Ok::<_, ConstructionError>((handle, layout))
|
||||
};
|
||||
let (value, value_layout) = claim()?;
|
||||
let (converter, converter_layout) = claim()?;
|
||||
@@ -293,7 +323,7 @@ mod node_registry_macros {
|
||||
(
|
||||
ProtoNodeIdentifier::new(concat!["graphene_core::ops::ConvertNode<", stringify!($to), ">"]),
|
||||
RegistryEntry {
|
||||
layout_meta: None,
|
||||
layout_meta: Some(core_types::record::LayoutMeta::retype(core_types::record::element_write::<$to>())),
|
||||
io: NodeIOTypes::new(
|
||||
concrete!(Context),
|
||||
core_types::registry::record_type::<$to>(),
|
||||
@@ -305,13 +335,9 @@ mod node_registry_macros {
|
||||
}
|
||||
let mut inputs = inputs.into_iter();
|
||||
let value = inputs.next().unwrap();
|
||||
let Some(value_layout) = value.layout().cloned() else {
|
||||
return Err(ConstructionError::MissingLayout);
|
||||
};
|
||||
let value_layout = value.layout().clone();
|
||||
let converter = inputs.next().unwrap();
|
||||
let Some(converter_layout) = converter.layout().cloned() else {
|
||||
return Err(ConstructionError::MissingLayout);
|
||||
};
|
||||
let converter_layout = converter.layout().clone();
|
||||
let node = graphene_std::ops::ConvertNode::<$to, _, _, $from, $convert>::new(
|
||||
value.downcast_record::<$from>()?,
|
||||
converter.downcast_record::<$convert>()?,
|
||||
@@ -325,7 +351,6 @@ mod node_registry_macros {
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
pub(crate) use convert_node;
|
||||
pub(crate) use into_node;
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
|
||||
DocumentNode {
|
||||
call_argument: concrete!(Context),
|
||||
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::new(ContextFeatures::VARARGS, ContextFeatures::INDEX),
|
||||
..Default::default()
|
||||
},
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
use std::cell::UnsafeCell;
|
||||
use std::collections::HashMap;
|
||||
use std::marker::PhantomData;
|
||||
use std::mem::MaybeUninit;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
|
||||
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.
|
||||
@@ -18,6 +19,18 @@ pub struct Arena {
|
||||
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 and the moved size, so a
|
||||
/// payload two records share is moved once and a mistyped sharer is
|
||||
/// refused. Cleared by [`Arena::reset`], so a forwarding holds for one
|
||||
/// generation.
|
||||
forwarded: Mutex<HashMap<usize, (usize, usize)>>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Arena {
|
||||
@@ -28,7 +41,28 @@ impl std::fmt::Debug for Arena {
|
||||
|
||||
struct DropEntry {
|
||||
offset: usize,
|
||||
/// The parked payload's own size, so [`Arena::move_park`] refuses a
|
||||
/// reference into a park of another type that shares the offset.
|
||||
size: usize,
|
||||
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.
|
||||
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
|
||||
@@ -81,6 +115,9 @@ impl Arena {
|
||||
offset: AtomicUsize::new(0),
|
||||
buf,
|
||||
drops: Mutex::new(Vec::new()),
|
||||
exhausted: AtomicBool::new(false),
|
||||
retained_heap: AtomicUsize::new(0),
|
||||
forwarded: Mutex::new(HashMap::new()),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -93,13 +130,44 @@ impl Arena {
|
||||
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
|
||||
}
|
||||
@@ -108,7 +176,8 @@ impl Arena {
|
||||
debug_assert!(align.is_power_of_two());
|
||||
let base = self.base() as usize;
|
||||
let mut start = 0;
|
||||
self.offset
|
||||
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.
|
||||
@@ -117,11 +186,34 @@ impl Arena {
|
||||
let end = start.checked_add(size)?;
|
||||
(end <= self.buf.len()).then_some(end)
|
||||
})
|
||||
.ok()?;
|
||||
.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 % 20000 == 0 {
|
||||
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>)> {
|
||||
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.
|
||||
@@ -133,12 +225,75 @@ impl Arena {
|
||||
unsafe fn glue<T>(p: *mut u8) {
|
||||
unsafe { p.cast::<T>().drop_in_place() }
|
||||
}
|
||||
self.drops.lock().unwrap().push(DropEntry { offset, drop_fn: glue::<T> });
|
||||
self.drops.lock().unwrap().push(DropEntry { offset, size: size_of::<T>(), 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.
|
||||
///
|
||||
/// `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.
|
||||
///
|
||||
/// `None` where `src` is not this arena's park of `T`'s own size, where
|
||||
/// `T` 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 a park of this arena at that address
|
||||
/// and size must be the `T` itself, not another type's park the address
|
||||
/// coincides with. `T` must own all of its content: the moved header may
|
||||
/// reference no storage of this arena.
|
||||
pub unsafe fn move_park<T: Send + Sync>(&self, src: *const u8, dst: &Arena, retained: usize) -> Option<*const T> {
|
||||
(size_of::<T>() != 0).then_some(())?;
|
||||
let offset = (src as usize).checked_sub(self.base() as usize)?;
|
||||
(offset < self.buf.len()).then_some(())?;
|
||||
let mut forwarded = self.forwarded.lock().unwrap();
|
||||
if let Some(&(moved, size)) = forwarded.get(&offset) {
|
||||
(size == size_of::<T>()).then_some(())?;
|
||||
return Some(moved as *const T);
|
||||
}
|
||||
let mut entries = self.drops.lock().unwrap();
|
||||
let entry = entry_at(&entries, offset)?;
|
||||
(entries[entry].size == size_of::<T>()).then_some(())?;
|
||||
let slot = dst.alloc_scratch::<T>(1)?;
|
||||
let target = slot.as_mut_ptr().cast::<T>();
|
||||
// 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>(), target, 1) };
|
||||
let parked = std::mem::replace(&mut entries[entry].retained, 0);
|
||||
entries[entry].drop_fn = inert;
|
||||
drop(entries);
|
||||
unsafe fn glue<T>(p: *mut u8) {
|
||||
unsafe { p.cast::<T>().drop_in_place() }
|
||||
}
|
||||
dst.drops.lock().unwrap().push(DropEntry {
|
||||
offset: target as usize - dst.base() as usize,
|
||||
size: size_of::<T>(),
|
||||
drop_fn: glue::<T>,
|
||||
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, size_of::<T>()));
|
||||
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) {
|
||||
@@ -160,18 +315,37 @@ impl Arena {
|
||||
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.
|
||||
pub fn handle_at(&self, ptr: *const u8) -> Option<ArenaWeak<u8>> {
|
||||
let offset = (ptr as usize).checked_sub(self.base() as usize)?;
|
||||
(offset < self.buf.len()).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() {
|
||||
// SAFETY: registered at alloc time; insert-only means the region was
|
||||
// never overwritten within this generation.
|
||||
unsafe { (entry.drop_fn)(base.add(entry.offset)) }
|
||||
// Decremented as each payload's heap is freed, so an unwinding reset
|
||||
// leaves the counter matching what is still parked.
|
||||
let retained = self.retained_heap.get_mut();
|
||||
*retained = retained.saturating_sub(entry.retained);
|
||||
}
|
||||
*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
|
||||
@@ -406,6 +580,150 @@ mod tests {
|
||||
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(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);
|
||||
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(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 {
|
||||
_first: String,
|
||||
_tail: u64,
|
||||
}
|
||||
let mut transient = Arena::new(1024).unwrap();
|
||||
let mut persistent = Arena::new(1024).unwrap();
|
||||
|
||||
let (parked, _) = transient.alloc(Owner { _first: String::from("a first member"), _tail: 0 }).unwrap();
|
||||
let src = std::ptr::from_ref(parked).cast::<u8>();
|
||||
assert!(unsafe { transient.move_park::<String>(src, &persistent, 0) }.is_none(), "a park of another size is refused");
|
||||
unsafe { transient.move_park::<Owner>(src, &persistent, 0) }.unwrap();
|
||||
assert!(unsafe { transient.move_park::<String>(src, &persistent, 0) }.is_none(), "the forwarding refuses the same mistype");
|
||||
|
||||
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);
|
||||
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(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);
|
||||
|
||||
@@ -26,7 +26,9 @@ pub trait Attribute: 'static {
|
||||
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.
|
||||
type Value<'e>: Copy + Default + std::fmt::Debug;
|
||||
/// The value outlives that evaluation, so its `'static` instantiation is
|
||||
/// the one the census registers and layouts stamp their type id from.
|
||||
type Value<'e>: Copy + Default + std::fmt::Debug + '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
|
||||
@@ -35,6 +37,11 @@ pub trait Attribute: 'static {
|
||||
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>;
|
||||
@@ -100,6 +107,12 @@ pub struct AttributeInfo {
|
||||
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.
|
||||
pub write_stored: unsafe fn(&dyn AnyAttributeValue, *mut u8, &crate::arena::Arena) -> Option<()>,
|
||||
}
|
||||
|
||||
fn write_default_bytes<A: Attribute>(out: &mut [u8]) {
|
||||
@@ -108,6 +121,29 @@ fn write_default_bytes<A: Attribute>(out: &mut [u8]) {
|
||||
unsafe { std::ptr::copy_nonoverlapping((&raw const value).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)
|
||||
}
|
||||
|
||||
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 {
|
||||
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()));
|
||||
|
||||
@@ -117,7 +153,7 @@ pub static ATTRIBUTE_REGISTRY: LazyLock<Mutex<HashMap<&'static str, AttributeInf
|
||||
/// claiming the name at a different value type panics.
|
||||
pub fn register<A: Attribute>()
|
||||
where
|
||||
A::Value<'static>: AnyAttributeValue,
|
||||
A::Value<'static>: AnyAttributeValue + graphene_hash::CacheHash + PartialEq,
|
||||
{
|
||||
let info = AttributeInfo {
|
||||
name: A::NAME,
|
||||
@@ -127,6 +163,8 @@ where
|
||||
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) => {
|
||||
@@ -164,10 +202,51 @@ pub fn default_value(name: &str) -> Option<Box<dyn AnyAttributeValue>> {
|
||||
///
|
||||
/// 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.
|
||||
/// 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;
|
||||
|
||||
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;
|
||||
@@ -181,6 +260,10 @@ macro_rules! attribute {
|
||||
}
|
||||
)?
|
||||
|
||||
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())
|
||||
}
|
||||
@@ -212,6 +295,10 @@ macro_rules! attribute {
|
||||
}
|
||||
)?
|
||||
|
||||
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() })
|
||||
}
|
||||
@@ -249,10 +336,42 @@ attribute! {
|
||||
pub OpacityFill("opacity_fill"): f64 = 1.;
|
||||
/// Whether an item inherits the alpha of the content beneath it (clipping mask).
|
||||
pub ClippingMask("clipping_mask"): bool;
|
||||
/// Artboard's top-left corner in document coordinates.
|
||||
pub Location("location"): DVec2;
|
||||
/// 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. Stored as an affine to allow non-axis-aligned frames in the future.
|
||||
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)]
|
||||
@@ -264,6 +383,8 @@ mod tests {
|
||||
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());
|
||||
}
|
||||
|
||||
@@ -271,6 +392,9 @@ mod tests {
|
||||
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]
|
||||
@@ -301,6 +425,10 @@ mod tests {
|
||||
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() })
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use crate::Color;
|
||||
use crate::lane::{LaneColumn, LaneSource};
|
||||
use glam::{DAffine2, DVec2};
|
||||
|
||||
#[derive(Clone, Copy, Default, Debug, PartialEq)]
|
||||
@@ -51,3 +52,62 @@ impl BoundingBox for Color {
|
||||
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,
|
||||
}
|
||||
}
|
||||
@@ -34,12 +34,39 @@ pub trait ExtractPointerPosition {
|
||||
pub trait ExtractPosition {
|
||||
fn try_position(&self) -> Option<impl Iterator<Item = DVec2>>;
|
||||
}
|
||||
pub trait ExtractIndex {
|
||||
/// The level sentinel for a reader whose level is not known at compile time,
|
||||
/// so every level of the index chain must survive nullification.
|
||||
pub const ALL_INDEX_LEVELS: u8 = u8::MAX;
|
||||
|
||||
pub trait ExtractIndices {
|
||||
fn try_index(&self) -> Option<impl Iterator<Item = usize>>;
|
||||
fn innermost_index(&self) -> u64 {
|
||||
self.try_index().and_then(|mut indices| indices.next()).unwrap_or(0) as u64
|
||||
}
|
||||
|
||||
/// The decompose half of decompose-and-promote: splits the flat innermost
|
||||
/// index over the content's inner extent into the pushed level's copy and
|
||||
/// the lane within it. Rectangular domains; an empty inner extent maps
|
||||
/// everything to copy 0.
|
||||
fn split_innermost(&self, inner: u64) -> (u64, u64) {
|
||||
let flat = self.innermost_index();
|
||||
match inner {
|
||||
0 => (0, 0),
|
||||
inner => (flat / inner, flat % inner),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `LEVEL` is the index-chain level a node reads, counted outwards from the
|
||||
/// innermost; only declared levels survive in the cache key. Repeat the bound
|
||||
/// to declare several, spelling the level at each `index` call.
|
||||
pub trait ExtractIndex<const LEVEL: u8 = 0>: ExtractIndices {
|
||||
fn index(&self) -> u64 {
|
||||
self.try_index().and_then(|mut levels| levels.nth(LEVEL as usize)).unwrap_or(0) as u64
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: ExtractIndices, const LEVEL: u8> ExtractIndex<LEVEL> for T {}
|
||||
pub trait ExtractVarArgs {
|
||||
// TODO: Consider returning a slice or something like that
|
||||
|
||||
@@ -142,7 +169,8 @@ pub enum ContextFeature {
|
||||
ExtractAnimationTime,
|
||||
ExtractPointerPosition,
|
||||
ExtractPosition,
|
||||
ExtractIndex,
|
||||
/// Carries the declared level, counted outwards from the innermost.
|
||||
ExtractIndex(u8),
|
||||
ExtractVarArgs,
|
||||
InjectFootprint,
|
||||
InjectRealTime,
|
||||
@@ -175,6 +203,118 @@ impl graphene_hash::CacheHash for ContextFeatures {
|
||||
}
|
||||
}
|
||||
|
||||
/// Which levels of the index chain survive nullification, as a mask over levels
|
||||
/// counted outwards from the innermost. Levels past 31 collapse to "all".
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, dyn_any::DynAny)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct IndexLevels(u32);
|
||||
|
||||
impl IndexLevels {
|
||||
pub const fn empty() -> Self {
|
||||
Self(0)
|
||||
}
|
||||
|
||||
pub const fn all() -> Self {
|
||||
Self(u32::MAX)
|
||||
}
|
||||
|
||||
/// The innermost level alone, which is what every reader but `read_index`
|
||||
/// addresses.
|
||||
pub const fn innermost() -> Self {
|
||||
Self(1)
|
||||
}
|
||||
|
||||
pub const fn is_empty(self) -> bool {
|
||||
self.0 == 0
|
||||
}
|
||||
|
||||
pub fn with_level(self, level: u8) -> Self {
|
||||
match level {
|
||||
ALL_INDEX_LEVELS => Self::all(),
|
||||
level if (level as u32) < u32::BITS => Self(self.0 | 1 << level),
|
||||
_ => Self::all(),
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn contains(self, other: Self) -> bool {
|
||||
self.0 & other.0 == other.0
|
||||
}
|
||||
|
||||
pub const fn is_all(self) -> bool {
|
||||
self.0 == u32::MAX
|
||||
}
|
||||
|
||||
/// The same requirement seen from outside an edge whose innermost `supplied`
|
||||
/// levels the reading node drives itself, and whose chain sits `delta`
|
||||
/// deeper than that node's. A supplied level leaves no requirement behind;
|
||||
/// the rest renumber by the depth difference. An all-levels mask stays
|
||||
/// saturated, since its reader's level is not known at compile time.
|
||||
pub const fn lifted(self, supplied: u8, delta: u8) -> Self {
|
||||
match self.0 {
|
||||
u32::MAX => self,
|
||||
mask => {
|
||||
let kept = match supplied as u32 >= u32::BITS {
|
||||
true => 0,
|
||||
false => mask & !((1 << supplied) - 1),
|
||||
};
|
||||
match delta as u32 >= u32::BITS {
|
||||
true => Self(0),
|
||||
false => Self(kept >> delta),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Levels at or past `u32::BITS` are only readable through the all-levels
|
||||
/// sentinel, so they count as declared whenever the mask is saturated.
|
||||
pub const fn contains_level(self, level: usize) -> bool {
|
||||
match level < u32::BITS as usize {
|
||||
true => self.0 & 1 << level != 0,
|
||||
false => self.is_all(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Zeroes every index level outside `levels` and drops zeroed levels off the
|
||||
/// outer end, so equal surviving indices key a memo identically whatever depth
|
||||
/// they arrived with. Interior zeroes keep their links, since outer levels are
|
||||
/// addressed by position. Returns `None` only when the arena is exhausted.
|
||||
pub fn nullify_index_levels<'s>(head: IndexLink<'s>, levels: IndexLevels, arena: &'s crate::arena::Arena) -> Option<IndexLink<'s>> {
|
||||
if levels.is_all() {
|
||||
return Some(head);
|
||||
}
|
||||
let indices: Vec<u64> = core::iter::successors(Some(&head), |link| link.outer).map(|link| link.index).collect();
|
||||
let masked = |level: usize| match levels.contains_level(level) {
|
||||
true => indices[level],
|
||||
false => 0,
|
||||
};
|
||||
// A reader past the chain's end reads 0, so trailing zeroed levels carry
|
||||
// no information.
|
||||
let depth = (0..indices.len()).rev().find(|&level| masked(level) != 0).map_or(1, |level| level + 1);
|
||||
if depth == indices.len() && (0..depth).all(|level| levels.contains_level(level) || indices[level] == 0) {
|
||||
return Some(head);
|
||||
}
|
||||
// Built outermost inwards so each link can reference the one already placed.
|
||||
let mut outer: Option<&'s IndexLink<'s>> = None;
|
||||
for level in (1..depth).rev() {
|
||||
let link = IndexLink { index: masked(level), outer };
|
||||
outer = Some(arena.alloc(link)?.0);
|
||||
}
|
||||
Some(IndexLink { index: masked(0), outer })
|
||||
}
|
||||
|
||||
impl core::ops::BitOrAssign for IndexLevels {
|
||||
fn bitor_assign(&mut self, other: Self) {
|
||||
self.0 |= other.0;
|
||||
}
|
||||
}
|
||||
|
||||
impl graphene_hash::CacheHash for IndexLevels {
|
||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
core::hash::Hash::hash(self, state);
|
||||
}
|
||||
}
|
||||
|
||||
impl ContextFeatures {
|
||||
pub fn name(&self) -> &'static str {
|
||||
match *self {
|
||||
@@ -199,13 +339,37 @@ impl ContextFeatures {
|
||||
pub struct ContextDependencies {
|
||||
pub extract: ContextFeatures,
|
||||
pub inject: ContextFeatures,
|
||||
/// Which index levels the node reads, non-empty exactly when `extract` keeps
|
||||
/// `INDEX`. Follows the node's signature, so it resolves from the registry
|
||||
/// instead of persisting.
|
||||
#[cfg_attr(feature = "serde", serde(skip))]
|
||||
pub index_levels: IndexLevels,
|
||||
/// Index levels pushed per input, in input order; a missing entry is 0.
|
||||
/// Resolves from the registry alongside [`Self::index_levels`].
|
||||
#[cfg_attr(feature = "serde", serde(skip))]
|
||||
pub pushed_levels: Vec<u8>,
|
||||
#[cfg_attr(feature = "serde", serde(default, deserialize_with = "deserialize_sorted_sources"))]
|
||||
sources: Vec<SourceId>,
|
||||
}
|
||||
|
||||
impl ContextDependencies {
|
||||
pub fn new(extract: ContextFeatures, inject: ContextFeatures) -> Self {
|
||||
Self { extract, inject, sources: Vec::new() }
|
||||
let index_levels = match extract.contains(ContextFeatures::INDEX) {
|
||||
true => IndexLevels::innermost(),
|
||||
false => IndexLevels::empty(),
|
||||
};
|
||||
Self {
|
||||
extract,
|
||||
inject,
|
||||
index_levels,
|
||||
pushed_levels: Vec::new(),
|
||||
sources: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_index_levels(mut self, index_levels: IndexLevels) -> Self {
|
||||
self.index_levels = index_levels;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn sources(&self) -> &[SourceId] {
|
||||
@@ -227,6 +391,9 @@ impl ContextDependencies {
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct ContextModification {
|
||||
pub features: ContextFeatures,
|
||||
/// Which index levels survive; consulted only when `features` keeps `INDEX`.
|
||||
#[cfg_attr(feature = "serde", serde(default = "IndexLevels::innermost"))]
|
||||
pub index_levels: IndexLevels,
|
||||
#[cfg_attr(feature = "serde", serde(deserialize_with = "deserialize_sorted_sources"))]
|
||||
sources: Vec<SourceId>,
|
||||
}
|
||||
@@ -241,10 +408,23 @@ impl ContextModification {
|
||||
}
|
||||
|
||||
pub fn from_sources(features: ContextFeatures, sources: &[SourceId]) -> Self {
|
||||
let mut modification = Self { features, sources: Vec::new() };
|
||||
let index_levels = match features.contains(ContextFeatures::INDEX) {
|
||||
true => IndexLevels::all(),
|
||||
false => IndexLevels::empty(),
|
||||
};
|
||||
let mut modification = Self {
|
||||
features,
|
||||
index_levels,
|
||||
sources: Vec::new(),
|
||||
};
|
||||
modification.add_sources(sources);
|
||||
modification
|
||||
}
|
||||
|
||||
pub fn with_index_levels(mut self, index_levels: IndexLevels) -> Self {
|
||||
self.index_levels = index_levels;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Restores the sorted-and-deduplicated invariant that `contains` and `difference`
|
||||
@@ -261,6 +441,7 @@ fn deserialize_sorted_sources<'de, D: serde::Deserializer<'de>>(deserializer: D)
|
||||
impl core::ops::BitOrAssign<&ContextModification> for ContextModification {
|
||||
fn bitor_assign(&mut self, other: &Self) {
|
||||
self.features |= other.features;
|
||||
self.index_levels |= other.index_levels;
|
||||
merge_sorted_sources(&mut self.sources, &other.sources);
|
||||
}
|
||||
}
|
||||
@@ -286,13 +467,14 @@ impl core::ops::BitAndAssign<ContextFeatures> for ContextModification {
|
||||
impl ContextModification {
|
||||
pub fn contains(&self, other: &Self) -> bool {
|
||||
debug_assert!(self.sources.is_sorted() && other.sources.is_sorted());
|
||||
self.features.contains(other.features) && other.sources.iter().all(|id| self.sources.binary_search(id).is_ok())
|
||||
self.features.contains(other.features) && self.index_levels.contains(other.index_levels) && other.sources.iter().all(|id| self.sources.binary_search(id).is_ok())
|
||||
}
|
||||
|
||||
pub fn difference(&self, other: &Self) -> Self {
|
||||
debug_assert!(other.sources.is_sorted());
|
||||
Self {
|
||||
features: self.features.difference(other.features),
|
||||
index_levels: self.index_levels,
|
||||
sources: self.sources.iter().copied().filter(|id| other.sources.binary_search(id).is_err()).collect(),
|
||||
}
|
||||
}
|
||||
@@ -314,14 +496,18 @@ impl From<&[ContextFeature]> for ContextDependencies {
|
||||
fn from(features: &[ContextFeature]) -> Self {
|
||||
let mut extract = ContextFeatures::empty();
|
||||
let mut inject = ContextFeatures::empty();
|
||||
let mut index_levels = IndexLevels::empty();
|
||||
for feature in features {
|
||||
if let ContextFeature::ExtractIndex(level) = feature {
|
||||
index_levels = index_levels.with_level(*level);
|
||||
}
|
||||
extract |= match feature {
|
||||
ContextFeature::ExtractFootprint => ContextFeatures::FOOTPRINT,
|
||||
ContextFeature::ExtractRealTime => ContextFeatures::REAL_TIME,
|
||||
ContextFeature::ExtractAnimationTime => ContextFeatures::ANIMATION_TIME,
|
||||
ContextFeature::ExtractPointerPosition => ContextFeatures::POINTER_POSITION,
|
||||
ContextFeature::ExtractPosition => ContextFeatures::POSITION,
|
||||
ContextFeature::ExtractIndex => ContextFeatures::INDEX,
|
||||
ContextFeature::ExtractIndex(_) => ContextFeatures::INDEX,
|
||||
ContextFeature::ExtractVarArgs => ContextFeatures::VARARGS,
|
||||
_ => ContextFeatures::empty(),
|
||||
};
|
||||
@@ -336,7 +522,13 @@ impl From<&[ContextFeature]> for ContextDependencies {
|
||||
_ => ContextFeatures::empty(),
|
||||
};
|
||||
}
|
||||
Self { extract, inject, sources: Vec::new() }
|
||||
Self {
|
||||
extract,
|
||||
inject,
|
||||
index_levels,
|
||||
pushed_levels: Vec::new(),
|
||||
sources: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -376,7 +568,7 @@ impl<T: ExtractPosition + Sync> ExtractPosition for Option<T> {
|
||||
self.as_ref().and_then(|x| x.try_position())
|
||||
}
|
||||
}
|
||||
impl<T: ExtractIndex> ExtractIndex for Option<T> {
|
||||
impl<T: ExtractIndices> ExtractIndices for Option<T> {
|
||||
fn try_index(&self) -> Option<impl Iterator<Item = usize>> {
|
||||
self.as_ref().and_then(|x| x.try_index())
|
||||
}
|
||||
@@ -434,7 +626,7 @@ impl<T: ExtractPosition + Sync> ExtractPosition for Arc<T> {
|
||||
(**self).try_position()
|
||||
}
|
||||
}
|
||||
impl<T: ExtractIndex> ExtractIndex for Arc<T> {
|
||||
impl<T: ExtractIndices> ExtractIndices for Arc<T> {
|
||||
fn try_index(&self) -> Option<impl Iterator<Item = usize>> {
|
||||
(**self).try_index()
|
||||
}
|
||||
@@ -624,6 +816,9 @@ pub struct EvalScope<'a> {
|
||||
pointer_position: Option<DVec2>,
|
||||
generations: &'a [(SourceId, u64)],
|
||||
arena: &'a Arena,
|
||||
/// The region no evaluation resets, borrowed for the whole evaluation so
|
||||
/// the flush's `&mut` cannot land while a value promoted into it is live.
|
||||
persistent: &'a Arena,
|
||||
hash: u64,
|
||||
}
|
||||
|
||||
@@ -635,12 +830,19 @@ impl<'a> EvalScope<'a> {
|
||||
pointer_position,
|
||||
generations,
|
||||
arena,
|
||||
persistent: arena,
|
||||
hash: 0,
|
||||
};
|
||||
scope.hash = scope.compute_hash(|_| true);
|
||||
scope
|
||||
}
|
||||
|
||||
/// Names the region memo levels are promoted into. A scope that names none
|
||||
/// promotes into its own arena, so its memos live exactly one generation.
|
||||
pub fn with_persistent(&self, persistent: &'a Arena) -> EvalScope<'a> {
|
||||
EvalScope { persistent, ..*self }
|
||||
}
|
||||
|
||||
pub fn with_real_time(&self, real_time: Option<f64>) -> EvalScope<'a> {
|
||||
let mut scope = EvalScope { real_time, ..*self };
|
||||
scope.hash = scope.compute_hash(|_| true);
|
||||
@@ -700,6 +902,10 @@ impl<'a> EvalScope<'a> {
|
||||
pub fn arena(&self) -> &'a Arena {
|
||||
self.arena
|
||||
}
|
||||
|
||||
pub fn persistent(&self) -> &'a Arena {
|
||||
self.persistent
|
||||
}
|
||||
}
|
||||
|
||||
pub trait ExtractArena {
|
||||
@@ -707,6 +913,19 @@ pub trait ExtractArena {
|
||||
fn arena(&self) -> Self::ArenaRef;
|
||||
}
|
||||
|
||||
/// The arena borrowed at the caller's scope, for kernels whose node shape
|
||||
/// cannot carry the evaluation lifetime (a flipped value node takes no fn
|
||||
/// lifetime).
|
||||
pub trait BorrowArena {
|
||||
fn borrow_arena(&self) -> &crate::arena::Arena;
|
||||
}
|
||||
|
||||
impl BorrowArena for ContextImpl<'_> {
|
||||
fn borrow_arena(&self) -> &crate::arena::Arena {
|
||||
ExtractArena::arena(self)
|
||||
}
|
||||
}
|
||||
|
||||
pub trait CtxFamily {
|
||||
type Ctx<'s>: Ctx + DeriveCtx<Family = Self>;
|
||||
}
|
||||
@@ -721,11 +940,13 @@ pub trait DeriveCtx {
|
||||
fn position_head(&self) -> Option<&PositionLink<'_>>;
|
||||
fn varargs_head(&self) -> Option<&VarArgLink<'_>>;
|
||||
fn promoted<'s>(&'s self, spilled_head: &'s IndexLink<'s>, inner_index: u64) -> Derived<'s, Self>;
|
||||
fn push_level<'s>(&'s self, frame: &'s mut IndexLink<'s>, copy: u64, inner: u64) -> Derived<'s, Self>;
|
||||
fn replaced<'s>(&'s self, inner_index: u64) -> Derived<'s, Self>;
|
||||
fn with_footprint<'s>(&'s self, footprint: &'s Footprint) -> Derived<'s, Self>;
|
||||
fn with_varargs<'s>(&'s self, varargs: &'s VarArgLink<'s>) -> Derived<'s, Self>;
|
||||
fn with_position<'s>(&'s self, position: &'s PositionLink<'s>) -> Derived<'s, Self>;
|
||||
fn with_scope<'s>(&'s self, scope: &'s EvalScope<'s>) -> Derived<'s, Self>;
|
||||
fn nullified<'s>(&'s self, keep: ContextFeatures, scope: &'s EvalScope<'s>) -> Derived<'s, Self>;
|
||||
fn nullified<'s>(&'s self, keep: ContextFeatures, index: IndexLink<'s>, scope: &'s EvalScope<'s>) -> Derived<'s, Self>;
|
||||
|
||||
fn modify_footprint(&self, modify: impl FnOnce(&mut Footprint)) -> ModifiedFootprint<'_, Self>
|
||||
where
|
||||
@@ -810,6 +1031,54 @@ impl CtxSnapshot {
|
||||
pub fn generations(&self) -> &[(SourceId, u64)] {
|
||||
&self.generations
|
||||
}
|
||||
|
||||
/// Rebuilds the captured context against `scope`, allocating the borrowed
|
||||
/// chains in the scope's arena; `None` reports arena exhaustion. The
|
||||
/// scope carries the serving generation, so the recreated evaluation reads
|
||||
/// current source data under the captured addressing.
|
||||
pub fn rehydrate<'e>(&'e self, scope: &'e EvalScope<'e>) -> Option<ContextImpl<'e>> {
|
||||
let arena = scope.arena();
|
||||
let mut ctx = ContextImpl::root(scope);
|
||||
if let Some(footprint) = self.footprint {
|
||||
let (footprint, _) = arena.alloc(footprint)?;
|
||||
ctx = ctx.with_footprint(footprint);
|
||||
}
|
||||
if let Some(levels) = &self.index {
|
||||
let mut outer = None;
|
||||
for &index in levels.iter().skip(1).rev() {
|
||||
let (link, _) = arena.alloc(IndexLink { index: index as u64, outer })?;
|
||||
outer = Some(link);
|
||||
}
|
||||
ctx.index = IndexLink {
|
||||
index: levels.first().copied().unwrap_or_default() as u64,
|
||||
outer,
|
||||
};
|
||||
}
|
||||
if let Some(positions) = &self.positions {
|
||||
let mut head = None;
|
||||
for &position in positions.iter().rev() {
|
||||
let (link, _) = arena.alloc(PositionLink { position, outer: head })?;
|
||||
head = Some(link);
|
||||
}
|
||||
if let Some(head) = head {
|
||||
ctx = ctx.with_position(head);
|
||||
}
|
||||
}
|
||||
let mut varargs = None;
|
||||
for args in self.varargs.iter().rev() {
|
||||
let slots: Vec<DynSlot<'e>> = args.iter().map(|slot| &**slot as DynSlot<'e>).collect();
|
||||
let slots = arena.alloc_slice_copy(&slots)?;
|
||||
let (link, _) = arena.alloc(VarArgLink {
|
||||
args: VarArgSlots::Slice(slots),
|
||||
outer: varargs,
|
||||
})?;
|
||||
varargs = Some(link);
|
||||
}
|
||||
if let Some(varargs) = varargs {
|
||||
ctx = ctx.with_varargs(varargs);
|
||||
}
|
||||
Some(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
impl ExtractFootprint for CtxSnapshot {
|
||||
@@ -836,7 +1105,7 @@ impl ExtractPointerPosition for CtxSnapshot {
|
||||
}
|
||||
}
|
||||
|
||||
impl ExtractIndex for CtxSnapshot {
|
||||
impl ExtractIndices for CtxSnapshot {
|
||||
fn try_index(&self) -> Option<impl Iterator<Item = usize>> {
|
||||
self.index.as_ref().map(|levels| levels.iter().copied())
|
||||
}
|
||||
@@ -961,15 +1230,12 @@ impl<'a> ContextImpl<'a> {
|
||||
ContextImpl { position: Some(position), ..*self }
|
||||
}
|
||||
|
||||
pub fn nullified<'s>(&self, keep: ContextFeatures, scope: &'s EvalScope<'s>) -> ContextImpl<'s>
|
||||
pub fn nullified<'s>(&self, keep: ContextFeatures, index: IndexLink<'s>, scope: &'s EvalScope<'s>) -> ContextImpl<'s>
|
||||
where
|
||||
'a: 's,
|
||||
{
|
||||
ContextImpl {
|
||||
index: match keep.contains(ContextFeatures::INDEX) {
|
||||
true => self.index,
|
||||
false => IndexLink { index: 0, outer: None },
|
||||
},
|
||||
index,
|
||||
position: self.position.filter(|_| keep.contains(ContextFeatures::POSITION)),
|
||||
varargs: self.varargs.filter(|_| keep.contains(ContextFeatures::VARARGS)),
|
||||
footprint: self.footprint.filter(|_| keep.contains(ContextFeatures::FOOTPRINT)),
|
||||
@@ -1004,6 +1270,18 @@ impl<'a> ContextImpl<'a> {
|
||||
frame.outer = self.index.outer;
|
||||
self.promoted(frame, inner)
|
||||
}
|
||||
|
||||
/// Derives the context with the innermost index replaced and the chain
|
||||
/// above it preserved: the remap primitive for same-level extent changes.
|
||||
pub fn replaced(&self, inner_index: u64) -> ContextImpl<'a> {
|
||||
ContextImpl {
|
||||
index: IndexLink {
|
||||
index: inner_index,
|
||||
outer: self.index.outer,
|
||||
},
|
||||
..*self
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Ctx for ContextImpl<'_> {}
|
||||
@@ -1034,7 +1312,7 @@ impl ExtractPointerPosition for ContextImpl<'_> {
|
||||
self.scope.pointer_position
|
||||
}
|
||||
}
|
||||
impl ExtractIndex for ContextImpl<'_> {
|
||||
impl ExtractIndices for ContextImpl<'_> {
|
||||
fn try_index(&self) -> Option<impl Iterator<Item = usize>> {
|
||||
Some(std::iter::successors(Some(&self.index), |link| link.outer).map(|link| link.index as usize))
|
||||
}
|
||||
@@ -1111,6 +1389,14 @@ impl<'a> DeriveCtx for ContextImpl<'a> {
|
||||
ContextImpl::promoted(self, spilled_head, inner_index)
|
||||
}
|
||||
|
||||
fn push_level<'s>(&'s self, frame: &'s mut IndexLink<'s>, copy: u64, inner: u64) -> ContextImpl<'s> {
|
||||
ContextImpl::push_level(self, frame, copy, inner)
|
||||
}
|
||||
|
||||
fn replaced<'s>(&'s self, inner_index: u64) -> ContextImpl<'s> {
|
||||
ContextImpl::replaced(self, inner_index)
|
||||
}
|
||||
|
||||
fn with_footprint<'s>(&'s self, footprint: &'s Footprint) -> ContextImpl<'s> {
|
||||
ContextImpl::with_footprint(self, footprint)
|
||||
}
|
||||
@@ -1127,8 +1413,8 @@ impl<'a> DeriveCtx for ContextImpl<'a> {
|
||||
ContextImpl::with_scope(self, scope)
|
||||
}
|
||||
|
||||
fn nullified<'s>(&'s self, keep: ContextFeatures, scope: &'s EvalScope<'s>) -> ContextImpl<'s> {
|
||||
ContextImpl::nullified(self, keep, scope)
|
||||
fn nullified<'s>(&'s self, keep: ContextFeatures, index: IndexLink<'s>, scope: &'s EvalScope<'s>) -> ContextImpl<'s> {
|
||||
ContextImpl::nullified(self, keep, index, scope)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1308,6 +1594,83 @@ mod context_impl_tests {
|
||||
assert_eq!(levels, vec![11, 0]);
|
||||
}
|
||||
|
||||
fn collected(head: &IndexLink) -> Vec<u64> {
|
||||
core::iter::successors(Some(head), |link| link.outer).map(|link| link.index).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lifting_a_fold_edge_clears_the_driven_level_in_place() {
|
||||
let reads = IndexLevels::innermost().with_level(2);
|
||||
assert_eq!(reads.lifted(1, 0), IndexLevels::empty().with_level(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lifting_a_pushed_edge_renumbers_outwards() {
|
||||
let reads = IndexLevels::innermost().with_level(2);
|
||||
assert_eq!(reads.lifted(1, 1), IndexLevels::empty().with_level(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lifting_a_decomposed_edge_drops_both_driven_levels() {
|
||||
let reads = IndexLevels::innermost().with_level(1).with_level(3);
|
||||
assert_eq!(reads.lifted(2, 1), IndexLevels::empty().with_level(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lifting_leaves_a_saturated_mask_alone() {
|
||||
assert_eq!(IndexLevels::all().lifted(2, 1), IndexLevels::all());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nullify_drops_trailing_zeroed_levels() {
|
||||
let arena = Arena::new(256).unwrap();
|
||||
let outer = IndexLink { index: 9, outer: None };
|
||||
let mid = IndexLink { index: 7, outer: Some(&outer) };
|
||||
let head = IndexLink { index: 4, outer: Some(&mid) };
|
||||
let result = nullify_index_levels(head, IndexLevels::innermost(), &arena).unwrap();
|
||||
assert_eq!(collected(&result), vec![4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nullify_canonicalizes_across_arrival_depths() {
|
||||
let arena = Arena::new(256).unwrap();
|
||||
let shallow = IndexLink { index: 4, outer: None };
|
||||
let outer = IndexLink { index: 7, outer: None };
|
||||
let deep = IndexLink { index: 4, outer: Some(&outer) };
|
||||
let a = nullify_index_levels(shallow, IndexLevels::innermost(), &arena).unwrap();
|
||||
let b = nullify_index_levels(deep, IndexLevels::innermost(), &arena).unwrap();
|
||||
assert_eq!(collected(&a), collected(&b));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nullify_keeps_interior_zeroes_positional() {
|
||||
let arena = Arena::new(256).unwrap();
|
||||
let levels = IndexLevels::innermost().with_level(2);
|
||||
let outer = IndexLink { index: 9, outer: None };
|
||||
let mid = IndexLink { index: 7, outer: Some(&outer) };
|
||||
let head = IndexLink { index: 4, outer: Some(&mid) };
|
||||
let result = nullify_index_levels(head, levels, &arena).unwrap();
|
||||
assert_eq!(collected(&result), vec![4, 0, 9]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nullify_with_no_kept_levels_yields_the_root_chain() {
|
||||
let arena = Arena::new(256).unwrap();
|
||||
let outer = IndexLink { index: 9, outer: None };
|
||||
let head = IndexLink { index: 4, outer: Some(&outer) };
|
||||
let result = nullify_index_levels(head, IndexLevels::empty(), &arena).unwrap();
|
||||
assert_eq!(collected(&result), vec![0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nullify_saturated_mask_is_identity() {
|
||||
let arena = Arena::new(256).unwrap();
|
||||
let outer = IndexLink { index: 0, outer: None };
|
||||
let head = IndexLink { index: 4, outer: Some(&outer) };
|
||||
let result = nullify_index_levels(head, IndexLevels::all(), &arena).unwrap();
|
||||
assert_eq!(collected(&result), vec![4, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vararg_chain_concatenates_innermost_first() {
|
||||
let arena = Arena::new(64).unwrap();
|
||||
|
||||
@@ -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 edge 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 edge'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 edges 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 wire'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,198 +0,0 @@
|
||||
use crate::gpoll::Finality;
|
||||
use std::cell::UnsafeCell;
|
||||
use std::mem::{ManuallyDrop, MaybeUninit};
|
||||
use std::sync::atomic::{AtomicU8, AtomicU64, Ordering};
|
||||
|
||||
const SLOT_EMPTY: u8 = 0;
|
||||
const SLOT_FINAL: u8 = 1;
|
||||
const SLOT_PARTIAL: u8 = 2;
|
||||
|
||||
pub struct FrameTable<T, const CAP: usize> {
|
||||
slots: [FrameSlot<T>; CAP],
|
||||
}
|
||||
|
||||
struct FrameSlot<T> {
|
||||
key: AtomicU64,
|
||||
state: AtomicU8,
|
||||
value: UnsafeCell<MaybeUninit<T>>,
|
||||
}
|
||||
|
||||
// SAFETY: the key CAS reserves a slot for one writer, and the Release store of its
|
||||
// state publishes the value to every Acquire load in `lookup`, so concurrent access
|
||||
// is ordered. Sharing the table hands out `&T` and drops `T` on whichever thread
|
||||
// drops the table, which is what the `Send + Sync` bounds cover.
|
||||
unsafe impl<T: Send + Sync, const CAP: usize> Sync for FrameTable<T, CAP> {}
|
||||
unsafe impl<T: Send, const CAP: usize> Send for FrameTable<T, CAP> {}
|
||||
|
||||
pub enum Lookup<'t, T> {
|
||||
Hit(Finality, &'t T),
|
||||
Vacant(VacantSlot<'t, T>),
|
||||
Full,
|
||||
}
|
||||
|
||||
pub struct VacantSlot<'t, T> {
|
||||
slot: &'t FrameSlot<T>,
|
||||
}
|
||||
|
||||
impl<T, const CAP: usize> Default for FrameTable<T, CAP> {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, const CAP: usize> FrameTable<T, CAP> {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
slots: std::array::from_fn(|_| FrameSlot {
|
||||
key: AtomicU64::new(0),
|
||||
state: AtomicU8::new(SLOT_EMPTY),
|
||||
value: UnsafeCell::new(MaybeUninit::uninit()),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn lookup(&self, hash: u64) -> Lookup<'_, T> {
|
||||
// Only hash 0 is remapped, so distinct hashes stay distinct keys.
|
||||
let key = if hash == 0 { 1 } else { hash };
|
||||
for probe in 0..CAP {
|
||||
let slot = &self.slots[(key as usize).wrapping_add(probe) % CAP];
|
||||
let stored = slot.key.load(Ordering::Acquire);
|
||||
if stored == key {
|
||||
return match slot.state.load(Ordering::Acquire) {
|
||||
// SAFETY: a published state was stored with Release after the
|
||||
// value write; the Acquire load above ordered that write.
|
||||
SLOT_FINAL => Lookup::Hit(Finality::AllFinal, unsafe { (*slot.value.get()).assume_init_ref() }),
|
||||
SLOT_PARTIAL => Lookup::Hit(Finality::Partial, unsafe { (*slot.value.get()).assume_init_ref() }),
|
||||
_ => Lookup::Full,
|
||||
};
|
||||
}
|
||||
if stored == 0 && slot.key.compare_exchange(0, key, Ordering::AcqRel, Ordering::Acquire).is_ok() {
|
||||
return Lookup::Vacant(VacantSlot { slot });
|
||||
}
|
||||
}
|
||||
Lookup::Full
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, const CAP: usize> Drop for FrameTable<T, CAP> {
|
||||
fn drop(&mut self) {
|
||||
for slot in &self.slots {
|
||||
if slot.state.load(Ordering::Acquire) != SLOT_EMPTY {
|
||||
// SAFETY: a non-empty state is only ever stored after the value
|
||||
// write in `publish`.
|
||||
unsafe { (*slot.value.get()).assume_init_drop() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'t, T> VacantSlot<'t, T> {
|
||||
pub fn publish(self, value: T, finality: Finality) -> &'t T {
|
||||
let slot = ManuallyDrop::new(self).slot;
|
||||
// SAFETY: the CAS in `lookup` reserved this slot exclusively for us and
|
||||
// its state is still SLOT_EMPTY, so nobody reads the value yet.
|
||||
let lent = unsafe { &*(*slot.value.get()).write(value) };
|
||||
let state = match finality {
|
||||
Finality::AllFinal => SLOT_FINAL,
|
||||
Finality::Partial => SLOT_PARTIAL,
|
||||
};
|
||||
slot.state.store(state, Ordering::Release);
|
||||
lent
|
||||
}
|
||||
|
||||
pub fn release(self) {
|
||||
drop(self);
|
||||
}
|
||||
}
|
||||
|
||||
/// Frees the reservation, so an early return or panic between `lookup` and
|
||||
/// `publish` cannot retire the slot for the rest of the table's life.
|
||||
impl<T> Drop for VacantSlot<'_, T> {
|
||||
fn drop(&mut self) {
|
||||
self.slot.key.store(0, Ordering::Release);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::AtomicU32;
|
||||
|
||||
#[test]
|
||||
fn publish_then_hit_with_finality() {
|
||||
let table = FrameTable::<u32, 8>::new();
|
||||
let Lookup::Vacant(slot) = table.lookup(7) else {
|
||||
panic!("fresh table must be vacant");
|
||||
};
|
||||
assert_eq!(*slot.publish(41, Finality::Partial), 41);
|
||||
let Lookup::Hit(finality, value) = table.lookup(7) else {
|
||||
panic!("published key must hit");
|
||||
};
|
||||
assert_eq!((finality, *value), (Finality::Partial, 41));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn released_slot_is_vacant_again() {
|
||||
let table = FrameTable::<u32, 8>::new();
|
||||
let Lookup::Vacant(slot) = table.lookup(7) else { unreachable!() };
|
||||
slot.release();
|
||||
assert!(matches!(table.lookup(7), Lookup::Vacant(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_reservation_frees_the_slot() {
|
||||
let table = FrameTable::<u32, 8>::new();
|
||||
let Lookup::Vacant(slot) = table.lookup(7) else { unreachable!() };
|
||||
drop(slot);
|
||||
assert!(matches!(table.lookup(7), Lookup::Vacant(_)), "an abandoned reservation must not retire the slot");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neighboring_hashes_do_not_share_an_entry() {
|
||||
let table = FrameTable::<u32, 8>::new();
|
||||
let Lookup::Vacant(slot) = table.lookup(6) else { unreachable!() };
|
||||
slot.publish(600, Finality::AllFinal);
|
||||
assert!(matches!(table.lookup(7), Lookup::Vacant(_)), "an even hash must not answer for its odd neighbor");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_zero_hash_round_trips() {
|
||||
let table = FrameTable::<u32, 8>::new();
|
||||
let Lookup::Vacant(slot) = table.lookup(0) else { unreachable!() };
|
||||
slot.publish(11, Finality::AllFinal);
|
||||
let Lookup::Hit(_, value) = table.lookup(0) else {
|
||||
panic!("the remapped sentinel hash must still hit");
|
||||
};
|
||||
assert_eq!(*value, 11);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distinct_keys_probe_past_collisions_until_full() {
|
||||
let table = FrameTable::<u32, 4>::new();
|
||||
for hash in [2, 4, 6, 8] {
|
||||
let Lookup::Vacant(slot) = table.lookup(hash) else {
|
||||
panic!("hash {hash} should find a vacant slot");
|
||||
};
|
||||
slot.publish(hash as u32, Finality::AllFinal);
|
||||
}
|
||||
assert!(matches!(table.lookup(100), Lookup::Full));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_runs_glue_for_published_values_only() {
|
||||
static DROPS: AtomicU32 = AtomicU32::new(0);
|
||||
struct Probe;
|
||||
impl Drop for Probe {
|
||||
fn drop(&mut self) {
|
||||
DROPS.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
let table = FrameTable::<Probe, 8>::new();
|
||||
let Lookup::Vacant(slot) = table.lookup(1) else { unreachable!() };
|
||||
slot.publish(Probe, Finality::AllFinal);
|
||||
let Lookup::Vacant(reserved_but_unpublished) = table.lookup(2) else { unreachable!() };
|
||||
reserved_but_unpublished.release();
|
||||
drop(table);
|
||||
assert_eq!(DROPS.load(Ordering::Relaxed), 1);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,9 @@ 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 {
|
||||
@@ -29,6 +32,13 @@ impl GraphError {
|
||||
self.trace.push(input_index);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn past_end() -> Self {
|
||||
Self {
|
||||
kind: ErrorKind::PastEnd,
|
||||
trace: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
@@ -139,6 +149,10 @@ impl<T> GPoll<T> {
|
||||
trace: Vec::new(),
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn past_end() -> Self {
|
||||
GPoll::Error(Box::new(GraphError::past_end()))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
@@ -166,6 +180,8 @@ impl<T> From<Interrupt> for GPoll<T> {
|
||||
pub enum Extent {
|
||||
Free,
|
||||
Exactly(usize),
|
||||
/// A sound lower bound; the true count is discoverable only by draining.
|
||||
AtLeast(usize),
|
||||
}
|
||||
|
||||
impl Extent {
|
||||
@@ -173,9 +189,48 @@ impl 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 edge 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)]
|
||||
|
||||
@@ -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.);
|
||||
}
|
||||
}
|
||||
@@ -5,8 +5,9 @@ pub mod attribute;
|
||||
pub mod bounds;
|
||||
pub mod consts;
|
||||
pub mod context;
|
||||
pub mod frame_table;
|
||||
pub mod extent;
|
||||
pub mod gpoll;
|
||||
pub mod lane;
|
||||
pub mod list;
|
||||
pub mod math;
|
||||
pub mod memo;
|
||||
@@ -30,9 +31,8 @@ pub use dyn_any::{StaticTypeSized, WasmNotSend, WasmNotSync};
|
||||
pub use graphene_hash;
|
||||
pub use graphene_hash::CacheHash;
|
||||
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_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_TYPE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME, ATTR_OPACITY, ATTR_OPACITY_FILL,
|
||||
ATTR_SPREAD_METHOD, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM, ATTR_TYPE,
|
||||
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_LETTER_SPACING, ATTR_LETTER_TILT,
|
||||
ATTR_LINE_HEIGHT, ATTR_LOCATION, 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 no_std_types::AsU32;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::attribute::Attribute as _;
|
||||
use crate::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use crate::math::quad::Quad;
|
||||
use crate::transform::ApplyTransform;
|
||||
use dyn_any::{StaticType, StaticTypeSized};
|
||||
use glam::DAffine2;
|
||||
@@ -9,86 +9,42 @@ use std::fmt::Debug;
|
||||
// =================================================
|
||||
// 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 = "transform";
|
||||
/// Item's `BlendMode`, controlling how it composites with content beneath it.
|
||||
pub const ATTR_BLEND_MODE: &str = "blend_mode";
|
||||
/// Item's opacity multiplier (`f64`, implicit default `1.`).
|
||||
/// Composed multiplicatively through nested groups. Affects content clipped to the item.
|
||||
pub const ATTR_OPACITY: &str = "opacity";
|
||||
/// Item's fill opacity multiplier (`f64`, implicit default `1.`).
|
||||
/// Like opacity but does not affect content clipped to the item.
|
||||
pub const ATTR_OPACITY_FILL: &str = "opacity_fill";
|
||||
/// `bool` for whether an item inherits the alpha of the content beneath it (clipping mask).
|
||||
pub const ATTR_CLIPPING_MASK: &str = "clipping_mask";
|
||||
/// `List<NodeId>` path from the root network to the layer node owning this item.
|
||||
/// Used by editor tools to route clicks/selection back to the originating layer.
|
||||
pub const ATTR_EDITOR_LAYER_PATH: &str = "editor:layer_path";
|
||||
/// `List<Graphic>` snapshot of the upstream content that fed into a destructive merge
|
||||
/// (Boolean Operation, Rasterize, etc.), so the editor can still surface click targets for
|
||||
/// the original child layers after their content has been collapsed.
|
||||
pub const ATTR_EDITOR_MERGED_LAYERS: &str = "editor:merged_layers";
|
||||
/// Optional `Vector` that overrides the item's own geometry for click-target generation.
|
||||
/// Used by the 'Text' node for per-glyph bounding-box rectangles so glyphs are selectable
|
||||
/// by clicking anywhere within their bounds, not just the filled letterform.
|
||||
pub const ATTR_EDITOR_CLICK_TARGET: &str = "editor:click_target";
|
||||
/// `DAffine2` mapping 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. Stored as an affine to allow non-axis-aligned frames in the future.
|
||||
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";
|
||||
/// Gradient's `GradientSpreadMethod` (`Pad`, `Reflect`, or `Repeat`).
|
||||
pub const ATTR_SPREAD_METHOD: &str = "spread_method";
|
||||
/// Gradient's `GradientType` (`Linear` or `Radial`).
|
||||
pub const ATTR_GRADIENT_TYPE: &str = "gradient_type";
|
||||
/// Vector graphics object's filled area paint, of type List<T> where T is any graphic type.
|
||||
pub const ATTR_FILL: &str = "fill";
|
||||
/// Vector graphics object's stroke paint, of type List<T> where T is any graphic type.
|
||||
pub const ATTR_STROKE: &str = "stroke";
|
||||
/// 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";
|
||||
pub const ATTR_TRANSFORM: &str = crate::attribute::Transform::NAME;
|
||||
pub const ATTR_BLEND_MODE: &str = crate::attribute::BlendMode::NAME;
|
||||
pub const ATTR_OPACITY: &str = crate::attribute::Opacity::NAME;
|
||||
pub const ATTR_OPACITY_FILL: &str = crate::attribute::OpacityFill::NAME;
|
||||
pub const ATTR_CLIPPING_MASK: &str = crate::attribute::ClippingMask::NAME;
|
||||
pub const ATTR_EDITOR_LAYER_PATH: &str = crate::attribute::EditorLayerPath::NAME;
|
||||
pub const ATTR_EDITOR_TEXT_FRAME: &str = crate::attribute::EditorTextFrame::NAME;
|
||||
pub const ATTR_START: &str = crate::attribute::Start::NAME;
|
||||
pub const ATTR_END: &str = crate::attribute::End::NAME;
|
||||
pub const ATTR_NAME: &str = crate::attribute::Name::NAME;
|
||||
pub const ATTR_TYPE: &str = crate::attribute::Type::NAME;
|
||||
pub const ATTR_LOCATION: &str = crate::attribute::Location::NAME;
|
||||
pub const ATTR_DIMENSIONS: &str = crate::attribute::Dimensions::NAME;
|
||||
pub const ATTR_BACKGROUND: &str = crate::attribute::Background::NAME;
|
||||
pub const ATTR_CLIP: &str = crate::attribute::Clip::NAME;
|
||||
pub const ATTR_FONT_SIZE: &str = crate::attribute::FontSize::NAME;
|
||||
pub const ATTR_LINE_HEIGHT: &str = crate::attribute::LineHeight::NAME;
|
||||
pub const ATTR_LETTER_SPACING: &str = crate::attribute::LetterSpacing::NAME;
|
||||
pub const ATTR_MAX_WIDTH: &str = crate::attribute::MaxWidth::NAME;
|
||||
pub const ATTR_MAX_HEIGHT: &str = crate::attribute::MaxHeight::NAME;
|
||||
pub const ATTR_LETTER_TILT: &str = crate::attribute::LetterTilt::NAME;
|
||||
|
||||
// ===========================
|
||||
// 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>> {
|
||||
match key {
|
||||
ATTR_OPACITY | ATTR_OPACITY_FILL => Some(Box::new(1_f64)),
|
||||
_ => None,
|
||||
}
|
||||
crate::attribute::ATTRIBUTE_REGISTRY.lock().unwrap().get(key).map(|info| (info.default)())
|
||||
}
|
||||
|
||||
/// Appends `count` copies of `key`'s implicit default to `attribute` (see [`implicit_default_value`]).
|
||||
@@ -381,20 +337,6 @@ impl AttributeDyn {
|
||||
self.0.len() == 0
|
||||
}
|
||||
|
||||
/// Builds a new attribute matching `target_len` items, taking values from this attribute (wrapping if shorter, truncating if longer).
|
||||
pub fn cloned_to_length(&self, key: &str, target_len: usize) -> Box<dyn AnyAttribute> {
|
||||
let mut result = self.0.new_with_defaults(0);
|
||||
let source_len = self.0.len();
|
||||
if source_len == 0 {
|
||||
pad_with_implicit_default(key, &mut result, target_len);
|
||||
return result;
|
||||
}
|
||||
for i in 0..target_len {
|
||||
let value = self.0.clone_value(i % source_len).expect("source_len > 0");
|
||||
result.push(value);
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for AttributeDyn {
|
||||
@@ -646,6 +588,11 @@ impl ItemAttributeValues {
|
||||
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 debug-formatted string representation of the attribute value for the given key, if it exists.
|
||||
/// The `overrides` function can provide custom formatting for specific type.
|
||||
pub fn display_value(&self, key: &str, overrides: fn(&dyn std::any::Any) -> Option<String>) -> Option<String> {
|
||||
@@ -781,6 +728,11 @@ impl Attributes {
|
||||
.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.
|
||||
fn remove_attribute(&mut self, key: &str) {
|
||||
if let Some(position) = self.attributes.iter().position(|(k, _)| k == key) {
|
||||
@@ -818,13 +770,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.
|
||||
/// 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) {
|
||||
@@ -1065,14 +1010,6 @@ impl<T> List<T> {
|
||||
self.attributes.set_value(key, index, value);
|
||||
}
|
||||
|
||||
/// Replaces (or adds) an attribute from a type-erased source. The source is wrapped or truncated to match this list's item count.
|
||||
pub fn set_attribute_dyn(&mut self, key: impl Into<String>, source: AttributeDyn) {
|
||||
let key = key.into();
|
||||
self.attributes.attributes.retain(|(k, _)| k != &key);
|
||||
let new_attribute = source.cloned_to_length(&key, self.element.len());
|
||||
self.attributes.attributes.push((key, new_attribute));
|
||||
}
|
||||
|
||||
/// Sets a single type-erased attribute value at the given index, creating the attribute from the value's underlying type if it doesn't exist (padded with defaults to match the list's length).
|
||||
/// Falls back to default if the value's type doesn't match an existing attribute.
|
||||
pub fn set_attribute_value_dyn(&mut self, key: impl Into<String>, index: usize, value: AttributeValueDyn) {
|
||||
@@ -1092,12 +1029,6 @@ impl<T> List<T> {
|
||||
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.
|
||||
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)
|
||||
@@ -1143,48 +1074,12 @@ impl<T> 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 {
|
||||
let mut combined_bounds = None;
|
||||
|
||||
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,
|
||||
}
|
||||
crate::bounds::lane_bounding_box(self, transform, include_stroke)
|
||||
}
|
||||
|
||||
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
|
||||
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,
|
||||
}
|
||||
crate::bounds::lane_thumbnail_bounding_box(self, transform, include_stroke)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1211,6 +1106,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> {
|
||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
self.element.cache_hash(state);
|
||||
|
||||
@@ -1,157 +1,157 @@
|
||||
use crate::context::InjectIndex;
|
||||
use crate::gpoll::{Extent, Finality, GPoll, GraphError, Interrupt};
|
||||
use crate::gpoll::{Extent, Finality, GPoll, GraphError, Interrupt, Level};
|
||||
use std::cell::Cell;
|
||||
use std::marker::PhantomData;
|
||||
use std::mem::MaybeUninit;
|
||||
use std::ops::Range;
|
||||
use std::ops::{Deref, Range};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum BatchStatus<'a, T> {
|
||||
Lent(RecordBatch<'a, T>, Finality),
|
||||
Filled(RecordBatch<'a, T>, Finality),
|
||||
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 edge; a driver answers with the
|
||||
/// per-lane serve and copy-out loop ([`crate::record::fill_frames`]).
|
||||
Unbatched,
|
||||
Pending,
|
||||
Error(GraphError),
|
||||
NeedBuffer,
|
||||
InvalidRange,
|
||||
}
|
||||
|
||||
/// Owns the initialized prefix of a caller-supplied scratch buffer, dropping every
|
||||
/// lane unless [`FilledBatch::into_values`] hands the obligation back to the caller.
|
||||
#[derive(Debug)]
|
||||
pub struct FilledBatch<'a, T> {
|
||||
values: &'a mut [T],
|
||||
}
|
||||
|
||||
impl<'a, T> FilledBatch<'a, T> {
|
||||
/// # Safety
|
||||
///
|
||||
/// The first `len` elements of `scratch` must be initialized, and `len` must not exceed `scratch.len()`.
|
||||
pub unsafe fn new(scratch: &'a mut [MaybeUninit<T>], len: usize) -> Self {
|
||||
Self {
|
||||
values: unsafe { assume_init_prefix_mut(scratch, len) },
|
||||
impl From<Interrupt> for BatchStatus<'_> {
|
||||
fn from(interrupt: Interrupt) -> Self {
|
||||
match interrupt {
|
||||
Interrupt::Pending => BatchStatus::Pending,
|
||||
Interrupt::Error(error) => BatchStatus::Error(*error),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn values(&self) -> &[T] {
|
||||
self.values
|
||||
}
|
||||
|
||||
pub fn into_values(self) -> &'a mut [T] {
|
||||
let mut guard = std::mem::ManuallyDrop::new(self);
|
||||
std::mem::take(&mut guard.values)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Drop for FilledBatch<'_, T> {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: every lane was initialized when the guard was built and none has
|
||||
// been moved out, since `into_values` consumes the guard instead.
|
||||
unsafe { std::ptr::drop_in_place(self.values as *mut [T]) }
|
||||
}
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
///
|
||||
/// The first `len` elements of `scratch` must be initialized, and `len` must not exceed `scratch.len()`.
|
||||
pub unsafe fn assume_init_prefix_mut<T>(scratch: &mut [MaybeUninit<T>], len: usize) -> &mut [T] {
|
||||
debug_assert!(len <= scratch.len());
|
||||
unsafe { std::slice::from_raw_parts_mut(scratch.as_mut_ptr().cast::<T>(), len) }
|
||||
}
|
||||
|
||||
/// A borrow-for-scope view over a batch of records whose element type is `T`,
|
||||
/// paired with their shared [`Layout`](crate::record::Layout). Row-major backed
|
||||
/// today; the interface (`len`/`layout`/`get`/`for_each`) is storage-agnostic so
|
||||
/// a columnar backing can replace it without touching consumers.
|
||||
#[derive(Debug)]
|
||||
pub struct RecordBatch<'a, T> {
|
||||
lanes: LaneStore<'a, T>,
|
||||
/// 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]>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum LaneStore<'a, T> {
|
||||
/// Borrows resident storage (the `Lent` status): no drop obligation.
|
||||
Borrowed(&'a [T]),
|
||||
/// Owns the caller scratch's initialized prefix (the `Filled` status).
|
||||
Owned(FilledBatch<'a, T>),
|
||||
}
|
||||
|
||||
impl<'a, T> RecordBatch<'a, T> {
|
||||
pub fn lent(values: &'a [T], layout: &'a crate::record::Layout) -> Self {
|
||||
Self { lanes: LaneStore::Borrowed(values), layout }
|
||||
}
|
||||
|
||||
pub fn filled(filled: FilledBatch<'a, T>, layout: &'a crate::record::Layout) -> Self {
|
||||
Self { lanes: LaneStore::Owned(filled), layout }
|
||||
}
|
||||
|
||||
fn lanes(&self) -> &[T] {
|
||||
match &self.lanes {
|
||||
LaneStore::Borrowed(values) => values,
|
||||
LaneStore::Owned(filled) => filled.values(),
|
||||
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.lanes().len()
|
||||
self.len
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.len() == 0
|
||||
self.len == 0
|
||||
}
|
||||
|
||||
pub fn layout(&self) -> &crate::record::Layout {
|
||||
pub fn layout(&self) -> &'a crate::record::Layout {
|
||||
self.layout
|
||||
}
|
||||
|
||||
/// Lends lane `lane`'s record to `f` for the callback's scope only.
|
||||
pub fn get<R>(&self, lane: usize, f: impl FnOnce(RecordLane<'_, T>) -> R) -> R {
|
||||
f(RecordLane { value: &self.lanes()[lane], layout: self.layout })
|
||||
pub(crate) fn frames_ptr(&self) -> *const u8 {
|
||||
self.frames
|
||||
}
|
||||
|
||||
/// Lends every lane's record in order, each for its callback's scope only.
|
||||
pub fn for_each(&self, mut f: impl FnMut(usize, RecordLane<'_, T>)) {
|
||||
for (lane, value) in self.lanes().iter().enumerate() {
|
||||
f(lane, RecordLane { value, layout: self.layout });
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
/// Hands the owned scratch prefix back to the caller, cancelling the drop
|
||||
/// obligation. Panics on a lent batch, which owns nothing to return.
|
||||
pub fn into_values(self) -> &'a mut [T] {
|
||||
match self.lanes {
|
||||
LaneStore::Owned(filled) => filled.into_values(),
|
||||
LaneStore::Borrowed(_) => panic!("into_values on a lent batch"),
|
||||
pub fn for_each(&self, mut f: impl FnMut(usize, RecordLane<'a>)) {
|
||||
for lane in 0..self.len {
|
||||
f(lane, self.get(lane));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One lane's record, lent for a callback scope. Derefs to the raw lane value;
|
||||
/// for record elements, [`rec`](RecordLane::rec) and [`attr`](RecordLane::attr)
|
||||
/// read the record through its layout.
|
||||
/// 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 RecordLane<'r, T> {
|
||||
value: &'r T,
|
||||
layout: &'r crate::record::Layout,
|
||||
pub struct RecordBatchMut<'a> {
|
||||
scratch: &'a mut [MaybeUninit<u64>],
|
||||
len: usize,
|
||||
layout: &'a crate::record::Layout,
|
||||
}
|
||||
|
||||
impl<T> std::ops::Deref for RecordLane<'_, T> {
|
||||
type Target = T;
|
||||
|
||||
fn deref(&self) -> &T {
|
||||
self.value
|
||||
impl<'a> RecordBatchMut<'a> {
|
||||
/// Minted only by a [`crate::record::SlotRun`] finishing its served lanes,
|
||||
/// which is what makes the initialized prefix 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 * layout.lane_stride() <= scratch.len() * 8);
|
||||
Self { scratch, len, layout }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> RecordLane<'_, T> {
|
||||
pub fn layout(&self) -> &crate::record::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) }
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
impl<'e> RecordLane<'_, crate::record::RecordValue<'e>> {
|
||||
/// The record pointer, resolved through the layout.
|
||||
pub fn rec(&self) -> crate::record::Rec {
|
||||
self.layout.rec(self.value)
|
||||
/// 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.
|
||||
@@ -159,36 +159,201 @@ impl<'e> RecordLane<'_, crate::record::RecordValue<'e>> {
|
||||
/// # 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>() }
|
||||
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.
|
||||
pub fn attr<A: crate::attribute::Attribute>(&self) -> A::Value<'e> {
|
||||
match self.layout.offset_of(A::NAME, 0) {
|
||||
Some(offset) => unsafe { self.rec().read::<A::Value<'e>>(offset) },
|
||||
None => A::default(),
|
||||
/// 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. The eventual
|
||||
/// `List` once `IList` is renamed.
|
||||
#[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> {
|
||||
type Output;
|
||||
|
||||
fn eval(&self, input: &Input) -> GPoll<Self::Output>;
|
||||
|
||||
fn extent(&self, _input: &Input) -> GPoll<Extent> {
|
||||
GPoll::Final(Extent::Free)
|
||||
}
|
||||
/// 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, as with [`extent`](Node::extent).
|
||||
fn extent_at(&self, _input: &Input, _level: u8) -> GPoll<Extent> {
|
||||
/// `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 {
|
||||
@@ -202,53 +367,27 @@ pub trait Node<Input> {
|
||||
|
||||
/// 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 stack sizing from the same
|
||||
/// layouts, in the dynamic executor and exported source alike.
|
||||
/// 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()
|
||||
}
|
||||
|
||||
fn eval_batch<'a>(&'a self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<Self::Output>]>) -> BatchStatus<'a, Self::Output>
|
||||
/// 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,
|
||||
Input: InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||
{
|
||||
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;
|
||||
};
|
||||
if scratch.len() < len {
|
||||
return BatchStatus::InvalidRange;
|
||||
}
|
||||
let mut local = *input;
|
||||
let mut finality = Finality::AllFinal;
|
||||
for offset in 0..len {
|
||||
local.set_index(range.start + offset as u64);
|
||||
let abort = match self.eval(&local) {
|
||||
GPoll::Final(value) => {
|
||||
scratch[offset].write(value);
|
||||
None
|
||||
}
|
||||
GPoll::Partial(value) => {
|
||||
scratch[offset].write(value);
|
||||
finality = Finality::Partial;
|
||||
None
|
||||
}
|
||||
GPoll::Pending => Some(BatchStatus::Pending),
|
||||
GPoll::Fallback(boxed) => Some(BatchStatus::Error(boxed.1)),
|
||||
GPoll::Error(e) => Some(BatchStatus::Error(*e)),
|
||||
};
|
||||
if let Some(status) = abort {
|
||||
for written in scratch[..offset].iter_mut() {
|
||||
// SAFETY: every lane before `offset` was written by this loop.
|
||||
unsafe { written.assume_init_drop() };
|
||||
}
|
||||
return status;
|
||||
}
|
||||
}
|
||||
// SAFETY: all `len` lanes were written by the loop above.
|
||||
BatchStatus::Filled(RecordBatch::filled(unsafe { FilledBatch::new(scratch, len) }, self.layout()), finality)
|
||||
let _ = (input, range, scratch, frames);
|
||||
BatchStatus::Unbatched
|
||||
}
|
||||
}
|
||||
|
||||
@@ -256,18 +395,18 @@ impl<Input, N> Node<Input> for &N
|
||||
where
|
||||
N: Node<Input> + ?Sized,
|
||||
{
|
||||
type Output = N::Output;
|
||||
|
||||
fn eval(&self, input: &Input) -> GPoll<Self::Output> {
|
||||
(**self).eval(input)
|
||||
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(&self, input: &Input) -> GPoll<Extent> {
|
||||
(**self).extent(input)
|
||||
}
|
||||
|
||||
fn extent_at(&self, input: &Input, level: u8) -> GPoll<Extent> {
|
||||
(**self).extent_at(input, level)
|
||||
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>> {
|
||||
@@ -278,11 +417,11 @@ where
|
||||
(**self).layout()
|
||||
}
|
||||
|
||||
fn eval_batch<'a>(&'a self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<Self::Output>]>) -> BatchStatus<'a, Self::Output>
|
||||
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,
|
||||
Input: InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||
{
|
||||
(**self).eval_batch(input, range, scratch)
|
||||
(**self).eval_batch(input, range, scratch, frames)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -290,18 +429,18 @@ impl<Input, N> Node<Input> for Box<N>
|
||||
where
|
||||
N: Node<Input> + ?Sized,
|
||||
{
|
||||
type Output = N::Output;
|
||||
|
||||
fn eval(&self, input: &Input) -> GPoll<Self::Output> {
|
||||
(**self).eval(input)
|
||||
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(&self, input: &Input) -> GPoll<Extent> {
|
||||
(**self).extent(input)
|
||||
}
|
||||
|
||||
fn extent_at(&self, input: &Input, level: u8) -> GPoll<Extent> {
|
||||
(**self).extent_at(input, level)
|
||||
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>> {
|
||||
@@ -312,11 +451,11 @@ where
|
||||
(**self).layout()
|
||||
}
|
||||
|
||||
fn eval_batch<'a>(&'a self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<Self::Output>]>) -> BatchStatus<'a, Self::Output>
|
||||
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,
|
||||
Input: InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||
{
|
||||
(**self).eval_batch(input, range, scratch)
|
||||
(**self).eval_batch(input, range, scratch, frames)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -324,18 +463,18 @@ impl<Input, N> Node<Input> for std::sync::Arc<N>
|
||||
where
|
||||
N: Node<Input> + ?Sized,
|
||||
{
|
||||
type Output = N::Output;
|
||||
|
||||
fn eval(&self, input: &Input) -> GPoll<Self::Output> {
|
||||
(**self).eval(input)
|
||||
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(&self, input: &Input) -> GPoll<Extent> {
|
||||
(**self).extent(input)
|
||||
}
|
||||
|
||||
fn extent_at(&self, input: &Input, level: u8) -> GPoll<Extent> {
|
||||
(**self).extent_at(input, level)
|
||||
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>> {
|
||||
@@ -346,11 +485,11 @@ where
|
||||
(**self).layout()
|
||||
}
|
||||
|
||||
fn eval_batch<'a>(&'a self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<Self::Output>]>) -> BatchStatus<'a, Self::Output>
|
||||
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,
|
||||
Input: InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||
{
|
||||
(**self).eval_batch(input, range, scratch)
|
||||
(**self).eval_batch(input, range, scratch, frames)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -375,23 +514,32 @@ impl StatusCell {
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn no_partial() -> Self {
|
||||
Self { no_partial: true, ..Self::new() }
|
||||
}
|
||||
|
||||
pub fn eval_input<Input, N: Node<Input>>(&self, input_index: usize, node: &N, input: &Input) -> Result<N::Output, Interrupt> {
|
||||
match node.eval(input) {
|
||||
GPoll::Final(value) => Ok(value),
|
||||
/// Claims the edge'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 edge'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(value) => {
|
||||
GPoll::Partial(served) => {
|
||||
self.finality.set(Finality::Partial);
|
||||
Ok(value)
|
||||
Ok(served.value())
|
||||
}
|
||||
GPoll::Fallback(boxed) => {
|
||||
let (value, error) = *boxed;
|
||||
let (served, error) = *boxed;
|
||||
let first = self.error.take();
|
||||
self.error.set(first.or(Some(error.traced(input_index))));
|
||||
Ok(value)
|
||||
Ok(served.value())
|
||||
}
|
||||
GPoll::Pending => Err(Interrupt::Pending),
|
||||
GPoll::Error(mut error) => {
|
||||
@@ -401,6 +549,20 @@ impl StatusCell {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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))),
|
||||
@@ -409,6 +571,7 @@ impl StatusCell {
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn merge<T>(self, poll: GPoll<T>) -> GPoll<T> {
|
||||
match poll {
|
||||
GPoll::Final(value) => self.finish(value),
|
||||
@@ -428,162 +591,96 @@ impl StatusCell {
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct LazyInput<'a, N> {
|
||||
pub struct LazyInput<'a, 'f, N> {
|
||||
node: &'a N,
|
||||
cell: &'a StatusCell,
|
||||
input_index: usize,
|
||||
frames: &'a crate::record::Frames<'f>,
|
||||
}
|
||||
|
||||
impl<'a, N> LazyInput<'a, N> {
|
||||
pub fn new(node: &'a N, cell: &'a StatusCell, input_index: usize) -> Self {
|
||||
Self { node, cell, input_index }
|
||||
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 }
|
||||
}
|
||||
|
||||
pub fn eval<Input>(&self, ctx: &Input) -> Result<N::Output, Interrupt>
|
||||
#[inline(always)]
|
||||
pub fn eval<'e, Input>(&self, ctx: &Input) -> Result<crate::record::RecordValue<'e>, Interrupt>
|
||||
where
|
||||
N: crate::record::DerivedRecordEdge<'e, Input>,
|
||||
'f: 'e,
|
||||
{
|
||||
self.node.eval_derived(self.cell, self.input_index, ctx, self.frames)
|
||||
}
|
||||
|
||||
/// The edge'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.cell.eval_input(self.input_index, self.node, ctx)
|
||||
self.node.extent(ctx, at, self.frames)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
|
||||
use crate::arena::Arena;
|
||||
use crate::context::ExtractArena;
|
||||
use crate::record::{LiftedSource, serve_edge};
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct TestInput {
|
||||
struct TestInput<'a> {
|
||||
index: u64,
|
||||
arena: &'a Arena,
|
||||
}
|
||||
|
||||
impl InjectIndex for TestInput {
|
||||
impl InjectIndex for TestInput<'_> {
|
||||
fn set_index(&mut self, index: u64) {
|
||||
self.index = index;
|
||||
}
|
||||
}
|
||||
|
||||
struct Double;
|
||||
impl<'a> ExtractArena for TestInput<'a> {
|
||||
type ArenaRef = &'a Arena;
|
||||
|
||||
impl Node<TestInput> for Double {
|
||||
type Output = u64;
|
||||
|
||||
fn eval(&self, input: &TestInput) -> GPoll<u64> {
|
||||
GPoll::Final(input.index * 2)
|
||||
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 spec_loop_fills_scratch_per_lane() {
|
||||
let input = TestInput { index: 0 };
|
||||
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 status = Double.eval_batch(&input, 2..6, Some(&mut scratch));
|
||||
let BatchStatus::Filled(batch, finality) = status else {
|
||||
panic!("expected filled, got {status:?}");
|
||||
};
|
||||
let mut got = Vec::new();
|
||||
batch.for_each(|_, lane| got.push(*lane));
|
||||
assert_eq!(got, vec![4, 6, 8, 10]);
|
||||
assert_eq!(finality, Finality::AllFinal);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_filled_batch_reclaims_every_lane() {
|
||||
static DROPS: AtomicU32 = AtomicU32::new(0);
|
||||
#[derive(Clone)]
|
||||
struct Probe;
|
||||
impl Drop for Probe {
|
||||
fn drop(&mut self) {
|
||||
DROPS.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
struct Probes;
|
||||
impl Node<TestInput> for Probes {
|
||||
type Output = Probe;
|
||||
|
||||
fn eval(&self, _input: &TestInput) -> GPoll<Probe> {
|
||||
GPoll::Final(Probe)
|
||||
}
|
||||
}
|
||||
|
||||
let input = TestInput { index: 0 };
|
||||
let mut scratch = [const { MaybeUninit::uninit() }; 3];
|
||||
let status = Probes.eval_batch(&input, 0..3, Some(&mut scratch));
|
||||
assert!(matches!(status, BatchStatus::Filled(..)));
|
||||
drop(status);
|
||||
assert_eq!(DROPS.load(Ordering::Relaxed), 3, "an unconsumed batch must not leak its lanes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn probe_without_scratch_requests_a_buffer() {
|
||||
let input = TestInput { index: 0 };
|
||||
assert!(matches!(Double.eval_batch(&input, 0..4, None), BatchStatus::NeedBuffer));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undersized_scratch_is_an_invalid_range() {
|
||||
let input = TestInput { index: 0 };
|
||||
let mut scratch = [const { MaybeUninit::uninit() }; 2];
|
||||
assert!(matches!(Double.eval_batch(&input, 0..4, Some(&mut scratch)), BatchStatus::InvalidRange));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_lane_downgrades_batch_finality() {
|
||||
struct PartialAtThree;
|
||||
impl Node<TestInput> for PartialAtThree {
|
||||
type Output = u64;
|
||||
fn eval(&self, input: &TestInput) -> GPoll<u64> {
|
||||
match input.index {
|
||||
3 => GPoll::Partial(input.index),
|
||||
index => GPoll::Final(index),
|
||||
}
|
||||
}
|
||||
}
|
||||
let input = TestInput { index: 0 };
|
||||
let mut scratch = [const { MaybeUninit::uninit() }; 4];
|
||||
let status = PartialAtThree.eval_batch(&input, 0..4, Some(&mut scratch));
|
||||
let BatchStatus::Filled(batch, finality) = status else {
|
||||
panic!("expected filled, got {status:?}");
|
||||
};
|
||||
let mut got = Vec::new();
|
||||
batch.for_each(|_, lane| got.push(*lane));
|
||||
assert_eq!(got, vec![0, 1, 2, 3]);
|
||||
assert_eq!(finality, Finality::Partial);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn abort_drops_already_written_lanes() {
|
||||
static DROPS: AtomicU32 = AtomicU32::new(0);
|
||||
struct Probe;
|
||||
impl Drop for Probe {
|
||||
fn drop(&mut self) {
|
||||
DROPS.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
struct PendingAtTwo;
|
||||
impl Node<TestInput> for PendingAtTwo {
|
||||
type Output = Probe;
|
||||
fn eval(&self, input: &TestInput) -> GPoll<Probe> {
|
||||
match input.index {
|
||||
2 => GPoll::Pending,
|
||||
_ => GPoll::Final(Probe),
|
||||
}
|
||||
}
|
||||
}
|
||||
let input = TestInput { index: 0 };
|
||||
let mut scratch = [const { MaybeUninit::uninit() }; 4];
|
||||
let status = PendingAtTwo.eval_batch(&input, 0..4, Some(&mut scratch));
|
||||
assert!(matches!(status, BatchStatus::Pending));
|
||||
assert_eq!(DROPS.load(Ordering::Relaxed), 2);
|
||||
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 erased: Box<dyn Node<TestInput, Output = u64>> = Box::new(Double);
|
||||
let input = TestInput { index: 21 };
|
||||
assert_eq!(erased.eval(&input), GPoll::Final(42));
|
||||
let mut scratch = [const { MaybeUninit::uninit() }; 2];
|
||||
let status = erased.eval_batch(&input, 0..2, Some(&mut scratch));
|
||||
assert!(matches!(status, BatchStatus::Filled(_, Finality::AllFinal)));
|
||||
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_edge(&*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));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -29,6 +29,8 @@ pub struct NodeMetadata {
|
||||
pub struct FieldMetadata {
|
||||
pub name: &'static str,
|
||||
pub description: &'static str,
|
||||
/// Index levels the node pushes when evaluating this input.
|
||||
pub pushed_levels: u8,
|
||||
pub hidden: bool,
|
||||
pub exposed: bool,
|
||||
pub widget_override: RegistryWidgetOverride,
|
||||
@@ -70,26 +72,17 @@ pub static NODE_METADATA: LazyLock<Mutex<HashMap<ProtoNodeIdentifier, NodeMetada
|
||||
|
||||
pub use crate::NodeIOTypes;
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub type ErasedNode<T> = dyn for<'c> Node<ContextImpl<'c>, Output = T> + Send + Sync;
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub type ErasedNode<T> = dyn for<'c> Node<ContextImpl<'c>, Output = T>;
|
||||
|
||||
/// Element-independent by erasure; the wire's `Type::Record(El)` keeps element reads proven at wiring.
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub type ErasedRecordNode = dyn for<'c> Node<ContextImpl<'c>, Output = crate::record::RecordValue<'c>> + Send + Sync;
|
||||
pub type ErasedRecordNode = dyn for<'c> Node<ContextImpl<'c>> + Send + Sync;
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub type ErasedRecordNode = dyn for<'c> Node<ContextImpl<'c>, Output = crate::record::RecordValue<'c>>;
|
||||
pub type ErasedRecordNode = dyn for<'c> Node<ContextImpl<'c>>;
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
type DynEdge = dyn std::any::Any + Send + Sync;
|
||||
#[cfg(target_family = "wasm")]
|
||||
type DynEdge = dyn std::any::Any;
|
||||
|
||||
pub fn edge_type<T: 'static>() -> Type {
|
||||
Type::Fn(Box::new(concrete!(Context)), Box::new(concrete!(T)))
|
||||
}
|
||||
|
||||
pub fn record_type<T: 'static>() -> Type {
|
||||
Type::Record(Box::new(concrete!(T)))
|
||||
}
|
||||
@@ -113,7 +106,6 @@ pub fn cache_key<C: CacheHash + ?Sized>(ctx: &C) -> u64 {
|
||||
pub enum ConstructionError {
|
||||
Arity { expected: usize, got: usize },
|
||||
Type { expected: Box<Type>, found: Box<Type> },
|
||||
MissingLayout,
|
||||
}
|
||||
|
||||
pub struct SharedEdge<N: ?Sized> {
|
||||
@@ -132,6 +124,13 @@ impl<N: ?Sized> SharedEdge<N> {
|
||||
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.
|
||||
pub fn rederive(&mut self) {
|
||||
self.ptr = std::ptr::NonNull::from(&*self.own);
|
||||
}
|
||||
}
|
||||
|
||||
// SAFETY: `ptr` is derived from the owned Arc and never mutated through, so the edge is exactly as
|
||||
@@ -144,53 +143,48 @@ impl<Input, N> Node<Input> for SharedEdge<N>
|
||||
where
|
||||
N: Node<Input> + ?Sized,
|
||||
{
|
||||
type Output = N::Output;
|
||||
|
||||
fn eval(&self, input: &Input) -> crate::gpoll::GPoll<Self::Output> {
|
||||
// Every node advances the record stack by exactly its own frame: it keeps
|
||||
// its output and reclaims its inputs. A mismatch is a leaked or
|
||||
// over-released frame.
|
||||
#[cfg(debug_assertions)]
|
||||
let sp_before = crate::record::stack::sp();
|
||||
/// A node takes exactly its own frame out of its caller's free space: the
|
||||
/// caller minted the claim and kept the cursor, so the frame accounting is
|
||||
/// structural here and asserted where a claim is split.
|
||||
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.
|
||||
let result = unsafe { self.ptr.as_ref() }.eval(input);
|
||||
#[cfg(debug_assertions)]
|
||||
debug_assert_eq!(
|
||||
crate::record::stack::sp(),
|
||||
sp_before + self.layout().frame_bytes(),
|
||||
"{} left the record stack misaligned",
|
||||
std::any::type_name::<N>(),
|
||||
);
|
||||
result
|
||||
unsafe { self.ptr.as_ref() }.serve(input, slot)
|
||||
}
|
||||
|
||||
fn extent(&self, input: &Input) -> crate::gpoll::GPoll<crate::gpoll::Extent> {
|
||||
// SAFETY: as in eval.
|
||||
unsafe { self.ptr.as_ref() }.extent(input)
|
||||
}
|
||||
|
||||
fn extent_at(&self, input: &Input, level: u8) -> crate::gpoll::GPoll<crate::gpoll::Extent> {
|
||||
// SAFETY: as in eval.
|
||||
unsafe { self.ptr.as_ref() }.extent_at(input, level)
|
||||
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 eval.
|
||||
// SAFETY: as in serve.
|
||||
unsafe { self.ptr.as_ref() }.serialize()
|
||||
}
|
||||
|
||||
fn layout(&self) -> &crate::record::Layout {
|
||||
// SAFETY: as in eval.
|
||||
// SAFETY: as in serve.
|
||||
unsafe { self.ptr.as_ref() }.layout()
|
||||
}
|
||||
|
||||
fn eval_batch<'a>(&'a self, input: &'a Input, range: std::ops::Range<u64>, scratch: Option<&'a mut [std::mem::MaybeUninit<Self::Output>]>) -> crate::node::BatchStatus<'a, Self::Output>
|
||||
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,
|
||||
Input: crate::context::InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'x crate::arena::Arena>,
|
||||
{
|
||||
// SAFETY: as in eval.
|
||||
unsafe { self.ptr.as_ref() }.eval_batch(input, range, scratch)
|
||||
// SAFETY: as in serve.
|
||||
unsafe { self.ptr.as_ref() }.eval_batch(input, range, scratch, frames)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -198,7 +192,8 @@ pub struct EdgeHandle {
|
||||
node: Box<DynEdge>,
|
||||
share: fn(&DynEdge) -> Box<DynEdge>,
|
||||
serialize: fn(&DynEdge) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>>,
|
||||
layout: fn(&DynEdge) -> Option<&crate::record::Layout>,
|
||||
layout: fn(&DynEdge) -> &crate::record::Layout,
|
||||
set_layout: fn(&mut DynEdge, crate::record::RecordLayout),
|
||||
ty: Type,
|
||||
}
|
||||
|
||||
@@ -216,10 +211,6 @@ unsafe impl Send for EdgeHandle {}
|
||||
unsafe impl Sync for EdgeHandle {}
|
||||
|
||||
impl EdgeHandle {
|
||||
pub fn new<T: 'static>(node: std::sync::Arc<ErasedNode<T>>) -> Self {
|
||||
Self::new_erased(node, edge_type::<T>())
|
||||
}
|
||||
|
||||
pub fn new_record<T: 'static>(node: std::sync::Arc<ErasedRecordNode>) -> Self {
|
||||
Self::new_erased(node, record_edge_type::<T>())
|
||||
}
|
||||
@@ -233,7 +224,13 @@ impl EdgeHandle {
|
||||
node: Box::new(SharedEdge::new(node)),
|
||||
share: |edge| Box::new(edge.downcast_ref::<SharedEdge<N>>().expect("share hook matches the stored edge type").share()),
|
||||
serialize: |edge| Node::<ContextImpl>::serialize(edge.downcast_ref::<SharedEdge<N>>().expect("serialize hook matches the stored edge type")),
|
||||
layout: |edge| Some(Node::<ContextImpl>::layout(edge.downcast_ref::<SharedEdge<N>>().expect("layout hook matches the stored edge type"))),
|
||||
layout: |edge| Node::<ContextImpl>::layout(edge.downcast_ref::<SharedEdge<N>>().expect("layout hook matches the stored edge type")),
|
||||
set_layout: |edge, layout| {
|
||||
let shared = edge.downcast_mut::<SharedEdge<N>>().expect("set_layout hook matches the stored edge type");
|
||||
let node = std::sync::Arc::get_mut(&mut shared.own).expect("layout is installed before the node is shared");
|
||||
Node::<ContextImpl>::set_layout(node, layout);
|
||||
shared.rederive();
|
||||
},
|
||||
ty,
|
||||
}
|
||||
}
|
||||
@@ -248,6 +245,7 @@ impl EdgeHandle {
|
||||
share: self.share,
|
||||
serialize: self.serialize,
|
||||
layout: self.layout,
|
||||
set_layout: self.set_layout,
|
||||
ty: self.ty.clone(),
|
||||
}
|
||||
}
|
||||
@@ -256,18 +254,24 @@ impl EdgeHandle {
|
||||
(self.serialize)(&*self.node)
|
||||
}
|
||||
|
||||
pub fn layout(&self) -> Option<&crate::record::Layout> {
|
||||
pub fn layout(&self) -> &crate::record::Layout {
|
||||
(self.layout)(&*self.node)
|
||||
}
|
||||
|
||||
pub fn downcast<T: 'static>(self) -> Result<SharedEdge<ErasedNode<T>>, ConstructionError> {
|
||||
self.downcast_erased(edge_type::<T>())
|
||||
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<SharedEdge<ErasedRecordNode>, ConstructionError> {
|
||||
self.downcast_erased(record_edge_type::<T>())
|
||||
}
|
||||
|
||||
/// The erased record edge, for callers that dispatch on the layout rather
|
||||
/// than a static element type. `None` for an edge erased to another node type.
|
||||
pub fn record_edge(self) -> Option<SharedEdge<ErasedRecordNode>> {
|
||||
self.node.downcast::<SharedEdge<ErasedRecordNode>>().ok().map(|edge| *edge)
|
||||
}
|
||||
|
||||
pub fn downcast_erased<N: ?Sized + 'static>(self, expected: Type) -> Result<SharedEdge<N>, ConstructionError> {
|
||||
let found = self.ty;
|
||||
self.node.downcast::<SharedEdge<N>>().map(|edge| *edge).map_err(|_| ConstructionError::Type {
|
||||
@@ -317,216 +321,262 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::SourceId;
|
||||
use crate::arena::Arena;
|
||||
use crate::context::{Ctx, EvalScope, ExtractArena};
|
||||
use crate::context::{Ctx, EvalScope, ExtractArena, ExtractIndices};
|
||||
use crate::gpoll::GPoll;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
|
||||
struct CountingNode(AtomicU32);
|
||||
use crate::record::{FrameClaim, Layout, LiftedSource, Served, element_write, read_element, serve_edge};
|
||||
|
||||
impl<Input> Node<Input> for CountingNode {
|
||||
type Output = u32;
|
||||
|
||||
fn eval(&self, _input: &Input) -> GPoll<u32> {
|
||||
GPoll::Final(self.0.fetch_add(1, Ordering::Relaxed) + 1)
|
||||
}
|
||||
}
|
||||
|
||||
struct ValueNode<T>(T);
|
||||
|
||||
impl<T: Clone, Input> Node<Input> for ValueNode<T> {
|
||||
type Output = T;
|
||||
|
||||
fn eval(&self, _input: &Input) -> GPoll<T> {
|
||||
GPoll::Final(self.0.clone())
|
||||
}
|
||||
}
|
||||
|
||||
struct LendNode(String);
|
||||
|
||||
impl<'e, Input: Ctx + ExtractArena<ArenaRef = &'e Arena>> Node<Input> for LendNode {
|
||||
type Output = &'e String;
|
||||
|
||||
fn eval(&self, input: &Input) -> GPoll<&'e String> {
|
||||
match input.arena().alloc(self.0.clone()) {
|
||||
Some((parked, _)) => GPoll::Final(parked),
|
||||
None => GPoll::arena_exhausted(),
|
||||
}
|
||||
}
|
||||
fn counting() -> LiftedSource<u32, impl for<'c> Fn(&ContextImpl<'c>) -> GPoll<u32>> {
|
||||
let count = AtomicU32::new(0);
|
||||
LiftedSource::new(move |_: &ContextImpl<'_>| GPoll::Final(count.fetch_add(1, Ordering::Relaxed) + 1))
|
||||
}
|
||||
|
||||
fn scope_fixture<'a>(generations: &'a [(SourceId, u64)], arena: &'a Arena) -> EvalScope<'a> {
|
||||
EvalScope::new(Some(0.5), None, None, generations, arena)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn borrow_carrying_value_types_wire_through_the_general_constructor() {
|
||||
struct SplitBorrow<'c>(&'c str, usize);
|
||||
/// 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,
|
||||
}
|
||||
|
||||
struct SplitNode<Node0> {
|
||||
content: Node0,
|
||||
impl LendNode {
|
||||
fn new(value: &str) -> Self {
|
||||
Self {
|
||||
value: value.to_string(),
|
||||
layout: Layout::default().with_writes(0, element_write::<&'static String>(), &[]),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'e, Input, Node0> Node<Input> for SplitNode<Node0>
|
||||
impl<Input: Ctx> Node<Input> for LendNode {
|
||||
fn serve<'e, 'l>(&self, input: &Input, slot: FrameClaim<'e, 'l>) -> GPoll<Served<'e>>
|
||||
where
|
||||
Input: Ctx,
|
||||
Node0: Node<Input, Output = &'e String>,
|
||||
Input: ExtractArena<ArenaRef = &'e Arena>,
|
||||
{
|
||||
type Output = SplitBorrow<'e>;
|
||||
|
||||
fn eval(&self, input: &Input) -> GPoll<SplitBorrow<'e>> {
|
||||
self.content.eval(input).map(|value| SplitBorrow(value, value.len()))
|
||||
match input.arena().alloc(self.value.clone()) {
|
||||
Some((parked, _)) => slot.lift_served(GPoll::Final(parked), input.arena()),
|
||||
None => GPoll::arena_exhausted(),
|
||||
}
|
||||
}
|
||||
|
||||
type ErasedSplitEdge = dyn for<'c> Node<ContextImpl<'c>, Output = SplitBorrow<'c>> + Send + Sync;
|
||||
fn layout(&self) -> &Layout {
|
||||
&self.layout
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn borrow_carrying_value_types_wire_through_the_general_constructor() {
|
||||
let arena = Arena::new(4096).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
let frames = crate::record::test_frames(1 << 12);
|
||||
|
||||
let node: Arc<ErasedSplitEdge> = Arc::new(SplitNode {
|
||||
content: LendNode("held".to_string()),
|
||||
});
|
||||
let handle = EdgeHandle::new_erased(node, concrete!(SplitBorrow<'static>));
|
||||
assert_eq!(*handle.ty(), concrete!(SplitBorrow<'static>));
|
||||
let node = LendNode::new("held");
|
||||
let layout = Node::<ContextImpl>::layout(&node).clone();
|
||||
let handle = EdgeHandle::new_erased(Arc::new(node) as Arc<ErasedRecordNode>, concrete!(String));
|
||||
assert_eq!(*handle.ty(), concrete!(String));
|
||||
|
||||
let wired = handle.downcast_erased::<ErasedSplitEdge>(concrete!(SplitBorrow<'static>)).unwrap();
|
||||
let GPoll::Final(split) = wired.eval(&ctx) else {
|
||||
panic!("borrow-carrying output must eval through the erased edge");
|
||||
let wired = handle.downcast_erased::<ErasedRecordNode>(concrete!(String)).unwrap();
|
||||
let GPoll::Final(value) = serve_edge(&wired, &ctx, &frames) else {
|
||||
panic!("borrow-carrying output must serve through the erased edge");
|
||||
};
|
||||
assert_eq!(split.0, "held");
|
||||
assert_eq!(split.1, 4);
|
||||
// SAFETY: the record was served at `layout`, whose element is the borrow.
|
||||
let held = unsafe { read_element::<&String>(layout.rec(&value)) };
|
||||
assert_eq!(held, "held");
|
||||
assert_eq!(held.len(), 4);
|
||||
}
|
||||
|
||||
/// Evaluates its content at three promoted index levels 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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<C, T, Node0> Node<C> for RepeatNode<Node0, T>
|
||||
where
|
||||
C: Ctx + crate::context::DeriveCtx,
|
||||
T: Clone + 'static,
|
||||
Vec<T>: Send + Sync + dyn_any::StaticTypeSized,
|
||||
Node0: for<'x> crate::record::DerivedRecordEdge<'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 layout(&self) -> &Layout {
|
||||
&self.layout
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn derive_ctx_repeat_pushes_index_levels_through_the_erased_edge() {
|
||||
use crate::context::{DeriveCtx, Derived, ExtractIndex};
|
||||
|
||||
struct RepeatNode<Node0> {
|
||||
content: Node0,
|
||||
}
|
||||
|
||||
impl<C, T, Node0> Node<C> for RepeatNode<Node0>
|
||||
where
|
||||
C: Ctx + DeriveCtx,
|
||||
Node0: for<'x> Node<Derived<'x, C>, Output = T>,
|
||||
{
|
||||
type Output = Vec<T>;
|
||||
|
||||
fn eval(&self, input: &C) -> GPoll<Vec<T>> {
|
||||
let spilled = input.index_head();
|
||||
let mut result = Vec::new();
|
||||
for index in 0..3 {
|
||||
let derived = input.promoted(&spilled, index);
|
||||
match self.content.eval(&derived) {
|
||||
GPoll::Final(value) => result.push(value),
|
||||
other => return other.map(|_| Vec::new()),
|
||||
}
|
||||
}
|
||||
GPoll::Final(result)
|
||||
}
|
||||
}
|
||||
|
||||
struct LevelsNode;
|
||||
|
||||
impl<Input: ExtractIndex> Node<Input> for LevelsNode {
|
||||
type Output = Vec<usize>;
|
||||
|
||||
fn eval(&self, input: &Input) -> GPoll<Vec<usize>> {
|
||||
GPoll::Final(input.try_index().map(|levels| levels.collect()).unwrap_or_default())
|
||||
}
|
||||
}
|
||||
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let nested = RepeatNode {
|
||||
content: RepeatNode { content: LevelsNode },
|
||||
};
|
||||
let erased: Box<ErasedNode<Vec<Vec<Vec<usize>>>>> = Box::new(nested);
|
||||
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(outer) = erased.eval(&ctx) else {
|
||||
let GPoll::Final(value) = serve_edge(&*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::DerivedRecordEdge<'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::{DeriveCtx, Derived, ExtractFootprint};
|
||||
use crate::context::ExtractFootprint;
|
||||
use crate::transform::Footprint;
|
||||
|
||||
struct ShiftFootprintNode<Node0> {
|
||||
content: Node0,
|
||||
}
|
||||
|
||||
impl<C, T, Node0> Node<C> for ShiftFootprintNode<Node0>
|
||||
where
|
||||
C: Ctx + DeriveCtx + ExtractFootprint,
|
||||
Node0: for<'x> Node<Derived<'x, C>, Output = T>,
|
||||
{
|
||||
type Output = T;
|
||||
|
||||
fn eval(&self, input: &C) -> GPoll<T> {
|
||||
let mut footprint = input.try_footprint().copied().unwrap_or(Footprint::DEFAULT);
|
||||
footprint.resolution.x += 7;
|
||||
let derived = input.with_footprint(&footprint);
|
||||
self.content.eval(&derived)
|
||||
}
|
||||
}
|
||||
|
||||
struct ResolutionNode;
|
||||
|
||||
impl<Input: ExtractFootprint> Node<Input> for ResolutionNode {
|
||||
type Output = u32;
|
||||
|
||||
fn eval(&self, input: &Input) -> GPoll<u32> {
|
||||
GPoll::Final(input.try_footprint().map(|footprint| footprint.resolution.x).unwrap_or(0))
|
||||
}
|
||||
}
|
||||
|
||||
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 graph: Box<ErasedNode<u32>> = Box::new(ShiftFootprintNode {
|
||||
content: ShiftFootprintNode { content: ResolutionNode },
|
||||
});
|
||||
assert_eq!(graph.eval(&ctx), GPoll::Final(Footprint::DEFAULT.resolution.x + 14));
|
||||
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_edge(&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<EdgeHandle>) -> Result<EdgeHandle, ConstructionError> {
|
||||
let mut args = args.into_iter();
|
||||
let value = args.next().ok_or(ConstructionError::Arity { expected: 1, got: 0 })?.downcast::<String>()?;
|
||||
let value = args.next().ok_or(ConstructionError::Arity { expected: 1, got: 0 })?.downcast_record::<String>()?;
|
||||
drop(value);
|
||||
Ok(EdgeHandle::new(Arc::new(ValueNode(0u32)) as Arc<ErasedNode<u32>>))
|
||||
Ok(crate::value::record_value_edge(0u32))
|
||||
}
|
||||
let entry = RegistryEntry {
|
||||
layout_meta: None,
|
||||
io: NodeIOTypes::new(concrete!(Context), concrete!(u32), vec![edge_type::<String>()]),
|
||||
io: NodeIOTypes::new(concrete!(Context), record_type::<u32>(), vec![record_edge_type::<String>()]),
|
||||
constructor: construct_strlen,
|
||||
};
|
||||
|
||||
let owned = EdgeHandle::new(Arc::new(ValueNode("typed".to_string())) as Arc<ErasedNode<String>>);
|
||||
let owned = crate::value::record_value_edge("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 = EdgeHandle::new(Arc::new(ValueNode(1.0f64)) as Arc<ErasedNode<f64>>);
|
||||
let mistyped = crate::value::record_value_edge(1.0f64);
|
||||
assert_eq!(
|
||||
construct(&entry, vec![mistyped]).unwrap_err(),
|
||||
ConstructionError::Type {
|
||||
expected: Box::new(edge_type::<String>()),
|
||||
found: Box::new(edge_type::<f64>()),
|
||||
expected: Box::new(record_edge_type::<String>()),
|
||||
found: Box::new(record_edge_type::<f64>()),
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -538,16 +588,21 @@ mod tests {
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let handle = EdgeHandle::new(Arc::new(CountingNode(AtomicU32::new(0))) as Arc<ErasedNode<u32>>);
|
||||
let counting = counting();
|
||||
let layout = Node::<ContextImpl>::layout(&counting).clone();
|
||||
let handle = EdgeHandle::new_record::<u32>(Arc::new(counting) as Arc<ErasedRecordNode>);
|
||||
let duplicate = handle.duplicate();
|
||||
assert_eq!(*duplicate.ty(), edge_type::<u32>());
|
||||
assert_eq!(*duplicate.ty(), record_edge_type::<u32>());
|
||||
let frames = crate::record::test_frames(1 << 12);
|
||||
|
||||
let first = handle.downcast::<u32>().unwrap();
|
||||
let second = duplicate.downcast::<u32>().unwrap();
|
||||
assert_eq!(first.eval(&ctx), GPoll::Final(1));
|
||||
assert_eq!(second.eval(&ctx), GPoll::Final(2));
|
||||
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_edge(&first, &ctx, &frames).map(count), GPoll::Final(1));
|
||||
assert_eq!(serve_edge(&second, &ctx, &frames).map(count), GPoll::Final(2));
|
||||
|
||||
drop(first);
|
||||
assert_eq!(second.eval(&ctx), GPoll::Final(3));
|
||||
assert_eq!(serve_edge(&second, &ctx, &frames).map(count), GPoll::Final(3));
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,7 @@ pub trait Runtime {
|
||||
fn spawn(&self, source: SourceId, future: SourceFuture) -> bool;
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
#[derive(Clone, dyn_any::DynAny)]
|
||||
pub struct RuntimeHandle(pub Arc<DynRuntime>);
|
||||
|
||||
// SAFETY: wasm is single threaded, so the handle never actually crosses a thread.
|
||||
@@ -168,10 +168,10 @@ impl<S: Spawner> Runtime for GraphRuntime<S> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::arena::Arena;
|
||||
use crate::context::{ContextImpl, Ctx, CtxSnapshot, EvalScope, ExtractFootprint, ExtractVarArgs, VarArgLink, VarArgSlots};
|
||||
use crate::context::{ContextImpl, Ctx, EvalScope, ExtractFootprint, ExtractVarArgs, VarArgLink, VarArgSlots};
|
||||
use crate::gpoll::GPoll;
|
||||
use crate::node::Node;
|
||||
use crate::record::{Layout, RecordExtract, RecordLift, element_write, stack};
|
||||
use crate::record::{Layout, LiftedSource, RecordExtract, element_write};
|
||||
use crate::transform::Footprint;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
@@ -248,27 +248,32 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
struct SourceNode<T>(T);
|
||||
|
||||
impl<T: Clone, Input> Node<Input> for SourceNode<T> {
|
||||
type Output = T;
|
||||
|
||||
fn eval(&self, _input: &Input) -> GPoll<T> {
|
||||
GPoll::Final(self.0.clone())
|
||||
}
|
||||
}
|
||||
|
||||
fn element_layout<T: Clone + Send + Sync + 'static>() -> Layout {
|
||||
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 + 'static>(value: T) -> RecordLift<T, SourceNode<T>> {
|
||||
RecordLift::new(SourceNode(value))
|
||||
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 + 'static, N>(graph: N) -> RecordExtract<El, N> {
|
||||
stack::reserve(1 << 12);
|
||||
RecordExtract::new(graph, &element_layout::<El>())
|
||||
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,
|
||||
});
|
||||
RecordExtract::new(graph, &layout)
|
||||
}
|
||||
|
||||
static SLOW_DOUBLE_RUNS: AtomicU32 = AtomicU32::new(0);
|
||||
@@ -317,17 +322,11 @@ mod tests {
|
||||
Ok(Box::pin(async move { value + addend }))
|
||||
}
|
||||
|
||||
struct GatedSource(Arc<std::sync::atomic::AtomicBool>, f64);
|
||||
|
||||
impl<Input> Node<Input> for GatedSource {
|
||||
type Output = f64;
|
||||
|
||||
fn eval(&self, _input: &Input) -> GPoll<f64> {
|
||||
match self.0.load(Ordering::Relaxed) {
|
||||
true => GPoll::Final(self.1),
|
||||
false => GPoll::Pending,
|
||||
}
|
||||
}
|
||||
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> {
|
||||
@@ -336,6 +335,7 @@ mod tests {
|
||||
|
||||
#[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);
|
||||
@@ -351,18 +351,19 @@ mod tests {
|
||||
&element_layout::<u64>(),
|
||||
));
|
||||
|
||||
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
|
||||
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
|
||||
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!(Node::eval(&graph, &ctx), GPoll::Final(42.0));
|
||||
assert_eq!(Node::eval(&graph, &ctx), GPoll::Final(42.0));
|
||||
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);
|
||||
@@ -378,13 +379,14 @@ mod tests {
|
||||
&element_layout::<u64>(),
|
||||
));
|
||||
|
||||
assert_eq!(Node::eval(&graph, &ctx), GPoll::Partial(-1.0));
|
||||
assert_eq!(graph.eval(&ctx, &frames), GPoll::Partial(-1.0));
|
||||
runtime.drain();
|
||||
assert_eq!(Node::eval(&graph, &ctx), GPoll::Final(42.0));
|
||||
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);
|
||||
@@ -400,13 +402,14 @@ mod tests {
|
||||
&element_layout::<u64>(),
|
||||
));
|
||||
|
||||
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
|
||||
assert_eq!(graph.eval(&ctx, &frames), GPoll::Pending);
|
||||
runtime.drain();
|
||||
assert_eq!(Node::eval(&graph, &ctx), GPoll::Final(42.0));
|
||||
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);
|
||||
@@ -422,17 +425,18 @@ mod tests {
|
||||
&element_layout::<u64>(),
|
||||
));
|
||||
|
||||
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
|
||||
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!(Node::eval(&graph, &ctx), GPoll::Pending);
|
||||
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!(Node::eval(&graph, &ctx), GPoll::Final(42.0));
|
||||
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);
|
||||
@@ -442,7 +446,7 @@ mod tests {
|
||||
let runtime = Arc::new(MockRuntime::default());
|
||||
let graph = extract::<f64, _>(StagedSumNode::new(
|
||||
lifted(40.0f64),
|
||||
RecordLift::<f64, _>::new(GatedSource(gate.clone(), 2.0)),
|
||||
gated(gate.clone(), 2.0),
|
||||
lifted(RuntimeHandle(runtime.clone())),
|
||||
lifted(9u64),
|
||||
&element_layout::<f64>(),
|
||||
@@ -451,16 +455,17 @@ mod tests {
|
||||
&element_layout::<u64>(),
|
||||
));
|
||||
|
||||
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
|
||||
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!(Node::eval(&graph, &ctx), GPoll::Pending);
|
||||
assert_eq!(graph.eval(&ctx, &frames), GPoll::Pending);
|
||||
assert_eq!(runtime.drain(), vec![9]);
|
||||
assert_eq!(Node::eval(&graph, &ctx), GPoll::Final(42.0));
|
||||
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);
|
||||
@@ -482,13 +487,14 @@ mod tests {
|
||||
&element_layout::<u64>(),
|
||||
));
|
||||
|
||||
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
|
||||
assert_eq!(graph.eval(&ctx, &frames), GPoll::Pending);
|
||||
runtime.drain();
|
||||
assert_eq!(Node::eval(&graph, &ctx), GPoll::Final(21.5));
|
||||
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);
|
||||
@@ -506,9 +512,9 @@ mod tests {
|
||||
&element_layout::<u64>(),
|
||||
));
|
||||
|
||||
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
|
||||
assert_eq!(graph.eval(&ctx, &frames), GPoll::Pending);
|
||||
runtime.drain();
|
||||
assert_eq!(Node::eval(&graph, &ctx), GPoll::Final(Footprint::DEFAULT.resolution.x));
|
||||
assert_eq!(graph.eval(&ctx, &frames), GPoll::Final(Footprint::DEFAULT.resolution.x));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -607,6 +613,7 @@ mod tests {
|
||||
|
||||
#[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]);
|
||||
@@ -622,7 +629,7 @@ mod tests {
|
||||
let snapshot = runtime.snapshot();
|
||||
let scope = EvalScope::new(None, None, None, &snapshot, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
assert_eq!(Node::eval(&graph, &ctx), GPoll::Final(42.0));
|
||||
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);
|
||||
@@ -630,6 +637,7 @@ mod tests {
|
||||
|
||||
#[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]);
|
||||
@@ -645,7 +653,7 @@ mod tests {
|
||||
let snapshot = runtime.snapshot();
|
||||
let scope = EvalScope::new(None, None, None, &snapshot, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
|
||||
assert_eq!(graph.eval(&ctx, &frames), GPoll::Pending);
|
||||
assert!(!runtime.take_dirty());
|
||||
|
||||
assert_eq!(runtime.spawner().drain(), 1);
|
||||
@@ -655,7 +663,7 @@ mod tests {
|
||||
|
||||
let bumped_scope = EvalScope::new(None, None, None, &bumped, &arena);
|
||||
let bumped_ctx = ContextImpl::root(&bumped_scope);
|
||||
assert_eq!(Node::eval(&graph, &bumped_ctx), GPoll::Final(42.0), "the own-generation-excluded key replays the landed slot");
|
||||
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));
|
||||
|
||||
@@ -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_rules! descriptor {
|
||||
($type:ty) => {
|
||||
$crate::TypeDescriptor {
|
||||
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,
|
||||
size: std::mem::size_of::<$type>(),
|
||||
align: std::mem::align_of::<$type>(),
|
||||
@@ -26,7 +35,7 @@ macro_rules! descriptor {
|
||||
($type:ty, $name:ty) => {
|
||||
$crate::TypeDescriptor {
|
||||
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))),
|
||||
size: std::mem::size_of::<$type>(),
|
||||
align: std::mem::align_of::<$type>(),
|
||||
@@ -60,18 +69,6 @@ macro_rules! future {
|
||||
};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! fn_type {
|
||||
($type:ty) => {
|
||||
$crate::Type::Fn(Box::new(concrete!(())), Box::new(concrete!($type)))
|
||||
};
|
||||
($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_rules! fn_type_fut {
|
||||
($type:ty) => {
|
||||
@@ -192,13 +189,13 @@ pub struct TypeDescriptor {
|
||||
|
||||
impl std::hash::Hash for TypeDescriptor {
|
||||
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 {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -216,7 +213,7 @@ impl PartialEq for TypeDescriptor {
|
||||
_ => {
|
||||
// TODO: Add a flag to disable this warning
|
||||
// warn!("TypeDescriptor::eq: comparing types without ids based on name");
|
||||
self.name == other.name
|
||||
normalize_type_name(&self.name) == normalize_type_name(&other.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -297,7 +294,7 @@ impl Type {
|
||||
pub fn new<T: dyn_any::StaticType + Sized>() -> Self {
|
||||
Self::Concrete(TypeDescriptor {
|
||||
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,
|
||||
size: size_of::<T>(),
|
||||
align: align_of::<T>(),
|
||||
|
||||
@@ -1,18 +1,3 @@
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct ClonedNode<T: Clone>(pub T);
|
||||
|
||||
impl<T: Clone, Input> crate::node::Node<Input> for ClonedNode<T> {
|
||||
type Output = T;
|
||||
|
||||
fn eval(&self, _input: &Input) -> crate::gpoll::GPoll<T> {
|
||||
crate::gpoll::GPoll::Final(self.0.clone())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn value_edge<T: Clone + crate::WasmNotSend + crate::WasmNotSync + 'static>(value: T) -> crate::registry::EdgeHandle {
|
||||
crate::registry::EdgeHandle::new(std::sync::Arc::new(ClonedNode(value)) as std::sync::Arc<crate::registry::ErasedNode<T>>)
|
||||
}
|
||||
|
||||
/// The node behind every value edge: clones its constant onto the record
|
||||
/// wire per evaluation.
|
||||
pub struct ValueSource<T> {
|
||||
@@ -20,7 +5,10 @@ pub struct ValueSource<T> {
|
||||
layout: crate::record::Layout,
|
||||
}
|
||||
|
||||
impl<T: Clone + Send + Sync + 'static> ValueSource<T> {
|
||||
impl<T: Clone + Send + Sync + dyn_any::StaticTypeSized> ValueSource<T>
|
||||
where
|
||||
T::Static: Clone + Send + Sync,
|
||||
{
|
||||
pub fn new(value: T) -> Self {
|
||||
Self {
|
||||
value,
|
||||
@@ -29,15 +17,15 @@ impl<T: Clone + Send + Sync + 'static> ValueSource<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<'e, C, T> crate::node::Node<C> for ValueSource<T>
|
||||
impl<C, T> crate::node::Node<C> for ValueSource<T>
|
||||
where
|
||||
C: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||
T: Clone + Send + Sync + 'static,
|
||||
T: Clone + Send + Sync + dyn_any::StaticTypeSized,
|
||||
{
|
||||
type Output = crate::record::RecordValue<'e>;
|
||||
|
||||
fn eval(&self, input: &C) -> crate::gpoll::GPoll<crate::record::RecordValue<'e>> {
|
||||
crate::record::lift_poll(crate::gpoll::GPoll::Final(self.value.clone()), &self.layout, input.arena())
|
||||
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())
|
||||
}
|
||||
|
||||
fn layout(&self) -> &crate::record::Layout {
|
||||
@@ -46,18 +34,66 @@ where
|
||||
}
|
||||
|
||||
/// The native record edge of a constant.
|
||||
pub fn record_value_edge<T: Clone + Send + Sync + 'static>(value: T) -> crate::registry::EdgeHandle {
|
||||
pub fn record_value_edge<T: Clone + Send + Sync + dyn_any::StaticTypeSized + 'static>(value: T) -> crate::registry::EdgeHandle
|
||||
where
|
||||
T::Static: Clone + Send + Sync,
|
||||
{
|
||||
crate::registry::EdgeHandle::new_record::<T>(std::sync::Arc::new(ValueSource::new(value)) as std::sync::Arc<crate::registry::ErasedRecordNode>)
|
||||
}
|
||||
|
||||
impl<T: Clone> ClonedNode<T> {
|
||||
pub const fn new(value: T) -> ClonedNode<T> {
|
||||
ClonedNode(value)
|
||||
/// The node behind a leveled value edge: 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: Clone> From<T> for ClonedNode<T> {
|
||||
fn from(value: T) -> Self {
|
||||
ClonedNode::new(value)
|
||||
impl<C, T> crate::node::Node<C> for LeveledValueSource<T>
|
||||
where
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
/// The native record edge of a constant level: the edge type is the element's.
|
||||
pub fn leveled_record_value_edge<T: Clone + Send + Sync + crate::CacheHash + PartialEq + dyn_any::StaticTypeSized + 'static>(values: Vec<T>) -> crate::registry::EdgeHandle
|
||||
where
|
||||
T::Static: Clone + Send + Sync,
|
||||
{
|
||||
crate::registry::EdgeHandle::new_record::<T>(std::sync::Arc::new(LeveledValueSource::new(values)) as std::sync::Arc<crate::registry::ErasedRecordNode>)
|
||||
}
|
||||
@@ -12,10 +12,10 @@ use glam::DAffine2;
|
||||
/// enclosing `List<Artboard>`, not as fields here. This keeps `Artboard` a pure type-system boundary
|
||||
/// that prevents arbitrary `List<List<...<Graphic>>>` nesting.
|
||||
#[derive(Clone, Debug, Default, CacheHash, PartialEq, DynAny)]
|
||||
pub struct Artboard(List<Graphic>);
|
||||
pub struct Artboard<'e>(List<Graphic<'e>>);
|
||||
|
||||
impl Artboard {
|
||||
pub fn new(content: List<Graphic>) -> Self {
|
||||
impl<'e> Artboard<'e> {
|
||||
pub fn new(content: List<Graphic<'e>>) -> Self {
|
||||
Self(content)
|
||||
}
|
||||
|
||||
@@ -23,28 +23,115 @@ impl Artboard {
|
||||
&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
|
||||
}
|
||||
|
||||
pub fn into_graphic_list(self) -> List<Graphic> {
|
||||
pub fn into_graphic_list(self) -> List<Graphic<'e>> {
|
||||
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 {
|
||||
fn from(content: List<Graphic>) -> Self {
|
||||
/// The deep copy-out for `Artboard` elements: as for `Graphic`, a plain
|
||||
/// 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> {
|
||||
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);
|
||||
}
|
||||
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)?;
|
||||
}
|
||||
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
|
||||
/// group-free content 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<()> {
|
||||
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
|
||||
// group-free content owns all of itself.
|
||||
let header = unsafe { src.cast::<*const u8>().read() };
|
||||
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));
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Artboard> for List<Graphic> {
|
||||
fn from(artboard: Artboard) -> Self {
|
||||
impl<'e> From<Artboard<'e>> for List<Graphic<'e>> {
|
||||
fn from(artboard: Artboard<'e>) -> Self {
|
||||
artboard.0
|
||||
}
|
||||
}
|
||||
|
||||
impl BoundingBox for Artboard {
|
||||
impl BoundingBox for Artboard<'_> {
|
||||
fn bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
|
||||
self.0.bounding_box(transform, include_stroke)
|
||||
}
|
||||
@@ -54,7 +141,7 @@ impl BoundingBox for Artboard {
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderComplexity for Artboard {
|
||||
impl RenderComplexity for Artboard<'_> {
|
||||
fn render_complexity(&self) -> usize {
|
||||
self.0.render_complexity()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
//! 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::GradientStops;
|
||||
|
||||
/// The outcome of materializing a leveled wire into a group.
|
||||
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::<GradientStops>(&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
@@ -1,5 +1,7 @@
|
||||
pub mod artboard;
|
||||
pub mod boundary;
|
||||
pub mod graphic;
|
||||
pub mod markers;
|
||||
|
||||
// Re-export all transitive dependencies so downstream crates only need to depend on graphic-types
|
||||
pub use core_types;
|
||||
@@ -9,6 +11,7 @@ pub use vector_types;
|
||||
// Re-export commonly used types at the crate root
|
||||
pub use artboard::Artboard;
|
||||
pub use graphic::{Graphic, IntoGraphicList, TryFromGraphic, Vector};
|
||||
pub use markers::{ATTR_EDITOR_MERGED_LAYERS, ATTR_FILL, ATTR_STROKE};
|
||||
|
||||
pub mod migrations {
|
||||
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 {}
|
||||
#[cfg(feature = "std")]
|
||||
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 {}
|
||||
@@ -1,12 +1,14 @@
|
||||
use crate::renderer::{RenderParams, format_transform_matrix, gradient_placement, transform_is_invertible};
|
||||
use crate::{Render, RenderSvgSegmentList, SvgRender};
|
||||
use core_types::Color;
|
||||
use core_types::attribute::Transform;
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::list::List;
|
||||
use core_types::uuid::generate_uuid;
|
||||
use core_types::{ATTR_GRADIENT_TYPE, ATTR_SPREAD_METHOD, ATTR_TRANSFORM, Color};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::Graphic;
|
||||
use graphic_types::vector_types::gradient::GradientType;
|
||||
use graphic_types::vector_types::markers::{GradientType as GradientTypeAttr, SpreadMethod};
|
||||
use graphic_types::vector_types::vector::style::{PaintOrder, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use std::fmt::Write;
|
||||
use vector_types::GradientStops;
|
||||
@@ -50,6 +52,20 @@ pub trait RenderExt {
|
||||
) -> Self::Output;
|
||||
}
|
||||
|
||||
/// The color paint attribute over any color lane source.
|
||||
pub fn render_color_paint<S: core_types::lane::LaneSource<Element = Color>>(source: &S, target: PaintTarget) -> String {
|
||||
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());
|
||||
if color.a() < 1. {
|
||||
let _ = write!(result, r#" {}="{}""#, target.opacity_attr(), (color.a() * 1000.).round() / 1000.);
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
impl RenderExt for List<Color> {
|
||||
type Output = String;
|
||||
|
||||
@@ -63,16 +79,7 @@ impl RenderExt for List<Color> {
|
||||
_render_params: &RenderParams,
|
||||
target: PaintTarget,
|
||||
) -> Self::Output {
|
||||
let Some(color) = self.element(0) else {
|
||||
return format!(r#" {}="none""#, target.paint_attr());
|
||||
};
|
||||
|
||||
let mut result = format!(r##" {}="#{}""##, target.paint_attr(), SRGBA8::from(*color).to_rgb_hex());
|
||||
if color.a() < 1. {
|
||||
let _ = write!(result, r#" {}="{}""#, target.opacity_attr(), (color.a() * 1000.).round() / 1000.);
|
||||
}
|
||||
|
||||
result
|
||||
render_color_paint(self, target)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,12 +97,20 @@ impl RenderExt for List<GradientStops> {
|
||||
_render_params: &RenderParams,
|
||||
_target: PaintTarget,
|
||||
) -> Self::Output {
|
||||
let mut stop = String::new();
|
||||
render_gradient_paint(self, svg_defs, item_transform, element_transform)
|
||||
}
|
||||
}
|
||||
|
||||
let Some(stops) = self.element(0) else { return 0 };
|
||||
let gradient_type: GradientType = self.attribute_cloned_or_default(ATTR_GRADIENT_TYPE, 0);
|
||||
let local_gradient_transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, 0);
|
||||
let spread_method: GradientSpreadMethod = self.attribute_cloned_or_default(ATTR_SPREAD_METHOD, 0);
|
||||
/// 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 = GradientStops>>(source: &S, svg_defs: &mut String, item_transform: DAffine2, element_transform: DAffine2) -> u64 {
|
||||
let mut stop = String::new();
|
||||
|
||||
{
|
||||
let Some(stops) = source.element(0) else { return 0 };
|
||||
let gradient_type: GradientType = source.attr::<GradientTypeAttr>(0);
|
||||
let local_gradient_transform: DAffine2 = source.attr::<Transform>(0);
|
||||
let spread_method: GradientSpreadMethod = source.attr::<SpreadMethod>(0);
|
||||
|
||||
for (position, color, original_midpoint) in stops.interpolated_samples() {
|
||||
stop.push_str("<stop");
|
||||
@@ -219,7 +234,7 @@ impl RenderExt for Stroke {
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderExt for List<Graphic> {
|
||||
impl RenderExt for List<Graphic<'_>> {
|
||||
type Output = String;
|
||||
|
||||
fn render(
|
||||
@@ -236,12 +251,12 @@ impl RenderExt for List<Graphic> {
|
||||
let paint_attr = target.paint_attr();
|
||||
|
||||
match fill_graphic {
|
||||
Some(Graphic::Color(color_list)) => color_list.render(svg_defs, item_transform, element_transform, stroke_transform, bounds, render_params, target),
|
||||
Some(Graphic::Gradient(gradient_list)) => {
|
||||
let gradient_id = gradient_list.render(svg_defs, item_transform, element_transform, stroke_transform, bounds, render_params, target);
|
||||
Some(Graphic::Color(color)) => render_color_paint(&core_types::lane::LeafLane::new(self, 0, color), target),
|
||||
Some(Graphic::Gradient(gradient)) => {
|
||||
let gradient_id = render_gradient_paint(&core_types::lane::LeafLane::new(self, 0, gradient), svg_defs, item_transform, element_transform);
|
||||
format!(r##" {paint_attr}="url(#{gradient_id})""##)
|
||||
}
|
||||
Some(Graphic::Vector(_)) | Some(Graphic::RasterCPU(_)) | Some(Graphic::RasterGPU(_)) | Some(Graphic::Graphic(_)) | Some(Graphic::Text(_)) => {
|
||||
Some(Graphic::Vector(_)) | Some(Graphic::RasterCPU(_)) | Some(Graphic::RasterGPU(_)) | Some(Graphic::Graphic(_)) | Some(Graphic::Text(_)) | Some(Graphic::Group(_)) => {
|
||||
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.
|
||||
let inverse = |len: f64| if len > 0. { 1. / len } else { 0. };
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -38,6 +38,13 @@ impl Default for Resource {
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for &Resource {
|
||||
fn default() -> Self {
|
||||
static EMPTY: std::sync::LazyLock<Resource> = std::sync::LazyLock::new(Resource::empty);
|
||||
std::sync::LazyLock::force(&EMPTY)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&Resource> for Arc<dyn AsRef<[u8]> + Send + Sync> {
|
||||
fn from(val: &Resource) -> Self {
|
||||
val.inner.clone()
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
extern crate log;
|
||||
|
||||
pub mod gradient;
|
||||
pub mod markers;
|
||||
pub mod math;
|
||||
pub mod subpath;
|
||||
pub mod vector;
|
||||
@@ -9,6 +10,7 @@ pub mod vector;
|
||||
// Re-export commonly used types at the crate root
|
||||
pub use core_types as gcore;
|
||||
pub use gradient::{GradientSpreadMethod, GradientStop, GradientStops, GradientType};
|
||||
pub use markers::{ATTR_EDITOR_CLICK_TARGET, ATTR_GRADIENT_TYPE, ATTR_SPREAD_METHOD};
|
||||
pub use math::{QuadExt, RectExt};
|
||||
pub use subpath::Subpath;
|
||||
pub use vector::Vector;
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
//! Attribute markers whose value types live in this crate, with their name
|
||||
//! constants for the string-keyed legacy readers and writers.
|
||||
|
||||
use core_types::attribute::Attribute;
|
||||
|
||||
core_types::attribute! {
|
||||
/// Gradient's spread behavior past its endpoints (`Pad`, `Reflect`, or `Repeat`).
|
||||
pub SpreadMethod("spread_method"): crate::gradient::GradientSpreadMethod;
|
||||
/// Gradient's shape (`Linear` or `Radial`).
|
||||
pub GradientType("gradient_type"): crate::gradient::GradientType;
|
||||
/// Optional `Vector` that overrides the item's own geometry for click-target generation.
|
||||
/// Used by the 'Text' node for per-glyph bounding-box rectangles so glyphs are selectable
|
||||
/// by clicking anywhere within their bounds, not just the filled letterform. An absent
|
||||
/// value means the item's own geometry is the click target.
|
||||
pub EditorClickTarget("editor:click_target"): Option<&crate::Vector>;
|
||||
}
|
||||
|
||||
pub const ATTR_SPREAD_METHOD: &str = SpreadMethod::NAME;
|
||||
pub const ATTR_GRADIENT_TYPE: &str = GradientType::NAME;
|
||||
pub const ATTR_EDITOR_CLICK_TARGET: &str = EditorClickTarget::NAME;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use core_types::attribute::info;
|
||||
use std::any::TypeId;
|
||||
|
||||
#[test]
|
||||
fn the_census_carries_this_crates_names() {
|
||||
assert_eq!(info("gradient_type").unwrap().value_type, TypeId::of::<crate::gradient::GradientType>());
|
||||
assert_eq!(info("spread_method").unwrap().value_type, TypeId::of::<crate::gradient::GradientSpreadMethod>());
|
||||
assert_eq!(info("editor:click_target").unwrap().value_type, TypeId::of::<Option<&'static crate::Vector>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_absent_click_target_defaults_to_none() {
|
||||
assert_eq!(<EditorClickTarget as Attribute>::default(), None);
|
||||
}
|
||||
}
|
||||
@@ -61,7 +61,7 @@ impl std::fmt::Debug for WgpuExecutor {
|
||||
}
|
||||
|
||||
/// Owned Arc handle carrying the executor as an ordinary wire value.
|
||||
#[derive(Clone, Debug)]
|
||||
#[derive(Clone, Debug, dyn_any::DynAny)]
|
||||
pub struct WgpuExecutorHandle(pub std::sync::Arc<WgpuExecutor>);
|
||||
|
||||
impl std::ops::Deref for WgpuExecutorHandle {
|
||||
|
||||
+1440
-634
File diff suppressed because it is too large.
Load diff
@@ -1,53 +1,35 @@
|
||||
use super::*;
|
||||
|
||||
/// How a record node's primary input lowers.
|
||||
/// How a record node's primary input lowers: `None` writes a fresh record,
|
||||
/// `Token` carries the element bytes through as `ElToken`, `Read` reads a
|
||||
/// concrete element at offset 0, and `LazyToken` is a derive-routing carrier
|
||||
/// the kernel evaluates itself, returning the row token it received. The
|
||||
/// element and write set fold from the IR.
|
||||
#[derive(Clone)]
|
||||
pub(crate) enum RecordCarrier {
|
||||
/// `_: ()`: no carrier edge, the kernel writes a fresh record.
|
||||
None,
|
||||
/// An unbounded generic returned in the element position: the element
|
||||
/// bytes carry through the copy plan and the kernel sees `ElToken`.
|
||||
Token(Ident),
|
||||
/// An element type read at offset 0, monomorphized per its
|
||||
/// implementations list where generic.
|
||||
Read(Type),
|
||||
Token,
|
||||
Read,
|
||||
LazyToken,
|
||||
}
|
||||
|
||||
/// The record io of a node fn: how the carrier lowers, the element write,
|
||||
/// and the markers written and removed. Present exactly when the signature
|
||||
/// declares attribute reads or writes in a shape the record tier supports;
|
||||
/// malformed record io is reported by validation and generates no node impl.
|
||||
/// A well-formed record-io node: only the carrier form is retained, so
|
||||
/// [`skips_carrier`] can gate the fresh-record path. Malformed record io yields
|
||||
/// `None` from [`record_shape`] and generates no node impl.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct RecordShape {
|
||||
pub(crate) carrier: RecordCarrier,
|
||||
pub(crate) element_write: Option<Type>,
|
||||
pub(crate) write_markers: Vec<Type>,
|
||||
pub(crate) removes: Vec<Type>,
|
||||
}
|
||||
|
||||
impl RecordShape {
|
||||
pub(crate) fn skips_carrier(&self) -> bool {
|
||||
matches!(self.carrier, RecordCarrier::None)
|
||||
}
|
||||
|
||||
pub(crate) fn carries_element(&self) -> bool {
|
||||
self.element_write.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
/// The record-tier lowering a node fn resolves to. Exactly one class per node,
|
||||
/// computed once by [`analyze`]; every downstream fragment reads the class
|
||||
/// instead of recomputing the classification predicates.
|
||||
pub(crate) enum Class {
|
||||
RecordIo(RecordShape),
|
||||
Routing(RoutingIo),
|
||||
Flip { carrier: bool },
|
||||
Opaque,
|
||||
}
|
||||
|
||||
/// The effect/return axis of a node's kernel, resolved once from the signature.
|
||||
/// Orthogonal to [`Class`]: it selects the eval tail (finish / merge / spawn)
|
||||
/// and the kernel signature wrapping across every class.
|
||||
/// It selects the eval tail (finish / merge / spawn) and the kernel signature
|
||||
/// wrapping across every node kind.
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
pub(crate) enum Dialect {
|
||||
Sync,
|
||||
@@ -71,63 +53,22 @@ pub(crate) fn dialect(parsed: &ParsedNodeFn) -> Dialect {
|
||||
}
|
||||
}
|
||||
|
||||
/// The result of classifying a node fn. A node with no supported lowering
|
||||
/// (an async node with lazy inputs, malformed record io, or a signature no
|
||||
/// class accepts) yields `None` and generates a struct and metadata but no
|
||||
/// `Node` impl.
|
||||
pub(crate) struct NodeModel {
|
||||
pub(crate) class: Class,
|
||||
pub(crate) dialect: Dialect,
|
||||
}
|
||||
|
||||
pub(crate) fn analyze(parsed: &ParsedNodeFn) -> Option<NodeModel> {
|
||||
/// The dialect of a node fn that lowers to a `Node` impl, or `None` when no
|
||||
/// lowering supports the signature (an async node with lazy inputs, malformed
|
||||
/// record io, or a shape no kind accepts). The kind itself is derived from the
|
||||
/// intent IR ([`crate::codegen::ir::node_kind`]); this only gates support.
|
||||
pub(crate) fn analyze(parsed: &ParsedNodeFn) -> Option<Dialect> {
|
||||
if parsed.is_async && parsed.fields.iter().any(|field| matches!(field.ty, ParsedFieldType::Node(_))) {
|
||||
return None;
|
||||
}
|
||||
let class = if let Some(shape) = record_shape(parsed) {
|
||||
Class::RecordIo(shape)
|
||||
let supported = if record_shape(parsed).is_some() {
|
||||
true
|
||||
} else if has_record_io(parsed) {
|
||||
return None;
|
||||
} else if let Some(routing) = routing_io(parsed) {
|
||||
Class::Routing(routing)
|
||||
} else if record_flip(parsed) {
|
||||
Class::Flip { carrier: flip_carrier(parsed) }
|
||||
} else if record_opaque(parsed) {
|
||||
Class::Opaque
|
||||
} else {
|
||||
return None;
|
||||
routing_io(parsed).is_some() || record_flip(parsed) || record_opaque(parsed) || has_materialized_input(parsed)
|
||||
};
|
||||
Some(NodeModel { class, dialect: dialect(parsed) })
|
||||
}
|
||||
|
||||
/// The per-field binding role, resolved once per regular field from the node
|
||||
/// class and field shape. Drives the eval bindings and the lazy-edge input
|
||||
/// types. The `lend` and `reads` axes stay field properties the value arms of
|
||||
/// `kernel_params`/`call_args`/`value_args` consult, since they cross roles.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) enum InputRole {
|
||||
RecordCarrier,
|
||||
FlipCarrier,
|
||||
ReadingSecondary,
|
||||
LendBorrow,
|
||||
RecordValue,
|
||||
PlainValue,
|
||||
DeriveRoutingSource,
|
||||
OpaqueRecordEdge,
|
||||
FlipRawLazyEdge,
|
||||
FlipLazy,
|
||||
RawLazy,
|
||||
Lazy,
|
||||
}
|
||||
|
||||
impl InputRole {
|
||||
/// A role that copies an element out of a record edge, so its record frame
|
||||
/// must be reclaimed after the read. The step lowering wraps such a bind in
|
||||
/// `mark`/`rewind`, making the stack discipline structural rather than
|
||||
/// hand-threaded through each read-out arm.
|
||||
pub(crate) fn reads_out(self) -> bool {
|
||||
matches!(self, InputRole::ReadingSecondary | InputRole::RecordValue)
|
||||
}
|
||||
supported.then(|| dialect(parsed))
|
||||
}
|
||||
|
||||
/// The tail form of a node's eval, selected from its class and dialect: forward
|
||||
@@ -155,28 +96,23 @@ pub(crate) enum EvalStep<'a> {
|
||||
/// or return-tuple writes. Reads on lazy inputs belong to the record lowering
|
||||
/// of the flip class instead.
|
||||
pub(crate) fn has_record_io(parsed: &ParsedNodeFn) -> bool {
|
||||
let value_reads = parsed
|
||||
.fields
|
||||
.iter()
|
||||
.any(|field| !field.attribute_reads.is_empty() && matches!(field.ty, ParsedFieldType::Regular(_)));
|
||||
let value_reads = parsed.fields.iter().any(|field| !field.attribute_reads.is_empty() && matches!(field.ty, ParsedFieldType::Regular(_)));
|
||||
value_reads || record_writes(&slot_value_type(&parsed.output_type)).is_some()
|
||||
}
|
||||
|
||||
pub(crate) fn has_lazy_reads(parsed: &ParsedNodeFn) -> bool {
|
||||
parsed
|
||||
.fields
|
||||
.iter()
|
||||
.any(|field| !field.attribute_reads.is_empty() && matches!(field.ty, ParsedFieldType::Node(_)))
|
||||
parsed.fields.iter().any(|field| !field.attribute_reads.is_empty() && matches!(field.ty, ParsedFieldType::Node(_)))
|
||||
}
|
||||
|
||||
/// The value inputs of a routing node (every regular field that is not a
|
||||
/// routing source), with their indices into the regular fields.
|
||||
pub(crate) fn routing_value_indices(regular_fields: &[&ParsedField], routing: &RoutingIo) -> Vec<usize> {
|
||||
/// The value inputs of a routing node (every regular field that is neither a
|
||||
/// routing source nor a ranked whole-list input), with their indices into the
|
||||
/// regular fields.
|
||||
pub(crate) fn routing_value_indices(regular_fields: &[&ParsedField], generic: &Ident) -> Vec<usize> {
|
||||
regular_fields
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, field)| match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => !matches!(ty, Type::Path(path) if path.path.get_ident() == Some(&routing.generic)),
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, list_levels, .. }) => *list_levels == 0 && !matches!(ty, Type::Path(path) if path.path.get_ident() == Some(generic)),
|
||||
ParsedFieldType::Node(_) => false,
|
||||
})
|
||||
.map(|(index, _)| index)
|
||||
@@ -196,11 +132,11 @@ pub(crate) fn lazy_read_fields<'a>(regular_fields: &[&'a ParsedField]) -> Vec<(u
|
||||
|
||||
/// The indices (into the unit-skipped regular fields) of value inputs whose
|
||||
/// reads resolve against their own wire rather than the carrier's.
|
||||
pub(crate) fn reading_secondary_indices(regular_fields: &[&ParsedField], shape: &RecordShape) -> Vec<usize> {
|
||||
pub(crate) fn reading_secondary_indices(regular_fields: &[&ParsedField], skips_carrier: bool) -> Vec<usize> {
|
||||
regular_fields
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(index, field)| !field.attribute_reads.is_empty() && (shape.skips_carrier() || *index != 0))
|
||||
.filter(|(index, field)| !field.attribute_reads.is_empty() && (skips_carrier || *index != 0))
|
||||
.map(|(index, _)| index)
|
||||
.collect()
|
||||
}
|
||||
@@ -270,18 +206,46 @@ pub(crate) fn substitute_routing_record(output: &Type, generic: &Ident, core_typ
|
||||
ty
|
||||
}
|
||||
|
||||
pub(crate) fn inject_attr_lifetimes(output: &Type) -> Option<Type> {
|
||||
pub(crate) fn inject_attr_lifetimes(output: &Type, lifetime: &str) -> Option<Type> {
|
||||
struct Injector<'a> {
|
||||
changed: bool,
|
||||
lifetime: &'a str,
|
||||
}
|
||||
|
||||
impl VisitMut for Injector<'_> {
|
||||
fn visit_path_segment_mut(&mut self, segment: &mut syn::PathSegment) {
|
||||
if segment.ident == "Attr"
|
||||
&& let PathArguments::AngleBracketed(args) = &mut segment.arguments
|
||||
&& !args.args.iter().any(|arg| matches!(arg, GenericArgument::Lifetime(_)))
|
||||
{
|
||||
args.args.insert(0, GenericArgument::Lifetime(Lifetime::new(self.lifetime, proc_macro2::Span::call_site())));
|
||||
self.changed = true;
|
||||
}
|
||||
syn::visit_mut::visit_path_segment_mut(self, segment);
|
||||
}
|
||||
}
|
||||
|
||||
let mut ty = output.clone();
|
||||
let mut injector = Injector { changed: false, lifetime };
|
||||
injector.visit_type_mut(&mut ty);
|
||||
injector.changed.then_some(ty)
|
||||
}
|
||||
|
||||
/// Binds a `Lane` output to the kernel's subject lifetime, replacing whatever
|
||||
/// the author spelled: the lane borrows the materialized subject, not the arena.
|
||||
pub(crate) fn inject_lane_lifetime(output: &Type) -> Option<Type> {
|
||||
struct Injector {
|
||||
changed: bool,
|
||||
}
|
||||
|
||||
impl VisitMut for Injector {
|
||||
fn visit_path_segment_mut(&mut self, segment: &mut syn::PathSegment) {
|
||||
if segment.ident == "Attr"
|
||||
if segment.ident == "Lane"
|
||||
&& let PathArguments::AngleBracketed(args) = &mut segment.arguments
|
||||
&& !args.args.iter().any(|arg| matches!(arg, GenericArgument::Lifetime(_)))
|
||||
{
|
||||
args.args.insert(0, GenericArgument::Lifetime(Lifetime::new("'__attr", proc_macro2::Span::call_site())));
|
||||
let kept: Vec<GenericArgument> = args.args.iter().filter(|arg| !matches!(arg, GenericArgument::Lifetime(_))).cloned().collect();
|
||||
args.args = kept.into_iter().collect();
|
||||
args.args.insert(0, GenericArgument::Lifetime(Lifetime::new("'__lane", proc_macro2::Span::call_site())));
|
||||
self.changed = true;
|
||||
}
|
||||
syn::visit_mut::visit_path_segment_mut(self, segment);
|
||||
@@ -318,72 +282,106 @@ pub(crate) fn unbounded_generic(parsed: &ParsedNodeFn, ty: &Type) -> Option<Iden
|
||||
}
|
||||
|
||||
pub(crate) fn record_shape(parsed: &ParsedNodeFn) -> Option<RecordShape> {
|
||||
let source = is_async_source(parsed);
|
||||
let value = match kernel_kind(&parsed.output_type) {
|
||||
KernelKind::Plain => parsed.output_type.clone(),
|
||||
KernelKind::Interrupt(inner) => inner,
|
||||
_ if source => slot_value_type(&parsed.output_type),
|
||||
_ => return None,
|
||||
};
|
||||
let writes = record_writes(&value);
|
||||
let has_reads = parsed
|
||||
.fields
|
||||
.iter()
|
||||
.any(|field| !field.attribute_reads.is_empty() && matches!(field.ty, ParsedFieldType::Regular(_)));
|
||||
let has_reads = parsed.fields.iter().any(|field| !field.attribute_reads.is_empty() && matches!(field.ty, ParsedFieldType::Regular(_)));
|
||||
if !has_reads && writes.is_none() {
|
||||
return None;
|
||||
}
|
||||
if parsed.is_async || parsed.fields.iter().any(|field| matches!(field.ty, ParsedFieldType::Node(_))) {
|
||||
return None;
|
||||
}
|
||||
let reads_well_placed = parsed.fields.iter().all(|field| {
|
||||
field.attribute_reads.is_empty() || (!field.is_data_field && matches!(&field.ty, ParsedFieldType::Regular(RegularParsedField { lend: None, .. })))
|
||||
});
|
||||
if !reads_well_placed {
|
||||
// An async source's slot stores the kernel's plain tuple; the per-eval lift
|
||||
// writes it through the claim, and the reads have no wire to bind against.
|
||||
if source && (has_reads || writes.is_none()) {
|
||||
return None;
|
||||
}
|
||||
let carrier_field = parsed.fields.first()?;
|
||||
if carrier_field.is_data_field {
|
||||
return None;
|
||||
}
|
||||
// A first-field lazy carrier: the kernel evaluates the derived content
|
||||
// itself and returns its opaque row token beside the write set.
|
||||
let lazy_carrier = matches!(&carrier_field.ty, ParsedFieldType::Node(_));
|
||||
// Lazy secondaries are consumed as plain elements; raw record edges and
|
||||
// ranked outputs have no element binding here.
|
||||
let unsupported_lazy_secondary = |field: &ParsedField| match &field.ty {
|
||||
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => is_served(output_type) || crate::codegen::ir::strip_ilist(output_type).1 > 0 || !field.attribute_reads.is_empty(),
|
||||
ParsedFieldType::Regular(_) => false,
|
||||
};
|
||||
if parsed.fields.iter().skip(lazy_carrier as usize).any(|field| unsupported_lazy_secondary(field)) {
|
||||
return None;
|
||||
}
|
||||
let reads_well_placed = parsed.fields.iter().enumerate().all(|(index, field)| {
|
||||
field.attribute_reads.is_empty() || (lazy_carrier && index == 0) || (!field.is_data_field && matches!(&field.ty, ParsedFieldType::Regular(RegularParsedField { lend: None, .. })))
|
||||
});
|
||||
if !reads_well_placed {
|
||||
return None;
|
||||
}
|
||||
if lazy_carrier {
|
||||
let ParsedFieldType::Node(NodeParsedField { output_type, .. }) = &carrier_field.ty else {
|
||||
unreachable!("guarded by the lazy_carrier match");
|
||||
};
|
||||
let token = unbounded_generic(parsed, output_type)?;
|
||||
let element = match writes {
|
||||
Some(RecordWrites { element, .. }) => element,
|
||||
None => value,
|
||||
};
|
||||
if !matches!(bare_ident(&element), Some(ident) if ident == &token) {
|
||||
return None;
|
||||
}
|
||||
return Some(RecordShape { carrier: RecordCarrier::LazyToken });
|
||||
}
|
||||
let ParsedFieldType::Regular(RegularParsedField { ty, lend: None, implementations, .. }) = &carrier_field.ty else {
|
||||
return None;
|
||||
};
|
||||
let carrier = match ty {
|
||||
Type::Tuple(tuple) if tuple.elems.is_empty() => RecordCarrier::None,
|
||||
// A gathered subject is never read as an element, so its generic stays open.
|
||||
let gathers = crate::codegen::ir::gathers_lane(parsed);
|
||||
let token = match ty {
|
||||
Type::Tuple(tuple) if tuple.elems.is_empty() => None,
|
||||
ty => match implementations.is_empty().then(|| unbounded_generic(parsed, ty)).flatten() {
|
||||
Some(token) => RecordCarrier::Token(token),
|
||||
Some(token) => Some(token),
|
||||
None => {
|
||||
if contains_open_generic(parsed, ty) {
|
||||
if !gathers && contains_open_generic(parsed, ty) {
|
||||
return None;
|
||||
}
|
||||
RecordCarrier::Read(ty.clone())
|
||||
None
|
||||
}
|
||||
},
|
||||
};
|
||||
let (element, write_markers, removes) = match writes {
|
||||
let carrier = match ty {
|
||||
Type::Tuple(tuple) if tuple.elems.is_empty() => RecordCarrier::None,
|
||||
_ if token.is_some() => RecordCarrier::Token,
|
||||
_ => RecordCarrier::Read,
|
||||
};
|
||||
let (element, _, removes) = match writes {
|
||||
Some(RecordWrites { element, markers, removes }) => (element, markers, removes),
|
||||
None => (value, Vec::new(), Vec::new()),
|
||||
};
|
||||
let element_write = match &carrier {
|
||||
RecordCarrier::Token(token) => match bare_ident(&element) {
|
||||
Some(ident) if ident == token => None,
|
||||
_ => return None,
|
||||
},
|
||||
_ => {
|
||||
if contains_open_generic(parsed, &element) {
|
||||
match &token {
|
||||
Some(token) => {
|
||||
if !matches!(bare_ident(&element), Some(ident) if ident == token) {
|
||||
return None;
|
||||
}
|
||||
Some(element)
|
||||
}
|
||||
};
|
||||
None => {
|
||||
if !gathers && contains_open_generic(parsed, &element) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
if matches!(carrier, RecordCarrier::None) && !removes.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(RecordShape {
|
||||
carrier,
|
||||
element_write,
|
||||
write_markers,
|
||||
removes,
|
||||
})
|
||||
// The byte-carried token never becomes a value, so it cannot cross a
|
||||
// future boundary.
|
||||
if source && matches!(carrier, RecordCarrier::Token) {
|
||||
return None;
|
||||
}
|
||||
Some(RecordShape { carrier })
|
||||
}
|
||||
|
||||
pub(crate) fn is_poll_kernel(output: &Type) -> bool {
|
||||
@@ -429,8 +427,15 @@ pub(crate) fn flip_carrier(parsed: &ParsedNodeFn) -> bool {
|
||||
/// fully-concrete value-input nodes in this cut; batch, shader, async, lend,
|
||||
/// lazy, and generic nodes keep the plain lowering until their record forms
|
||||
/// land.
|
||||
pub(crate) fn has_materialized_input(parsed: &ParsedNodeFn) -> bool {
|
||||
parsed
|
||||
.fields
|
||||
.iter()
|
||||
.any(|field| matches!(&field.ty, ParsedFieldType::Regular(RegularParsedField { list_levels, .. }) if *list_levels > 0))
|
||||
}
|
||||
|
||||
pub(crate) fn record_flip(parsed: &ParsedNodeFn) -> bool {
|
||||
if record_shape(parsed).is_some() || has_record_io(parsed) || routing_io(parsed).is_some() {
|
||||
if record_shape(parsed).is_some() || has_record_io(parsed) || routing_io(parsed).is_some() || record_opaque(parsed) {
|
||||
return false;
|
||||
}
|
||||
// Shader nodes flip like any value node: the kernel doubles as the
|
||||
@@ -462,7 +467,10 @@ pub(crate) fn record_flip(parsed: &ParsedNodeFn) -> bool {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
GenericParam::Lifetime(_) | GenericParam::Const(_) => return false,
|
||||
// A named lifetime is the serving lifetime: wire types substitute
|
||||
// its erased projection in registry and layout contexts.
|
||||
GenericParam::Lifetime(_) => {}
|
||||
GenericParam::Const(_) => return false,
|
||||
}
|
||||
}
|
||||
true
|
||||
@@ -505,15 +513,17 @@ pub(crate) fn generic_assignment(field_ty: &Type, row_ty: &Type, generic: &Ident
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn is_record_value(ty: &Type) -> bool {
|
||||
matches!(ty, Type::Path(path) if path.path.segments.last().is_some_and(|segment| segment.ident == "RecordValue"))
|
||||
/// A whole-record position: the served proof a record-opaque kernel hands
|
||||
/// back, or the subject it receives without naming an element.
|
||||
pub(crate) fn is_served(ty: &Type) -> bool {
|
||||
matches!(ty, Type::Path(path) if path.path.segments.last().is_some_and(|segment| segment.ident == "Served"))
|
||||
}
|
||||
|
||||
/// Whether a kernel operates on whole records: it names `RecordValue` in its
|
||||
/// output, receives raw record edges paired with the node's layout, and
|
||||
/// Whether a kernel operates on whole records: it serves through the claim it
|
||||
/// was handed, receives raw record edges paired with the node's layout, and
|
||||
/// takes on the record APIs' unsafe contracts itself.
|
||||
pub(crate) fn record_opaque(parsed: &ParsedNodeFn) -> bool {
|
||||
is_record_value(&slot_value_type(&parsed.output_type))
|
||||
is_served(&slot_value_type(&parsed.output_type))
|
||||
}
|
||||
|
||||
pub(crate) fn routing_io(parsed: &ParsedNodeFn) -> Option<RoutingIo> {
|
||||
@@ -544,7 +554,7 @@ pub(crate) fn routing_io(parsed: &ParsedNodeFn) -> Option<RoutingIo> {
|
||||
input_type,
|
||||
implementations,
|
||||
}) => {
|
||||
if bare_ident(output_type) == Some(&ident) {
|
||||
if routing_source_output(output_type, &ident) {
|
||||
// A source forwards its whole record opaquely; declared
|
||||
// reads contradict that and are rejected by validation.
|
||||
if !implementations.is_empty() || type_contains_ident(input_type, &ident) || !field.attribute_reads.is_empty() {
|
||||
@@ -575,6 +585,13 @@ pub(crate) fn bare_ident(ty: &Type) -> Option<&Ident> {
|
||||
path.path.get_ident()
|
||||
}
|
||||
|
||||
/// Whether a lazy input's declared output is the routing generic, at any
|
||||
/// `IList` nesting: the nesting is rank depth, not a distinct row type.
|
||||
pub(crate) fn routing_source_output(output_type: &Type, generic: &Ident) -> bool {
|
||||
let (stripped, _) = crate::codegen::ir::strip_ilist(output_type);
|
||||
bare_ident(&stripped) == Some(generic)
|
||||
}
|
||||
|
||||
pub(crate) fn tokens_contain_ident(tokens: TokenStream2, ident: &Ident) -> bool {
|
||||
tokens.into_iter().any(|token| match token {
|
||||
proc_macro2::TokenTree::Ident(candidate) => &candidate == ident,
|
||||
@@ -598,6 +615,24 @@ pub(crate) fn is_source_kernel(output: &Type) -> bool {
|
||||
matches!(kernel_kind(output), KernelKind::Future(_) | KernelKind::FutureInterrupt(_))
|
||||
}
|
||||
|
||||
/// A kernel whose value completes off the evaluation: an `async fn` or a
|
||||
/// `SourceFuture` return. Its slot persists a plain value across evaluations,
|
||||
/// so nothing it returns may borrow the arena.
|
||||
pub(crate) fn is_async_source(parsed: &ParsedNodeFn) -> bool {
|
||||
parsed.is_async || is_source_kernel(&parsed.output_type)
|
||||
}
|
||||
|
||||
/// The type an async source's slot persists. A writing source's value outlives
|
||||
/// the evaluation, so every lifetime it names, including a bare `Attr<M>`'s
|
||||
/// elided one, is `'static`.
|
||||
pub(crate) fn slot_static_type(output: &Type) -> Type {
|
||||
let value = slot_value_type(output);
|
||||
match record_writes(&value).is_some() {
|
||||
true => substitute_lifetimes(&inject_attr_lifetimes(&value, "'static").unwrap_or_else(|| value.clone()), "'static"),
|
||||
false => value,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) enum KernelKind {
|
||||
Plain,
|
||||
Interrupt(Type),
|
||||
@@ -681,10 +716,6 @@ pub(crate) fn type_disqualifies(ty: &Type) -> bool {
|
||||
fn visit_type_impl_trait(&mut self, _: &'ast syn::TypeImplTrait) {
|
||||
self.found = true;
|
||||
}
|
||||
|
||||
fn visit_lifetime(&mut self, _: &'ast Lifetime) {
|
||||
self.found = true;
|
||||
}
|
||||
}
|
||||
|
||||
let mut visitor = Disqualifier { found: false };
|
||||
@@ -692,6 +723,54 @@ pub(crate) fn type_disqualifies(ty: &Type) -> bool {
|
||||
visitor.found
|
||||
}
|
||||
|
||||
/// The wire type with every named serving lifetime replaced: `'static` for
|
||||
/// registry, layout, and declaration contexts (the erased projection shares
|
||||
/// its type id and layout), `'_` for eval bindings, where inference recovers
|
||||
/// the serving lifetime.
|
||||
pub(crate) fn substitute_lifetimes(ty: &Type, replacement: &str) -> Type {
|
||||
struct Subst {
|
||||
replacement: &'static str,
|
||||
}
|
||||
|
||||
impl VisitMut for Subst {
|
||||
fn visit_lifetime_mut(&mut self, lifetime: &mut Lifetime) {
|
||||
if lifetime.ident != "static" {
|
||||
*lifetime = Lifetime::new(self.replacement, lifetime.span());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let replacement = match replacement {
|
||||
"'static" => "'static",
|
||||
_ => "'_",
|
||||
};
|
||||
let mut ty = ty.clone();
|
||||
Subst { replacement }.visit_type_mut(&mut ty);
|
||||
ty
|
||||
}
|
||||
|
||||
/// The serving lifetime a wire type names, so a materialized binding can tie
|
||||
/// the list view to the element's own region.
|
||||
pub(crate) fn named_serving_lifetime(ty: &Type) -> Option<Lifetime> {
|
||||
struct Find {
|
||||
found: Option<Lifetime>,
|
||||
}
|
||||
|
||||
impl<'ast> Visit<'ast> for Find {
|
||||
fn visit_lifetime(&mut self, lifetime: &'ast Lifetime) {
|
||||
if self.found.is_none() && lifetime.ident != "static" {
|
||||
self.found = Some(lifetime.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut visitor = Find { found: None };
|
||||
visitor.visit_type(ty);
|
||||
visitor.found
|
||||
}
|
||||
|
||||
/// Rewrites a kernel-declared `ExtractArena<'e>` bound into the equality the
|
||||
/// trait names.
|
||||
pub(crate) fn desugar_extract_lifetime(bound: &TypeParamBound, core_types: &TokenStream2) -> TokenStream2 {
|
||||
let TypeParamBound::Trait(trait_bound) = bound else {
|
||||
return quote!(#bound);
|
||||
@@ -713,3 +792,15 @@ pub(crate) fn desugar_extract_lifetime(bound: &TypeParamBound, core_types: &Toke
|
||||
};
|
||||
quote!(#core_types::context::ExtractArena<ArenaRef = &#lifetime #core_types::arena::Arena>)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod lifetime_subst_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn named_lifetimes_erase_to_static() {
|
||||
let ty: Type = syn::parse_quote!(Graphic<'e>);
|
||||
let erased = substitute_lifetimes(&ty, "'static");
|
||||
assert_eq!(quote::quote!(#erased).to_string(), "Graphic < 'static >");
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,17 @@
|
||||
use super::*;
|
||||
use proc_macro_error2::emit_error;
|
||||
use proc_macro2::TokenStream as TokenStream2;
|
||||
use quote::{format_ident, quote};
|
||||
use syn::spanned::Spanned;
|
||||
use syn::{GenericParam, Ident, Type};
|
||||
|
||||
pub(crate) fn entries_tokens(parsed: &ParsedNodeFn, class: &Class, struct_name: &Ident, data_field_generic_idents: &[Ident], regular_fields: &[&ParsedField]) -> TokenStream2 {
|
||||
pub(crate) fn entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, data_field_generic_idents: &[Ident], regular_fields: &[&ParsedField]) -> TokenStream2 {
|
||||
if !data_field_generic_idents.is_empty() {
|
||||
return quote!();
|
||||
}
|
||||
match class {
|
||||
Class::RecordIo(_) => record_entries_tokens(parsed, struct_name, regular_fields),
|
||||
Class::Routing(_) => routing_entries_tokens(parsed, struct_name, regular_fields),
|
||||
Class::Flip { .. } => flip_entries_tokens(parsed, struct_name, regular_fields),
|
||||
Class::Opaque => record_opaque_entries_tokens(parsed, struct_name, regular_fields),
|
||||
match crate::codegen::ir::node_kind(&crate::codegen::ir::build(parsed)) {
|
||||
crate::codegen::ir::NodeKind::Flip => flip_entries_tokens(parsed, struct_name, regular_fields),
|
||||
_ => single_row_entries(parsed, struct_name, regular_fields),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ fn flip_entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, regular_field
|
||||
if rows.is_empty() {
|
||||
return quote!();
|
||||
}
|
||||
let output = slot_value_type(&parsed.output_type);
|
||||
let output = substitute_lifetimes(&slot_value_type(&parsed.output_type), "'static");
|
||||
|
||||
let field_type = |field: &ParsedField| match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => ty.clone(),
|
||||
@@ -56,7 +56,8 @@ fn flip_entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, regular_field
|
||||
let arity = regular_fields.len();
|
||||
let names: Vec<&Ident> = regular_fields.iter().map(|field| &field.pat_ident.ident).collect();
|
||||
let node_underscores: Vec<TokenStream2> = regular_fields.iter().map(|_| quote!(_)).collect();
|
||||
let carrier_present = flip_carrier(parsed);
|
||||
let node = crate::codegen::ir::build(parsed);
|
||||
let core_types = quote!(gcore);
|
||||
|
||||
// Shorthand associated types in the output only resolve against the
|
||||
// generics' bounds, so rows name the output through a bounded alias. Only
|
||||
@@ -112,6 +113,8 @@ fn flip_entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, regular_field
|
||||
.iter()
|
||||
.map(|(generic, index)| generic_assignment(&field_type(regular_fields[*index]), &row[*index], generic).map(|assigned| (generic.clone(), assigned)))
|
||||
.collect::<Option<_>>()?;
|
||||
let row: Vec<Type> = row.iter().map(|ty| substitute_lifetimes(ty, "'static")).collect();
|
||||
let assignments: Vec<(Ident, Type)> = assignments.into_iter().map(|(generic, ty)| (generic, substitute_lifetimes(&ty, "'static"))).collect();
|
||||
if type_disqualifies(&substitute_ident_types(&output, &assignments)) {
|
||||
return None;
|
||||
}
|
||||
@@ -133,9 +136,7 @@ fn flip_entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, regular_field
|
||||
let layout = format_ident!("__layout_{index}");
|
||||
quote! {
|
||||
let #handle = inputs.next().unwrap();
|
||||
let Some(#layout) = #handle.layout().cloned() else {
|
||||
return Err(gcore::registry::ConstructionError::MissingLayout);
|
||||
};
|
||||
let #layout = #handle.layout().clone();
|
||||
let #name = #handle.downcast_record::<#ty>()?;
|
||||
}
|
||||
});
|
||||
@@ -143,15 +144,11 @@ fn flip_entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, regular_field
|
||||
let layout = format_ident!("__layout_{index}");
|
||||
quote!(&#layout,)
|
||||
});
|
||||
let element_spec = quote!(gcore::record::ElementSpec::Concrete({ use gcore::record::{ElementWritePickHashed as _, ElementWritePickPlain as _}; (&gcore::record::ElementWritePick::<#row_output>(::core::marker::PhantomData)).element_write() }));
|
||||
let layout_meta = crate::codegen::ir::layout_meta_tokens(&node, element_spec, &core_types);
|
||||
Some(quote! {
|
||||
gcore::registry::RegistryEntry {
|
||||
layout_meta: Some(gcore::record::LayoutMeta {
|
||||
carrier: #carrier_present,
|
||||
element: gcore::record::ElementSpec::Concrete(gcore::record::element_write::<#row_output>()),
|
||||
writes: ::std::vec::Vec::new(),
|
||||
removes: ::std::vec::Vec::new(),
|
||||
level_delta: 0,
|
||||
}),
|
||||
layout_meta: Some(#layout_meta),
|
||||
io: gcore::registry::NodeIOTypes::new(
|
||||
gcore::concrete!(gcore::context::ContextImpl<'static>),
|
||||
gcore::registry::record_type::<#row_output>(),
|
||||
@@ -182,323 +179,307 @@ fn flip_entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, regular_field
|
||||
}
|
||||
}
|
||||
|
||||
/// The registry row of a routing node: one instance covers every element,
|
||||
/// sources claim generic record edges, and the constructor wraps each source
|
||||
/// in its union translation and stores the union as the node's layout.
|
||||
fn routing_entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields: &[&ParsedField]) -> TokenStream2 {
|
||||
let Some(routing) = routing_io(parsed) else {
|
||||
return quote!();
|
||||
};
|
||||
let is_source = |field: &ParsedField| {
|
||||
let ty = match &field.ty {
|
||||
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => output_type,
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => ty,
|
||||
};
|
||||
matches!(ty, Type::Path(path) if path.path.get_ident() == Some(&routing.generic))
|
||||
};
|
||||
let values_concrete = regular_fields.iter().filter(|field| !is_source(field)).all(|field| {
|
||||
let (ty, lend) = match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, lend, .. }) => (ty, lend.is_some()),
|
||||
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => (output_type, false),
|
||||
};
|
||||
!contains_open_generic(parsed, ty) && (lend || !type_disqualifies(ty))
|
||||
});
|
||||
if !values_concrete {
|
||||
return quote!();
|
||||
/// Which record wire an input claims and how its value is recovered. Base slots
|
||||
/// are the record edges whose layouts form the output; value slots are record
|
||||
/// edges read for their layout.
|
||||
enum SlotKind {
|
||||
/// A generic record edge whose element is only known at runtime; the runtime
|
||||
/// type is captured for the output wrap or the union.
|
||||
BaseGeneric(String),
|
||||
/// A concrete record carrier read for its layout.
|
||||
BaseConcrete(Type),
|
||||
/// A concrete record edge read for its layout only.
|
||||
Value(Type),
|
||||
/// A record edge whose element extracts to the node's plain value input.
|
||||
Extracted(Type),
|
||||
/// A ranked record edge consumed whole; no layout rides to the constructor.
|
||||
Ranked(Type),
|
||||
}
|
||||
|
||||
impl SlotKind {
|
||||
fn is_base(&self) -> bool {
|
||||
matches!(self, SlotKind::BaseGeneric(_) | SlotKind::BaseConcrete(_))
|
||||
}
|
||||
}
|
||||
|
||||
/// The single registry row shared by record-io, routing, and opaque nodes: one
|
||||
/// instance covers the wire, each input's edge type and downcast follow its
|
||||
/// slot, and the output layout folds from the base slots.
|
||||
fn single_row_entries(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields: &[&ParsedField]) -> TokenStream2 {
|
||||
use crate::codegen::ir;
|
||||
let fn_name = &parsed.fn_name;
|
||||
let entries_name = format_ident!("{}_entries", fn_name);
|
||||
let arity = regular_fields.len();
|
||||
let names: Vec<&Ident> = regular_fields.iter().map(|field| &field.pat_ident.ident).collect();
|
||||
let token_name = routing.generic.to_string();
|
||||
let node = ir::build(parsed);
|
||||
let core_types = quote!(gcore);
|
||||
let lend = |field: &ParsedField| matches!(&field.ty, ParsedFieldType::Regular(RegularParsedField { lend: Some(_), .. }));
|
||||
|
||||
let input_types = regular_fields.iter().map(|field| {
|
||||
if is_source(field) {
|
||||
return quote!(gcore::registry::generic_record_edge_type(#token_name));
|
||||
}
|
||||
match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => quote!(gcore::registry::record_edge_type::<#ty>()),
|
||||
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => quote!(gcore::registry::edge_type::<#output_type>()),
|
||||
}
|
||||
});
|
||||
let source_layouts: Vec<Ident> = regular_fields
|
||||
// A subject is its record edge (concrete carrier or erased generic); a
|
||||
// non-subject value rides a record edge when it reads its layout.
|
||||
let slots: Option<Vec<SlotKind>> = regular_fields
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, field)| is_source(field))
|
||||
.map(|(index, _)| format_ident!("__layout_{index}"))
|
||||
.collect();
|
||||
let downcasts = regular_fields.iter().enumerate().map(|(index, field)| {
|
||||
let name = &field.pat_ident.ident;
|
||||
if is_source(field) {
|
||||
let layout = format_ident!("__layout_{index}");
|
||||
let handle = format_ident!("__handle_{index}");
|
||||
let ty = format_ident!("__ty_{index}");
|
||||
return quote! {
|
||||
let #handle = inputs.next().unwrap();
|
||||
let #ty = #handle.ty().clone();
|
||||
let Some(#layout) = #handle.layout().cloned() else {
|
||||
return Err(gcore::registry::ConstructionError::MissingLayout);
|
||||
};
|
||||
let #name = #handle.downcast_erased::<gcore::registry::ErasedRecordNode>(#ty.clone())?;
|
||||
};
|
||||
}
|
||||
match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => {
|
||||
let handle = format_ident!("__handle_{index}");
|
||||
let layout = format_ident!("__in_layout_{index}");
|
||||
quote! {
|
||||
let #handle = inputs.next().unwrap();
|
||||
let Some(#layout) = #handle.layout().cloned() else {
|
||||
return Err(gcore::registry::ConstructionError::MissingLayout);
|
||||
};
|
||||
let #name = #handle.downcast_record::<#ty>()?;
|
||||
}
|
||||
.map(|(index, field)| {
|
||||
let input = &node.inputs[index];
|
||||
if input.subject {
|
||||
return Some(match &input.shape.element {
|
||||
ir::Element::Concrete(ty) => SlotKind::BaseConcrete(ty.clone()),
|
||||
ir::Element::Generic(ident) => SlotKind::BaseGeneric(ident.to_string()),
|
||||
ir::Element::Opaque => SlotKind::BaseGeneric("T".to_string()),
|
||||
});
|
||||
}
|
||||
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => quote!(let #name = inputs.next().unwrap().downcast::<#output_type>()?;),
|
||||
}
|
||||
});
|
||||
let value_layout_args = regular_fields
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, field)| !is_source(field) && matches!(field.ty, ParsedFieldType::Regular(_)))
|
||||
.map(|(index, _)| {
|
||||
let layout = format_ident!("__in_layout_{index}");
|
||||
quote!(&#layout,)
|
||||
});
|
||||
let source_wraps = regular_fields.iter().enumerate().filter(|(_, field)| is_source(field)).map(|(index, field)| {
|
||||
let name = &field.pat_ident.ident;
|
||||
let layout = format_ident!("__layout_{index}");
|
||||
quote!(let #name = gcore::record::RecordSource::new(#name, &#layout, &__union);)
|
||||
});
|
||||
let first_source_ty = regular_fields
|
||||
.iter()
|
||||
.enumerate()
|
||||
.find(|(_, field)| is_source(field))
|
||||
.map(|(index, _)| format_ident!("__ty_{index}"))
|
||||
.expect("routing nodes have a source");
|
||||
|
||||
quote! {
|
||||
pub fn #entries_name() -> ::std::vec::Vec<gcore::registry::RegistryEntry> {
|
||||
vec![gcore::registry::RegistryEntry {
|
||||
layout_meta: None,
|
||||
io: gcore::registry::NodeIOTypes::new(
|
||||
gcore::concrete!(gcore::context::ContextImpl<'static>),
|
||||
gcore::Type::Record(Box::new(gcore::Type::Generic(::std::borrow::Cow::Borrowed(#token_name)))),
|
||||
vec![#(#input_types),*],
|
||||
),
|
||||
constructor: |inputs| {
|
||||
if inputs.len() != #arity {
|
||||
return Err(gcore::registry::ConstructionError::Arity { expected: #arity, got: inputs.len() });
|
||||
}
|
||||
let mut inputs = inputs.into_iter();
|
||||
#(#downcasts)*
|
||||
let __union = gcore::record::Layout::union(&[#(&#source_layouts),*]);
|
||||
#(#source_wraps)*
|
||||
let __node = #struct_name::new(#(#names,)* &__union, #(#value_layout_args)*);
|
||||
Ok(gcore::registry::EdgeHandle::new_erased(
|
||||
::std::sync::Arc::new(__node) as ::std::sync::Arc<gcore::registry::ErasedRecordNode>,
|
||||
#first_source_ty,
|
||||
))
|
||||
},
|
||||
}]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn record_opaque_entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields: &[&ParsedField]) -> TokenStream2 {
|
||||
let is_record = |field: &ParsedField| matches!(&field.ty, ParsedFieldType::Node(NodeParsedField { output_type, .. }) if is_record_value(output_type));
|
||||
let values_concrete = regular_fields.iter().filter(|field| !is_record(field)).all(|field| {
|
||||
let (ty, lend) = match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, lend, .. }) => (ty, lend.is_some()),
|
||||
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => (output_type, false),
|
||||
};
|
||||
!contains_open_generic(parsed, ty) && (lend || !type_disqualifies(ty))
|
||||
});
|
||||
if !values_concrete {
|
||||
return quote!();
|
||||
}
|
||||
|
||||
let fn_name = &parsed.fn_name;
|
||||
let entries_name = format_ident!("{}_entries", fn_name);
|
||||
let arity = regular_fields.len();
|
||||
let names: Vec<&Ident> = regular_fields.iter().map(|field| &field.pat_ident.ident).collect();
|
||||
|
||||
let input_types = regular_fields.iter().map(|field| {
|
||||
if is_record(field) {
|
||||
return quote!(gcore::registry::generic_record_edge_type("T"));
|
||||
}
|
||||
match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, lend: Some(_), .. }) => quote!(gcore::registry::edge_type::<#ty>()),
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => quote!(gcore::registry::edge_type::<#ty>()),
|
||||
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => quote!(gcore::registry::edge_type::<#output_type>()),
|
||||
}
|
||||
});
|
||||
let downcasts = regular_fields.iter().enumerate().map(|(index, field)| {
|
||||
let name = &field.pat_ident.ident;
|
||||
if is_record(field) {
|
||||
let layout = format_ident!("__layout_{index}");
|
||||
let handle = format_ident!("__handle_{index}");
|
||||
let ty = format_ident!("__ty_{index}");
|
||||
return quote! {
|
||||
let #handle = inputs.next().unwrap();
|
||||
let #ty = #handle.ty().clone();
|
||||
let Some(#layout) = #handle.layout().cloned() else {
|
||||
return Err(gcore::registry::ConstructionError::MissingLayout);
|
||||
};
|
||||
let #name = #handle.downcast_erased::<gcore::registry::ErasedRecordNode>(#ty.clone())?;
|
||||
};
|
||||
}
|
||||
match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, lend: Some(_), .. }) => quote!(let #name = inputs.next().unwrap().downcast::<#ty>()?;),
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => quote!(let #name = inputs.next().unwrap().downcast::<#ty>()?;),
|
||||
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => quote!(let #name = inputs.next().unwrap().downcast::<#output_type>()?;),
|
||||
}
|
||||
});
|
||||
let first_record = regular_fields.iter().position(|field| is_record(field)).expect("record-opaque nodes have a record input");
|
||||
let record_layout = format_ident!("__layout_{first_record}");
|
||||
let record_ty = format_ident!("__ty_{first_record}");
|
||||
|
||||
quote! {
|
||||
pub fn #entries_name() -> ::std::vec::Vec<gcore::registry::RegistryEntry> {
|
||||
vec![gcore::registry::RegistryEntry {
|
||||
layout_meta: None,
|
||||
io: gcore::registry::NodeIOTypes::new(
|
||||
gcore::concrete!(gcore::context::ContextImpl<'static>),
|
||||
gcore::Type::Record(Box::new(gcore::Type::Generic(::std::borrow::Cow::Borrowed("T")))),
|
||||
vec![#(#input_types),*],
|
||||
),
|
||||
constructor: |inputs| {
|
||||
if inputs.len() != #arity {
|
||||
return Err(gcore::registry::ConstructionError::Arity { expected: #arity, got: inputs.len() });
|
||||
}
|
||||
let mut inputs = inputs.into_iter();
|
||||
#(#downcasts)*
|
||||
let __node = #struct_name::new(#(#names,)* &#record_layout);
|
||||
Ok(gcore::registry::EdgeHandle::new_erased(
|
||||
::std::sync::Arc::new(__node) as ::std::sync::Arc<gcore::registry::ErasedRecordNode>,
|
||||
#record_ty,
|
||||
))
|
||||
},
|
||||
}]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn record_entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields: &[&ParsedField]) -> TokenStream2 {
|
||||
let Some(shape) = record_shape(parsed) else {
|
||||
return quote!();
|
||||
};
|
||||
let carrier_in_fields = !shape.skips_carrier();
|
||||
let values_concrete = regular_fields.iter().skip(carrier_in_fields as usize).all(|field| match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, lend, .. }) => !contains_open_generic(parsed, ty) && (lend.is_some() || !type_disqualifies(ty)),
|
||||
_ => false,
|
||||
});
|
||||
if !values_concrete {
|
||||
return quote!();
|
||||
}
|
||||
|
||||
let fn_name = &parsed.fn_name;
|
||||
let entries_name = format_ident!("{}_entries", fn_name);
|
||||
let arity = regular_fields.len();
|
||||
let names: Vec<&Ident> = regular_fields.iter().map(|field| &field.pat_ident.ident).collect();
|
||||
let reading_secondaries = reading_secondary_indices(regular_fields, &shape);
|
||||
|
||||
let input_types = regular_fields.iter().enumerate().map(|(index, field)| {
|
||||
let ParsedFieldType::Regular(RegularParsedField { ty, .. }) = &field.ty else {
|
||||
unreachable!("record nodes take no lazy inputs")
|
||||
};
|
||||
if carrier_in_fields && index == 0 {
|
||||
return match &shape.carrier {
|
||||
RecordCarrier::Token(token) => {
|
||||
let name = token.to_string();
|
||||
quote!(gcore::registry::generic_record_edge_type(#name))
|
||||
match &field.ty {
|
||||
// An element-consuming lazy secondary of a record node rides a
|
||||
// record edge with a layout slot, like a reading secondary.
|
||||
ParsedFieldType::Node(NodeParsedField { output_type, .. })
|
||||
if matches!(ir::node_kind(&node), ir::NodeKind::RecordIo) && matches!(ir::lazy_binding(&node, index), ir::LazyBinding::Element) =>
|
||||
{
|
||||
Some(SlotKind::Value(output_type.clone()))
|
||||
}
|
||||
RecordCarrier::Read(carrier_ty) => quote!(gcore::registry::record_edge_type::<#carrier_ty>()),
|
||||
RecordCarrier::None => unreachable!(),
|
||||
};
|
||||
}
|
||||
match field.attribute_reads.is_empty() {
|
||||
true => quote!(gcore::registry::edge_type::<#ty>()),
|
||||
false => quote!(gcore::registry::record_edge_type::<#ty>()),
|
||||
}
|
||||
});
|
||||
let downcasts = regular_fields.iter().enumerate().map(|(index, field)| {
|
||||
let name = &field.pat_ident.ident;
|
||||
let ParsedFieldType::Regular(RegularParsedField { ty, .. }) = &field.ty else {
|
||||
unreachable!("record nodes take no lazy inputs")
|
||||
};
|
||||
if carrier_in_fields && index == 0 {
|
||||
return quote! {
|
||||
let __carrier_handle = inputs.next().unwrap();
|
||||
let __carrier_ty = __carrier_handle.ty().clone();
|
||||
let Some(__carrier_layout) = __carrier_handle.layout().cloned() else {
|
||||
return Err(gcore::registry::ConstructionError::MissingLayout);
|
||||
};
|
||||
let #name = __carrier_handle.downcast_erased::<gcore::registry::ErasedRecordNode>(__carrier_ty.clone())?;
|
||||
};
|
||||
}
|
||||
if !field.attribute_reads.is_empty() {
|
||||
let layout_local = format_ident!("__in_layout_{index}");
|
||||
return quote! {
|
||||
let __in_handle = inputs.next().unwrap();
|
||||
let __in_ty = __in_handle.ty().clone();
|
||||
let Some(#layout_local) = __in_handle.layout().cloned() else {
|
||||
return Err(gcore::registry::ConstructionError::MissingLayout);
|
||||
};
|
||||
let #name = __in_handle.downcast_erased::<gcore::registry::ErasedRecordNode>(__in_ty)?;
|
||||
};
|
||||
}
|
||||
quote!(let #name = inputs.next().unwrap().downcast::<#ty>()?;)
|
||||
});
|
||||
let wire_layout_arg = carrier_in_fields.then(|| quote!(&__carrier_layout,)).into_iter();
|
||||
let input_layout_args = reading_secondaries.iter().map(|index| {
|
||||
let layout_local = format_ident!("__in_layout_{index}");
|
||||
quote!(&#layout_local,)
|
||||
});
|
||||
let (io_output, construct_output) = match (&shape.carrier, &shape.element_write) {
|
||||
(RecordCarrier::Token(token), _) => {
|
||||
let name = token.to_string();
|
||||
(
|
||||
quote!(gcore::Type::Record(Box::new(gcore::Type::Generic(::std::borrow::Cow::Borrowed(#name))))),
|
||||
quote!(Ok(gcore::registry::EdgeHandle::new_erased(
|
||||
::std::sync::Arc::new(__node) as ::std::sync::Arc<gcore::registry::ErasedRecordNode>,
|
||||
__carrier_ty,
|
||||
))),
|
||||
)
|
||||
}
|
||||
(_, Some(element)) => (
|
||||
quote!(gcore::registry::record_type::<#element>()),
|
||||
quote!(Ok(gcore::registry::EdgeHandle::new_record::<#element>(::std::sync::Arc::new(__node)))),
|
||||
),
|
||||
(_, None) => unreachable!("non-token record nodes write an element"),
|
||||
ParsedFieldType::Node(_) => {
|
||||
emit_error!(field.pat_ident.span(), "plain (non-record) io is unsupported: this lazy input needs a record edge");
|
||||
None
|
||||
}
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => match ir::value_binding(&node, index) {
|
||||
ir::ValueBinding::Materialized => Some(SlotKind::Ranked(ty.clone())),
|
||||
ir::ValueBinding::ReadingSecondary | ir::ValueBinding::RecordElement => Some(SlotKind::Value(ty.clone())),
|
||||
// One wire kind: a record node's plain value still rides a
|
||||
// record edge, extracted to its element at construction.
|
||||
_ if matches!(ir::node_kind(&node), ir::NodeKind::RecordIo) => Some(SlotKind::Extracted(ty.clone())),
|
||||
_ => {
|
||||
emit_error!(field.pat_ident.span(), "plain (non-record) io is unsupported: this value input needs a record edge");
|
||||
None
|
||||
}
|
||||
},
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let Some(slots) = slots else {
|
||||
return quote!();
|
||||
};
|
||||
|
||||
let layout_meta_fn = format_ident!("{}_layout_meta", fn_name);
|
||||
// A ranked input's element generic monomorphizes the kernel, so its
|
||||
// implementations expand to one registry row each; every other slot
|
||||
// (erased routing generics included) is row-invariant. The carried list
|
||||
// mirrors the struct's carried generic parameters in declaration order.
|
||||
let ctx_ident = context_param(parsed).map(|ctx| ctx.ident.clone());
|
||||
let ranked_generic_idents: Vec<Ident> = parsed
|
||||
.fn_generics
|
||||
.iter()
|
||||
.filter_map(|param| match param {
|
||||
GenericParam::Type(type_param) if Some(&type_param.ident) != ctx_ident.as_ref() => Some(type_param.ident.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.filter(|ident| {
|
||||
regular_fields.iter().any(|field| match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, list_levels, .. }) => *list_levels > 0 && crate::codegen::type_contains_ident(ty, ident),
|
||||
_ => false,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let ranked_source = |generic: &Ident| {
|
||||
regular_fields.iter().position(|field| match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, list_levels, implementations, .. }) => *list_levels > 0 && !implementations.is_empty() && generic_extractable(ty, generic),
|
||||
_ => false,
|
||||
})
|
||||
};
|
||||
let carried: Option<Vec<(Ident, usize)>> = ranked_generic_idents.iter().map(|ident| ranked_source(ident).map(|index| (ident.clone(), index))).collect();
|
||||
let Some(carried) = carried else {
|
||||
return quote!();
|
||||
};
|
||||
let impls_of = |index: usize| match ®ular_fields[index].ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { implementations, .. }) => implementations.iter().cloned().collect::<Vec<Type>>(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let row_count = carried.iter().map(|(_, index)| impls_of(*index).len()).max().unwrap_or(1).max(1);
|
||||
let row_assignments: Vec<Vec<(Ident, Type)>> = (0..row_count)
|
||||
.map(|row| {
|
||||
carried
|
||||
.iter()
|
||||
.filter_map(|(generic, index)| {
|
||||
let impls = impls_of(*index);
|
||||
let row_ty = ir::strip_ilist(&impls[row.min(impls.len() - 1)]).0;
|
||||
let field_ty = match ®ular_fields[*index].ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => ty.clone(),
|
||||
_ => unreachable!("ranked sources are regular fields"),
|
||||
};
|
||||
generic_assignment(&field_ty, &row_ty, generic).map(|ty| (generic.clone(), ty))
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.collect();
|
||||
|
||||
let entries_name = format_ident!("{}_entries", fn_name);
|
||||
let arity = regular_fields.len();
|
||||
let names: Vec<&Ident> = regular_fields.iter().map(|field| &field.pat_ident.ident).collect();
|
||||
|
||||
let entries: Vec<TokenStream2> = row_assignments
|
||||
.iter()
|
||||
.filter_map(|assignments| {
|
||||
// A row whose assignments did not all solve cannot instantiate the struct.
|
||||
if assignments.len() != carried.len() {
|
||||
return None;
|
||||
}
|
||||
let slots: Vec<SlotKind> = slots
|
||||
.iter()
|
||||
.map(|slot| match slot {
|
||||
SlotKind::BaseGeneric(name) => SlotKind::BaseGeneric(name.clone()),
|
||||
SlotKind::BaseConcrete(ty) => SlotKind::BaseConcrete(substitute_lifetimes(&substitute_ident_types(ty, assignments), "'static")),
|
||||
SlotKind::Value(ty) => SlotKind::Value(substitute_lifetimes(&substitute_ident_types(ty, assignments), "'static")),
|
||||
SlotKind::Extracted(ty) => SlotKind::Extracted(substitute_lifetimes(&substitute_ident_types(ty, assignments), "'static")),
|
||||
SlotKind::Ranked(ty) => SlotKind::Ranked(substitute_lifetimes(&substitute_ident_types(ty, assignments), "'static")),
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Every non-base value input must be concrete.
|
||||
let values_concrete = regular_fields.iter().zip(&slots).all(|(field, slot)| match slot {
|
||||
SlotKind::BaseGeneric(_) | SlotKind::BaseConcrete(_) => true,
|
||||
SlotKind::Value(ty) | SlotKind::Extracted(ty) | SlotKind::Ranked(ty) => !contains_open_generic(parsed, ty) && (lend(field) || !type_disqualifies(ty)),
|
||||
});
|
||||
if !values_concrete {
|
||||
return None;
|
||||
}
|
||||
|
||||
let input_types = slots.iter().map(|slot| match slot {
|
||||
SlotKind::BaseGeneric(name) => quote!(gcore::registry::generic_record_edge_type(#name)),
|
||||
SlotKind::BaseConcrete(ty) | SlotKind::Value(ty) | SlotKind::Extracted(ty) | SlotKind::Ranked(ty) => quote!(gcore::registry::record_edge_type::<#ty>()),
|
||||
});
|
||||
|
||||
let downcasts = names.iter().zip(&slots).enumerate().map(|(index, (name, slot))| {
|
||||
let handle = format_ident!("__handle_{index}");
|
||||
let layout = format_ident!("__layout_{index}");
|
||||
let ty = format_ident!("__ty_{index}");
|
||||
match slot {
|
||||
SlotKind::BaseGeneric(_) | SlotKind::BaseConcrete(_) => quote! {
|
||||
let #handle = inputs.next().unwrap();
|
||||
let #ty = #handle.ty().clone();
|
||||
let #layout = #handle.layout().clone();
|
||||
let #name = #handle.downcast_erased::<gcore::registry::ErasedRecordNode>(#ty.clone())?;
|
||||
},
|
||||
SlotKind::Value(value_ty) => quote! {
|
||||
let #handle = inputs.next().unwrap();
|
||||
let #layout = #handle.layout().clone();
|
||||
let #name = #handle.downcast_record::<#value_ty>()?;
|
||||
},
|
||||
// The node reads the element off the edge's own layout, so
|
||||
// neither slot rides a layout to the constructor.
|
||||
SlotKind::Extracted(value_ty) | SlotKind::Ranked(value_ty) => quote! {
|
||||
let #name = inputs.next().unwrap().downcast_record::<#value_ty>()?;
|
||||
},
|
||||
}
|
||||
});
|
||||
|
||||
let base_indices: Vec<usize> = slots.iter().enumerate().filter(|(_, slot)| slot.is_base()).map(|(index, _)| index).collect();
|
||||
let value_indices: Vec<usize> = slots.iter().enumerate().filter(|(_, slot)| matches!(slot, SlotKind::Value(_))).map(|(index, _)| index).collect();
|
||||
let value_layout_args: Vec<TokenStream2> = value_indices
|
||||
.iter()
|
||||
.map(|index| {
|
||||
let layout = format_ident!("__layout_{index}");
|
||||
quote!(&#layout,)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let carried_meta = || {
|
||||
let meta = ir::layout_meta_tokens(&node, quote!(gcore::record::ElementSpec::Carried), &core_types);
|
||||
quote!(Some(#meta))
|
||||
};
|
||||
|
||||
// The output wire and node wrap follow the output element: a concrete (or
|
||||
// row-assigned) element is a typed record; a generic or opaque element is
|
||||
// an erased record carrying the first base slot's runtime type.
|
||||
let output_element = match &node.output.shape.element {
|
||||
ir::Element::Concrete(element) => Some(substitute_ident_types(element, assignments)),
|
||||
ir::Element::Generic(ident) => assignments.iter().find(|(generic, _)| generic == ident).map(|(_, ty)| ty.clone()),
|
||||
ir::Element::Opaque => None,
|
||||
};
|
||||
let output_element = output_element.map(|element| substitute_lifetimes(&element, "'static"));
|
||||
let (io_output, wrap) = match &output_element {
|
||||
Some(element) => (
|
||||
quote!(gcore::registry::record_type::<#element>()),
|
||||
quote!(Ok(gcore::registry::EdgeHandle::new_record::<#element>(::std::sync::Arc::new(__node)))),
|
||||
),
|
||||
None => {
|
||||
let name = match &node.output.shape.element {
|
||||
ir::Element::Generic(ident) => ident.to_string(),
|
||||
_ => "T".to_string(),
|
||||
};
|
||||
let base_ty = format_ident!("__ty_{}", base_indices[0]);
|
||||
(
|
||||
quote!(gcore::Type::Record(Box::new(gcore::Type::Generic(::std::borrow::Cow::Borrowed(#name))))),
|
||||
quote!(Ok(gcore::registry::EdgeHandle::new_erased(::std::sync::Arc::new(__node) as ::std::sync::Arc<gcore::registry::ErasedRecordNode>, #base_ty))),
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
let (prelude, new_layout_args, layout_meta) = match ir::node_kind(&node) {
|
||||
ir::NodeKind::RecordIo => {
|
||||
let carrier_arg = (node.inputs.first().is_some_and(|input| input.subject) && ir::materialized_levels(&node, 0) == 0).then(|| quote!(&__layout_0,));
|
||||
let layout_meta_fn = format_ident!("{}_layout_meta", fn_name);
|
||||
(quote!(), quote!(#carrier_arg #(#value_layout_args)*), quote!(Some(self::#layout_meta_fn())))
|
||||
}
|
||||
ir::NodeKind::Routing => {
|
||||
let source_layouts = base_indices.iter().map(|index| format_ident!("__layout_{index}"));
|
||||
let source_wraps = base_indices.iter().map(|index| {
|
||||
let name = names[*index];
|
||||
let layout = format_ident!("__layout_{index}");
|
||||
quote!(let #name = gcore::record::RecordSource::new(#name, &#layout, &__union);)
|
||||
});
|
||||
let prelude = quote! {
|
||||
let __union = gcore::record::Layout::union(&[#(&#source_layouts),*]);
|
||||
#(#source_wraps)*
|
||||
};
|
||||
(prelude, quote!(&__union, #(#value_layout_args)*), carried_meta())
|
||||
}
|
||||
ir::NodeKind::Opaque => {
|
||||
let record_layout = format_ident!("__layout_{}", base_indices[0]);
|
||||
(quote!(), quote!(&#record_layout), carried_meta())
|
||||
}
|
||||
ir::NodeKind::Flip => unreachable!("flip has its own multi-row emitter"),
|
||||
};
|
||||
|
||||
// A carried generic instantiates through the struct's trailing phantom
|
||||
// parameters, so the constructor names the row's types after one inferred
|
||||
// slot per input field.
|
||||
let turbofish = (!carried.is_empty()).then(|| {
|
||||
let underscores = (0..arity).map(|_| quote!(_));
|
||||
let carried_types = carried
|
||||
.iter()
|
||||
.filter_map(|(generic, _)| assignments.iter().find(|(ident, _)| ident == generic).map(|(_, ty)| quote!(#ty)));
|
||||
quote!(::<#(#underscores,)* #(#carried_types,)*>)
|
||||
});
|
||||
|
||||
Some(quote! {
|
||||
gcore::registry::RegistryEntry {
|
||||
layout_meta: #layout_meta,
|
||||
io: gcore::registry::NodeIOTypes::new(
|
||||
gcore::concrete!(gcore::context::ContextImpl<'static>),
|
||||
#io_output,
|
||||
vec![#(#input_types),*],
|
||||
),
|
||||
constructor: |inputs| {
|
||||
if inputs.len() != #arity {
|
||||
return Err(gcore::registry::ConstructionError::Arity { expected: #arity, got: inputs.len() });
|
||||
}
|
||||
let mut inputs = inputs.into_iter();
|
||||
#(#downcasts)*
|
||||
#prelude
|
||||
let __node = #struct_name #turbofish::new(#(#names,)* #new_layout_args);
|
||||
#wrap
|
||||
},
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
if entries.is_empty() {
|
||||
return quote!();
|
||||
}
|
||||
quote! {
|
||||
pub fn #entries_name() -> ::std::vec::Vec<gcore::registry::RegistryEntry> {
|
||||
vec![gcore::registry::RegistryEntry {
|
||||
layout_meta: Some(self::#layout_meta_fn()),
|
||||
io: gcore::registry::NodeIOTypes::new(
|
||||
gcore::concrete!(gcore::context::ContextImpl<'static>),
|
||||
#io_output,
|
||||
vec![#(#input_types),*],
|
||||
),
|
||||
constructor: |inputs| {
|
||||
if inputs.len() != #arity {
|
||||
return Err(gcore::registry::ConstructionError::Arity { expected: #arity, got: inputs.len() });
|
||||
}
|
||||
let mut inputs = inputs.into_iter();
|
||||
#(#downcasts)*
|
||||
let __node = #struct_name::new(#(#names,)* #(#wire_layout_arg)* #(#input_layout_args)*);
|
||||
#construct_output
|
||||
},
|
||||
}]
|
||||
vec![#(#entries),*]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn implementation_rows(parsed: &ParsedNodeFn, regular_fields: &[&ParsedField]) -> Option<Vec<Vec<Type>>> {
|
||||
pub(crate) fn implementation_rows(parsed: &ParsedNodeFn, regular_fields: &[&ParsedField]) -> Option<Vec<Vec<Type>>> {
|
||||
let ctx_ident = context_param(parsed).map(|ctx| ctx.ident.clone());
|
||||
let open_generics: Vec<&Ident> = parsed
|
||||
.fn_generics
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -16,11 +16,12 @@ pub(crate) fn generate_node_input_references(
|
||||
let (mut modified, mut generic_collector) = FilterUsedGenerics::new(fn_generics);
|
||||
|
||||
for (input_index, (parsed_input, input_ident)) in parsed.fields.iter().zip(field_idents).enumerate() {
|
||||
let mut ty = match &parsed_input.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => ty,
|
||||
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => output_type,
|
||||
}
|
||||
.clone();
|
||||
// `IList` nesting is rank metadata, not part of the value type.
|
||||
let ty = match &parsed_input.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => ty.clone(),
|
||||
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => crate::codegen::ir::strip_ilist(output_type).0,
|
||||
};
|
||||
let mut ty = crate::codegen::classify::substitute_lifetimes(&ty, "'static");
|
||||
|
||||
// We only want the necessary generics.
|
||||
let used = generic_collector.filter_unnecessary_generics(&mut modified, &mut ty);
|
||||
@@ -91,7 +92,6 @@ pub(crate) fn generate_phantom_data<'a>(fn_generics: impl Iterator<Item = &'a cr
|
||||
(fn_generic_params, phantom_data_declerations)
|
||||
}
|
||||
|
||||
|
||||
/// Get only the necessary generics.
|
||||
struct FilterUsedGenerics {
|
||||
all: Vec<crate::GenericParam>,
|
||||
|
||||
@@ -7,8 +7,8 @@ use syn::punctuated::Punctuated;
|
||||
use syn::spanned::Spanned;
|
||||
use syn::token::{Comma, RArrow};
|
||||
use syn::{
|
||||
AttrStyle, Attribute, Error, Expr, FnArg, GenericArgument, GenericParam, Ident, ItemFn, Lit, LitFloat, LitInt, LitStr, Meta, Pat, PatIdent, PatType, Path, PathArguments, ReturnType,
|
||||
TraitBound, Type, TypeImplTrait, TypeParam, TypeParamBound, Visibility, WhereClause, parse_quote,
|
||||
AttrStyle, Attribute, Error, Expr, FnArg, GenericArgument, GenericParam, Ident, ItemFn, Lit, LitFloat, LitInt, LitStr, Meta, Pat, PatIdent, PatType, Path, PathArguments, ReturnType, TraitBound,
|
||||
Type, TypeImplTrait, TypeParam, TypeParamBound, Visibility, WhereClause, parse_quote,
|
||||
};
|
||||
|
||||
use crate::codegen::generate_node_code;
|
||||
@@ -33,8 +33,12 @@ pub(crate) struct ParsedNodeFn {
|
||||
pub(crate) where_clause: Option<WhereClause>,
|
||||
pub(crate) input: Input,
|
||||
pub(crate) output_type: Type,
|
||||
pub(crate) output_depth: u8,
|
||||
pub(crate) is_async: bool,
|
||||
pub(crate) fields: Vec<ParsedField>,
|
||||
/// The caller's frame claim, declared by a record-opaque kernel that
|
||||
/// serves through it; not a wired input.
|
||||
pub(crate) claim: Option<PatType>,
|
||||
pub(crate) body: TokenStream2,
|
||||
pub(crate) description: String,
|
||||
}
|
||||
@@ -128,6 +132,8 @@ pub(crate) struct NodeFnAttributes {
|
||||
pub(crate) placeholder: Option<Path>,
|
||||
/// Function overriding the generated `extent` method
|
||||
pub(crate) extent: Option<Path>,
|
||||
/// Function overriding the generated `extent` method with the raw node/ctx/level form
|
||||
pub(crate) extent_raw: Option<Path>,
|
||||
/// Function overriding the generated `eval_batch` method
|
||||
pub(crate) batch: Option<Path>,
|
||||
/// Whether partial upstream values are mapped to `Pending` instead of flowing into this node
|
||||
@@ -313,6 +319,8 @@ impl Parse for NumberRange {
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct RegularParsedField {
|
||||
pub ty: Type,
|
||||
/// `IList` nesting stripped from `ty` at parse; `ty` holds the element row.
|
||||
pub list_levels: u8,
|
||||
/// The original reference tokens when the parameter was written `&T`; `ty` holds the peeled inner type.
|
||||
pub lend: Option<syn::TypeReference>,
|
||||
pub exposed: bool,
|
||||
@@ -340,7 +348,7 @@ pub(crate) struct Input {
|
||||
pub(crate) pat_ident: PatIdent,
|
||||
pub(crate) ty: Type,
|
||||
pub(crate) implementations: Punctuated<Type, Comma>,
|
||||
pub(crate) context_features: Vec<Ident>,
|
||||
pub(crate) context_features: Vec<ContextFeatureDecl>,
|
||||
}
|
||||
|
||||
impl Parse for Implementation {
|
||||
@@ -397,6 +405,7 @@ impl Parse for NodeFnAttributes {
|
||||
let mut inject_scope = false;
|
||||
let mut placeholder = None;
|
||||
let mut extent = None;
|
||||
let mut extent_raw = None;
|
||||
let mut batch = None;
|
||||
let mut no_partial = false;
|
||||
let mut plain = false;
|
||||
@@ -569,6 +578,21 @@ impl Parse for NodeFnAttributes {
|
||||
let parsed_path: Path = meta.parse_args().map_err(|_| Error::new_spanned(meta, "Expected a valid path for 'extent', e.g., extent(my_extent)"))?;
|
||||
extent = Some(parsed_path);
|
||||
}
|
||||
// Escape hatch for extent overrides needing arbitrary context access: the raw
|
||||
// `(node, ctx, level)` form instead of the typed `extent(fn)` input surface.
|
||||
//
|
||||
// Example usage:
|
||||
// #[node_macro::node(..., extent_raw(my_extent), ...)]
|
||||
"extent_raw" => {
|
||||
let meta = meta.require_list()?;
|
||||
if extent_raw.is_some() {
|
||||
return Err(Error::new_spanned(meta, "Multiple 'extent_raw' attributes are not allowed"));
|
||||
}
|
||||
let parsed_path: Path = meta
|
||||
.parse_args()
|
||||
.map_err(|_| Error::new_spanned(meta, "Expected a valid path for 'extent_raw', e.g., extent_raw(my_extent)"))?;
|
||||
extent_raw = Some(parsed_path);
|
||||
}
|
||||
// Function overriding the generated `eval_batch` method, replacing the trait's per-lane spec loop.
|
||||
//
|
||||
// Example usage:
|
||||
@@ -605,7 +629,7 @@ impl Parse for NodeFnAttributes {
|
||||
indoc!(
|
||||
r#"
|
||||
Unsupported attribute in `node`.
|
||||
Supported attributes are 'category', 'name', 'path', 'skip_impl', 'properties', 'cfg', 'shader_node', 'serialize', 'memoize', 'inject_scope', 'placeholder', 'extent', 'batch', and 'no_partial'.
|
||||
Supported attributes are 'category', 'name', 'path', 'skip_impl', 'properties', 'cfg', 'shader_node', 'serialize', 'memoize', 'inject_scope', 'placeholder', 'extent', 'extent_raw', 'batch', and 'no_partial'.
|
||||
Example usage:
|
||||
#[node_macro::node(..., name("Test Node"), ...)]
|
||||
"#
|
||||
@@ -628,6 +652,10 @@ impl Parse for NodeFnAttributes {
|
||||
));
|
||||
}
|
||||
|
||||
if let (Some(_), Some(raw)) = (&extent, &extent_raw) {
|
||||
return Err(Error::new_spanned(raw, "'extent' and 'extent_raw' are mutually exclusive"));
|
||||
}
|
||||
|
||||
Ok(NodeFnAttributes {
|
||||
category,
|
||||
display_name,
|
||||
@@ -641,6 +669,7 @@ impl Parse for NodeFnAttributes {
|
||||
inject_scope,
|
||||
placeholder,
|
||||
extent,
|
||||
extent_raw,
|
||||
batch,
|
||||
no_partial,
|
||||
plain,
|
||||
@@ -648,7 +677,7 @@ impl Parse for NodeFnAttributes {
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_node_fn(attr: TokenStream2, item: TokenStream2) -> syn::Result<ParsedNodeFn> {
|
||||
pub(crate) fn parse_node_fn(attr: TokenStream2, item: TokenStream2) -> syn::Result<ParsedNodeFn> {
|
||||
let attributes = syn::parse2::<NodeFnAttributes>(attr.clone()).map_err(|e| Error::new(e.span(), format!("Failed to parse node_fn attributes:\n{e}")))?;
|
||||
let input_fn = syn::parse2::<ItemFn>(item.clone()).map_err(|e| Error::new(e.span(), format!("Failed to parse function: {e}. Make sure it's a valid Rust function.")))?;
|
||||
|
||||
@@ -659,8 +688,8 @@ fn parse_node_fn(attr: TokenStream2, item: TokenStream2) -> syn::Result<ParsedNo
|
||||
let fn_generics = input_fn.sig.generics.params.into_iter().collect();
|
||||
let is_async = input_fn.sig.asyncness.is_some();
|
||||
|
||||
let (input, fields) = parse_inputs(&input_fn.sig.inputs)?;
|
||||
let output_type = parse_output(&input_fn.sig.output)?;
|
||||
let (input, fields, claim) = parse_inputs(&input_fn.sig.inputs)?;
|
||||
let (output_type, output_depth) = crate::codegen::ir::strip_output_rank(&parse_output(&input_fn.sig.output)?);
|
||||
let where_clause = input_fn.sig.generics.where_clause;
|
||||
let body = input_fn.block.to_token_stream();
|
||||
let description = input_fn
|
||||
@@ -689,17 +718,20 @@ fn parse_node_fn(attr: TokenStream2, item: TokenStream2) -> syn::Result<ParsedNo
|
||||
fn_generics,
|
||||
input,
|
||||
output_type,
|
||||
output_depth,
|
||||
is_async,
|
||||
fields,
|
||||
claim,
|
||||
where_clause,
|
||||
body,
|
||||
description,
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_inputs(inputs: &Punctuated<FnArg, Comma>) -> syn::Result<(Input, Vec<ParsedField>)> {
|
||||
fn parse_inputs(inputs: &Punctuated<FnArg, Comma>) -> syn::Result<(Input, Vec<ParsedField>, Option<PatType>)> {
|
||||
let mut fields = Vec::new();
|
||||
let mut input = None;
|
||||
let mut claim = None;
|
||||
|
||||
for (index, arg) in inputs.iter().enumerate() {
|
||||
if let FnArg::Typed(PatType { pat, ty, attrs, .. }) = arg {
|
||||
@@ -738,6 +770,17 @@ fn parse_inputs(inputs: &Punctuated<FnArg, Comma>) -> syn::Result<(Input, Vec<Pa
|
||||
if attr_marker(ty).is_some() {
|
||||
return Err(Error::new_spanned(pat_ident, "an attribute read binds to an input: destructure it as `(value, Attr<..>)`"));
|
||||
}
|
||||
// The claim is the caller's, not an input: it reaches the kernel
|
||||
// from the serve the node is lowered into.
|
||||
if is_frame_claim(ty) {
|
||||
claim = Some(PatType {
|
||||
attrs: Vec::new(),
|
||||
pat: pat.clone(),
|
||||
colon_token: Default::default(),
|
||||
ty: ty.clone(),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
let field = parse_field(pat_ident.clone(), (**ty).clone(), attrs).map_err(|e| Error::new_spanned(pat_ident, format!("Failed to parse argument '{}': {}", pat_ident.ident, e)))?;
|
||||
fields.push(field);
|
||||
} else if let Pat::Tuple(pat_tuple) = &**pat {
|
||||
@@ -762,7 +805,13 @@ fn parse_inputs(inputs: &Punctuated<FnArg, Comma>) -> syn::Result<(Input, Vec<Pa
|
||||
}
|
||||
|
||||
let input = input.ok_or_else(|| Error::new_spanned(inputs, "Expected at least one input argument. The first argument should be the node input type."))?;
|
||||
Ok((input, fields))
|
||||
Ok((input, fields, claim))
|
||||
}
|
||||
|
||||
/// Whether the parameter is the caller-provided frame claim a record-opaque
|
||||
/// kernel serves through.
|
||||
fn is_frame_claim(ty: &Type) -> bool {
|
||||
matches!(ty, Type::Path(path) if path.path.segments.last().is_some_and(|segment| segment.ident == "FrameClaim"))
|
||||
}
|
||||
|
||||
/// Splits a lazy input's `Output = (T, Attr<..>..)` tuple into the element
|
||||
@@ -833,10 +882,7 @@ fn parse_read_tuple(pat_tuple: &syn::PatTuple, ty: &Type, attrs: &[Attribute], i
|
||||
let Pat::Ident(pat_ident) = pat else {
|
||||
return Err(Error::new_spanned(pat, "Expected a simple identifier for the attribute read"));
|
||||
};
|
||||
Ok(AttributeRead {
|
||||
pat_ident: pat_ident.clone(),
|
||||
marker,
|
||||
})
|
||||
Ok(AttributeRead { pat_ident: pat_ident.clone(), marker })
|
||||
})
|
||||
.collect::<syn::Result<_>>()?;
|
||||
let mut field = parse_field(value_ident.clone(), value_ty.clone(), attrs).map_err(|e| Error::new_spanned(&value_ident, format!("Failed to parse argument '{}': {}", value_ident.ident, e)))?;
|
||||
@@ -844,8 +890,46 @@ fn parse_read_tuple(pat_tuple: &syn::PatTuple, ty: &Type, attrs: &[Attribute], i
|
||||
Ok(field)
|
||||
}
|
||||
|
||||
/// A declared context feature; `ExtractIndex` carries the index level it reads.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub(crate) struct ContextFeatureDecl {
|
||||
pub(crate) ident: Ident,
|
||||
pub(crate) level: Option<u8>,
|
||||
}
|
||||
|
||||
impl ContextFeatureDecl {
|
||||
pub(crate) fn new(ident: Ident) -> Self {
|
||||
Self { ident, level: None }
|
||||
}
|
||||
}
|
||||
|
||||
impl quote::ToTokens for ContextFeatureDecl {
|
||||
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
|
||||
let ident = &self.ident;
|
||||
match self.level {
|
||||
Some(level) => tokens.extend(quote::quote!(#ident(#level))),
|
||||
None => ident.to_tokens(tokens),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The level of an `ExtractIndex<N>` bound, defaulting to the innermost.
|
||||
fn parse_index_level(segment: &syn::PathSegment) -> u8 {
|
||||
let syn::PathArguments::AngleBracketed(arguments) = &segment.arguments else {
|
||||
return 0;
|
||||
};
|
||||
for argument in &arguments.args {
|
||||
if let syn::GenericArgument::Const(syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Int(int), .. })) = argument
|
||||
&& let Ok(level) = int.base10_parse::<u8>()
|
||||
{
|
||||
return level;
|
||||
}
|
||||
}
|
||||
0
|
||||
}
|
||||
|
||||
/// Parse context feature identifiers from the trait bounds of a context parameter.
|
||||
fn parse_context_feature_idents(ty: &Type) -> Vec<Ident> {
|
||||
fn parse_context_feature_idents(ty: &Type) -> Vec<ContextFeatureDecl> {
|
||||
let mut features = Vec::new();
|
||||
|
||||
// Check if this is an impl trait (impl Ctx + ...)
|
||||
@@ -855,23 +939,38 @@ fn parse_context_feature_idents(ty: &Type) -> Vec<Ident> {
|
||||
// Extract the last segment of the trait path
|
||||
if let Some(segment) = path.segments.last() {
|
||||
match segment.ident.to_string().as_str() {
|
||||
"ExtractIndex" => features.push(ContextFeatureDecl {
|
||||
ident: segment.ident.clone(),
|
||||
level: Some(parse_index_level(segment)),
|
||||
}),
|
||||
// Reading the chain without a statically known level keeps every level.
|
||||
"ExtractIndices" => features.push(ContextFeatureDecl {
|
||||
ident: format_ident!("ExtractIndex"),
|
||||
level: Some(u8::MAX),
|
||||
}),
|
||||
"ExtractFootprint"
|
||||
| "ExtractRealTime"
|
||||
| "ExtractAnimationTime"
|
||||
| "ExtractPointerPosition"
|
||||
| "ExtractPosition"
|
||||
| "ExtractIndex"
|
||||
| "ExtractVarArgs"
|
||||
| "InjectFootprint"
|
||||
| "InjectRealTime"
|
||||
| "InjectAnimationTime"
|
||||
| "InjectPointerPosition"
|
||||
| "InjectPosition"
|
||||
| "InjectIndex"
|
||||
| "InjectVarArgs" => {
|
||||
features.push(segment.ident.clone());
|
||||
features.push(ContextFeatureDecl::new(segment.ident.clone()));
|
||||
}
|
||||
// Skip Modify* traits as they don't affect usage tracking
|
||||
// Modify* is conditionally transparent: the node rewrites the
|
||||
// field only on its content's behalf, so it names no
|
||||
// requirement of its own and the field nullifies early when
|
||||
// nothing upstream reads it.
|
||||
"ModifyFootprint" | "ModifyRealTime" | "ModifyAnimationTime" | "ModifyPointerPosition" | "ModifyPosition" | "ModifyIndex" | "ModifyVarArgs" => {}
|
||||
// InjectIndex stays undeclared: a record node's injection
|
||||
// re-addresses lanes derived from the incoming index, so it
|
||||
// must not cancel the cone's index requirement in the
|
||||
// nullification pass.
|
||||
// Also ignore other traits like Ctx, ExtractAll, etc.
|
||||
_ => {}
|
||||
}
|
||||
@@ -911,6 +1010,7 @@ fn parse_node_implementations<T: Parse>(attr: &Attribute, name: &Ident) -> syn::
|
||||
}
|
||||
|
||||
fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Result<ParsedField> {
|
||||
let (ty, list_levels) = crate::codegen::ir::strip_ilist(&ty);
|
||||
let ident = &pat_ident.ident;
|
||||
|
||||
// Checks for the #[data] attribute, indicating that this is a data field rather than an input parameter to the node.
|
||||
@@ -1051,9 +1151,10 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
|
||||
));
|
||||
}
|
||||
|
||||
let (input_type, output_type) = node_input_type
|
||||
.zip(node_output_type)
|
||||
.ok_or_else(|| Error::new_spanned(&ty, "Invalid Node type. Expected `impl Node<Input, Output = OutputType>`"))?;
|
||||
let input_type = node_input_type.ok_or_else(|| Error::new_spanned(&ty, "Invalid Node type. Expected `impl Node<Input>` or `impl Node<Input, Output = OutputType>`"))?;
|
||||
// A subject named without an output is a whole-record wire: the kernel
|
||||
// serves it through its own claim rather than reading an element.
|
||||
let output_type = node_output_type.unwrap_or_else(|| syn::parse_quote!(Served<'_>));
|
||||
if !matches!(&value_source, ParsedValueSource::None) {
|
||||
return Err(Error::new_spanned(&ty, "No default values for `impl Node` allowed"));
|
||||
}
|
||||
@@ -1122,6 +1223,7 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
|
||||
number_hard_max,
|
||||
number_mode_range,
|
||||
ty,
|
||||
list_levels,
|
||||
lend,
|
||||
value_source,
|
||||
implementations,
|
||||
@@ -1236,6 +1338,7 @@ impl ParsedNodeFn {
|
||||
widget_override: ParsedWidgetOverride::Hidden,
|
||||
ty: ParsedFieldType::Regular(RegularParsedField {
|
||||
ty,
|
||||
list_levels: 0,
|
||||
lend: None,
|
||||
exposed: false,
|
||||
value_source,
|
||||
@@ -1386,6 +1489,7 @@ mod tests {
|
||||
inject_scope: false,
|
||||
placeholder: None,
|
||||
extent: None,
|
||||
extent_raw: None,
|
||||
batch: None,
|
||||
no_partial: false,
|
||||
plain: false,
|
||||
@@ -1402,7 +1506,9 @@ mod tests {
|
||||
context_features: vec![],
|
||||
},
|
||||
output_type: parse_quote!(f64),
|
||||
output_depth: 0,
|
||||
is_async: false,
|
||||
claim: None,
|
||||
fields: vec![ParsedField {
|
||||
pat_ident: pat_ident("b"),
|
||||
name: None,
|
||||
@@ -1410,6 +1516,7 @@ mod tests {
|
||||
widget_override: ParsedWidgetOverride::None,
|
||||
ty: ParsedFieldType::Regular(RegularParsedField {
|
||||
lend: None,
|
||||
list_levels: 0,
|
||||
ty: parse_quote!(f64),
|
||||
exposed: false,
|
||||
value_source: ParsedValueSource::None,
|
||||
@@ -1463,6 +1570,7 @@ mod tests {
|
||||
inject_scope: false,
|
||||
placeholder: None,
|
||||
extent: None,
|
||||
extent_raw: None,
|
||||
batch: None,
|
||||
no_partial: false,
|
||||
plain: false,
|
||||
@@ -1479,7 +1587,9 @@ mod tests {
|
||||
context_features: vec![],
|
||||
},
|
||||
output_type: parse_quote!(T),
|
||||
output_depth: 0,
|
||||
is_async: false,
|
||||
claim: None,
|
||||
fields: vec![
|
||||
ParsedField {
|
||||
pat_ident: pat_ident("transform_target"),
|
||||
@@ -1503,7 +1613,8 @@ mod tests {
|
||||
description: String::new(),
|
||||
widget_override: ParsedWidgetOverride::None,
|
||||
ty: ParsedFieldType::Regular(RegularParsedField {
|
||||
lend: None,
|
||||
lend: None,
|
||||
list_levels: 0,
|
||||
ty: parse_quote!(DVec2),
|
||||
exposed: false,
|
||||
value_source: ParsedValueSource::None,
|
||||
@@ -1555,6 +1666,7 @@ mod tests {
|
||||
inject_scope: false,
|
||||
placeholder: None,
|
||||
extent: None,
|
||||
extent_raw: None,
|
||||
batch: None,
|
||||
no_partial: false,
|
||||
plain: false,
|
||||
@@ -1568,10 +1680,12 @@ mod tests {
|
||||
pat_ident: pat_ident("_"),
|
||||
ty: parse_quote!(impl Ctx + ExtractFootprint),
|
||||
implementations: Punctuated::new(),
|
||||
context_features: vec![format_ident!("ExtractFootprint")],
|
||||
context_features: vec![ContextFeatureDecl::new(format_ident!("ExtractFootprint"))],
|
||||
},
|
||||
output_type: parse_quote!(Vector),
|
||||
output_depth: 0,
|
||||
is_async: false,
|
||||
claim: None,
|
||||
fields: vec![ParsedField {
|
||||
pat_ident: pat_ident("radius"),
|
||||
name: None,
|
||||
@@ -1579,6 +1693,7 @@ mod tests {
|
||||
widget_override: ParsedWidgetOverride::None,
|
||||
ty: ParsedFieldType::Regular(RegularParsedField {
|
||||
lend: None,
|
||||
list_levels: 0,
|
||||
ty: parse_quote!(f64),
|
||||
exposed: false,
|
||||
value_source: ParsedValueSource::Default(quote!(50.)),
|
||||
@@ -1628,6 +1743,7 @@ mod tests {
|
||||
inject_scope: false,
|
||||
placeholder: None,
|
||||
extent: None,
|
||||
extent_raw: None,
|
||||
batch: None,
|
||||
no_partial: false,
|
||||
plain: false,
|
||||
@@ -1644,7 +1760,9 @@ mod tests {
|
||||
context_features: vec![],
|
||||
},
|
||||
output_type: parse_quote!(List<Raster<P>>),
|
||||
output_depth: 0,
|
||||
is_async: false,
|
||||
claim: None,
|
||||
fields: vec![ParsedField {
|
||||
pat_ident: pat_ident("shadows"),
|
||||
name: None,
|
||||
@@ -1652,6 +1770,7 @@ mod tests {
|
||||
widget_override: ParsedWidgetOverride::None,
|
||||
ty: ParsedFieldType::Regular(RegularParsedField {
|
||||
lend: None,
|
||||
list_levels: 0,
|
||||
ty: parse_quote!(f64),
|
||||
exposed: false,
|
||||
value_source: ParsedValueSource::None,
|
||||
@@ -1713,6 +1832,7 @@ mod tests {
|
||||
inject_scope: false,
|
||||
placeholder: None,
|
||||
extent: None,
|
||||
extent_raw: None,
|
||||
batch: None,
|
||||
no_partial: false,
|
||||
plain: false,
|
||||
@@ -1729,7 +1849,9 @@ mod tests {
|
||||
context_features: vec![],
|
||||
},
|
||||
output_type: parse_quote!(f64),
|
||||
output_depth: 0,
|
||||
is_async: false,
|
||||
claim: None,
|
||||
fields: vec![ParsedField {
|
||||
pat_ident: pat_ident("b"),
|
||||
name: None,
|
||||
@@ -1737,6 +1859,7 @@ mod tests {
|
||||
widget_override: ParsedWidgetOverride::None,
|
||||
ty: ParsedFieldType::Regular(RegularParsedField {
|
||||
lend: None,
|
||||
list_levels: 0,
|
||||
ty: parse_quote!(f64),
|
||||
exposed: false,
|
||||
value_source: ParsedValueSource::None,
|
||||
@@ -1801,6 +1924,7 @@ mod tests {
|
||||
inject_scope: false,
|
||||
placeholder: None,
|
||||
extent: None,
|
||||
extent_raw: None,
|
||||
batch: None,
|
||||
no_partial: false,
|
||||
plain: false,
|
||||
@@ -1817,7 +1941,9 @@ mod tests {
|
||||
context_features: vec![],
|
||||
},
|
||||
output_type: parse_quote!(List<Raster<CPU>>),
|
||||
output_depth: 0,
|
||||
is_async: true,
|
||||
claim: None,
|
||||
fields: vec![ParsedField {
|
||||
pat_ident: pat_ident("path"),
|
||||
name: None,
|
||||
@@ -1825,6 +1951,7 @@ mod tests {
|
||||
widget_override: ParsedWidgetOverride::None,
|
||||
ty: ParsedFieldType::Regular(RegularParsedField {
|
||||
lend: None,
|
||||
list_levels: 0,
|
||||
ty: parse_quote!(String),
|
||||
exposed: true,
|
||||
value_source: ParsedValueSource::None,
|
||||
@@ -1874,6 +2001,7 @@ mod tests {
|
||||
inject_scope: false,
|
||||
placeholder: None,
|
||||
extent: None,
|
||||
extent_raw: None,
|
||||
batch: None,
|
||||
no_partial: false,
|
||||
plain: false,
|
||||
@@ -1890,7 +2018,9 @@ mod tests {
|
||||
context_features: vec![],
|
||||
},
|
||||
output_type: parse_quote!(i32),
|
||||
output_depth: 0,
|
||||
is_async: false,
|
||||
claim: None,
|
||||
fields: vec![],
|
||||
body: TokenStream2::new(),
|
||||
description: String::new(),
|
||||
|
||||
@@ -232,6 +232,7 @@ impl PerPixelAdjustCodegen<'_> {
|
||||
widget_override: Default::default(),
|
||||
ty: ParsedFieldType::Regular(RegularParsedField {
|
||||
ty: parse_quote!(#wgpu_executor::WgpuExecutorHandle),
|
||||
list_levels: 0,
|
||||
lend: None,
|
||||
exposed: true,
|
||||
value_source: ParsedValueSource::Scope(Box::new(parse_quote!("graphene_std::platform_application_io::WgpuExecutorNode"))),
|
||||
@@ -316,6 +317,8 @@ impl PerPixelAdjustCodegen<'_> {
|
||||
context_features: self.parsed.input.context_features.clone(),
|
||||
},
|
||||
output_type: raster_gpu,
|
||||
output_depth: 0,
|
||||
claim: None,
|
||||
is_async: false,
|
||||
fields,
|
||||
body,
|
||||
|
||||
@@ -39,24 +39,28 @@ fn validate_record_io(parsed: &ParsedNodeFn) {
|
||||
}
|
||||
|
||||
let writes = record_writes(&value);
|
||||
let has_reads = parsed
|
||||
.fields
|
||||
.iter()
|
||||
.any(|field| !field.attribute_reads.is_empty() && matches!(field.ty, ParsedFieldType::Regular(_)));
|
||||
let has_reads = parsed.fields.iter().any(|field| !field.attribute_reads.is_empty() && matches!(field.ty, ParsedFieldType::Regular(_)));
|
||||
if !has_reads && writes.is_none() {
|
||||
return;
|
||||
}
|
||||
|
||||
if parsed.is_async || crate::codegen::is_source_kernel(&parsed.output_type) {
|
||||
emit_error!(parsed.output_type.span(), "attribute io is not supported on async source kernels");
|
||||
let async_source = crate::codegen::classify::is_async_source(parsed);
|
||||
if async_source && has_reads {
|
||||
emit_error!(parsed.fn_name.span(), "attribute reads are not supported on async source kernels, only writes");
|
||||
}
|
||||
if crate::codegen::is_poll_kernel(&parsed.output_type) {
|
||||
emit_error!(parsed.output_type.span(), "attribute io needs a plain or `Result<_, Interrupt>` kernel, not a `GPoll` one");
|
||||
}
|
||||
|
||||
for field in parsed.fields.iter().skip(1) {
|
||||
if matches!(field.ty, ParsedFieldType::Node(_)) {
|
||||
emit_error!(field.pat_ident.span(), "record nodes take no lazy inputs yet");
|
||||
if let ParsedFieldType::Node(NodeParsedField { output_type, .. }) = &field.ty {
|
||||
// Lazy secondaries are consumed as plain elements through the wire.
|
||||
if crate::codegen::classify::is_served(output_type) || crate::codegen::ir::strip_ilist(output_type).1 > 0 {
|
||||
emit_error!(field.pat_ident.span(), "a record node's lazy inputs consume plain elements, not record or ranked wires");
|
||||
}
|
||||
if !field.attribute_reads.is_empty() {
|
||||
emit_error!(field.pat_ident.span(), "attribute reads on a record node's lazy inputs are not supported yet");
|
||||
}
|
||||
}
|
||||
}
|
||||
for (index, field) in parsed.fields.iter().enumerate() {
|
||||
@@ -90,49 +94,57 @@ fn validate_record_io(parsed: &ParsedNodeFn) {
|
||||
}
|
||||
|
||||
let Some(carrier) = parsed.fields.first() else {
|
||||
emit_error!(
|
||||
parsed.fn_name.span(),
|
||||
"attribute io needs a primary input as the first parameter after the context (`_: ()` for none)"
|
||||
);
|
||||
emit_error!(parsed.fn_name.span(), "attribute io needs a primary input as the first parameter after the context (`_: ()` for none)");
|
||||
return;
|
||||
};
|
||||
let lazy_carrier = matches!(&crate::codegen::record_shape(parsed), Some(shape) if matches!(shape.carrier, crate::codegen::RecordCarrier::LazyToken));
|
||||
let carrier_ty = match &carrier.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, lend: None, .. }) if !carrier.is_data_field => Some(ty),
|
||||
ParsedFieldType::Node(NodeParsedField { output_type, .. }) if lazy_carrier => Some(output_type),
|
||||
_ => None,
|
||||
};
|
||||
let Some(carrier_ty) = carrier_ty else {
|
||||
emit_error!(
|
||||
carrier.pat_ident.span(),
|
||||
"a record node's primary input is an owned element, an unbounded passthrough generic, or `_: ()`; not `#[data]`, `&T`, or `impl Node`"
|
||||
"a record node's primary input is an owned element, an unbounded passthrough generic, a lazy passthrough source, or `_: ()`; not `#[data]` or `&T`"
|
||||
);
|
||||
return;
|
||||
};
|
||||
let node = crate::codegen::ir::build(parsed);
|
||||
if lazy_carrier && !node.derives {
|
||||
emit_error!(parsed.input.pat_ident.span(), "a lazy record carrier evaluates at derived contexts; spell `impl Ctx + DeriveCtx`");
|
||||
return;
|
||||
}
|
||||
if node.output.gathers && crate::codegen::ir::gathered_subject(&node).is_none() {
|
||||
emit_error!(parsed.output_type.span(), "a `Lane` output gathers a materialized subject; give the primary input an `IList` type");
|
||||
return;
|
||||
}
|
||||
|
||||
let no_carrier = matches!(carrier_ty, Type::Tuple(tuple) if tuple.elems.is_empty());
|
||||
let token = match (no_carrier, &carrier.ty) {
|
||||
(false, ParsedFieldType::Regular(RegularParsedField { ty, implementations, .. })) if implementations.is_empty() => crate::codegen::unbounded_generic(parsed, ty),
|
||||
(false, ParsedFieldType::Node(NodeParsedField { output_type, .. })) if lazy_carrier => crate::codegen::unbounded_generic(parsed, output_type),
|
||||
_ => None,
|
||||
};
|
||||
if async_source && token.is_some() {
|
||||
emit_error!(carrier.pat_ident.span(), "an async source's element crosses the future boundary as a value; a passthrough generic element has none");
|
||||
}
|
||||
let element = writes.as_ref().map(|writes| &writes.element).unwrap_or(&value);
|
||||
match &token {
|
||||
Some(token) => {
|
||||
if !matches!(crate::codegen::bare_ident(element), Some(ident) if ident == token) {
|
||||
emit_error!(
|
||||
parsed.output_type.span(),
|
||||
"a generic element passes through unchanged: return `{}` in the first tuple position",
|
||||
token
|
||||
);
|
||||
emit_error!(parsed.output_type.span(), "a generic element passes through unchanged: return `{}` in the first tuple position", token);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if let Some(ident) = crate::codegen::unbounded_generic(parsed, element) {
|
||||
emit_error!(parsed.output_type.span(), "the returned generic element `{}` has no matching input", ident);
|
||||
} else if !no_carrier && crate::codegen::contains_open_generic(parsed, carrier_ty) {
|
||||
} else if !no_carrier && !node.output.gathers && crate::codegen::contains_open_generic(parsed, carrier_ty) {
|
||||
emit_error!(
|
||||
carrier.pat_ident.span(),
|
||||
"record element reads are monomorphic for now; use a concrete element type or an unbounded passthrough generic"
|
||||
);
|
||||
} else if crate::codegen::contains_open_generic(parsed, element) {
|
||||
} else if !node.output.gathers && crate::codegen::contains_open_generic(parsed, element) {
|
||||
emit_error!(parsed.output_type.span(), "a written element must be a concrete type");
|
||||
}
|
||||
}
|
||||
@@ -178,20 +190,23 @@ fn validate_lazy_reads(parsed: &ParsedNodeFn) {
|
||||
if !crate::codegen::has_lazy_reads(parsed) {
|
||||
return;
|
||||
}
|
||||
if !crate::codegen::record_flip(parsed) {
|
||||
let lazy_carrier = matches!(&crate::codegen::record_shape(parsed), Some(shape) if matches!(shape.carrier, crate::codegen::RecordCarrier::LazyToken));
|
||||
if !crate::codegen::record_flip(parsed) && !lazy_carrier {
|
||||
emit_error!(
|
||||
parsed.fn_name.span(),
|
||||
"attribute reads on a lazy input need the record lowering; routing, `plain`, shader, batch, and non-row-assignable generic nodes keep the plain one"
|
||||
);
|
||||
}
|
||||
for field in &parsed.fields {
|
||||
for (index, field) in parsed.fields.iter().enumerate() {
|
||||
let ParsedFieldType::Node(NodeParsedField { output_type, .. }) = &field.ty else {
|
||||
continue;
|
||||
};
|
||||
if field.attribute_reads.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if crate::codegen::unbounded_generic(parsed, output_type).is_some() {
|
||||
// The lazy carrier forwards its token AND reads: the reads resolve
|
||||
// against its wired layout, not the row type.
|
||||
if crate::codegen::unbounded_generic(parsed, output_type).is_some() && !(lazy_carrier && index == 0) {
|
||||
emit_error!(
|
||||
field.pat_ident.span(),
|
||||
"an unbounded generic source forwards its whole record; attribute reads need a concrete output type"
|
||||
@@ -393,12 +408,14 @@ fn validate_primary_input_expose(parsed: &ParsedNodeFn) {
|
||||
fn validate_implementations_for_generics(parsed: &ParsedNodeFn) {
|
||||
let has_skip_impl = parsed.attributes.skip_impl;
|
||||
let routing = crate::codegen::routing_io(parsed);
|
||||
let record_token = crate::codegen::record_shape(parsed).and_then(|shape| match shape.carrier {
|
||||
crate::codegen::RecordCarrier::Token(token) => Some(token),
|
||||
let node = crate::codegen::ir::build(parsed);
|
||||
let record_token = match (crate::codegen::ir::node_kind(&node), &node.output.shape.element) {
|
||||
(crate::codegen::ir::NodeKind::RecordIo, crate::codegen::ir::Element::Generic(ident)) => Some(ident.clone()),
|
||||
_ => None,
|
||||
});
|
||||
};
|
||||
let opaque_record_generic = |ty: &Type| {
|
||||
let ident = match ty {
|
||||
let (stripped, _) = crate::codegen::ir::strip_ilist(ty);
|
||||
let ident = match &stripped {
|
||||
Type::Path(path) => path.path.get_ident(),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
@@ -1,223 +1,27 @@
|
||||
use core_types::list::List;
|
||||
use core_types::attribute::{Attr, BlendMode as BlendModeAttr, ClippingMask, Opacity, OpacityFill};
|
||||
use core_types::registry::types::Percentage;
|
||||
use core_types::{ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_OPACITY, ATTR_OPACITY_FILL, BlendMode, Color, Ctx};
|
||||
use graphic_types::Graphic;
|
||||
use graphic_types::Vector;
|
||||
use graphic_types::raster_types::{CPU, Raster};
|
||||
use vector_types::GradientStops;
|
||||
|
||||
pub(crate) trait MultiplyAlpha {
|
||||
fn multiply_alpha(&mut self, factor: f64);
|
||||
}
|
||||
|
||||
impl MultiplyAlpha for Color {
|
||||
fn multiply_alpha(&mut self, factor: f64) {
|
||||
*self = Color::from_rgbaf32_unchecked(self.r(), self.g(), self.b(), (self.a() * factor as f32).clamp(0., 1.))
|
||||
}
|
||||
}
|
||||
|
||||
fn multiply_list_attribute<T>(list: &mut List<T>, key: &str, factor: f64) {
|
||||
if let Some(values) = list.iter_attribute_values_mut::<f64>(key) {
|
||||
for v in values {
|
||||
*v *= factor;
|
||||
}
|
||||
} else {
|
||||
for v in list.iter_attribute_values_mut_or_default::<f64>(key) {
|
||||
*v = factor;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl MultiplyAlpha for List<Vector> {
|
||||
fn multiply_alpha(&mut self, factor: f64) {
|
||||
multiply_list_attribute(self, ATTR_OPACITY, factor);
|
||||
}
|
||||
}
|
||||
impl MultiplyAlpha for List<Graphic> {
|
||||
fn multiply_alpha(&mut self, factor: f64) {
|
||||
multiply_list_attribute(self, ATTR_OPACITY, factor);
|
||||
}
|
||||
}
|
||||
impl MultiplyAlpha for List<Raster<CPU>> {
|
||||
fn multiply_alpha(&mut self, factor: f64) {
|
||||
multiply_list_attribute(self, ATTR_OPACITY, factor);
|
||||
}
|
||||
}
|
||||
impl MultiplyAlpha for List<Color> {
|
||||
fn multiply_alpha(&mut self, factor: f64) {
|
||||
multiply_list_attribute(self, ATTR_OPACITY, factor);
|
||||
}
|
||||
}
|
||||
impl MultiplyAlpha for List<GradientStops> {
|
||||
fn multiply_alpha(&mut self, factor: f64) {
|
||||
multiply_list_attribute(self, ATTR_OPACITY, factor);
|
||||
}
|
||||
}
|
||||
impl MultiplyAlpha for List<String> {
|
||||
fn multiply_alpha(&mut self, factor: f64) {
|
||||
multiply_list_attribute(self, ATTR_OPACITY, factor);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) trait MultiplyFill {
|
||||
fn multiply_fill(&mut self, factor: f64);
|
||||
}
|
||||
impl MultiplyFill for Color {
|
||||
fn multiply_fill(&mut self, factor: f64) {
|
||||
*self = Color::from_rgbaf32_unchecked(self.r(), self.g(), self.b(), (self.a() * factor as f32).clamp(0., 1.))
|
||||
}
|
||||
}
|
||||
impl MultiplyFill for List<Vector> {
|
||||
fn multiply_fill(&mut self, factor: f64) {
|
||||
multiply_list_attribute(self, ATTR_OPACITY_FILL, factor);
|
||||
}
|
||||
}
|
||||
impl MultiplyFill for List<Graphic> {
|
||||
fn multiply_fill(&mut self, factor: f64) {
|
||||
multiply_list_attribute(self, ATTR_OPACITY_FILL, factor);
|
||||
}
|
||||
}
|
||||
impl MultiplyFill for List<Raster<CPU>> {
|
||||
fn multiply_fill(&mut self, factor: f64) {
|
||||
multiply_list_attribute(self, ATTR_OPACITY_FILL, factor);
|
||||
}
|
||||
}
|
||||
impl MultiplyFill for List<Color> {
|
||||
fn multiply_fill(&mut self, factor: f64) {
|
||||
multiply_list_attribute(self, ATTR_OPACITY_FILL, factor);
|
||||
}
|
||||
}
|
||||
impl MultiplyFill for List<GradientStops> {
|
||||
fn multiply_fill(&mut self, factor: f64) {
|
||||
multiply_list_attribute(self, ATTR_OPACITY_FILL, factor);
|
||||
}
|
||||
}
|
||||
impl MultiplyFill for List<String> {
|
||||
fn multiply_fill(&mut self, factor: f64) {
|
||||
multiply_list_attribute(self, ATTR_OPACITY_FILL, factor);
|
||||
}
|
||||
}
|
||||
|
||||
trait SetBlendMode {
|
||||
fn set_blend_mode(&mut self, blend_mode: BlendMode);
|
||||
}
|
||||
|
||||
fn set_list_blend_mode<T>(list: &mut List<T>, blend_mode: BlendMode) {
|
||||
for v in list.iter_attribute_values_mut_or_default::<BlendMode>(ATTR_BLEND_MODE) {
|
||||
*v = blend_mode;
|
||||
}
|
||||
}
|
||||
|
||||
impl SetBlendMode for List<Vector> {
|
||||
fn set_blend_mode(&mut self, blend_mode: BlendMode) {
|
||||
set_list_blend_mode(self, blend_mode);
|
||||
}
|
||||
}
|
||||
impl SetBlendMode for List<Graphic> {
|
||||
fn set_blend_mode(&mut self, blend_mode: BlendMode) {
|
||||
set_list_blend_mode(self, blend_mode);
|
||||
}
|
||||
}
|
||||
impl SetBlendMode for List<Raster<CPU>> {
|
||||
fn set_blend_mode(&mut self, blend_mode: BlendMode) {
|
||||
set_list_blend_mode(self, blend_mode);
|
||||
}
|
||||
}
|
||||
impl SetBlendMode for List<Color> {
|
||||
fn set_blend_mode(&mut self, blend_mode: BlendMode) {
|
||||
set_list_blend_mode(self, blend_mode);
|
||||
}
|
||||
}
|
||||
impl SetBlendMode for List<GradientStops> {
|
||||
fn set_blend_mode(&mut self, blend_mode: BlendMode) {
|
||||
set_list_blend_mode(self, blend_mode);
|
||||
}
|
||||
}
|
||||
impl SetBlendMode for List<String> {
|
||||
fn set_blend_mode(&mut self, blend_mode: BlendMode) {
|
||||
set_list_blend_mode(self, blend_mode);
|
||||
}
|
||||
}
|
||||
|
||||
trait SetClip {
|
||||
fn set_clip(&mut self, clip: bool);
|
||||
}
|
||||
|
||||
fn set_list_clip<T>(list: &mut List<T>, clip: bool) {
|
||||
for v in list.iter_attribute_values_mut_or_default::<bool>(ATTR_CLIPPING_MASK) {
|
||||
*v = clip;
|
||||
}
|
||||
}
|
||||
|
||||
impl SetClip for List<Vector> {
|
||||
fn set_clip(&mut self, clip: bool) {
|
||||
set_list_clip(self, clip);
|
||||
}
|
||||
}
|
||||
impl SetClip for List<Graphic> {
|
||||
fn set_clip(&mut self, clip: bool) {
|
||||
set_list_clip(self, clip);
|
||||
}
|
||||
}
|
||||
impl SetClip for List<Raster<CPU>> {
|
||||
fn set_clip(&mut self, clip: bool) {
|
||||
set_list_clip(self, clip);
|
||||
}
|
||||
}
|
||||
impl SetClip for List<Color> {
|
||||
fn set_clip(&mut self, clip: bool) {
|
||||
set_list_clip(self, clip);
|
||||
}
|
||||
}
|
||||
impl SetClip for List<GradientStops> {
|
||||
fn set_clip(&mut self, clip: bool) {
|
||||
set_list_clip(self, clip);
|
||||
}
|
||||
}
|
||||
impl SetClip for List<String> {
|
||||
fn set_clip(&mut self, clip: bool) {
|
||||
set_list_clip(self, clip);
|
||||
}
|
||||
}
|
||||
use core_types::{BlendMode, Ctx};
|
||||
|
||||
/// Applies the blend mode to the input graphics. Setting this allows for customizing how overlapping content is composited together.
|
||||
#[node_macro::node(category("Blending"))]
|
||||
fn blend_mode<T: SetBlendMode>(
|
||||
fn blend_mode<T>(
|
||||
_: impl Ctx,
|
||||
/// The layer stack that will be composited when rendering.
|
||||
#[implementations(
|
||||
List<Graphic>,
|
||||
List<Vector>,
|
||||
List<Raster<CPU>>,
|
||||
List<Color>,
|
||||
List<GradientStops>,
|
||||
List<String>,
|
||||
)]
|
||||
mut content: T,
|
||||
(element, _content_blend_mode): (T, Attr<BlendModeAttr>),
|
||||
/// The choice of equation that controls how brightness and color blends between overlapping pixels.
|
||||
blend_mode: BlendMode,
|
||||
) -> T {
|
||||
// TODO: Find a way to make this apply once to the list's parent (i.e. its item in its parent List<T> or Item<T>) rather than applying to each item in its own list, which produces the undesired result
|
||||
content.set_blend_mode(blend_mode);
|
||||
content
|
||||
) -> (T, Attr<BlendModeAttr>) {
|
||||
(element, Attr(blend_mode))
|
||||
}
|
||||
|
||||
/// Modifies the opacity and/or fill of the input graphics by multiplying the existing values by these percentages.
|
||||
/// Opacity affects the transparency of the content (together with anything above which is clipped to it).
|
||||
/// Fill affects the transparency of the content itself, independent of any content clipped to it.
|
||||
#[node_macro::node(category("Blending"))]
|
||||
fn opacity<T: MultiplyAlpha + MultiplyFill>(
|
||||
fn opacity<T>(
|
||||
_: impl Ctx,
|
||||
/// The layer stack that will be composited when rendering.
|
||||
#[implementations(
|
||||
List<Graphic>,
|
||||
List<Vector>,
|
||||
List<Raster<CPU>>,
|
||||
List<Color>,
|
||||
List<GradientStops>,
|
||||
List<String>,
|
||||
)]
|
||||
mut content: T,
|
||||
(element, content_opacity, content_fill): (T, Attr<Opacity>, Attr<OpacityFill>),
|
||||
/// Whether the *Opacity* property is enabled, multiplying the existing opacity by the chosen percentage.
|
||||
#[widget(ParsedWidgetOverride::Hidden)]
|
||||
#[default(true)]
|
||||
@@ -235,35 +39,26 @@ fn opacity<T: MultiplyAlpha + MultiplyFill>(
|
||||
#[widget(ParsedWidgetOverride::Custom = "optional_percentage")]
|
||||
#[default(100.)]
|
||||
fill: Percentage,
|
||||
) -> T {
|
||||
// TODO: Find a way to make this apply once to the list's parent (i.e. its item in its parent List<T> or Item<T>) rather than applying to each item in its own list, which produces the undesired result
|
||||
if has_opacity {
|
||||
content.multiply_alpha(opacity / 100.);
|
||||
}
|
||||
if has_fill {
|
||||
content.multiply_fill(fill / 100.);
|
||||
}
|
||||
content
|
||||
) -> (T, Attr<Opacity>, Attr<OpacityFill>) {
|
||||
let opacity = match has_opacity {
|
||||
true => *content_opacity * (opacity / 100.),
|
||||
false => *content_opacity,
|
||||
};
|
||||
let fill = match has_fill {
|
||||
true => *content_fill * (fill / 100.),
|
||||
false => *content_fill,
|
||||
};
|
||||
(element, Attr(opacity), Attr(fill))
|
||||
}
|
||||
|
||||
/// Sets whether the input graphics inherit the alpha of the content beneath them, "clipping" them to that content.
|
||||
#[node_macro::node(category("Blending"))]
|
||||
fn clipping_mask<T: SetClip>(
|
||||
fn clipping_mask<T>(
|
||||
_: impl Ctx,
|
||||
/// The layer stack that will be composited when rendering.
|
||||
#[implementations(
|
||||
List<Graphic>,
|
||||
List<Vector>,
|
||||
List<Raster<CPU>>,
|
||||
List<Color>,
|
||||
List<GradientStops>,
|
||||
List<String>,
|
||||
)]
|
||||
mut content: T,
|
||||
(element, _content_clip): (T, Attr<ClippingMask>),
|
||||
/// Whether the content inherits the alpha of the content beneath it.
|
||||
clip: bool,
|
||||
) -> T {
|
||||
// TODO: Find a way to make this apply once to the list's parent (i.e. its item in its parent List<T> or Item<T>) rather than applying to each item in its own list, which produces the undesired result
|
||||
content.set_clip(clip);
|
||||
content
|
||||
) -> (T, Attr<ClippingMask>) {
|
||||
(element, Attr(clip))
|
||||
}
|
||||
@@ -1,22 +1,25 @@
|
||||
use crate::brush_cache::BrushCache;
|
||||
use crate::brush_stroke::{BrushStroke, BrushStyle};
|
||||
use core_types::Ctx;
|
||||
use core_types::attribute::{Attr, BlendMode as BlendModeAttr, ClippingMask, EditorLayerPath, Opacity, OpacityFill, Transform as TransformAttr};
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::color::{Alpha, Color, Pixel, Sample};
|
||||
use core_types::extent::{LevelIn, ListIn};
|
||||
use core_types::gpoll::{Extent, GPoll, GraphError, Interrupt};
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::math::bbox::{AxisAlignedBbox, Bbox};
|
||||
use core_types::transform::Transform;
|
||||
use core_types::uuid::NodeId;
|
||||
use core_types::{ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM};
|
||||
use core_types::{ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM};
|
||||
use core_types::{Ctx, ExtractIndex, InjectIndex};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use raster_nodes::blending_nodes::blend_colors;
|
||||
use raster_nodes::std_nodes::{empty_image, extend_image_to_bounds};
|
||||
use raster_nodes::std_nodes::{empty_image_core, extend_image_to_bounds_core};
|
||||
use raster_types::BitmapMut;
|
||||
use raster_types::Image;
|
||||
use raster_types::{CPU, Raster};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, dyn_any::DynAny)]
|
||||
pub struct BrushStampGenerator<P: Pixel + Alpha> {
|
||||
color: P,
|
||||
feather_exponent: f32,
|
||||
@@ -134,7 +137,11 @@ where
|
||||
pub fn create_brush_texture(brush_style: &BrushStyle) -> Raster<CPU> {
|
||||
let stamp = brush_stamp_generator(&(), brush_style.diameter, brush_style.color, brush_style.hardness, brush_style.flow);
|
||||
let transform = DAffine2::from_scale_angle_translation(DVec2::splat(brush_style.diameter), 0., -DVec2::splat(brush_style.diameter / 2.));
|
||||
let blank_texture = empty_image(&(), transform, List::new_from_element(Color::TRANSPARENT)).into_iter().next().unwrap_or_default();
|
||||
let blank_texture = {
|
||||
let mut item = Item::new_from_element(empty_image_core(transform, Color::TRANSPARENT));
|
||||
item.set_attribute(ATTR_TRANSFORM, transform);
|
||||
item
|
||||
};
|
||||
let image = blend_stamp_closure(stamp, blank_texture, |a, b| blend_colors(a, b, BlendMode::Normal, 1.));
|
||||
|
||||
image.into_element()
|
||||
@@ -182,29 +189,97 @@ pub fn blend_with_mode(background: Item<Raster<CPU>>, foreground: Item<Raster<CP
|
||||
}
|
||||
}
|
||||
|
||||
/// Lane 0 of the materialized background as the legacy item the brush core works
|
||||
/// on; an empty level starts from a blank item, as the pre-flip node did.
|
||||
fn legacy_background(background: core_types::node::List<'_, Raster<CPU>>) -> Item<Raster<CPU>> {
|
||||
if background.is_empty() {
|
||||
return Item::default();
|
||||
}
|
||||
let lane = background.lane(0);
|
||||
let mut item = Item::new_from_element(background.element_ref(0).clone());
|
||||
item.set_attribute(ATTR_TRANSFORM, lane.attr::<TransformAttr>());
|
||||
item.set_attribute(ATTR_BLEND_MODE, lane.attr::<BlendModeAttr>());
|
||||
item.set_attribute(ATTR_OPACITY, lane.attr::<Opacity>());
|
||||
item.set_attribute(ATTR_OPACITY_FILL, lane.attr::<OpacityFill>());
|
||||
item.set_attribute(ATTR_CLIPPING_MASK, lane.attr::<ClippingMask>());
|
||||
item
|
||||
}
|
||||
|
||||
/// The brushed image replaces the whole background level with one lane.
|
||||
fn brush_extent(_background: ListIn<'_, Raster<CPU>>, _trace: ListIn<'_, BrushStroke>, _level: LevelIn) -> GPoll<Extent> {
|
||||
GPoll::Final(Extent::Exactly(1))
|
||||
}
|
||||
|
||||
/// Generates the brush strokes painted with the Brush tool as a raster image.
|
||||
/// If an input image is supplied, strokes are drawn on top of it, expanding bounds as needed.
|
||||
#[node_macro::node(category("Raster"))]
|
||||
fn brush(
|
||||
_: impl Ctx,
|
||||
#[node_macro::node(category("Raster"), extent(brush_extent))]
|
||||
fn brush<'e>(
|
||||
ctx: impl Ctx + ExtractArena<'e> + ExtractIndex + InjectIndex + Copy,
|
||||
/// Optional raster content that may be drawn onto.
|
||||
mut background: List<Raster<CPU>>,
|
||||
background: IList<Raster<CPU>>,
|
||||
/// The list of brush stroke paths drawn by the Brush tool, with each including both its coordinates and styles.
|
||||
trace: List<BrushStroke>,
|
||||
trace: IList<BrushStroke>,
|
||||
/// Internal cache data used to accelerate rendering of the brush content.
|
||||
#[data]
|
||||
cache: BrushCache,
|
||||
) -> List<Raster<CPU>> {
|
||||
if background.is_empty() {
|
||||
background.push(Item::default());
|
||||
) -> Result<
|
||||
IList<(
|
||||
Raster<CPU>,
|
||||
Attr<'e, TransformAttr>,
|
||||
Attr<'e, BlendModeAttr>,
|
||||
Attr<'e, Opacity>,
|
||||
Attr<'e, OpacityFill>,
|
||||
Attr<'e, ClippingMask>,
|
||||
Attr<'e, EditorLayerPath>,
|
||||
)>,
|
||||
Interrupt,
|
||||
> {
|
||||
if ctx.innermost_index() > 0 {
|
||||
return Err(GraphError::past_end().into());
|
||||
}
|
||||
// TODO: Find a way to handle more than one item
|
||||
let list_item = background.clone_item(0).expect("Expected the one item we just pushed");
|
||||
// The layer path only rides through, so it is read off the source lane
|
||||
// rather than round-tripped as a legacy list attribute.
|
||||
let layer_path: Vec<NodeId> = match background.is_empty() {
|
||||
true => Vec::new(),
|
||||
false => background.lane(0).attr::<EditorLayerPath>().to_vec(),
|
||||
};
|
||||
let strokes: Vec<BrushStroke> = (0..trace.len()).map(|row| trace.element_ref(row).clone()).collect();
|
||||
let actual_image = brush_core(legacy_background(background), strokes, cache);
|
||||
|
||||
let transform: DAffine2 = actual_image.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let blend_mode: BlendMode = actual_image.attribute_cloned_or_default(ATTR_BLEND_MODE);
|
||||
let opacity: f64 = actual_image.attribute_cloned_or(ATTR_OPACITY, 1.);
|
||||
let fill: f64 = actual_image.attribute_cloned_or(ATTR_OPACITY_FILL, 1.);
|
||||
let clip: bool = actual_image.attribute_cloned_or_default(ATTR_CLIPPING_MASK);
|
||||
let layer_path = ctx
|
||||
.arena()
|
||||
.alloc(layer_path)
|
||||
.ok_or_else(|| {
|
||||
Interrupt::from(GraphError {
|
||||
kind: core_types::gpoll::ErrorKind::ArenaExhausted,
|
||||
trace: Vec::new(),
|
||||
})
|
||||
})?
|
||||
.0;
|
||||
|
||||
Ok((
|
||||
actual_image.into_element(),
|
||||
Attr(transform),
|
||||
Attr(blend_mode),
|
||||
Attr(opacity),
|
||||
Attr(fill),
|
||||
Attr(clip),
|
||||
Attr(layer_path.as_slice()),
|
||||
))
|
||||
}
|
||||
|
||||
/// The pre-flip brush body, on legacy items: one background item plus every
|
||||
/// stroke in order, returning the painted image.
|
||||
fn brush_core(list_item: Item<Raster<CPU>>, strokes: Vec<BrushStroke>, cache: &BrushCache) -> Item<Raster<CPU>> {
|
||||
let bounds = List::new_from_item(list_item.clone()).bounding_box(DAffine2::IDENTITY, false);
|
||||
let [start, end] = if let RenderBoundingBox::Rectangle(rect) = bounds { rect } else { [DVec2::ZERO, DVec2::ZERO] };
|
||||
let background_bbox = AxisAlignedBbox { start, end };
|
||||
let stroke_bbox = trace.iter_element_values().map(|s| s.bounding_box()).reduce(|a, b| a.union(&b)).unwrap_or(AxisAlignedBbox::ZERO);
|
||||
let stroke_bbox = strokes.iter().map(|s| s.bounding_box()).reduce(|a, b| a.union(&b)).unwrap_or(AxisAlignedBbox::ZERO);
|
||||
let bbox = if background_bbox.size().length() < 0.1 {
|
||||
stroke_bbox
|
||||
} else {
|
||||
@@ -212,17 +287,19 @@ fn brush(
|
||||
};
|
||||
let background_bounds = bbox.to_transform();
|
||||
|
||||
let mut draw_strokes: Vec<_> = trace
|
||||
.iter_element_values()
|
||||
.filter(|&s| !matches!(s.style.blend_mode, BlendMode::Erase | BlendMode::Restore))
|
||||
.cloned()
|
||||
.collect();
|
||||
let mut draw_strokes: Vec<_> = strokes.iter().filter(|s| !matches!(s.style.blend_mode, BlendMode::Erase | BlendMode::Restore)).cloned().collect();
|
||||
|
||||
let mut brush_plan = cache.compute_brush_plan(list_item, &draw_strokes);
|
||||
|
||||
// TODO: Find a way to handle more than one item
|
||||
let Some(mut actual_image) = extend_image_to_bounds(&(), List::new_from_item(brush_plan.background), background_bounds).into_iter().next() else {
|
||||
return List::new();
|
||||
let mut actual_image = {
|
||||
let background = brush_plan.background;
|
||||
let transform: DAffine2 = background.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let (element, attributes) = background.into_parts();
|
||||
let (element, transform) = extend_image_to_bounds_core(element, transform, background_bounds);
|
||||
let mut item = Item::from_parts(element, attributes);
|
||||
item.set_attribute(ATTR_TRANSFORM, transform);
|
||||
item
|
||||
};
|
||||
|
||||
let final_stroke_idx = brush_plan.strokes.len().saturating_sub(1);
|
||||
@@ -254,9 +331,16 @@ fn brush(
|
||||
|
||||
let blit_target = if idx == 0 {
|
||||
let target = core::mem::take(&mut brush_plan.first_stroke_texture);
|
||||
extend_image_to_bounds(&(), List::new_from_item(target), stroke_to_layer)
|
||||
let transform: DAffine2 = target.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let (element, attributes) = target.into_parts();
|
||||
let (element, transform) = extend_image_to_bounds_core(element, transform, stroke_to_layer);
|
||||
let mut item = Item::from_parts(element, attributes);
|
||||
item.set_attribute(ATTR_TRANSFORM, transform);
|
||||
List::new_from_item(item)
|
||||
} else {
|
||||
empty_image(&(), stroke_to_layer, List::new_from_element(Color::TRANSPARENT))
|
||||
let mut item = Item::new_from_element(empty_image_core(stroke_to_layer, Color::TRANSPARENT));
|
||||
item.set_attribute(ATTR_TRANSFORM, stroke_to_layer);
|
||||
List::new_from_item(item)
|
||||
};
|
||||
|
||||
let list = blit(&(), blit_target, brush_texture, positions, |a, b| blend_colors(a, b, BlendMode::Normal, 1.));
|
||||
@@ -273,12 +357,12 @@ fn brush(
|
||||
actual_image = blend_with_mode(actual_image, stroke_texture, stroke.style.blend_mode, (stroke.style.color.a() * 100.) as f64);
|
||||
}
|
||||
|
||||
let has_erase_or_restore_strokes = trace.iter_element_values().any(|s| matches!(s.style.blend_mode, BlendMode::Erase | BlendMode::Restore));
|
||||
let has_erase_or_restore_strokes = strokes.iter().any(|s| matches!(s.style.blend_mode, BlendMode::Erase | BlendMode::Restore));
|
||||
if has_erase_or_restore_strokes {
|
||||
let opaque_image = Image::new(bbox.size().x as u32, bbox.size().y as u32, Color::WHITE);
|
||||
let mut erase_restore_mask = Item::new_from_element(Raster::new_cpu(opaque_image)).with_attribute(ATTR_TRANSFORM, background_bounds);
|
||||
|
||||
for stroke in trace.into_iter().map(|row| row.into_element()) {
|
||||
for stroke in strokes {
|
||||
let mut brush_texture = cache.get_cached_brush(&stroke.style);
|
||||
if brush_texture.is_none() {
|
||||
let tex = create_brush_texture(&stroke.style);
|
||||
@@ -306,22 +390,7 @@ fn brush(
|
||||
actual_image = blend_image_closure(erase_restore_mask, actual_image, |a, b| blend_colors(a, b, BlendMode::MultiplyAlpha, 1.));
|
||||
}
|
||||
|
||||
let transform: DAffine2 = actual_image.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let blend_mode: BlendMode = actual_image.attribute_cloned_or_default(ATTR_BLEND_MODE);
|
||||
let opacity: f64 = actual_image.attribute_cloned_or(ATTR_OPACITY, 1.);
|
||||
let fill: f64 = actual_image.attribute_cloned_or(ATTR_OPACITY_FILL, 1.);
|
||||
let clip: bool = actual_image.attribute_cloned_or_default(ATTR_CLIPPING_MASK);
|
||||
let layer: List<NodeId> = actual_image.attribute_cloned_or_default(ATTR_EDITOR_LAYER_PATH);
|
||||
|
||||
*background.element_mut(0).unwrap() = actual_image.into_element();
|
||||
background.set_attribute(ATTR_TRANSFORM, 0, transform);
|
||||
background.set_attribute(ATTR_BLEND_MODE, 0, blend_mode);
|
||||
background.set_attribute(ATTR_OPACITY, 0, opacity);
|
||||
background.set_attribute(ATTR_OPACITY_FILL, 0, fill);
|
||||
background.set_attribute(ATTR_CLIPPING_MASK, 0, clip);
|
||||
background.set_attribute(ATTR_EDITOR_LAYER_PATH, 0, layer);
|
||||
|
||||
background
|
||||
actual_image
|
||||
}
|
||||
|
||||
pub fn blend_image_closure(foreground: Item<Raster<CPU>>, mut background: Item<Raster<CPU>>, map_fn: impl Fn(Color, Color) -> Color) -> Item<Raster<CPU>> {
|
||||
@@ -406,11 +475,9 @@ mod test {
|
||||
|
||||
#[test]
|
||||
fn test_brush_output_size() {
|
||||
let image = brush(
|
||||
&(),
|
||||
&BrushCache::default(),
|
||||
List::new_from_element(Raster::new_cpu(Image::<Color>::default())),
|
||||
List::new_from_element(BrushStroke {
|
||||
let image = brush_core(
|
||||
Item::new_from_element(Raster::new_cpu(Image::<Color>::default())),
|
||||
vec![BrushStroke {
|
||||
trace: vec![crate::brush_stroke::BrushInputSample { position: DVec2::ZERO }],
|
||||
style: BrushStyle {
|
||||
color: Color::BLACK,
|
||||
@@ -420,8 +487,9 @@ mod test {
|
||||
spacing: 20.,
|
||||
blend_mode: BlendMode::Normal,
|
||||
},
|
||||
}),
|
||||
}],
|
||||
&BrushCache::default(),
|
||||
);
|
||||
assert_eq!(image.element(0).unwrap().width, 20);
|
||||
assert_eq!(image.element().width, 20);
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,14 @@
|
||||
use core_types::gpoll::{Extent, GPoll, GraphError, Interrupt};
|
||||
use core_types::list::List;
|
||||
use core_types::{Color, ExtractVarArgs};
|
||||
use core_types::{Ctx, ExtractIndex, ExtractPosition};
|
||||
use core_types::{Ctx, ExtractIndex, ExtractIndices, ExtractPosition};
|
||||
use glam::DVec2;
|
||||
use graphic_types::vector_types::GradientStops;
|
||||
use graphic_types::{Graphic, Vector};
|
||||
use raster_types::{CPU, Raster};
|
||||
|
||||
#[node_macro::node(category("Context"), path(graphene_core::vector))]
|
||||
fn read_graphic(ctx: impl Ctx + ExtractVarArgs) -> List<Graphic> {
|
||||
fn read_graphic(ctx: impl Ctx + ExtractVarArgs) -> List<Graphic<'static>> {
|
||||
let Ok(var_arg) = ctx.vararg(0) else { return Default::default() };
|
||||
let var_arg = var_arg as &dyn std::any::Any;
|
||||
|
||||
@@ -46,6 +47,78 @@ fn read_gradient(ctx: impl Ctx + ExtractVarArgs) -> List<GradientStops> {
|
||||
var_arg.downcast_ref().cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The mapped row riding as vararg 0, in the production single-item shape.
|
||||
fn vararg_list<'a, T: 'static>(ctx: &'a impl ExtractVarArgs) -> Option<&'a List<T>> {
|
||||
let arg = ctx.vararg(0).ok()?;
|
||||
(arg as &dyn std::any::Any).downcast_ref::<List<T>>()
|
||||
}
|
||||
|
||||
/// Lanes of a leveled vararg source: one per item, none without a row,
|
||||
/// matching the legacy empty-list return.
|
||||
fn vararg_lanes<T: 'static>(ctx: &impl ExtractVarArgs, level: u8) -> GPoll<Extent> {
|
||||
match level {
|
||||
0 => GPoll::Final(Extent::Exactly(vararg_list::<T>(ctx).map_or(0, List::len))),
|
||||
_ => GPoll::Final(Extent::Exactly(1)),
|
||||
}
|
||||
}
|
||||
|
||||
fn vararg_element<T: Clone + 'static>(ctx: &(impl ExtractVarArgs + ExtractIndex)) -> Result<T, Interrupt> {
|
||||
vararg_list::<T>(ctx)
|
||||
.and_then(|list| list.element(ctx.index() as usize))
|
||||
.cloned()
|
||||
.ok_or_else(|| GraphError::new("vararg row addressed past its items").into())
|
||||
}
|
||||
|
||||
/// Rank-model vararg source: the mapped row's items as lanes, elements only.
|
||||
#[node_macro::node(category("Test"), extent_raw(read_graphic_row_extent))]
|
||||
pub fn read_graphic_row(ctx: impl Ctx + ExtractVarArgs + ExtractIndex) -> Result<IList<Graphic<'static>>, Interrupt> {
|
||||
vararg_element(ctx)
|
||||
}
|
||||
|
||||
fn read_graphic_row_extent<C: Ctx + ExtractVarArgs>(_: &ReadGraphicRowNode, ctx: &C, level: u8) -> GPoll<Extent> {
|
||||
vararg_lanes::<Graphic>(ctx, level)
|
||||
}
|
||||
|
||||
/// Rank-model vararg source: the mapped row's items as lanes, elements only.
|
||||
#[node_macro::node(category("Test"), extent_raw(read_vector_row_extent))]
|
||||
pub fn read_vector_row(ctx: impl Ctx + ExtractVarArgs + ExtractIndex) -> Result<IList<Vector>, Interrupt> {
|
||||
vararg_element(ctx)
|
||||
}
|
||||
|
||||
fn read_vector_row_extent<C: Ctx + ExtractVarArgs>(_: &ReadVectorRowNode, ctx: &C, level: u8) -> GPoll<Extent> {
|
||||
vararg_lanes::<Vector>(ctx, level)
|
||||
}
|
||||
|
||||
/// Rank-model vararg source: the mapped row's items as lanes, elements only.
|
||||
#[node_macro::node(category("Test"), extent_raw(read_raster_row_extent))]
|
||||
pub fn read_raster_row(ctx: impl Ctx + ExtractVarArgs + ExtractIndex) -> Result<IList<Raster<CPU>>, Interrupt> {
|
||||
vararg_element(ctx)
|
||||
}
|
||||
|
||||
fn read_raster_row_extent<C: Ctx + ExtractVarArgs>(_: &ReadRasterRowNode, ctx: &C, level: u8) -> GPoll<Extent> {
|
||||
vararg_lanes::<Raster<CPU>>(ctx, level)
|
||||
}
|
||||
|
||||
/// Rank-model vararg source: the mapped row's items as lanes, elements only.
|
||||
#[node_macro::node(category("Test"), extent_raw(read_color_row_extent))]
|
||||
pub fn read_color_row(ctx: impl Ctx + ExtractVarArgs + ExtractIndex) -> Result<IList<Color>, Interrupt> {
|
||||
vararg_element(ctx)
|
||||
}
|
||||
|
||||
fn read_color_row_extent<C: Ctx + ExtractVarArgs>(_: &ReadColorRowNode, ctx: &C, level: u8) -> GPoll<Extent> {
|
||||
vararg_lanes::<Color>(ctx, level)
|
||||
}
|
||||
|
||||
/// Rank-model vararg source: the mapped row's items as lanes, elements only.
|
||||
#[node_macro::node(category("Test"), extent_raw(read_gradient_row_extent))]
|
||||
pub fn read_gradient_row(ctx: impl Ctx + ExtractVarArgs + ExtractIndex) -> Result<IList<GradientStops>, Interrupt> {
|
||||
vararg_element(ctx)
|
||||
}
|
||||
|
||||
fn read_gradient_row_extent<C: Ctx + ExtractVarArgs>(_: &ReadGradientRowNode, ctx: &C, level: u8) -> GPoll<Extent> {
|
||||
vararg_lanes::<GradientStops>(ctx, level)
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Context"), path(core_types::vector))]
|
||||
fn read_position(
|
||||
ctx: impl Ctx + ExtractPosition,
|
||||
@@ -65,12 +138,16 @@ fn read_position(
|
||||
/// Nested loops can enable 2D or higher-dimensional iteration by using the *Loop Level* parameter to read the index from outer levels of loops.
|
||||
#[node_macro::node(category("Context"), path(core_types::vector))]
|
||||
fn read_index(
|
||||
ctx: impl Ctx + ExtractIndex,
|
||||
// `loop_level` is a runtime input, so no level is statically known and the
|
||||
// whole chain has to survive nullification.
|
||||
ctx: impl Ctx + ExtractIndices,
|
||||
_primary: (),
|
||||
/// The number of nested loops to traverse outwards (from the innermost loop) to get the index from. The most upstream loop is level 0, and downstream loops add levels.
|
||||
///
|
||||
/// In programming terms: inside the double loop `i { j { ... } }`, *Loop Level* 0 = `j` and 1 = `i`. After inserting a third loop `k { ... }`, inside it, levels would be 0 = `k`, 1 = `j`, and 2 = `i`.
|
||||
loop_level: u32,
|
||||
) -> f64 {
|
||||
ctx.try_index().and_then(|mut iter| iter.nth(loop_level as usize).or_else(|| iter.last())).unwrap_or(0) as f64
|
||||
// The chain's innermost entry is the consuming wire's own lane from the
|
||||
// decompose-and-promote split; the loops the reader counts sit above it.
|
||||
ctx.try_index().and_then(|mut iter| iter.nth(loop_level as usize + 1)).unwrap_or(0) as f64
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
use core_types::context::{Context, ContextModification, Ctx, DeriveCtx};
|
||||
use core_types::gpoll::Interrupt;
|
||||
use core_types::context::{ContextFeatures, ContextModification, Ctx, DeriveCtx, IndexLink, nullify_index_levels};
|
||||
use core_types::gpoll::{ErrorKind, GraphError, Interrupt};
|
||||
|
||||
/// Filters out what should be unused components of the context based on the specified requirements.
|
||||
/// This node is inserted by the compiler to "zero out" unused context components.
|
||||
@@ -12,5 +12,15 @@ fn context_modification<T>(
|
||||
modification: ContextModification,
|
||||
) -> Result<T, Interrupt> {
|
||||
let scope = ctx.scope().nullified(modification.features, Some(modification.sources()));
|
||||
value.eval(&ctx.nullified(modification.features, &scope))
|
||||
let exhausted = || {
|
||||
Interrupt::from(GraphError {
|
||||
kind: ErrorKind::ArenaExhausted,
|
||||
trace: Vec::new(),
|
||||
})
|
||||
};
|
||||
let index = match modification.features.contains(ContextFeatures::INDEX) {
|
||||
true => nullify_index_levels(ctx.index_head(), modification.index_levels, scope.arena()).ok_or_else(exhausted)?,
|
||||
false => IndexLink { index: 0, outer: None },
|
||||
};
|
||||
value.eval(&ctx.nullified(modification.features, index, &scope))
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
use core_types::Ctx;
|
||||
use core_types::list::List;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use raster_types::{CPU, Raster};
|
||||
|
||||
@@ -31,6 +30,6 @@ fn unwrap_option<T: Default>(_: impl Ctx, #[implementations(Option<f64>, Option<
|
||||
|
||||
/// Clones the element out of its record wire.
|
||||
#[node_macro::node(category("Debug"))]
|
||||
fn clone<T: Clone>(_: impl Ctx, #[implementations(List<Raster<CPU>>)] value: &T) -> T {
|
||||
fn clone<T: Clone>(_: impl Ctx, #[implementations(Raster<CPU>, f64)] value: &T) -> T {
|
||||
value.clone()
|
||||
}
|
||||
+567
-158
@@ -1,127 +1,257 @@
|
||||
use core_types::arena::ArenaCell;
|
||||
use core_types::context::{Ctx, CtxSnapshot, DeriveCtx, ExtractAll, ExtractArena};
|
||||
use core_types::frame_table::{FrameTable, Lookup};
|
||||
use core_types::gpoll::{Extent, Finality, GPoll};
|
||||
use core_types::context::{Ctx, CtxSnapshot, DeriveCtx, ExtractAll, ModifyIndex};
|
||||
use core_types::gpoll::{Finality, GPoll};
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::memo::IORecord;
|
||||
use core_types::node::Node;
|
||||
use core_types::record::{OwnedRecord, RecordCapture, RecordValue, copy_record_bytes, record_from_bytes};
|
||||
use core_types::record::{FrameClaim, LevelStatus, MaterializedSpan, OwnedRecord, Promotion, Served};
|
||||
use core_types::registry::cache_key;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
|
||||
/// The memo entry: the deep copies survive a persistent flush, while the span
|
||||
/// serves lanes straight out of the persistent region (generation-guarded), so
|
||||
/// a hit before the next flush allocates nothing.
|
||||
#[derive(Debug)]
|
||||
pub struct MemoLevel {
|
||||
key: u64,
|
||||
/// The persistent region the level was promoted into, resolvable only
|
||||
/// while that region's epoch is live.
|
||||
span: Option<MaterializedSpan>,
|
||||
lanes: Vec<OwnedRecord>,
|
||||
finality: Finality,
|
||||
}
|
||||
|
||||
/// Helps speed up repeated renders in a computationally-heavy part of the node graph.
|
||||
///
|
||||
/// Stores a deep copy of the last record that flowed through this node and replays it on subsequent renders if the context has not changed.
|
||||
#[node_macro::node(category("General"), path(graphene_core::memo), extent(memoize_extent))]
|
||||
fn memoize<'e>(
|
||||
ctx: impl Ctx + CacheHash + ExtractArena<'e>,
|
||||
#[data] cache: Arc<Mutex<Option<(u64, OwnedRecord, Finality)>>>,
|
||||
content: impl Node<Context<'_>, Output = RecordValue<'e>>,
|
||||
) -> GPoll<RecordValue<'e>> {
|
||||
let key = cache_key(&ctx);
|
||||
if let Some((hash, copy, finality)) = cache.lock().unwrap().as_ref()
|
||||
&& *hash == key
|
||||
{
|
||||
return match copy.replay(content.layout(), ctx.arena()) {
|
||||
Some(value) => match finality {
|
||||
Finality::AllFinal => GPoll::Final(value),
|
||||
Finality::Partial => GPoll::Partial(value),
|
||||
},
|
||||
/// Stores a deep copy of the last record (a scalar wire) or the last whole
|
||||
/// level (a leveled wire) that flowed through this node and replays it on
|
||||
/// subsequent renders if the context has not changed. The owned copies survive
|
||||
/// a persistent flush, so this is the memo for content whose recomputation is
|
||||
/// expensive. A leveled wire's cache key normalizes the addressed lane away,
|
||||
/// so per-lane pulls share one materialization of the content instead of
|
||||
/// re-evaluating it per lane.
|
||||
#[node_macro::node(category("General"), path(graphene_core::memo))]
|
||||
fn memoize<'e, 'l>(
|
||||
ctx: impl Ctx + CacheHash + DeriveCtx + ExtractArena<'e> + ModifyIndex + Copy,
|
||||
#[data] cache: Arc<Mutex<Option<MemoLevel>>>,
|
||||
content: impl Node<Context<'_>>,
|
||||
slot: FrameClaim<'e, 'l>,
|
||||
) -> GPoll<Served<'e>> {
|
||||
// A scalar wire's value may depend on the consuming lane (index readers),
|
||||
// so only a leveled wire, whose level covers every lane by construction,
|
||||
// keys with the lane normalized away.
|
||||
let leveled = content.layout().depth > 0;
|
||||
let lane = match leveled {
|
||||
true => ctx.index() as usize,
|
||||
false => 0,
|
||||
};
|
||||
let key = match leveled {
|
||||
true => {
|
||||
let mut keyed = *ctx;
|
||||
keyed.set_index(0);
|
||||
cache_key(&keyed)
|
||||
}
|
||||
false => cache_key(&ctx),
|
||||
};
|
||||
let mut slot = slot;
|
||||
let promotion = Promotion::new(ctx.arena(), slot.frames().bounds(), ctx.scope().persistent());
|
||||
let persistent = ctx.scope().persistent();
|
||||
let finalized = |value: Served<'e>, finality: &Finality| match finality {
|
||||
Finality::AllFinal => GPoll::Final(value),
|
||||
Finality::Partial => GPoll::Partial(value),
|
||||
};
|
||||
// The claim is this node's output frame: a hit fills it from the cached
|
||||
// bytes, and every valueless exit drops it with the frame still claimed.
|
||||
let serve = |entry: &MemoLevel, mut slot: FrameClaim<'e, 'l>| {
|
||||
if lane >= entry.lanes.len() {
|
||||
// The cached level ends here; the past-end signal serves drains.
|
||||
return GPoll::Error(Box::new(core_types::gpoll::GraphError::past_end()));
|
||||
}
|
||||
if let Some(span) = entry.span
|
||||
&& let Some(src) = span.lane(persistent, lane, content.layout())
|
||||
{
|
||||
// SAFETY: the span resolved in generation, so the lane is live and
|
||||
// immutable at the layout it was promoted under.
|
||||
unsafe { slot.fill_copy(src) };
|
||||
// SAFETY: the copy images a complete record of this layout.
|
||||
return finalized(unsafe { slot.finish_served() }, &entry.finality);
|
||||
}
|
||||
match entry.lanes[lane].replay_into(&mut slot, ctx.arena()) {
|
||||
// SAFETY: the replay completes the record in the frame.
|
||||
Some(()) => finalized(unsafe { slot.finish_served() }, &entry.finality),
|
||||
None => GPoll::arena_exhausted(),
|
||||
}
|
||||
};
|
||||
if let Some(entry) = cache.lock().unwrap().as_ref()
|
||||
&& entry.key == key
|
||||
{
|
||||
return serve(entry, slot);
|
||||
}
|
||||
if leveled {
|
||||
return match content.materialize_level(&ctx, ctx.arena()) {
|
||||
LevelStatus::Batch(batch, finality) => {
|
||||
let layout = content.layout();
|
||||
// SAFETY: the batch came from this edge, so it carries the edge's layout.
|
||||
let lanes: Vec<OwnedRecord> = (0..batch.len()).map(|index| unsafe { OwnedRecord::copy_out(layout, batch.get(index).rec()) }).collect();
|
||||
let entry = MemoLevel {
|
||||
key,
|
||||
// SAFETY: as above.
|
||||
span: unsafe { MaterializedSpan::to_persistent(&batch, &promotion) },
|
||||
lanes,
|
||||
finality,
|
||||
};
|
||||
let result = serve(&entry, slot);
|
||||
*cache.lock().unwrap() = Some(entry);
|
||||
result
|
||||
}
|
||||
LevelStatus::Pending => GPoll::Pending,
|
||||
LevelStatus::Error(error) => GPoll::Error(Box::new(error)),
|
||||
};
|
||||
}
|
||||
let result = content.eval(&ctx);
|
||||
// The output layout is the content's, so the claim is the content's frame.
|
||||
let result = content.serve(&ctx, slot);
|
||||
let publishable = match &result {
|
||||
GPoll::Final(value) => Some((value, Finality::AllFinal)),
|
||||
GPoll::Partial(value) => Some((value, Finality::Partial)),
|
||||
GPoll::Final(served) => Some((served.record(), Finality::AllFinal)),
|
||||
GPoll::Partial(served) => Some((served.record(), Finality::Partial)),
|
||||
GPoll::Pending | GPoll::Fallback(_) | GPoll::Error(_) => None,
|
||||
};
|
||||
if let Some((value, finality)) = publishable {
|
||||
// SAFETY: the value came from this edge, so it carries the edge's layout.
|
||||
let copy = unsafe { OwnedRecord::copy_out(content.layout(), content.layout().rec(value)) };
|
||||
*cache.lock().unwrap() = Some((key, copy, finality));
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn memoize_extent<C, NodeContent>(node: &MemoizeNode<NodeContent>, ctx: &C) -> GPoll<Extent>
|
||||
where
|
||||
NodeContent: Node<C>,
|
||||
{
|
||||
node.content.extent(ctx)
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), path(graphene_core::memo), extent(frame_memo_extent))]
|
||||
fn frame_memo<'e>(
|
||||
ctx: impl Ctx + CacheHash + ExtractArena<'e>,
|
||||
#[data] cell: ArenaCell<FrameTable<Box<[u8]>, 32>>,
|
||||
content: impl Node<Context<'_>, Output = RecordValue<'e>>,
|
||||
) -> GPoll<RecordValue<'e>> {
|
||||
let arena = ctx.arena();
|
||||
let table = match cell.load(arena) {
|
||||
Some(table) => table,
|
||||
None => match arena.alloc(FrameTable::new()) {
|
||||
Some((table, weak)) => {
|
||||
cell.store(weak);
|
||||
table
|
||||
}
|
||||
None => return content.eval(&ctx),
|
||||
},
|
||||
};
|
||||
// SAFETY: published bytes are same-frame copies of this edge's records,
|
||||
// so they carry the edge's layout with live parked references.
|
||||
let revive = |bytes: &'e Box<[u8]>| unsafe { record_from_bytes(content.layout(), bytes) };
|
||||
match table.lookup(cache_key(ctx)) {
|
||||
Lookup::Hit(Finality::AllFinal, bytes) => GPoll::Final(revive(bytes)),
|
||||
Lookup::Hit(Finality::Partial, bytes) => GPoll::Partial(revive(bytes)),
|
||||
Lookup::Vacant(slot) => match content.eval(&ctx) {
|
||||
GPoll::Final(value) => {
|
||||
// SAFETY: the value came from this edge, so it carries the edge's layout.
|
||||
let bytes = unsafe { copy_record_bytes(content.layout(), content.layout().rec(&value)) };
|
||||
GPoll::Final(revive(slot.publish(bytes, Finality::AllFinal)))
|
||||
}
|
||||
GPoll::Partial(value) => {
|
||||
// SAFETY: as above.
|
||||
let bytes = unsafe { copy_record_bytes(content.layout(), content.layout().rec(&value)) };
|
||||
GPoll::Partial(revive(slot.publish(bytes, Finality::Partial)))
|
||||
}
|
||||
unpublishable => {
|
||||
slot.release();
|
||||
unpublishable
|
||||
}
|
||||
},
|
||||
Lookup::Full => content.eval(&ctx),
|
||||
}
|
||||
}
|
||||
|
||||
fn frame_memo_extent<C, NodeContent>(node: &FrameMemoNode<NodeContent>, ctx: &C) -> GPoll<Extent>
|
||||
where
|
||||
NodeContent: Node<C>,
|
||||
{
|
||||
node.content.extent(ctx)
|
||||
}
|
||||
|
||||
type MonitorValue = Arc<Mutex<Option<IORecord<CtxSnapshot, RecordCapture>>>>;
|
||||
|
||||
/// The Monitor node is used by the editor to access the data flowing through it.
|
||||
#[node_macro::node(category(""), path(graphene_core::memo), serialize(serialize_monitor), properties("monitor_properties"))]
|
||||
fn monitor<'e>(ctx: impl Ctx + DeriveCtx + ExtractAll + ExtractArena<'e>, #[data] io: MonitorValue, content: impl Node<Context<'_>, Output = RecordValue<'e>>) -> GPoll<RecordValue<'e>> {
|
||||
let result = content.eval(&ctx);
|
||||
if let GPoll::Final(value) | GPoll::Partial(value) = &result {
|
||||
// SAFETY: the value came from this edge, so it carries the edge's layout.
|
||||
let captured = unsafe { RecordCapture::capture(content.layout(), content.layout().rec(value), ctx.arena()) };
|
||||
*io.lock().unwrap() = captured.map(|output| IORecord {
|
||||
input: CtxSnapshot::capture(ctx),
|
||||
output,
|
||||
let layout = content.layout();
|
||||
// SAFETY: the value came from this edge, so it carries the edge's
|
||||
// layout, and one record of it is a batch of one lane.
|
||||
let batch = unsafe { core_types::node::RecordBatch::new(layout.rec(value).ptr(), 1, layout) };
|
||||
// SAFETY: as above.
|
||||
let copy = unsafe { OwnedRecord::copy_out(layout, layout.rec(value)) };
|
||||
*cache.lock().unwrap() = Some(MemoLevel {
|
||||
key,
|
||||
// SAFETY: as above.
|
||||
span: unsafe { MaterializedSpan::to_persistent(&batch, &promotion) },
|
||||
lanes: vec![copy],
|
||||
finality,
|
||||
});
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// The span memo's entry: the span resolves only while the persistent epoch
|
||||
/// that published it is live, so a flush costs a re-publish and nothing else.
|
||||
#[derive(Debug)]
|
||||
pub struct SpanLevel {
|
||||
key: u64,
|
||||
span: MaterializedSpan,
|
||||
finality: Finality,
|
||||
}
|
||||
|
||||
/// The cheap memo the compiler inserts at context boundaries: a published
|
||||
/// level lives in the persistent region and serves cross-evaluation hits by
|
||||
/// byte copy until the next flush, which costs a re-publish rather than a deep
|
||||
/// copy.
|
||||
#[node_macro::node(category(""), path(graphene_core::memo))]
|
||||
fn frame_memo<'e, 'l>(
|
||||
ctx: impl Ctx + CacheHash + DeriveCtx + ExtractArena<'e> + ModifyIndex + Copy,
|
||||
#[data] cache: Arc<Mutex<Option<SpanLevel>>>,
|
||||
content: impl Node<Context<'_>>,
|
||||
slot: FrameClaim<'e, 'l>,
|
||||
) -> GPoll<Served<'e>> {
|
||||
// A scalar wire's value may depend on the consuming lane (index readers),
|
||||
// so only a leveled wire, whose level covers every lane by construction,
|
||||
// keys with the lane normalized away.
|
||||
let leveled = content.layout().depth > 0;
|
||||
let lane = match leveled {
|
||||
true => ctx.index() as usize,
|
||||
false => 0,
|
||||
};
|
||||
let key = match leveled {
|
||||
true => {
|
||||
let mut keyed = *ctx;
|
||||
keyed.set_index(0);
|
||||
cache_key(&keyed)
|
||||
}
|
||||
false => cache_key(&ctx),
|
||||
};
|
||||
let mut slot = slot;
|
||||
let promotion = Promotion::new(ctx.arena(), slot.frames().bounds(), ctx.scope().persistent());
|
||||
let persistent = ctx.scope().persistent();
|
||||
let finalized = |value: Served<'e>, finality: Finality| match finality {
|
||||
Finality::AllFinal => GPoll::Final(value),
|
||||
Finality::Partial => GPoll::Partial(value),
|
||||
};
|
||||
// The claim is this node's output frame: a hit fills it from the published
|
||||
// bytes, and every valueless exit drops it with the frame still claimed.
|
||||
let serve = |src: *const u8, finality: Finality, mut slot: FrameClaim<'e, 'l>| {
|
||||
// SAFETY: the source images a complete record of this layout, and the
|
||||
// span resolved in generation, so its parked payloads are live.
|
||||
unsafe { slot.fill_copy(src) };
|
||||
// SAFETY: the copy images a complete record of this layout.
|
||||
finalized(unsafe { slot.finish_served() }, finality)
|
||||
};
|
||||
let past_end = || GPoll::Error(Box::new(core_types::gpoll::GraphError::past_end()));
|
||||
let entry = cache.lock().unwrap().as_ref().filter(|entry| entry.key == key).map(|entry| (entry.span, entry.finality));
|
||||
// A span that no longer resolves was flushed; the miss below re-publishes.
|
||||
if let Some((span, finality)) = entry
|
||||
&& let Some(published) = span.batch(persistent, content.layout())
|
||||
{
|
||||
if lane >= published.len() {
|
||||
// The cached level ends here; the past-end signal serves drains.
|
||||
return past_end();
|
||||
}
|
||||
return serve(published.get(lane).rec().ptr(), finality, slot);
|
||||
}
|
||||
if leveled {
|
||||
return match content.materialize_level(&ctx, ctx.arena()) {
|
||||
LevelStatus::Batch(batch, finality) => {
|
||||
// SAFETY: the batch came from this edge, so it carries the edge's layout.
|
||||
let span = unsafe { MaterializedSpan::to_persistent(&batch, &promotion) };
|
||||
*cache.lock().unwrap() = span.map(|span| SpanLevel { key, span, finality });
|
||||
match lane < batch.len() {
|
||||
// The publishing evaluation reads the resident batch, not the copy.
|
||||
true => serve(batch.get(lane).rec().ptr(), finality, slot),
|
||||
false => past_end(),
|
||||
}
|
||||
}
|
||||
LevelStatus::Pending => GPoll::Pending,
|
||||
LevelStatus::Error(error) => GPoll::Error(Box::new(error)),
|
||||
};
|
||||
}
|
||||
// The output layout is the content's, so the claim is the content's frame.
|
||||
let result = content.serve(&ctx, slot);
|
||||
let publishable = match &result {
|
||||
GPoll::Final(served) => Some((served.record(), Finality::AllFinal)),
|
||||
GPoll::Partial(served) => Some((served.record(), Finality::Partial)),
|
||||
GPoll::Pending | GPoll::Fallback(_) | GPoll::Error(_) => None,
|
||||
};
|
||||
if let Some((value, finality)) = publishable {
|
||||
let layout = content.layout();
|
||||
// SAFETY: the value came from this edge, so it carries the edge's
|
||||
// layout, and one record of it is a batch of one lane.
|
||||
let batch = unsafe { core_types::node::RecordBatch::new(layout.rec(value).ptr(), 1, layout) };
|
||||
// SAFETY: as above.
|
||||
let span = unsafe { MaterializedSpan::to_persistent(&batch, &promotion) };
|
||||
*cache.lock().unwrap() = span.map(|span| SpanLevel { key, span, finality });
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
type MonitorValue = Arc<Mutex<Option<CtxSnapshot>>>;
|
||||
|
||||
/// The Monitor node is used by the editor to access the data flowing through
|
||||
/// it. It stores only the evaluation context: the output is pure over
|
||||
/// (context, source generations), so introspection recreates it by
|
||||
/// re-evaluating this edge with the rehydrated snapshot.
|
||||
#[node_macro::node(category(""), path(graphene_core::memo), serialize(serialize_monitor), properties("monitor_properties"))]
|
||||
fn monitor<'e, 'l>(
|
||||
ctx: impl Ctx + DeriveCtx + ExtractAll + ExtractArena<'e> + ModifyIndex + Copy,
|
||||
#[data] io: MonitorValue,
|
||||
content: impl Node<Context<'_>>,
|
||||
slot: FrameClaim<'e, 'l>,
|
||||
) -> GPoll<Served<'e>> {
|
||||
if ctx.index() == 0 {
|
||||
*io.lock().unwrap() = Some(CtxSnapshot::capture(ctx));
|
||||
}
|
||||
content.serve(&ctx, slot)
|
||||
}
|
||||
|
||||
fn serialize_monitor(io: &MonitorValue) -> Option<Arc<dyn std::any::Any + Send + Sync>> {
|
||||
let io = io.lock().unwrap();
|
||||
io.as_ref().map(|io| Arc::new(io.clone()) as Arc<dyn std::any::Any + Send + Sync>)
|
||||
io.as_ref().map(|snapshot| Arc::new(snapshot.clone()) as Arc<dyn std::any::Any + Send + Sync>)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -130,92 +260,180 @@ mod tests {
|
||||
use core_types::SourceId;
|
||||
use core_types::arena::Arena;
|
||||
use core_types::context::{ContextImpl, EvalScope};
|
||||
use core_types::registry::{EdgeHandle, ErasedNode, ErasedRecordNode};
|
||||
use core_types::node::Node;
|
||||
use core_types::record::LiftedSource;
|
||||
use core_types::registry::{EdgeHandle, ErasedRecordNode};
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
|
||||
struct CountingNode(AtomicU32);
|
||||
|
||||
impl<Input> Node<Input> for CountingNode {
|
||||
type Output = u32;
|
||||
|
||||
fn eval(&self, _input: &Input) -> GPoll<u32> {
|
||||
GPoll::Final(self.0.fetch_add(1, Ordering::Relaxed) + 1)
|
||||
}
|
||||
fn lifted<T: Clone + Send + Sync + core_types::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()))
|
||||
}
|
||||
|
||||
struct PartialCountingNode(AtomicU32);
|
||||
|
||||
impl<Input> Node<Input> for PartialCountingNode {
|
||||
type Output = u32;
|
||||
|
||||
fn eval(&self, _input: &Input) -> GPoll<u32> {
|
||||
GPoll::Partial(self.0.fetch_add(1, Ordering::Relaxed) + 1)
|
||||
}
|
||||
fn counting() -> LiftedSource<u32, impl for<'c> Fn(&ContextImpl<'c>) -> GPoll<u32>> {
|
||||
let count = AtomicU32::new(0);
|
||||
LiftedSource::new(move |_: &ContextImpl<'_>| GPoll::Final(count.fetch_add(1, Ordering::Relaxed) + 1))
|
||||
}
|
||||
|
||||
struct ValueNode<T>(T);
|
||||
|
||||
impl<T: Clone, Input> Node<Input> for ValueNode<T> {
|
||||
type Output = T;
|
||||
|
||||
fn eval(&self, _input: &Input) -> GPoll<T> {
|
||||
GPoll::Final(self.0.clone())
|
||||
}
|
||||
fn partial_counting() -> LiftedSource<u32, impl for<'c> Fn(&ContextImpl<'c>) -> GPoll<u32>> {
|
||||
let count = AtomicU32::new(0);
|
||||
LiftedSource::new(move |_: &ContextImpl<'_>| GPoll::Partial(count.fetch_add(1, Ordering::Relaxed) + 1))
|
||||
}
|
||||
|
||||
fn scope_fixture<'a>(generations: &'a [(SourceId, u64)], arena: &'a Arena) -> EvalScope<'a> {
|
||||
core_types::record::stack::reserve(1 << 16);
|
||||
EvalScope::new(Some(0.5), None, None, generations, arena)
|
||||
}
|
||||
|
||||
fn element_layout<T: Clone + Send + Sync + 'static>() -> core_types::record::Layout {
|
||||
fn element_layout<T: Clone + Send + Sync + core_types::StaticTypeSized>() -> core_types::record::Layout
|
||||
where
|
||||
T::Static: Clone + Send + Sync,
|
||||
{
|
||||
core_types::record::Layout::default().with_writes(0, core_types::record::element_write::<T>(), &[])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn monitor_serialize_exposes_the_capture_through_the_edge() {
|
||||
fn monitor_serialize_recreates_the_value_from_its_snapshot() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let layout = element_layout::<u32>();
|
||||
let monitor = MonitorNode::new(core_types::record::RecordLift::<u32, _>::new(ValueNode(11u32)), &layout);
|
||||
let monitor = MonitorNode::new(lifted::<u32>(11u32), &layout);
|
||||
let handle = EdgeHandle::new_record::<u32>(Arc::new(monitor) as Arc<ErasedRecordNode>);
|
||||
assert!(handle.serialize().is_none(), "no capture before the first eval");
|
||||
assert!(handle.serialize().is_none(), "no snapshot before the first eval");
|
||||
|
||||
let edge = handle.duplicate().downcast_record::<u32>().unwrap();
|
||||
let GPoll::Final(_) = edge.eval(&ctx) else {
|
||||
let GPoll::Final(_) = core_types::record::serve_edge(&edge, &ctx, &frames) else {
|
||||
panic!("expected a final record");
|
||||
};
|
||||
|
||||
let io = handle.serialize().expect("the eval landed a capture");
|
||||
let io = io.downcast_ref::<IORecord<CtxSnapshot, RecordCapture>>().expect("the capture is the monitor io");
|
||||
assert!(
|
||||
core_types::context::ExtractFootprint::try_footprint(&io.input).is_none(),
|
||||
"the root context has no footprint to capture"
|
||||
let io = handle.serialize().expect("the eval landed a snapshot");
|
||||
let snapshot = io.downcast_ref::<CtxSnapshot>().expect("the monitor serializes its context snapshot");
|
||||
let ctx = snapshot.rehydrate(&scope).expect("the arena holds the chains");
|
||||
let GPoll::Final(served) = core_types::record::capture(&edge, &ctx, &frames) else {
|
||||
panic!("expected a final record");
|
||||
};
|
||||
assert_eq!(served.element::<u32>(), 11);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_leveled_monitor_recreates_the_whole_extent() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(1 << 12).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let source = core_types::value::LeveledValueSource::new(vec![10u32, 20, 30]);
|
||||
let layout = Node::<ContextImpl>::layout(&source).clone();
|
||||
let monitor = MonitorNode::new(source, &layout);
|
||||
let handle = EdgeHandle::new_record::<u32>(Arc::new(monitor) as Arc<ErasedRecordNode>);
|
||||
|
||||
let edge = handle.duplicate().downcast_record::<u32>().unwrap();
|
||||
let GPoll::Final(_) = core_types::record::serve_edge(&edge, &ctx, &frames) else {
|
||||
panic!("expected a final record");
|
||||
};
|
||||
|
||||
let io = handle.serialize().expect("the eval landed a snapshot");
|
||||
let snapshot = io.downcast_ref::<CtxSnapshot>().expect("the monitor serializes its context snapshot");
|
||||
let ctx = snapshot.rehydrate(&scope).expect("the arena holds the chains");
|
||||
let LevelStatus::Batch(batch, _) = core_types::record::materialize_level(&edge, &ctx, &arena, &frames) else {
|
||||
panic!("expected a materialized level");
|
||||
};
|
||||
assert_eq!(batch.len(), 3, "the recreation holds the whole extent, not the addressed lane");
|
||||
let lanes = unsafe { core_types::node::List::<u32>::new(batch) };
|
||||
let values: Vec<u32> = (0..lanes.len()).map(|lane| *lanes.element_ref(lane)).collect();
|
||||
assert_eq!(values, vec![10, 20, 30]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memo_copy_out_consults_the_deep_element_clone() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
#[derive(Clone, Debug, PartialEq, dyn_any::DynAny)]
|
||||
struct Payload(String, u32);
|
||||
unsafe fn deep(ptr: *const u8) -> Box<dyn std::any::Any + Send + Sync> {
|
||||
let value = unsafe { core_types::record::borrow_element::<Payload>(core_types::record::Rec::new(ptr)) };
|
||||
Box::new(Payload(value.0.clone(), value.1 + 1))
|
||||
}
|
||||
unsafe fn deep_repark(value: &(dyn std::any::Any + Send + Sync), dst: *mut u8, arena: &Arena) -> Option<()> {
|
||||
let value = value.downcast_ref::<Payload>().expect("an element replays at its own type");
|
||||
unsafe { core_types::record::write_element(dst, Payload(value.0.clone(), value.1 + 1), arena) }
|
||||
}
|
||||
core_types::record::register_deep_element_clone::<Payload>(deep, deep_repark);
|
||||
|
||||
let arena = Arena::new(4096).unwrap();
|
||||
let persistent = Arena::new(4096).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena).with_persistent(&persistent);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let layout = element_layout::<Payload>();
|
||||
let memoized = MemoizeNode::new(lifted::<Payload>(Payload("deep".to_string(), 0)), &layout);
|
||||
let memoized = core_types::record::RecordExtract::<Payload, _>::new(memoized, &layout);
|
||||
|
||||
assert_eq!(memoized.eval(&ctx, &frames), GPoll::Final(Payload("deep".to_string(), 0)), "the miss serves the live value");
|
||||
assert_eq!(
|
||||
memoized.eval(&ctx, &frames),
|
||||
GPoll::Final(Payload("deep".to_string(), 2)),
|
||||
"promoting across regions runs both halves of the deep glue"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_promote_within_one_region_shares_instead_of_cloning() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
#[derive(Clone, Debug, PartialEq, dyn_any::DynAny)]
|
||||
struct Shared(String, u32);
|
||||
unsafe fn deep(ptr: *const u8) -> Box<dyn std::any::Any + Send + Sync> {
|
||||
let value = unsafe { core_types::record::borrow_element::<Shared>(core_types::record::Rec::new(ptr)) };
|
||||
Box::new(Shared(value.0.clone(), value.1 + 1))
|
||||
}
|
||||
unsafe fn deep_repark(value: &(dyn std::any::Any + Send + Sync), dst: *mut u8, arena: &Arena) -> Option<()> {
|
||||
let value = value.downcast_ref::<Shared>().expect("an element replays at its own type");
|
||||
unsafe { core_types::record::write_element(dst, Shared(value.0.clone(), value.1 + 1), arena) }
|
||||
}
|
||||
core_types::record::register_deep_element_clone::<Shared>(deep, deep_repark);
|
||||
|
||||
let arena = Arena::new(4096).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let layout = element_layout::<Shared>();
|
||||
let memoized = MemoizeNode::new(lifted::<Shared>(Shared("shared".to_string(), 0)), &layout);
|
||||
let memoized = core_types::record::RecordExtract::<Shared, _>::new(memoized, &layout);
|
||||
|
||||
assert_eq!(memoized.eval(&ctx, &frames), GPoll::Final(Shared("shared".to_string(), 0)), "the miss serves the live value");
|
||||
assert_eq!(
|
||||
memoized.eval(&ctx, &frames),
|
||||
GPoll::Final(Shared("shared".to_string(), 0)),
|
||||
"a payload already living as long as the span is shared, so no glue runs"
|
||||
);
|
||||
let element = io.output.materialize_element(&arena).expect("the capture materializes inside the window");
|
||||
assert_eq!(*element.downcast_ref::<u32>().unwrap(), 11);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memoize_caches_across_evals() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let layout = element_layout::<u32>();
|
||||
let memoized = MemoizeNode::new(core_types::record::RecordLift::<u32, _>::new(CountingNode(AtomicU32::new(0))), &layout);
|
||||
let memoized = MemoizeNode::new(counting(), &layout);
|
||||
let memoized = core_types::record::RecordExtract::<u32, _>::new(memoized, &layout);
|
||||
|
||||
assert_eq!(memoized.eval(&ctx), GPoll::Final(1));
|
||||
assert_eq!(memoized.eval(&ctx), GPoll::Final(1));
|
||||
assert_eq!(memoized.eval(&ctx, &frames), GPoll::Final(1));
|
||||
assert_eq!(memoized.eval(&ctx, &frames), GPoll::Final(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memo_invalidates_on_generation_bump() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let source: SourceId = 7;
|
||||
let before = [(source, 1)];
|
||||
@@ -224,60 +442,223 @@ mod tests {
|
||||
let scope_after = scope_fixture(&after, &arena);
|
||||
|
||||
let layout = element_layout::<u32>();
|
||||
let memoized = MemoizeNode::new(core_types::record::RecordLift::<u32, _>::new(CountingNode(AtomicU32::new(0))), &layout);
|
||||
let memoized = MemoizeNode::new(counting(), &layout);
|
||||
let memoized = core_types::record::RecordExtract::<u32, _>::new(memoized, &layout);
|
||||
|
||||
assert_eq!(memoized.eval(&ContextImpl::root(&scope_before)), GPoll::Final(1));
|
||||
assert_eq!(memoized.eval(&ContextImpl::root(&scope_before)), GPoll::Final(1));
|
||||
assert_eq!(memoized.eval(&ContextImpl::root(&scope_after)), GPoll::Final(2));
|
||||
assert_eq!(memoized.eval(&ContextImpl::root(&scope_before), &frames), GPoll::Final(1));
|
||||
assert_eq!(memoized.eval(&ContextImpl::root(&scope_before), &frames), GPoll::Final(1));
|
||||
assert_eq!(memoized.eval(&ContextImpl::root(&scope_after), &frames), GPoll::Final(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memo_replays_partiality_on_hit() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let layout = element_layout::<u32>();
|
||||
let memoized = MemoizeNode::new(core_types::record::RecordLift::<u32, _>::new(PartialCountingNode(AtomicU32::new(0))), &layout);
|
||||
let memoized = MemoizeNode::new(partial_counting(), &layout);
|
||||
let memoized = core_types::record::RecordExtract::<u32, _>::new(memoized, &layout);
|
||||
|
||||
assert_eq!(memoized.eval(&ctx), GPoll::Partial(1));
|
||||
assert_eq!(memoized.eval(&ctx), GPoll::Partial(1));
|
||||
assert_eq!(memoized.eval(&ctx, &frames), GPoll::Partial(1));
|
||||
assert_eq!(memoized.eval(&ctx, &frames), GPoll::Partial(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memoized_edges_stack_and_rewire() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let layout = element_layout::<u32>();
|
||||
let edge = EdgeHandle::new_record::<u32>(Arc::new(core_types::record::RecordLift::<u32, _>::new(CountingNode(AtomicU32::new(0)))) as Arc<ErasedRecordNode>);
|
||||
let edge = EdgeHandle::new_record::<u32>(Arc::new(counting()) as Arc<ErasedRecordNode>);
|
||||
let memoized = EdgeHandle::new_record::<u32>(Arc::new(MemoizeNode::new(edge.downcast_record::<u32>().unwrap(), &layout)) as Arc<ErasedRecordNode>);
|
||||
let stacked = MemoizeNode::new(memoized.downcast_record::<u32>().unwrap(), &layout);
|
||||
let stacked = core_types::record::RecordExtract::<u32, _>::new(stacked, &layout);
|
||||
|
||||
assert_eq!(stacked.eval(&ctx), GPoll::Final(1));
|
||||
assert_eq!(stacked.eval(&ctx), GPoll::Final(1));
|
||||
assert_eq!(stacked.eval(&ctx, &frames), GPoll::Final(1));
|
||||
assert_eq!(stacked.eval(&ctx, &frames), GPoll::Final(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cross_evaluation_hit_serves_the_promoted_payload() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let mut arena = Arena::new(4096).unwrap();
|
||||
let persistent = Arena::new(4096).unwrap();
|
||||
let generations = [];
|
||||
|
||||
let layout = element_layout::<String>();
|
||||
let memo = MemoizeNode::new(lifted::<String>("promoted".to_string()), &layout);
|
||||
let served_at = |arena: &Arena| {
|
||||
let scope = scope_fixture(&generations, arena).with_persistent(&persistent);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
let GPoll::Final(value) = core_types::record::serve_edge(&memo, &ctx, &frames) else {
|
||||
panic!("the memo must serve a final record");
|
||||
};
|
||||
let element: &String = unsafe { core_types::record::borrow_element(layout.rec(&value)) };
|
||||
assert_eq!(element, "promoted");
|
||||
std::ptr::from_ref(element)
|
||||
};
|
||||
|
||||
served_at(&arena);
|
||||
let first = served_at(&arena);
|
||||
arena.reset();
|
||||
let second = served_at(&arena);
|
||||
assert_eq!(first, second, "a hit copies the promoted bytes rather than re-parking the payload");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flush_invalidates_every_span_memo_entry() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(4096).unwrap();
|
||||
let mut persistent = Arena::new(4096).unwrap();
|
||||
let generations = [];
|
||||
|
||||
let layout = element_layout::<u32>();
|
||||
let memoized = FrameMemoNode::new(counting(), &layout);
|
||||
let memoized = core_types::record::RecordExtract::<u32, _>::new(memoized, &layout);
|
||||
let eval = |persistent: &Arena| {
|
||||
let scope = scope_fixture(&generations, &arena).with_persistent(persistent);
|
||||
memoized.eval(&ContextImpl::root(&scope), &frames)
|
||||
};
|
||||
|
||||
assert_eq!(eval(&persistent), GPoll::Final(1));
|
||||
assert_eq!(eval(&persistent), GPoll::Final(1), "the published level serves the hit");
|
||||
persistent.reset();
|
||||
assert_eq!(eval(&persistent), GPoll::Final(2), "the flush invalidates the span");
|
||||
assert_eq!(eval(&persistent), GPoll::Final(2), "the miss re-published the level");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_owned_tier_survives_a_flush_without_recomputing() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(4096).unwrap();
|
||||
let mut persistent = Arena::new(4096).unwrap();
|
||||
let generations = [];
|
||||
|
||||
let layout = element_layout::<u32>();
|
||||
let memoized = MemoizeNode::new(counting(), &layout);
|
||||
let memoized = core_types::record::RecordExtract::<u32, _>::new(memoized, &layout);
|
||||
let eval = |persistent: &Arena, generations: &[(SourceId, u64)]| {
|
||||
let scope = scope_fixture(generations, &arena).with_persistent(persistent);
|
||||
memoized.eval(&ContextImpl::root(&scope), &frames)
|
||||
};
|
||||
|
||||
assert_eq!(eval(&persistent, &generations), GPoll::Final(1));
|
||||
assert_eq!(eval(&persistent, &generations), GPoll::Final(1), "the promoted level serves the hit");
|
||||
persistent.reset();
|
||||
assert_eq!(eval(&persistent, &generations), GPoll::Final(1), "the owned copies replay across the flush");
|
||||
let bumped = [(7 as SourceId, 3)];
|
||||
assert_eq!(eval(&persistent, &bumped), GPoll::Final(2), "only a key change recomputes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_span_never_resolves_against_another_region() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(4096).unwrap();
|
||||
let promoted = Arena::new(4096).unwrap();
|
||||
let foreign = Arena::new(4096).unwrap();
|
||||
let generations = [];
|
||||
|
||||
let layout = element_layout::<u32>();
|
||||
let memoized = FrameMemoNode::new(counting(), &layout);
|
||||
let memoized = core_types::record::RecordExtract::<u32, _>::new(memoized, &layout);
|
||||
let eval = |persistent: &Arena| {
|
||||
let scope = scope_fixture(&generations, &arena).with_persistent(persistent);
|
||||
memoized.eval(&ContextImpl::root(&scope), &frames)
|
||||
};
|
||||
|
||||
assert_eq!(eval(&promoted), GPoll::Final(1));
|
||||
assert_eq!(eval(&promoted), GPoll::Final(1));
|
||||
assert_eq!(eval(&foreign), GPoll::Final(2), "a stale or foreign span misses like an absent one");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refused_promote_recomputes_and_marks_the_region() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(4096).unwrap();
|
||||
let persistent = Arena::new(0).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena).with_persistent(&persistent);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let layout = element_layout::<u32>();
|
||||
let memoized = FrameMemoNode::new(counting(), &layout);
|
||||
let memoized = core_types::record::RecordExtract::<u32, _>::new(memoized, &layout);
|
||||
|
||||
assert_eq!(memoized.eval(&ctx, &frames), GPoll::Final(1));
|
||||
assert_eq!(memoized.eval(&ctx, &frames), GPoll::Final(2), "an unpublished level recomputes");
|
||||
assert!(persistent.exhausted(), "the refused promote marks the region for a flush");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refused_promote_leaves_the_owned_tier_serving() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(4096).unwrap();
|
||||
let persistent = Arena::new(0).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena).with_persistent(&persistent);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let layout = element_layout::<u32>();
|
||||
let memoized = MemoizeNode::new(counting(), &layout);
|
||||
let memoized = core_types::record::RecordExtract::<u32, _>::new(memoized, &layout);
|
||||
|
||||
assert_eq!(memoized.eval(&ctx, &frames), GPoll::Final(1));
|
||||
assert_eq!(memoized.eval(&ctx, &frames), GPoll::Final(1), "the owned tier answers where the promote was refused");
|
||||
assert!(persistent.exhausted(), "the refused promote marks the region for a flush");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_leveled_memo_signals_past_end_beyond_the_level() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(1 << 12).unwrap();
|
||||
let persistent = Arena::new(1 << 12).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena).with_persistent(&persistent);
|
||||
|
||||
let source = core_types::value::LeveledValueSource::new(vec![10u32, 20, 30]);
|
||||
let layout = Node::<ContextImpl>::layout(&source).clone();
|
||||
let memo = MemoizeNode::new(source, &layout);
|
||||
let at = |lane: u64| {
|
||||
let mut ctx = ContextImpl::root(&scope);
|
||||
core_types::context::InjectIndex::set_index(&mut ctx, lane);
|
||||
core_types::record::serve_edge(&memo, &ctx, &frames)
|
||||
};
|
||||
|
||||
let GPoll::Final(value) = at(1) else {
|
||||
panic!("the level covers lane 1");
|
||||
};
|
||||
assert_eq!(unsafe { core_types::record::read_element::<u32>(layout.rec(&value)) }, 20);
|
||||
let GPoll::Error(error) = at(3) else {
|
||||
panic!("lane 3 is past the level");
|
||||
};
|
||||
assert_eq!(error.kind, core_types::gpoll::ErrorKind::PastEnd);
|
||||
let GPoll::Error(error) = at(3) else {
|
||||
panic!("the cached level answers the drain the same way");
|
||||
};
|
||||
assert_eq!(error.kind, core_types::gpoll::ErrorKind::PastEnd);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frame_memo_shares_one_record_copy_per_frame() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(4096).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let layout = element_layout::<String>();
|
||||
let memo = FrameMemoNode::new(core_types::record::RecordLift::<String, _>::new(ValueNode("lent out".to_string())), &layout);
|
||||
let memo = FrameMemoNode::new(lifted::<String>("lent out".to_string()), &layout);
|
||||
|
||||
let GPoll::Final(first) = memo.eval(&ctx) else {
|
||||
panic!("the miss must fill the frame table");
|
||||
let GPoll::Final(first) = core_types::record::serve_edge(&memo, &ctx, &frames) else {
|
||||
panic!("the miss must publish the record");
|
||||
};
|
||||
let GPoll::Final(second) = memo.eval(&ctx) else {
|
||||
let GPoll::Final(second) = core_types::record::serve_edge(&memo, &ctx, &frames) else {
|
||||
panic!("the hit must revive the published record");
|
||||
};
|
||||
let first: &String = unsafe { core_types::record::borrow_element(layout.rec(&first)) };
|
||||
@@ -285,4 +666,32 @@ mod tests {
|
||||
assert_eq!(first, "lent out");
|
||||
assert!(std::ptr::eq(first, second), "the hit shares the parked payload");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_span_memo_hit_crosses_evaluations_on_one_payload() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let mut arena = Arena::new(4096).unwrap();
|
||||
let persistent = Arena::new(4096).unwrap();
|
||||
let generations = [];
|
||||
|
||||
let layout = element_layout::<String>();
|
||||
let memo = FrameMemoNode::new(lifted::<String>("published".to_string()), &layout);
|
||||
let served_at = |arena: &Arena| {
|
||||
let scope = scope_fixture(&generations, arena).with_persistent(&persistent);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
let GPoll::Final(value) = core_types::record::serve_edge(&memo, &ctx, &frames) else {
|
||||
panic!("the span memo must serve a final record");
|
||||
};
|
||||
let element: &String = unsafe { core_types::record::borrow_element(layout.rec(&value)) };
|
||||
assert_eq!(element, "published");
|
||||
std::ptr::from_ref(element)
|
||||
};
|
||||
|
||||
served_at(&arena);
|
||||
let first = served_at(&arena);
|
||||
arena.reset();
|
||||
let second = served_at(&arena);
|
||||
assert_eq!(first, second, "the hit names the published payload rather than re-parking it");
|
||||
assert!(persistent.contains(first.cast::<u8>()), "the payload the hits share lives in the persistent region");
|
||||
}
|
||||
}
|
||||
+2200
-336
File diff suppressed because it is too large.
Load diff
@@ -1,41 +1,42 @@
|
||||
use core_types::gpoll::Interrupt;
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::attribute::{Attr, Background, Clip, Dimensions, Location};
|
||||
use core_types::extent::{ExtentIn, LevelIn, ValueIn};
|
||||
use core_types::gpoll::{Extent, GPoll, Interrupt};
|
||||
use core_types::transform::TransformMut;
|
||||
use core_types::{ATTR_BACKGROUND, ATTR_CLIP, ATTR_DIMENSIONS, ATTR_LOCATION, Color, Context, Ctx, DeriveCtx, ModifyFootprint};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::graphic::{Graphic, IntoGraphicList};
|
||||
use graphic_types::{Artboard, Vector};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
use vector_types::GradientStops;
|
||||
use core_types::{Color, Ctx, DeriveCtx, ModifyFootprint};
|
||||
use glam::DVec2;
|
||||
use graphic_types::Artboard;
|
||||
use graphic_types::graphic::Graphic;
|
||||
|
||||
/// Constructs a single-element `Artboard[]` with the given content and metadata stored as row attributes.
|
||||
/// Evaluates the content within a footprint translated by `offset`, so the
|
||||
/// content culls and resolves against its position inside the artboard.
|
||||
#[node_macro::node(category(""), extent(translate_footprint_extent))]
|
||||
pub fn translate_footprint<T>(ctx: impl Ctx + DeriveCtx + ModifyFootprint, content: impl Node<Context<'_>, Output = T>, offset: DVec2) -> Result<T, Interrupt> {
|
||||
let translated = ctx.modify_footprint(|footprint| footprint.translate(offset));
|
||||
content.eval(&translated.ctx())
|
||||
}
|
||||
|
||||
fn translate_footprint_extent(content: ExtentIn<'_>, _offset: ValueIn<'_, DVec2>, level: LevelIn) -> GPoll<Extent> {
|
||||
content.at(level)
|
||||
}
|
||||
|
||||
/// Constructs an artboard element with the given content and metadata stored as attributes.
|
||||
#[node_macro::node(category(""))]
|
||||
pub fn create_artboard<T: IntoGraphicList>(
|
||||
ctx: impl Ctx + DeriveCtx + ModifyFootprint,
|
||||
pub fn create_artboard<'e>(
|
||||
_: impl Ctx,
|
||||
/// Graphics to include within the artboard.
|
||||
#[implementations(
|
||||
Context -> List<Graphic>,
|
||||
Context -> List<Vector>,
|
||||
Context -> List<String>,
|
||||
Context -> List<Raster<CPU>>,
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<GradientStops>,
|
||||
Context -> DAffine2,
|
||||
)]
|
||||
content: impl Node<Context<'_>, Output = T>,
|
||||
content: IList<Graphic<'e>>,
|
||||
/// Coordinate of the top-left corner of the artboard within the document.
|
||||
location: DVec2,
|
||||
/// Width and height of the artboard within the document.
|
||||
dimensions: DVec2,
|
||||
/// Color of the artboard background.
|
||||
background: List<Color>,
|
||||
background: IList<Color>,
|
||||
/// Whether to cut off the contained content that extends outside the artboard, or keep it visible.
|
||||
#[default(true)]
|
||||
clip: bool,
|
||||
) -> Result<List<Artboard>, Interrupt> {
|
||||
let translated = ctx.modify_footprint(|footprint| footprint.translate(location));
|
||||
let content = content.eval(&translated.ctx())?.into_graphic_list();
|
||||
) -> (Artboard<'e>, Attr<Location>, Attr<Dimensions>, Attr<Background>, Attr<Clip>) {
|
||||
let item = content.as_group_item();
|
||||
let content = core_types::list::List::new_from_element(Graphic::Group(core_types::record::Group { row: None, content: item }));
|
||||
|
||||
// Normalize so `location` is the top-left corner and `dimensions` are positive (allowing negative input
|
||||
// dimensions to represent dragging from the opposite corner). Compute the corner using the raw signed
|
||||
@@ -43,14 +44,11 @@ pub fn create_artboard<T: IntoGraphicList>(
|
||||
let normalized_location = location.min(location + dimensions);
|
||||
let normalized_dimensions = dimensions.abs().max(DVec2::ONE);
|
||||
|
||||
let background = background.element(0).copied().unwrap_or(Color::WHITE);
|
||||
let background = match background.len() {
|
||||
0 => Color::WHITE,
|
||||
_ => background.get(0),
|
||||
};
|
||||
|
||||
// Name is not stored here, it's resolved live from the parent layer's display name
|
||||
Ok(List::new_from_item(
|
||||
Item::new_from_element(Artboard::new(content))
|
||||
.with_attribute(ATTR_LOCATION, normalized_location)
|
||||
.with_attribute(ATTR_DIMENSIONS, normalized_dimensions)
|
||||
.with_attribute(ATTR_BACKGROUND, background)
|
||||
.with_attribute(ATTR_CLIP, clip),
|
||||
))
|
||||
(Artboard::new(content), Attr(normalized_location), Attr(normalized_dimensions), Attr(background), Attr(clip))
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,5 +1,6 @@
|
||||
pub mod artboard;
|
||||
pub mod graphic;
|
||||
pub mod record;
|
||||
|
||||
// Re-export all nodes
|
||||
pub use artboard::*;
|
||||
|
||||
Loaded 100 of 124 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user