mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
106
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ca0f288f43 | ||
|
|
394c6aad32 | ||
|
|
80ececea5f | ||
|
|
ff074b2a1c | ||
|
|
d278fd666d | ||
|
|
f726e712bc | ||
|
|
46e0a4f2f5 | ||
|
|
1fff59f380 | ||
|
|
26de6912f7 | ||
|
|
5f0c02e240 | ||
|
|
5e30501560 | ||
|
|
334d48c7fb | ||
|
|
76a6bae528 | ||
|
|
e10d56c261 | ||
|
|
f566e8ee17 | ||
|
|
6910a12f71 | ||
|
|
f726014c93 | ||
|
|
23313bd5ae | ||
|
|
a06039c6c8 | ||
|
|
7cd6e7cd04 | ||
|
|
0a4288eca6 | ||
|
|
5baeb8fd46 | ||
|
|
f04d439b33 | ||
|
|
6e22d6a412 | ||
|
|
5eb80721dd | ||
|
|
fc94487d0b | ||
|
|
37c0d0852d | ||
|
|
9b92edc0e9 | ||
|
|
348e9022a6 | ||
|
|
0001cdf04d | ||
|
|
c2845def11 | ||
|
|
b8bd9499fc | ||
|
|
e92ced1e4a | ||
|
|
e322d8957d | ||
|
|
296185b7fc | ||
|
|
b321c094d2 | ||
|
|
d4768d606f | ||
|
|
148008c695 | ||
|
|
2b5845464c | ||
|
|
5e388cb38f | ||
|
|
49daf2895e | ||
|
|
682d3dafbd | ||
|
|
ad03b5b0bf | ||
|
|
324925aedb | ||
|
|
e78a987e3e | ||
|
|
2c8fa44eb4 | ||
|
|
6b22316077 | ||
|
|
98cabee4c6 | ||
|
|
e0848abc59 | ||
|
|
f237a5ee50 | ||
|
|
df99ab3a72 | ||
|
|
0fc4424a09 | ||
|
|
e9a3199456 | ||
|
|
ef8312806d | ||
|
|
548cbfbf4e | ||
|
|
313c591f70 | ||
|
|
f07f708ee8 | ||
|
|
5f73044b6b | ||
|
|
11aedd8196 | ||
|
|
f4f266b1ba | ||
|
|
77e4e8c894 | ||
|
|
c231bd0eb8 | ||
|
|
095e0bb4ff | ||
|
|
369f7db992 | ||
|
|
79750fb52d | ||
|
|
f7360688f2 | ||
|
|
00920823aa | ||
|
|
0426a01e82 | ||
|
|
02f9cf3e6b | ||
|
|
33f7257e47 | ||
|
|
2921f44e5c | ||
|
|
1e91511f93 | ||
|
|
daf0231c0c | ||
|
|
92adc524ca | ||
|
|
9f0e0ebc96 | ||
|
|
a911bcc165 | ||
|
|
5bedfa4d11 | ||
|
|
e52af0cee0 | ||
|
|
fbdba0e545 | ||
|
|
6cdab6b95d | ||
|
|
e92faf763d | ||
|
|
305c36fb25 | ||
|
|
fc9e69a7a7 | ||
|
|
c9525d76c4 | ||
|
|
451922c217 | ||
|
|
92ea594a2a | ||
|
|
9d3abe385f | ||
|
|
96521333d6 | ||
|
|
d80651e85c | ||
|
|
a16a4c6354 | ||
|
|
d294d75198 | ||
|
|
8f7d3936f8 | ||
|
|
6961687172 | ||
|
|
38d479bdfa | ||
|
|
14660bdb64 | ||
|
|
b362452ff2 | ||
|
|
30573e6eb6 | ||
|
|
9ac039074d | ||
|
|
fdde760259 | ||
|
|
1be90ebb4a | ||
|
|
8fa250a9f9 | ||
|
|
0b70b18338 | ||
|
|
40efbc3261 | ||
|
|
39ce55ab61 | ||
|
|
3e1a9a1acf | ||
|
|
ab93e1f071 |
No files matched your search
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_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
|
||||
{"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":{"HasTransform":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[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}],[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}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[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}],[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}],[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}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[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}],[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}],[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}],[1789832635968548900,{"inputs":[{"Node":{"node_id":1924303400883620400,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.9822506,"green":0.20507872,"blue":0.012983031,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.25,"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":{"HasTransform":true},"exposed":false}Line 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_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
|
||||
{"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}],[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}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[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}],[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}],[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}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[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}],[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}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[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"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[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":Line 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_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
|
||||
{"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}],[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}],[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}],[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}],[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}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[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}},{"Value":{"tagged_value":{"F64":1.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::NoisePatternNode"}},"visible":true,"skip_deduplication":false}],[6565638614909771142,{"inputs":[{"Node":{"node_id":7624113397561636853,"output_index":0}},{"Node":{"node_id":80924370013313595,"output_iLine 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_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
|
||||
{"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}],[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}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[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}],[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":{"HasTransform":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[20.0,0.0,0.0,20.0,-10.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[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}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":1,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":7,"output_index":0}}],"call_argument":{"Concrete":{"name":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_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
|
||||
{"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}],[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}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[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}],[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}],[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}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[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}],[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":{"HasTransform":false},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[1.0,0.0,0.0,1.0,0.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[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}],[7828034197076821310,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":3}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"math_nodes::AsU32Node"}},"visible":true,"skip_deduplication":false}],[11731553664207576737,{"inputs":[{"Node":{"node_id":14514477720912258595,"output_index":0}},{"Value":{"tagged_value":{"F64":48.900000000000006},"exposed":false}},{"Node":{"node_id":7828034197076821310,"output_index":0}},{"Value":{"tagged_value":{"Bool":false},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.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
|
||||
{"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":{"HasTransform":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[31.55635094002563,-2.7755575615628914e-17,2.7755575615628914e-17,31.55635094002563,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[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}],[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}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[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}],[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}],[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}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[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":[],"segment_range":[],"fill":[]},"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"}},"iLine 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_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
|
||||
{"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}],[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}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[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":{"HasTransform":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[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}],[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}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[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}],[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}],[5,{"inputs":[{"NLine 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_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
|
||||
{"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}],[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}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[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}],[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}],[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}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[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}],[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}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[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}],[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}],[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}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[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}}],"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}],[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}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}Line truncated
|
||||
@@ -492,15 +492,11 @@ mod test {
|
||||
if let FrontendMessage::UpdateLayout {
|
||||
layout_target: LayoutTarget::DialogColumn1,
|
||||
diff,
|
||||
} = response
|
||||
} = response && let DiffUpdate::Layout(sub_layout) = &diff[0].new_value
|
||||
&& let LayoutGroup::Row(WidgetRow { widgets }) = &sub_layout.0[0]
|
||||
&& let Widget::TextLabel(TextLabel { value, .. }) = &*widgets[0].widget
|
||||
{
|
||||
if let DiffUpdate::Layout(sub_layout) = &diff[0].new_value {
|
||||
if let LayoutGroup::Row(WidgetRow { widgets }) = &sub_layout.0[0] {
|
||||
if let Widget::TextLabel(TextLabel { value, .. }) = &*widgets[0].widget {
|
||||
print_problem_to_terminal_on_failure(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
print_problem_to_terminal_on_failure(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -465,7 +465,7 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
|
||||
];
|
||||
let (mut key_up, mut key_down, mut key_up_no_repeat, mut key_down_no_repeat, mut double_click, mut wheel_scroll, mut pointer_move, mut pointer_shake) = mappings;
|
||||
|
||||
let sort = |list: &mut KeyMappingEntries| list.0.sort_by(|a, b| b.modifiers.count_ones().cmp(&a.modifiers.count_ones()));
|
||||
let sort = |list: &mut KeyMappingEntries| list.0.sort_by_key(|entry| std::cmp::Reverse(entry.modifiers.count_ones()));
|
||||
// Sort the sublists of `key_up`, `key_down`, `key_up_no_repeat`, and `key_down_no_repeat`
|
||||
for list in [&mut key_up, &mut key_down, &mut key_up_no_repeat, &mut key_down_no_repeat] {
|
||||
for sublist in list {
|
||||
|
||||
@@ -37,8 +37,8 @@ pub enum PathStep {
|
||||
#[derive(PartialEq, Eq, Clone, Copy, Default, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum VectorTableTab {
|
||||
#[default]
|
||||
Properties,
|
||||
Points,
|
||||
Segments,
|
||||
Regions,
|
||||
Handles,
|
||||
}
|
||||
@@ -376,7 +376,7 @@ impl TableItemLayout for Vector {
|
||||
)
|
||||
}
|
||||
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
let table_tab_entries = [VectorTableTab::Properties, VectorTableTab::Points, VectorTableTab::Segments, VectorTableTab::Regions]
|
||||
let table_tab_entries = [VectorTableTab::Points, VectorTableTab::Segments, VectorTableTab::Regions, VectorTableTab::Handles]
|
||||
.into_iter()
|
||||
.map(|tab| {
|
||||
RadioEntryData::new(format!("{tab:?}"))
|
||||
@@ -388,61 +388,6 @@ impl TableItemLayout for Vector {
|
||||
|
||||
let mut table_rows = Vec::new();
|
||||
match data.vector_table_tab {
|
||||
VectorTableTab::Properties => {
|
||||
table_rows.push(column_headings(&["property", "value"]));
|
||||
|
||||
if let Some(stroke) = self.stroke.as_ref() {
|
||||
table_rows.push(vec![
|
||||
TextLabel::new("Stroke Weight").narrow(true).widget_instance(),
|
||||
TextLabel::new(format!("{} px", stroke.weight)).narrow(true).widget_instance(),
|
||||
]);
|
||||
table_rows.push(vec![
|
||||
TextLabel::new("Stroke Dash Lengths").narrow(true).widget_instance(),
|
||||
TextLabel::new(if stroke.dash_lengths.is_empty() {
|
||||
"-".to_string()
|
||||
} else {
|
||||
format!("[{}]", stroke.dash_lengths.iter().map(|x| format!("{x} px")).collect::<Vec<_>>().join(", "))
|
||||
})
|
||||
.narrow(true)
|
||||
.widget_instance(),
|
||||
]);
|
||||
table_rows.push(vec![
|
||||
TextLabel::new("Stroke Dash Offset").narrow(true).widget_instance(),
|
||||
TextLabel::new(format!("{}", stroke.dash_offset)).narrow(true).widget_instance(),
|
||||
]);
|
||||
table_rows.push(vec![
|
||||
TextLabel::new("Stroke Cap").narrow(true).widget_instance(),
|
||||
TextLabel::new(stroke.cap.to_string()).narrow(true).widget_instance(),
|
||||
]);
|
||||
table_rows.push(vec![
|
||||
TextLabel::new("Stroke Join").narrow(true).widget_instance(),
|
||||
TextLabel::new(stroke.join.to_string()).narrow(true).widget_instance(),
|
||||
]);
|
||||
table_rows.push(vec![
|
||||
TextLabel::new("Stroke Join Miter Limit").narrow(true).widget_instance(),
|
||||
TextLabel::new(format!("{}", stroke.join_miter_limit)).narrow(true).widget_instance(),
|
||||
]);
|
||||
table_rows.push(vec![
|
||||
TextLabel::new("Stroke Align").narrow(true).widget_instance(),
|
||||
TextLabel::new(stroke.align.to_string()).narrow(true).widget_instance(),
|
||||
]);
|
||||
table_rows.push(vec![
|
||||
TextLabel::new("Stroke Transform").narrow(true).widget_instance(),
|
||||
TextLabel::new(format_transform_matrix(stroke.transform)).narrow(true).widget_instance(),
|
||||
]);
|
||||
table_rows.push(vec![
|
||||
TextLabel::new("Stroke Paint Order").narrow(true).widget_instance(),
|
||||
TextLabel::new(stroke.paint_order.to_string()).narrow(true).widget_instance(),
|
||||
]);
|
||||
}
|
||||
|
||||
let colinear = self.colinear_manipulators.iter().map(|[a, b]| format!("[{a} / {b}]")).collect::<Vec<_>>().join(", ");
|
||||
let colinear = if colinear.is_empty() { "-".to_string() } else { colinear };
|
||||
table_rows.push(vec![
|
||||
TextLabel::new("Colinear Handle IDs").narrow(true).widget_instance(),
|
||||
TextLabel::new(colinear).narrow(true).widget_instance(),
|
||||
]);
|
||||
}
|
||||
VectorTableTab::Points => {
|
||||
table_rows.push(column_headings(&["", "position"]));
|
||||
table_rows.extend(self.point_domain.iter().map(|(id, position)| {
|
||||
@@ -473,6 +418,16 @@ impl TableItemLayout for Vector {
|
||||
]
|
||||
}));
|
||||
}
|
||||
VectorTableTab::Handles => {
|
||||
table_rows.push(column_headings(&["", "colinear_manipulators[0]", "colinear_manipulators[1]"]));
|
||||
table_rows.extend(self.colinear_manipulators.iter().enumerate().map(|(index, [a, b])| {
|
||||
vec![
|
||||
TextLabel::new(format!("{index}")).narrow(true).widget_instance(),
|
||||
TextLabel::new(format!("{a}")).narrow(true).widget_instance(),
|
||||
TextLabel::new(format!("{b}")).narrow(true).widget_instance(),
|
||||
]
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
vec![LayoutGroup::row(table_tabs), LayoutGroup::table(table_rows, false)]
|
||||
|
||||
@@ -11,9 +11,8 @@ use crate::messages::portfolio::utility_types::PanelType;
|
||||
use crate::messages::prelude::*;
|
||||
use glam::{DAffine2, IVec2};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::Appearance;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::Graphic;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::raster::BlendMode;
|
||||
use graphene_std::raster::Image;
|
||||
use graphene_std::transform::Footprint;
|
||||
@@ -245,14 +244,10 @@ pub enum DocumentMessage {
|
||||
vector_data: HashMap<NodeId, Arc<Vector>>,
|
||||
},
|
||||
// `Message` is only serialized at `editor_wrapper.rs`, and only inputs from JS pass through it.
|
||||
// `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.
|
||||
// `UpdateAppearanceAttributes` is produced inside `editor.handle_message` by `node_graph_executor.rs` and consumed in the same dispatch loop, so it never reaches that serialization point.
|
||||
#[serde(skip)]
|
||||
UpdateFillAttributes {
|
||||
fill_attributes: HashMap<NodeId, Arc<List<Graphic<'static>>>>,
|
||||
},
|
||||
#[serde(skip)]
|
||||
UpdateStrokeAttributes {
|
||||
stroke_attributes: HashMap<NodeId, Arc<List<Graphic<'static>>>>,
|
||||
UpdateAppearanceAttributes {
|
||||
appearance_attributes: HashMap<NodeId, Arc<Appearance>>,
|
||||
},
|
||||
Undo,
|
||||
UngroupSelectedLayers,
|
||||
|
||||
@@ -37,7 +37,7 @@ use graph_craft::application_io::wgpu_available;
|
||||
use graph_craft::descriptor;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput, NodeNetwork, OldNodeNetwork};
|
||||
use graphene_std::graphic::is_paint_present;
|
||||
use graphene_std::Cover;
|
||||
use graphene_std::math::quad::Quad;
|
||||
use graphene_std::path_bool_nodes::boolean_intersect;
|
||||
use graphene_std::raster::BlendMode;
|
||||
@@ -1502,9 +1502,9 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
.collect();
|
||||
self.network_interface.update_vector_data(layer_vector_data);
|
||||
}
|
||||
DocumentMessage::UpdateFillAttributes { fill_attributes } => {
|
||||
DocumentMessage::UpdateAppearanceAttributes { appearance_attributes } => {
|
||||
// Convert NodeId keys to LayerNodeIdentifier keys, filtering to only layers
|
||||
let layer_fill_attributes = fill_attributes
|
||||
let layer_appearance_attributes = appearance_attributes
|
||||
.into_iter()
|
||||
.filter(|(node_id, _)| self.network_interface.document_network().nodes.contains_key(node_id))
|
||||
.filter_map(|(node_id, attrs)| {
|
||||
@@ -1514,21 +1514,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
self.network_interface.update_fill_attributes(layer_fill_attributes);
|
||||
}
|
||||
DocumentMessage::UpdateStrokeAttributes { stroke_attributes } => {
|
||||
// Convert NodeId keys to LayerNodeIdentifier keys, filtering to only layers
|
||||
let layer_stroke_attributes = stroke_attributes
|
||||
.into_iter()
|
||||
.filter(|(node_id, _)| self.network_interface.document_network().nodes.contains_key(node_id))
|
||||
.filter_map(|(node_id, attrs)| {
|
||||
self.network_interface.is_layer(&node_id, &[]).then(|| {
|
||||
let layer = LayerNodeIdentifier::new(node_id, &self.network_interface);
|
||||
(layer, attrs)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
self.network_interface.update_stroke_attributes(layer_stroke_attributes);
|
||||
self.network_interface.update_appearance_attributes(layer_appearance_attributes);
|
||||
}
|
||||
DocumentMessage::Undo => {
|
||||
if self.network_interface.transaction_status() != TransactionStatus::Finished {
|
||||
@@ -2763,20 +2749,19 @@ impl DocumentMessageHandler {
|
||||
let mut resulting_layers: Vec<NodeId> = Vec::new();
|
||||
|
||||
for layer in selected_layers {
|
||||
let Some(vector_data) = self.network_interface.document_metadata().layer_vector_data.get(&layer) else {
|
||||
if !self.network_interface.document_metadata().layer_vector_data.contains_key(&layer) {
|
||||
resulting_layers.push(layer.to_node());
|
||||
continue;
|
||||
};
|
||||
let stroke = vector_data.stroke.as_ref();
|
||||
}
|
||||
|
||||
let fill_graphic_list = self.network_interface.document_metadata().layer_fill_attributes.get(&layer);
|
||||
let stroke_graphic_list = self.network_interface.document_metadata().layer_stroke_attributes.get(&layer);
|
||||
let appearance = self.network_interface.document_metadata().layer_appearance_attributes.get(&layer);
|
||||
|
||||
let has_fill = fill_graphic_list.is_some_and(|list| is_paint_present(list));
|
||||
// `Vector.stroke` captures stroke geometry, even with weight 0 or transparent paint.
|
||||
// So stroke visibility must be checked from `ATTR_STROKE`, the paint source of truth.
|
||||
let stroke_visible = stroke_graphic_list.is_some_and(|list| list.element(0).is_some_and(|g| !g.is_fully_transparent()));
|
||||
let has_stroke = stroke.as_ref().is_some_and(|s| s.has_renderable_stroke()) && stroke_visible;
|
||||
let has_fill = appearance.is_some_and(|appearance| appearance.has_painted_cover(Cover::Fill));
|
||||
// A visible stroke needs both renderable geometry (non-zero weight) and paint that draws something
|
||||
let has_stroke = appearance.is_some_and(|appearance| {
|
||||
appearance.first_coverage_of(Cover::Stroke).is_some_and(|coverage| coverage.stroke_params().has_renderable_stroke())
|
||||
&& appearance.first_paint_of(Cover::Stroke).is_some_and(|paint| !paint.is_fully_transparent())
|
||||
});
|
||||
|
||||
// No stroke means there's nothing to solidify. Fill-only layers are already in the desired form, so skip.
|
||||
if !has_stroke {
|
||||
@@ -4105,10 +4090,11 @@ mod document_message_handler_tests {
|
||||
async fn get_layer_by_bounds(editor: &mut EditorTestUtils, min_x: f64, min_y: f64) -> Option<LayerNodeIdentifier> {
|
||||
let document = editor.active_document();
|
||||
for layer in document.metadata().all_layers() {
|
||||
if let Some(bbox) = document.metadata().bounding_box_viewport(layer) {
|
||||
if (bbox[0].x - min_x).abs() < 1. && (bbox[0].y - min_y).abs() < 1. {
|
||||
return Some(layer);
|
||||
}
|
||||
if let Some(bbox) = document.metadata().bounding_box_viewport(layer)
|
||||
&& (bbox[0].x - min_x).abs() < 1.
|
||||
&& (bbox[0].y - min_y).abs() < 1.
|
||||
{
|
||||
return Some(layer);
|
||||
}
|
||||
}
|
||||
None
|
||||
@@ -4163,9 +4149,8 @@ mod document_message_handler_tests {
|
||||
.await;
|
||||
|
||||
// The operation completed without crashing
|
||||
// Verifying application still functions by performing another operation
|
||||
// Verifying application still functions by performing another operation, which panics if the folder move left the editor broken
|
||||
editor.handle_message(DocumentMessage::CreateEmptyFolder).await;
|
||||
assert!(true, "Application didn't crash after folder move operation");
|
||||
}
|
||||
|
||||
// Merging nodes whose output isn't wired downstream produces an encapsulating subnetwork with no exports.
|
||||
|
||||
@@ -10,7 +10,7 @@ use graphene_std::raster::BlendMode;
|
||||
use graphene_std::raster_types::Image;
|
||||
use graphene_std::subpath::Subpath;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::style::{GradientSpreadMethod, GradientType, Stroke};
|
||||
use graphene_std::vector::style::{GradientSpreadMethod, GradientType, PaintOrder, Stroke};
|
||||
use graphene_std::vector::{GradientStops, PointId, VectorModificationType};
|
||||
|
||||
#[impl_message(Message, DocumentMessage, GraphOperation)]
|
||||
@@ -63,6 +63,10 @@ pub enum GraphOperationMessage {
|
||||
color: Option<Color>,
|
||||
stroke: Stroke,
|
||||
},
|
||||
StrokePaintOrderSet {
|
||||
layer: LayerNodeIdentifier,
|
||||
paint_order: PaintOrder,
|
||||
},
|
||||
TransformChange {
|
||||
layer: LayerNodeIdentifier,
|
||||
transform: DAffine2,
|
||||
|
||||
+9
-2
@@ -13,7 +13,7 @@ use graph_craft::document::{NodeId, NodeInput};
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::renderer::convert_usvg_path::convert_usvg_path;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::style::{GradientSpreadMethod, GradientStop, GradientStops, GradientType, PaintOrder, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use graphene_std::vector::style::{GradientSpreadMethod, GradientStop, GradientStops, GradientType, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use graphene_std::{Artboard, Color};
|
||||
|
||||
#[derive(ExtractField)]
|
||||
@@ -96,6 +96,14 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
modify_inputs.stroke_set(color, stroke);
|
||||
}
|
||||
}
|
||||
GraphOperationMessage::StrokePaintOrderSet { layer, paint_order } => {
|
||||
if let Some(stroke_node_id) = crate::messages::tool::common_functionality::graph_modification_utils::get_stroke_id(layer, network_interface) {
|
||||
if super::utility_types::set_stroke_paint_order(network_interface, &[], stroke_node_id, paint_order) {
|
||||
responses.add(PropertiesPanelMessage::Refresh);
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
}
|
||||
}
|
||||
GraphOperationMessage::TransformChange {
|
||||
layer,
|
||||
transform,
|
||||
@@ -792,7 +800,6 @@ fn apply_usvg_stroke(stroke: &usvg::Stroke, modify_inputs: &mut ModifyInputsCont
|
||||
},
|
||||
join_miter_limit: stroke.miterlimit().get() as f64,
|
||||
align: StrokeAlign::Center,
|
||||
paint_order: PaintOrder::StrokeAbove,
|
||||
transform,
|
||||
},
|
||||
)
|
||||
|
||||
@@ -15,7 +15,7 @@ use graphene_std::raster::BlendMode;
|
||||
use graphene_std::raster_types::Image;
|
||||
use graphene_std::subpath::Subpath;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::style::{GradientSpreadMethod, GradientType, Stroke};
|
||||
use graphene_std::vector::style::{GradientSpreadMethod, GradientType, HasTransform, PaintOrder, Stroke};
|
||||
use graphene_std::vector::{GradientStops, PointId, Vector, VectorModification, VectorModificationType};
|
||||
use graphene_std::{Artboard, Color, Graphic, NodeInputDecleration};
|
||||
|
||||
@@ -490,7 +490,12 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
if transform_is_value {
|
||||
self.set_input_with_refresh(
|
||||
InputConnector::node(fill_node_id, graphene_std::vector::fill::TransformInput::INDEX),
|
||||
NodeInput::value(TaggedValue::OptionalDAffine2(Some(transform)), false),
|
||||
NodeInput::value(TaggedValue::DAffine2(transform), false),
|
||||
true,
|
||||
);
|
||||
self.set_input_with_refresh(
|
||||
InputConnector::node(fill_node_id, graphene_std::vector::fill::HasTransformInput::INDEX),
|
||||
NodeInput::value(TaggedValue::HasTransform(HasTransform(true)), false),
|
||||
true,
|
||||
);
|
||||
}
|
||||
@@ -727,8 +732,6 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::StrokeJoin(stroke.join), false), true);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::MiterLimitInput::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.join_miter_limit), false), false);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintOrderInput::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::PaintOrder(stroke.paint_order), false), false);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashLengthsInput::INDEX);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64Array(stroke.dash_lengths), false), true);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashOffsetInput::INDEX);
|
||||
@@ -864,3 +867,63 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The wires feeding off a node's primary output.
|
||||
fn primary_output_consumers(network_interface: &mut NodeNetworkInterface, network_path: &[NodeId], node_id: NodeId) -> Vec<InputConnector> {
|
||||
network_interface
|
||||
.outward_wires(network_path)
|
||||
.and_then(|wires| wires.get(&OutputConnector::node(node_id, 0)).cloned())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The fill wired directly to the stroke on either side, and whether the stroke currently paints above it.
|
||||
/// The downstream node of the pair appends its cover last, so it paints on top.
|
||||
pub fn adjacent_fill_of_stroke(network_interface: &mut NodeNetworkInterface, network_path: &[NodeId], stroke_node_id: NodeId) -> Option<(NodeId, bool)> {
|
||||
let fill_reference = DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER);
|
||||
let is_fill = |network_interface: &NodeNetworkInterface, node_id: &NodeId| network_interface.reference(node_id, network_path) == Some(fill_reference.clone());
|
||||
|
||||
let stroke_primary_source = match network_interface.input_from_connector(&InputConnector::node(stroke_node_id, 0), network_path) {
|
||||
Some(NodeInput::Node { node_id, output_index: 0, .. }) => Some(*node_id),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(source) = stroke_primary_source.filter(|source| is_fill(network_interface, source)) {
|
||||
return Some((source, true));
|
||||
}
|
||||
let consumers = primary_output_consumers(network_interface, network_path, stroke_node_id);
|
||||
let fill_consumer = consumers.iter().find_map(|connector| match connector {
|
||||
InputConnector::Node { node_id, input_index: 0 } if is_fill(network_interface, node_id) => Some(*node_id),
|
||||
_ => None,
|
||||
});
|
||||
fill_consumer.map(|fill_node_id| (fill_node_id, false))
|
||||
}
|
||||
|
||||
/// Swaps a chain's directly adjacent Stroke and Fill nodes when their order disagrees with the requested
|
||||
/// paint order: both nodes append their cover, so the downstream one of the pair paints on top, following
|
||||
/// the painter's algorithm. Without a fill wired directly to the stroke, nothing changes.
|
||||
/// Returns whether the graph changed.
|
||||
pub fn set_stroke_paint_order(network_interface: &mut NodeNetworkInterface, network_path: &[NodeId], stroke_node_id: NodeId, paint_order: PaintOrder) -> bool {
|
||||
let Some((fill_node_id, currently_above)) = adjacent_fill_of_stroke(network_interface, network_path, stroke_node_id) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
if (paint_order == PaintOrder::StrokeAbove) == currently_above {
|
||||
return false;
|
||||
}
|
||||
|
||||
let (upstream, downstream) = if currently_above { (fill_node_id, stroke_node_id) } else { (stroke_node_id, fill_node_id) };
|
||||
let Some(upstream_source) = network_interface.input_from_connector(&InputConnector::node(upstream, 0), network_path).cloned() else {
|
||||
return false;
|
||||
};
|
||||
let downstream_consumers = primary_output_consumers(network_interface, network_path, downstream);
|
||||
|
||||
network_interface.set_input(&InputConnector::node(downstream, 0), upstream_source, network_path);
|
||||
network_interface.set_input(&InputConnector::node(upstream, 0), NodeInput::node(downstream, 0), network_path);
|
||||
for consumer in &downstream_consumers {
|
||||
if matches!(consumer, InputConnector::Node { node_id, .. } if *node_id == upstream || *node_id == downstream) {
|
||||
continue;
|
||||
}
|
||||
network_interface.set_input(consumer, NodeInput::node(upstream, 0), network_path);
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
@@ -1038,6 +1038,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
},
|
||||
DocumentNode {
|
||||
inputs: vec![
|
||||
NodeInput::value(TaggedValue::None, false),
|
||||
NodeInput::import(generic!(T), 0),
|
||||
NodeInput::import(concrete!(Footprint), 1),
|
||||
NodeInput::node(NodeId(1), 0),
|
||||
|
||||
@@ -157,7 +157,8 @@ pub enum NodeGraphMessage {
|
||||
SetInputValue {
|
||||
node_id: NodeId,
|
||||
input_index: usize,
|
||||
value: TaggedValue,
|
||||
// Boxed to keep the whole editor message tree small; `TaggedValue` alone is 568 bytes
|
||||
value: Box<TaggedValue>,
|
||||
},
|
||||
SetInput {
|
||||
input_connector: InputConnector,
|
||||
|
||||
@@ -1765,6 +1765,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
NodeGraphMessage::SetInputValue { node_id, input_index, value } => {
|
||||
use graphene_std::vector::generator_nodes::*;
|
||||
|
||||
let value = *value;
|
||||
let reference = network_interface.reference(&node_id, selection_network_path);
|
||||
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));
|
||||
|
||||
@@ -33,7 +33,7 @@ use graphene_std::transform::{Footprint, ReferencePoint, ScaleType, Transform};
|
||||
use graphene_std::vector::misc::BooleanOperation;
|
||||
use graphene_std::vector::misc::{ArcType, CentroidType, ExtrudeJoiningAlgorithm, GridType, InterpolationDistribution, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns, SpiralType};
|
||||
use graphene_std::vector::style::{
|
||||
FillChoice, FillChoiceUI, GradientSpreadMethod, GradientStops, GradientStopsUI, GradientType, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin, build_transform_with_y_preservation,
|
||||
FillChoice, FillChoiceUI, GradientSpreadMethod, GradientStops, GradientStopsUI, GradientType, HasTransform, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin, build_transform_with_y_preservation,
|
||||
};
|
||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
|
||||
|
||||
@@ -44,7 +44,12 @@ pub(crate) fn string_properties(text: &str) -> Vec<LayoutGroup> {
|
||||
|
||||
fn optionally_update_value<T>(value: impl Fn(&T) -> Option<TaggedValue> + 'static + Send + Sync, node_id: NodeId, input_index: usize) -> impl Fn(&T) -> Message + 'static + Send + Sync {
|
||||
move |input_value: &T| match value(input_value) {
|
||||
Some(value) => NodeGraphMessage::SetInputValue { node_id, input_index, value }.into(),
|
||||
Some(value) => NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index,
|
||||
value: Box::new(value),
|
||||
}
|
||||
.into(),
|
||||
None => Message::NoOp,
|
||||
}
|
||||
}
|
||||
@@ -867,7 +872,7 @@ pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetI
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: graphene_std::text::text::FontInput::INDEX,
|
||||
value: TaggedValue::Resource(resource_id),
|
||||
value: Box::new(TaggedValue::Resource(resource_id)),
|
||||
}
|
||||
.into(),
|
||||
]),
|
||||
@@ -1437,7 +1442,7 @@ fn build_shared_spectrum_section(node_id: NodeId, context: &mut NodePropertiesCo
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index,
|
||||
value: TaggedValue::F32(percent.clamp(0., 100.) as f32),
|
||||
value: Box::new(TaggedValue::F32(percent.clamp(0., 100.) as f32)),
|
||||
}
|
||||
.into()
|
||||
}
|
||||
@@ -1594,7 +1599,7 @@ fn spectrum_slider_row(
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index,
|
||||
value: TaggedValue::F32(position_to_value(new_position).clamp(value_min, value_max) as f32),
|
||||
value: Box::new(TaggedValue::F32(position_to_value(new_position).clamp(value_min, value_max) as f32)),
|
||||
}
|
||||
.into()
|
||||
})
|
||||
@@ -2148,13 +2153,13 @@ pub(crate) fn string_capitalization_properties(node_id: NodeId, context: &mut No
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: UseJoinerInput::INDEX,
|
||||
value: TaggedValue::Bool(true),
|
||||
value: Box::new(TaggedValue::Bool(true)),
|
||||
}
|
||||
.into(),
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: JoinerInput::INDEX,
|
||||
value: TaggedValue::String(value.clone()),
|
||||
value: Box::new(TaggedValue::String(value.clone())),
|
||||
}
|
||||
.into(),
|
||||
]),
|
||||
@@ -2214,13 +2219,13 @@ pub(crate) fn rectangle_properties(node_id: NodeId, context: &mut NodeProperties
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: IndividualCornerRadiiInput::INDEX,
|
||||
value: TaggedValue::Bool(false),
|
||||
value: Box::new(TaggedValue::Bool(false)),
|
||||
}
|
||||
.into(),
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: CornerRadiusInput::INDEX,
|
||||
value: TaggedValue::F64(uniform_val),
|
||||
value: Box::new(TaggedValue::F64(uniform_val)),
|
||||
}
|
||||
.into(),
|
||||
]),
|
||||
@@ -2234,13 +2239,13 @@ pub(crate) fn rectangle_properties(node_id: NodeId, context: &mut NodeProperties
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: IndividualCornerRadiiInput::INDEX,
|
||||
value: TaggedValue::Bool(true),
|
||||
value: Box::new(TaggedValue::Bool(true)),
|
||||
}
|
||||
.into(),
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: CornerRadiusInput::INDEX,
|
||||
value: TaggedValue::F64Array(individual_val_for_switch.clone()),
|
||||
value: Box::new(TaggedValue::F64Array(individual_val_for_switch.clone())),
|
||||
}
|
||||
.into(),
|
||||
]),
|
||||
@@ -2549,13 +2554,13 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: FillInput::INDEX,
|
||||
value: TaggedValue::Color(color),
|
||||
value: Box::new(TaggedValue::Color(color)),
|
||||
}
|
||||
.into(),
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: BackupColorInput::INDEX,
|
||||
value: TaggedValue::Color(color),
|
||||
value: Box::new(TaggedValue::Color(color)),
|
||||
}
|
||||
.into(),
|
||||
]),
|
||||
@@ -2566,13 +2571,13 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: FillInput::INDEX,
|
||||
value: TaggedValue::Gradient(gradient.clone()),
|
||||
value: Box::new(TaggedValue::Gradient(gradient.clone())),
|
||||
}
|
||||
.into(),
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: BackupGradientInput::INDEX,
|
||||
value: TaggedValue::Gradient(gradient),
|
||||
value: Box::new(TaggedValue::Gradient(gradient)),
|
||||
}
|
||||
.into(),
|
||||
]),
|
||||
@@ -2672,7 +2677,23 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
|
||||
} else {
|
||||
"Swap the start and end points of the gradient line."
|
||||
})
|
||||
.on_update(update_value(move |_| TaggedValue::OptionalDAffine2(Some(new_transform)), node_id, TransformInput::INDEX))
|
||||
.on_update(move |_: &IconButton| Message::Batched {
|
||||
// The reversed placement is explicit even when the original was derived, so the toggle is set alongside it
|
||||
messages: Box::new([
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: TransformInput::INDEX,
|
||||
value: Box::new(TaggedValue::DAffine2(new_transform)),
|
||||
}
|
||||
.into(),
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: HasTransformInput::INDEX,
|
||||
value: Box::new(TaggedValue::HasTransform(HasTransform(true))),
|
||||
}
|
||||
.into(),
|
||||
]),
|
||||
})
|
||||
.widget_instance();
|
||||
spread_methods_row.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
spread_methods_row.push(reverse_direction_button);
|
||||
@@ -2739,9 +2760,6 @@ pub fn stroke_properties(node_id: NodeId, context: &mut NodePropertiesContext) -
|
||||
ParameterWidgetsInfo::new(node_id, MiterLimitInput::INDEX, true, context),
|
||||
NumberInput::default().min(0.).disabled(miter_limit_disabled),
|
||||
);
|
||||
let paint_order = enum_choice::<PaintOrder>()
|
||||
.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::INDEX, true, context), TextInput::default().centered(true));
|
||||
let number_input = disabled_number_input;
|
||||
@@ -2754,7 +2772,6 @@ pub fn stroke_properties(node_id: NodeId, context: &mut NodePropertiesContext) -
|
||||
cap,
|
||||
join,
|
||||
LayoutGroup::row(miter_limit),
|
||||
paint_order,
|
||||
LayoutGroup::row(dash_lengths),
|
||||
LayoutGroup::row(dash_offset),
|
||||
]
|
||||
|
||||
@@ -106,12 +106,10 @@ fn overlay_bezier_handle_specific_point(
|
||||
let not_under_anchor = |position: DVec2, anchor: DVec2| position.distance_squared(anchor) >= HIDE_HANDLE_DISTANCE * HIDE_HANDLE_DISTANCE;
|
||||
|
||||
match bezier.handles {
|
||||
BezierHandles::Quadratic { handle } => {
|
||||
if not_under_anchor(handle, bezier.start) && not_under_anchor(handle, bezier.end) {
|
||||
let end = if start == point_to_render { bezier.start } else { bezier.end };
|
||||
overlay_context.line(handle, end, None, None);
|
||||
overlay_context.manipulator_handle(handle, is_selected(ManipulatorPointId::PrimaryHandle(segment_id)), None);
|
||||
}
|
||||
BezierHandles::Quadratic { handle } if not_under_anchor(handle, bezier.start) && not_under_anchor(handle, bezier.end) => {
|
||||
let end = if start == point_to_render { bezier.start } else { bezier.end };
|
||||
overlay_context.line(handle, end, None, None);
|
||||
overlay_context.manipulator_handle(handle, is_selected(ManipulatorPointId::PrimaryHandle(segment_id)), None);
|
||||
}
|
||||
BezierHandles::Cubic { handle_start, handle_end } => {
|
||||
if not_under_anchor(handle_start, bezier.start) && (point_to_render == start) {
|
||||
|
||||
@@ -20,9 +20,7 @@ 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.
|
||||
/// Dev tool: writes each demo's migrated re-save into the directory named by `DEMO_OUT`, leaving the checked-in originals untouched.
|
||||
#[test]
|
||||
#[ignore = "dev tool: set DEMO_OUT and run explicitly"]
|
||||
fn migrate_demo_artwork_into_demo_out() {
|
||||
|
||||
@@ -6,8 +6,7 @@ use crate::messages::portfolio::document::utility_types::network_interface::Flow
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::Graphic;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::Appearance;
|
||||
use graphene_std::math::quad::Quad;
|
||||
use graphene_std::subpath;
|
||||
use graphene_std::transform::Footprint;
|
||||
@@ -41,12 +40,9 @@ pub struct DocumentMetadata {
|
||||
/// Vector data keyed by layer ID, used as fallback when no Path node exists.
|
||||
/// This provides accurate SegmentIds for layers without explicit Path nodes.
|
||||
pub layer_vector_data: HashMap<LayerNodeIdentifier, Arc<Vector>>,
|
||||
/// Per-layer `ATTR_FILL` attribute, exposed so message handlers can read paint
|
||||
/// information that lives on the list.
|
||||
pub layer_fill_attributes: HashMap<LayerNodeIdentifier, Arc<List<Graphic<'static>>>>,
|
||||
/// Per-layer `ATTR_STROKE` attribute, exposed so message handlers can read
|
||||
/// stroke paint information that lives on the list.
|
||||
pub layer_stroke_attributes: HashMap<LayerNodeIdentifier, Arc<List<Graphic<'static>>>>,
|
||||
/// Per-layer resolved appearance snapshot, exposed so message handlers can
|
||||
/// read the paint and stroke parameters that live on the coverage rows.
|
||||
pub layer_appearance_attributes: HashMap<LayerNodeIdentifier, Arc<Appearance>>,
|
||||
/// Transform from document space to viewport space.
|
||||
pub document_to_viewport: DAffine2,
|
||||
}
|
||||
@@ -233,10 +229,15 @@ impl DocumentMetadata {
|
||||
/// stroke geometry when the layer is a vector with a stroke style. Falls back to the click-target-based
|
||||
/// bounds for non-vector layers (groups, raster, text, color, gradient).
|
||||
pub fn bounding_box_document_with_stroke(&self, layer: LayerNodeIdentifier) -> Option<[DVec2; 2]> {
|
||||
if let Some(vector) = self.layer_vector_data.get(&layer)
|
||||
&& let Some(bounds) = vector.stroke_inclusive_bounding_box_with_transform(self.transform_to_document(layer))
|
||||
{
|
||||
return Some(bounds);
|
||||
if let Some(vector) = self.layer_vector_data.get(&layer) {
|
||||
let stroke = self
|
||||
.layer_appearance_attributes
|
||||
.get(&layer)
|
||||
.and_then(|appearance| appearance.first_coverage_of(graphene_std::Cover::Stroke))
|
||||
.map(graphene_std::Coverage::stroke_params);
|
||||
if let Some(bounds) = vector.stroke_inclusive_bounding_box_with_transform(self.transform_to_document(layer), stroke.as_ref()) {
|
||||
return Some(bounds);
|
||||
}
|
||||
}
|
||||
self.bounding_box_document(layer)
|
||||
}
|
||||
|
||||
@@ -24,8 +24,7 @@ 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::Graphic;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::Appearance;
|
||||
use graphene_std::math::quad::Quad;
|
||||
use graphene_std::subpath::Subpath;
|
||||
use graphene_std::transform::Footprint;
|
||||
@@ -2729,12 +2728,12 @@ impl NodeNetworkInterface {
|
||||
DocumentNodeClickTargets {
|
||||
node_click_target,
|
||||
port_click_targets,
|
||||
node_type_metadata: NodeTypeClickTargets::Layer(LayerClickTargets {
|
||||
node_type_metadata: NodeTypeClickTargets::Layer(Box::new(LayerClickTargets {
|
||||
visibility_click_target,
|
||||
lock_click_target,
|
||||
grip_click_target,
|
||||
name_click_target,
|
||||
}),
|
||||
})),
|
||||
}
|
||||
};
|
||||
|
||||
@@ -3439,14 +3438,9 @@ impl NodeNetworkInterface {
|
||||
self.document_metadata.layer_vector_data = new_layer_vector_data;
|
||||
}
|
||||
|
||||
/// Update the per-layer `ATTR_FILL` snapshot.
|
||||
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<'static>>>>) {
|
||||
self.document_metadata.layer_stroke_attributes = new_layer_stroke_attributes;
|
||||
/// Update the per-layer resolved appearance snapshot.
|
||||
pub fn update_appearance_attributes(&mut self, new_layer_appearance_attributes: HashMap<LayerNodeIdentifier, Arc<Appearance>>) {
|
||||
self.document_metadata.layer_appearance_attributes = new_layer_appearance_attributes;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5311,7 +5305,7 @@ impl NodeNetworkInterface {
|
||||
})
|
||||
.collect::<Vec<(NodeId, i32)>>();
|
||||
|
||||
node_ids_with_position.sort_unstable_by(|a, b| a.1.cmp(&b.1));
|
||||
node_ids_with_position.sort_unstable_by_key(|entry| entry.1);
|
||||
Some(node_ids_with_position.into_iter().map(|(node_id, _)| node_id).collect::<Vec<_>>())
|
||||
}
|
||||
|
||||
@@ -6953,7 +6947,7 @@ pub struct LayerTransientMetadata {
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum NodeTypeClickTargets {
|
||||
Layer(LayerClickTargets),
|
||||
Layer(Box<LayerClickTargets>),
|
||||
Node, // No transient click targets are stored exclusively for nodes
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
// This file contains lots of hacky code for upgrading old documents to the new format
|
||||
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::set_stroke_paint_order;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, resolve_document_node_type, resolve_network_node_type, resolve_proto_node_type};
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeTemplate, OutputConnector};
|
||||
@@ -15,7 +16,7 @@ use graphene_std::text::{TextAlign, TypesettingConfig};
|
||||
use graphene_std::transform::ScaleType;
|
||||
use graphene_std::uuid::NodeId;
|
||||
use graphene_std::vector::graphic_types;
|
||||
use graphene_std::vector::style::{PaintOrder, StrokeAlign};
|
||||
use graphene_std::vector::style::{HasTransform, PaintOrder, StrokeAlign};
|
||||
use std::collections::HashMap;
|
||||
use std::f64::consts::PI;
|
||||
use std::ops::Range;
|
||||
@@ -1024,12 +1025,6 @@ 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") {
|
||||
@@ -1051,12 +1046,6 @@ 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
|
||||
}
|
||||
|
||||
@@ -1433,6 +1422,18 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_definition.default_node_template());
|
||||
}
|
||||
|
||||
// Rebuild stale Rasterize subgraphs from before the async-source conversion gave the inner proto node a unit primary input (5 inputs, now 6).
|
||||
if let DocumentNodeImplementation::Network(inner) = &node.implementation
|
||||
&& inner
|
||||
.nodes
|
||||
.values()
|
||||
.any(|n| n.inputs.len() == 5 && matches!(&n.implementation, DocumentNodeImplementation::ProtoNode(id) if id.as_str().contains("rasterize")))
|
||||
&& document.network_interface.reference(node_id, network_path) == Some(DefinitionIdentifier::Network("Rasterize".into()))
|
||||
&& let Some(node_definition) = resolve_document_node_type(&DefinitionIdentifier::Network("Rasterize".into()))
|
||||
{
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_definition.default_node_template());
|
||||
}
|
||||
|
||||
// Upgrade old nodes to use `Context` instead of `()` or `Footprint` as their call argument
|
||||
if node.call_argument == graph_craft::concrete!(()) || node.call_argument == graph_craft::concrete!(graphene_std::transform::Footprint) {
|
||||
document.network_interface.set_call_argument(node_id, network_path, graph_craft::concrete!(graphene_std::Context));
|
||||
@@ -1613,7 +1614,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
}
|
||||
|
||||
// Upgrade the legacy 4-input Fill node (content, fill: Fill, _backup_color, _backup_gradient: Gradient) to the
|
||||
// value-model 7-input shape (content, fill: generic paint list, _backup_color, _backup_gradient, _gradient_type, _spread_method, _transform).
|
||||
// value-model 8-input shape (content, fill: generic paint list, _backup_color, _backup_gradient, _gradient_type, _spread_method, _has_transform, _transform).
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector_nodes::fill::IDENTIFIER) && inputs_count == 4 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
@@ -1648,16 +1649,19 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
network_path,
|
||||
);
|
||||
|
||||
let transform = if gradient.absolute {
|
||||
Some(gradient.transform * gradient.to_transform())
|
||||
// An unbaked placement keeps the template's `HasTransform(false)` default, the probe the deferred bake looks for
|
||||
if gradient.absolute {
|
||||
let transform = gradient.transform * gradient.to_transform();
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 6), NodeInput::value(TaggedValue::HasTransform(HasTransform(true)), false), network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 7), NodeInput::value(TaggedValue::DAffine2(transform), false), network_path);
|
||||
} else {
|
||||
// Baking a legacy bounding-box-relative gradient is deferred until the measurement pre-pass can supply the paint target's bounds
|
||||
document.pending_gradient_bbox_bake.push((network_path.to_vec(), *node_id, gradient.clone()));
|
||||
None
|
||||
};
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 6), NodeInput::value(TaggedValue::OptionalDAffine2(transform), false), network_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Wired/exposed fill keeps the connection.
|
||||
@@ -1692,28 +1696,62 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
network_path,
|
||||
);
|
||||
|
||||
let transform = if g.absolute {
|
||||
Some(g.transform * g.to_transform())
|
||||
// As above: only an absolute placement writes the toggle pair, a deferred bake keeps the default
|
||||
if g.absolute {
|
||||
let transform = g.transform * g.to_transform();
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 6), NodeInput::value(TaggedValue::HasTransform(HasTransform(true)), false), network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 7), NodeInput::value(TaggedValue::DAffine2(transform), false), network_path);
|
||||
} else {
|
||||
document.pending_gradient_bbox_bake.push((network_path.to_vec(), *node_id, g.clone()));
|
||||
None
|
||||
};
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 6), NodeInput::value(TaggedValue::OptionalDAffine2(transform), false), network_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inputs_count = 7;
|
||||
inputs_count = 8;
|
||||
}
|
||||
|
||||
// Upgrade Stroke node to reorder parameters and add "Align" and "Paint Order" (#2644)
|
||||
// Upgrade Fill's optional placement transform into the has-transform toggle pair, fixing the input's name and count
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector_nodes::fill::IDENTIFIER) && inputs_count == 7 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
|
||||
for index in 0..6 {
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, index), old_inputs[index].clone(), network_path);
|
||||
}
|
||||
match old_inputs[6].as_value() {
|
||||
Some(TaggedValue::OptionalDAffine2(Some(transform))) => {
|
||||
let transform = *transform;
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 6), NodeInput::value(TaggedValue::HasTransform(HasTransform(true)), false), network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 7), NodeInput::value(TaggedValue::DAffine2(transform), false), network_path);
|
||||
}
|
||||
// The unset placeholder becomes the toggle's default false, deriving placement from the bounds
|
||||
Some(TaggedValue::OptionalDAffine2(None)) => {}
|
||||
// A wired transform source keeps its connection, marked explicit
|
||||
_ => {
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 6), NodeInput::value(TaggedValue::HasTransform(HasTransform(true)), false), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 7), old_inputs[6].clone(), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
inputs_count = 8;
|
||||
}
|
||||
|
||||
// Upgrade Stroke node to reorder parameters and add "Align" (#2644), landing on the shape without the retired "Paint Order" input
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER) && inputs_count == 8 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
|
||||
let align_input = NodeInput::value(TaggedValue::StrokeAlign(StrokeAlign::Center), false);
|
||||
let paint_order_input = NodeInput::value(TaggedValue::PaintOrder(PaintOrder::StrokeAbove), false);
|
||||
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[1].clone(), network_path);
|
||||
@@ -1722,9 +1760,32 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 4), old_inputs[5].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 5), old_inputs[6].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 6), old_inputs[7].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 7), paint_order_input, network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 8), old_inputs[3].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 9), old_inputs[4].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 7), old_inputs[3].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 8), old_inputs[4].clone(), network_path);
|
||||
|
||||
inputs_count = 9;
|
||||
}
|
||||
|
||||
// The Stroke node's "Paint Order" input was retired in favor of the relative order of the Fill and Stroke
|
||||
// nodes in the chain, so the stored value becomes a topology rewrite that reorders the two nodes.
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER) && inputs_count == 10 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
|
||||
// A wired paint order input cannot be evaluated statically, so it degrades to the default and leaves its source disconnected
|
||||
let paint_order = match old_inputs.get(7).and_then(|input| input.as_value()) {
|
||||
Some(&TaggedValue::PaintOrder(value)) => value,
|
||||
_ => PaintOrder::StrokeAbove,
|
||||
};
|
||||
|
||||
for (index, input) in old_inputs.iter().enumerate().take(7) {
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, index), input.clone(), network_path);
|
||||
}
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 7), old_inputs[8].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 8), old_inputs[9].clone(), network_path);
|
||||
inputs_count = 9;
|
||||
|
||||
set_stroke_paint_order(&mut document.network_interface, network_path, *node_id, paint_order);
|
||||
}
|
||||
|
||||
// Upgrade Text node to include line height and character spacing, which were previously hardcoded to 1, from https://github.com/GraphiteEditor/Graphite/pull/2016
|
||||
@@ -2604,10 +2665,12 @@ 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"]);
|
||||
fn a_written_attribute_no_longer_resets_the_layer_definitions() {
|
||||
// The node resolves natively again, so a document carrying it keeps
|
||||
// its own layer internals instead of rebuilding them.
|
||||
assert!(!document_migration_reset_node_definition(
|
||||
r#"{"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}}}"#
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -52,7 +52,7 @@ pub enum PortfolioMessage {
|
||||
reopened: bool,
|
||||
#[serde(skip, default)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore", Clone(clone_with = "clone_to_none"))]
|
||||
gdd: Option<document_format::GddV1>,
|
||||
gdd: Option<Box<document_format::GddV1>>,
|
||||
},
|
||||
DestroyAllDocuments,
|
||||
EditorPreferences,
|
||||
|
||||
@@ -305,7 +305,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
// Document was closed before its working copy finished mounting.
|
||||
return;
|
||||
};
|
||||
document.set_storage(gdd);
|
||||
document.set_storage(gdd.map(|gdd| *gdd));
|
||||
if !reopened {
|
||||
document.commit_storage_snapshot(&resource_storage.resources_mut(), preferences.validate_storage_round_trip);
|
||||
document.retire_storage_interaction();
|
||||
@@ -1914,7 +1914,7 @@ impl PortfolioMessageHandler {
|
||||
Message::Portfolio(PortfolioMessage::DocumentStorageMounted {
|
||||
document_id,
|
||||
reopened,
|
||||
gdd: Some(gdd),
|
||||
gdd: Some(Box::new(gdd)),
|
||||
})
|
||||
};
|
||||
future.into()
|
||||
|
||||
@@ -182,12 +182,18 @@ impl DrawingToolState {
|
||||
cap: self.stroke_cap.unwrap_or_default(),
|
||||
join: self.stroke_join.unwrap_or_default(),
|
||||
join_miter_limit: self.miter_limit.unwrap_or(4.),
|
||||
paint_order: self.paint_order.unwrap_or_default(),
|
||||
dash_lengths: self.effective_dash_lengths(),
|
||||
dash_offset: self.dash_offset.unwrap_or(0.),
|
||||
transform: glam::DAffine2::IDENTITY,
|
||||
};
|
||||
responses.add(GraphOperationMessage::StrokeSet { layer, color, stroke });
|
||||
// The paint order is the chain order of the Fill and Stroke nodes, so a below choice reorders the new pair
|
||||
if self.paint_order.unwrap_or_default() == graphene_std::vector::style::PaintOrder::StrokeBelow {
|
||||
responses.add(GraphOperationMessage::StrokePaintOrderSet {
|
||||
layer,
|
||||
paint_order: graphene_std::vector::style::PaintOrder::StrokeBelow,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
@@ -69,6 +69,8 @@ impl SpiralTurns {
|
||||
self.handle_state == SpiralTurnsState::Dragging
|
||||
}
|
||||
|
||||
// Records one snapshot of the spiral's parameters; grouping them would only move the same fields into a struct
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn store_initial_parameters(
|
||||
&mut self,
|
||||
layer: LayerNodeIdentifier,
|
||||
|
||||
@@ -14,7 +14,7 @@ use graphene_std::raster_types::{CPU, GPU, Image, Raster};
|
||||
use graphene_std::subpath::Subpath;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::misc::ManipulatorPointId;
|
||||
use graphene_std::vector::style::{FillChoice, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin, initial_gradient_transform_for_bounding_box};
|
||||
use graphene_std::vector::style::{FillChoice, HasTransform, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin, initial_gradient_transform_for_bounding_box};
|
||||
use graphene_std::vector::{GradientSpreadMethod, GradientStops, GradientType, PointId, SegmentId, VectorModificationType};
|
||||
use std::collections::VecDeque;
|
||||
|
||||
@@ -565,9 +565,22 @@ pub fn get_stroke_options(layer: LayerNodeIdentifier, network_interface: &NodeNe
|
||||
Some(TaggedValue::F64(value)) => *value,
|
||||
_ => 4.,
|
||||
};
|
||||
let paint_order = match read(graphene_std::vector::stroke::PaintOrderInput::INDEX) {
|
||||
Some(TaggedValue::PaintOrder(value)) => *value,
|
||||
_ => PaintOrder::default(),
|
||||
// The paint order is the chain order of the Fill and Stroke nodes: the downstream one of an adjacent pair paints on top
|
||||
let paint_order = {
|
||||
let stroke_node_id = get_stroke_id(layer, network_interface);
|
||||
let primary_source = |node_id: Option<NodeId>| {
|
||||
node_id.and_then(|node_id| match network_interface.input_from_connector(&InputConnector::node(node_id, 0), &[]) {
|
||||
Some(NodeInput::Node { node_id, output_index: 0, .. }) => Some(*node_id),
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
if primary_source(stroke_node_id).is_some_and(|source| Some(source) == get_fill_id(layer, network_interface)) {
|
||||
PaintOrder::StrokeAbove
|
||||
} else if primary_source(get_fill_id(layer, network_interface)).is_some_and(|source| Some(source) == stroke_node_id) {
|
||||
PaintOrder::StrokeBelow
|
||||
} else {
|
||||
PaintOrder::default()
|
||||
}
|
||||
};
|
||||
let dash_lengths = match read(graphene_std::vector::stroke::DashLengthsInput::INDEX) {
|
||||
Some(TaggedValue::F64Array(value)) => value.clone(),
|
||||
@@ -613,7 +626,7 @@ pub fn set_stroke_weight_for_selected_layers(weight: f64, document: &DocumentMes
|
||||
for layer in layers {
|
||||
if let Some(node_id) = get_stroke_id(layer, &document.network_interface) {
|
||||
let input_index = graphene_std::vector::stroke::WeightInput::INDEX;
|
||||
let value = TaggedValue::F64(weight);
|
||||
let value = Box::new(TaggedValue::F64(weight));
|
||||
responses.add(NodeGraphMessage::SetInputValue { node_id, input_index, value });
|
||||
} else if weight > 0. {
|
||||
let color = Some(Color::BLACK);
|
||||
@@ -648,9 +661,14 @@ pub fn read_fill_node_gradient(fill_node: &DocumentNode, bounding_box: impl FnOn
|
||||
Some(&TaggedValue::GradientSpreadMethod(value)) => value,
|
||||
_ => GradientSpreadMethod::default(),
|
||||
};
|
||||
let has_transform = matches!(
|
||||
fill_node.inputs.get(fill::HasTransformInput::INDEX).and_then(|input| input.as_value()),
|
||||
Some(&TaggedValue::HasTransform(HasTransform(true)))
|
||||
);
|
||||
let transform_input = fill_node.inputs.get(fill::TransformInput::INDEX).and_then(|input| input.as_value());
|
||||
let transform = match transform_input {
|
||||
Some(&TaggedValue::OptionalDAffine2(value)) => value.unwrap_or_else(|| initial_gradient_transform_for_bounding_box(bounding_box())),
|
||||
Some(&TaggedValue::DAffine2(value)) if has_transform => value,
|
||||
Some(_) => initial_gradient_transform_for_bounding_box(bounding_box()),
|
||||
_ => DAffine2::IDENTITY,
|
||||
};
|
||||
|
||||
@@ -798,10 +816,10 @@ pub fn set_fill_for_selected_layers(fill_choice: FillChoice, document: &Document
|
||||
Some(TaggedValue::GradientSpreadMethod(value)) => *value,
|
||||
_ => GradientSpreadMethod::default(),
|
||||
};
|
||||
let has_transform = matches!(read(graphene_std::vector::fill::HasTransformInput::INDEX), Some(&TaggedValue::HasTransform(HasTransform(true))));
|
||||
let transform = match read(graphene_std::vector::fill::TransformInput::INDEX) {
|
||||
Some(TaggedValue::OptionalDAffine2(value)) => {
|
||||
value.unwrap_or_else(|| initial_gradient_transform_for_bounding_box(document.network_interface.document_metadata().nonzero_bounding_box(layer)))
|
||||
}
|
||||
Some(&TaggedValue::DAffine2(value)) if has_transform => value,
|
||||
Some(_) => initial_gradient_transform_for_bounding_box(document.network_interface.document_metadata().nonzero_bounding_box(layer)),
|
||||
_ => DAffine2::IDENTITY,
|
||||
};
|
||||
|
||||
@@ -825,7 +843,7 @@ pub fn set_stroke_color_for_selected_layers(color: Option<Color>, weight: f64, d
|
||||
for layer in layers {
|
||||
if let Some(node_id) = get_stroke_id(layer, &document.network_interface) {
|
||||
let input_index = graphene_std::vector::stroke::PaintInput::INDEX;
|
||||
let value = TaggedValue::Color(color);
|
||||
let value = Box::new(TaggedValue::Color(color));
|
||||
responses.add(NodeGraphMessage::SetInputValue { node_id, input_index, value });
|
||||
} else {
|
||||
let stroke = graphene_std::vector::style::Stroke::new(weight);
|
||||
@@ -896,7 +914,7 @@ pub fn set_proto_node_input_for_selected_layers(
|
||||
responses.add(NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index,
|
||||
value: value.clone(),
|
||||
value: Box::new(value.clone()),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,11 +88,8 @@ impl ShapeType {
|
||||
}
|
||||
|
||||
pub fn tooltip_description(&self) -> String {
|
||||
(match self {
|
||||
// TODO: Add descriptions to all the shape tools
|
||||
_ => "",
|
||||
})
|
||||
.into()
|
||||
// TODO: Add descriptions to all the shape tools
|
||||
String::new()
|
||||
}
|
||||
|
||||
pub fn icon_name(&self) -> String {
|
||||
|
||||
@@ -677,7 +677,6 @@ mod tests {
|
||||
down: [10., 15.].map(|y| Rect::from_square(DVec2::new(0., y), 2.)).to_vec(),
|
||||
left: [-12., -15.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.)).to_vec(),
|
||||
right: [12., 15.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.)).to_vec(),
|
||||
..Default::default()
|
||||
};
|
||||
let source = Rect::from_square(DVec2::new(0.3, 0.4), 2.);
|
||||
let snap_results = &mut SnapResults::default();
|
||||
|
||||
@@ -209,7 +209,10 @@ pub fn apply_miter_limit(drawing: &mut DrawingToolState, limit: f64, document: &
|
||||
|
||||
pub fn apply_paint_order(drawing: &mut DrawingToolState, order: PaintOrder, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
drawing.paint_order = Some(order);
|
||||
set_stroke_input_for_selected(document, graphene_std::vector::stroke::PaintOrderInput::INDEX, TaggedValue::PaintOrder(order), responses);
|
||||
// The paint order is the chain order of the Fill and Stroke nodes, so applying it reorders the pair
|
||||
for layer in document.network_interface.selected_nodes().selected_layers_except_artboards(&document.network_interface) {
|
||||
responses.add(GraphOperationMessage::StrokePaintOrderSet { layer, paint_order: order });
|
||||
}
|
||||
}
|
||||
|
||||
pub fn apply_dash_lengths(drawing: &mut DrawingToolState, lengths: Vec<f64>, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
|
||||
@@ -576,7 +576,7 @@ mod test_artboard {
|
||||
|
||||
/// A leveled wire introspects as its whole legacy list, so each `extend`
|
||||
/// occurrence yields one list rather than one element.
|
||||
async fn get_artboards(editor: &mut EditorTestUtils) -> List<Artboard> {
|
||||
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}"),
|
||||
|
||||
@@ -208,8 +208,7 @@ mod test_fill {
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::vector::fill;
|
||||
|
||||
/// Paint inputs are single-typed now, so the monitored wire carries the
|
||||
/// colors themselves and the `Graphic` conversion sits downstream of it.
|
||||
/// The monitored fill wire carries `Color`; the `Graphic` conversion sits downstream of the monitor.
|
||||
async fn get_fills(editor: &mut EditorTestUtils) -> Vec<Color> {
|
||||
let instrumented = match editor.eval_graph().await {
|
||||
Ok(instrumented) => instrumented,
|
||||
|
||||
@@ -2014,7 +2014,7 @@ mod test_gradient {
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::NodeInputDecleration;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::vector::style::{GradientSpreadMethod, build_transform_with_y_preservation};
|
||||
use graphene_std::vector::style::{GradientSpreadMethod, HasTransform, build_transform_with_y_preservation};
|
||||
use graphene_std::vector::{GradientStop, GradientStops, fill};
|
||||
|
||||
use super::gradient_space_transform;
|
||||
@@ -2067,8 +2067,12 @@ mod test_gradient {
|
||||
_ => GradientSpreadMethod::default(),
|
||||
};
|
||||
|
||||
let has_transform = matches!(
|
||||
fill_node.inputs.get(fill::HasTransformInput::INDEX).and_then(|input| input.as_value()),
|
||||
Some(&TaggedValue::HasTransform(HasTransform(true)))
|
||||
);
|
||||
let local_transform = match fill_node.inputs.get(fill::TransformInput::INDEX).and_then(|input| input.as_value()) {
|
||||
Some(&TaggedValue::OptionalDAffine2(Some(value))) => value,
|
||||
Some(&TaggedValue::DAffine2(value)) if has_transform => value,
|
||||
_ => DAffine2::IDENTITY,
|
||||
};
|
||||
|
||||
@@ -2146,7 +2150,7 @@ mod test_gradient {
|
||||
.handle_message(NodeGraphMessage::SetInputValue {
|
||||
node_id: gradient_node_id,
|
||||
input_index: 1,
|
||||
value: TaggedValue::Gradient(GradientStops::new([
|
||||
value: Box::new(TaggedValue::Gradient(GradientStops::new([
|
||||
GradientStop {
|
||||
position: 0.,
|
||||
midpoint: 0.5,
|
||||
@@ -2157,7 +2161,7 @@ mod test_gradient {
|
||||
midpoint: 0.5,
|
||||
color: Color::BLUE,
|
||||
},
|
||||
])),
|
||||
]))),
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -2183,7 +2187,7 @@ mod test_gradient {
|
||||
.handle_message(NodeGraphMessage::SetInputValue {
|
||||
node_id: gradient_node_id,
|
||||
input_index: 1,
|
||||
value: TaggedValue::Gradient(GradientStops::new([
|
||||
value: Box::new(TaggedValue::Gradient(GradientStops::new([
|
||||
GradientStop {
|
||||
position: 0.,
|
||||
midpoint: 0.5,
|
||||
@@ -2194,7 +2198,7 @@ mod test_gradient {
|
||||
midpoint: 0.5,
|
||||
color: Color::BLUE,
|
||||
},
|
||||
])),
|
||||
]))),
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -2826,7 +2830,7 @@ mod test_gradient {
|
||||
.handle_message(NodeGraphMessage::SetInputValue {
|
||||
node_id: gradient_value_id,
|
||||
input_index: 1,
|
||||
value: TaggedValue::Gradient(GradientStops::new([
|
||||
value: Box::new(TaggedValue::Gradient(GradientStops::new([
|
||||
GradientStop {
|
||||
position: 0.,
|
||||
midpoint: 0.5,
|
||||
@@ -2837,7 +2841,7 @@ mod test_gradient {
|
||||
midpoint: 0.5,
|
||||
color: Color::BLUE,
|
||||
},
|
||||
])),
|
||||
]))),
|
||||
})
|
||||
.await;
|
||||
|
||||
|
||||
@@ -118,7 +118,7 @@ fn create_text_widgets(tool: &TextTool, font_catalog: &FontCatalog, document: &D
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: graphene_std::text::text::FontInput::INDEX,
|
||||
value: TaggedValue::Resource(resource_id),
|
||||
value: Box::new(TaggedValue::Resource(resource_id)),
|
||||
}
|
||||
.into(),
|
||||
]),
|
||||
@@ -349,7 +349,7 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Text
|
||||
responses.add(NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: graphene_std::text::text::SizeInput::INDEX,
|
||||
value: TaggedValue::F64(font_size),
|
||||
value: Box::new(TaggedValue::F64(font_size)),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -364,7 +364,7 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Text
|
||||
responses.add(NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: graphene_std::text::text::AlignInput::INDEX,
|
||||
value: TaggedValue::TextAlign(align),
|
||||
value: Box::new(TaggedValue::TextAlign(align)),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ use graphene_std::list::List;
|
||||
use graphene_std::raster::{CPU, Raster};
|
||||
use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box};
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphene_std::vector::style::HasTransform;
|
||||
use graphene_std::vector::{Vector, graphic_types};
|
||||
use graphene_std::{ATTR_TRANSFORM, Graphic, NodeInputDecleration};
|
||||
use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta;
|
||||
@@ -47,7 +48,7 @@ pub struct CompilationResponse {
|
||||
}
|
||||
|
||||
pub enum NodeGraphUpdate {
|
||||
ExecutionResponse(ExecutionResponse),
|
||||
ExecutionResponse(Box<ExecutionResponse>),
|
||||
CompilationResponse(CompilationResponse),
|
||||
EyedropperPreview(Raster<CPU>),
|
||||
NodeGraphUpdateMessage(NodeGraphUpdateMessage),
|
||||
@@ -368,7 +369,7 @@ impl NodeGraphExecutor {
|
||||
responses: existing_responses,
|
||||
vector_modify,
|
||||
inspect_result,
|
||||
} = execution_response;
|
||||
} = *execution_response;
|
||||
|
||||
while let Some(&(queued_execution_id, _)) = self.futures.front() {
|
||||
if queued_execution_id < execution_id {
|
||||
@@ -625,10 +626,14 @@ impl NodeGraphExecutor {
|
||||
if fill_transform_unbaked(document, &network_path, fill_node_id) {
|
||||
let absolute_gradient = gradient.to_absolute(bounding_box, item_transform);
|
||||
let gradient_transform = absolute_gradient.transform * absolute_gradient.to_transform();
|
||||
let input = InputConnector::node(fill_node_id, graphene_std::vector::fill::TransformInput::INDEX);
|
||||
let transform_input = InputConnector::node(fill_node_id, graphene_std::vector::fill::TransformInput::INDEX);
|
||||
let has_transform_input = InputConnector::node(fill_node_id, graphene_std::vector::fill::HasTransformInput::INDEX);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&input, NodeInput::value(TaggedValue::OptionalDAffine2(Some(gradient_transform)), false), &network_path);
|
||||
.set_input(&transform_input, NodeInput::value(TaggedValue::DAffine2(gradient_transform), false), &network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&has_transform_input, NodeInput::value(TaggedValue::HasTransform(HasTransform(true)), false), &network_path);
|
||||
}
|
||||
|
||||
// The transform is settled, so its entry no longer needs to persist for a retry on the next open
|
||||
@@ -710,8 +715,7 @@ impl NodeGraphExecutor {
|
||||
text_frames,
|
||||
clip_targets,
|
||||
vector_data,
|
||||
fill_attributes,
|
||||
stroke_attributes,
|
||||
appearance_attributes,
|
||||
backgrounds: _,
|
||||
} = render_output.metadata;
|
||||
|
||||
@@ -726,8 +730,7 @@ impl NodeGraphExecutor {
|
||||
responses.add(DocumentMessage::UpdateTextFrames { text_frames });
|
||||
responses.add(DocumentMessage::UpdateClipTargets { clip_targets });
|
||||
responses.add(DocumentMessage::UpdateVectorData { vector_data });
|
||||
responses.add(DocumentMessage::UpdateFillAttributes { fill_attributes });
|
||||
responses.add(DocumentMessage::UpdateStrokeAttributes { stroke_attributes });
|
||||
responses.add(DocumentMessage::UpdateAppearanceAttributes { appearance_attributes });
|
||||
responses.add(DocumentMessage::RenderScrollbars);
|
||||
responses.add(DocumentMessage::RenderRulers);
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
@@ -832,16 +835,16 @@ impl NodeGraphExecutor {
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// Whether the fill node's transform input is still the unset `OptionalDAffine2(None)` placeholder that the migration leaves
|
||||
/// behind, meaning its gradient placement has not yet been baked (or set by the user), so a measured bake may safely be written.
|
||||
/// Whether the fill node's gradient placement is still the unset `HasTransform(false)` placeholder that the migration leaves
|
||||
/// behind, meaning it has not yet been baked (or set by the user), so a measured bake may safely be written.
|
||||
fn fill_transform_unbaked(document: &DocumentMessageHandler, network_path: &[NodeId], fill_node_id: NodeId) -> bool {
|
||||
let Some(network) = document.network_interface.document_network().nested_network(network_path) else {
|
||||
return false;
|
||||
};
|
||||
let Some(node) = network.nodes.get(&fill_node_id) else { return false };
|
||||
matches!(
|
||||
node.inputs.get(graphene_std::vector::fill::TransformInput::INDEX).and_then(|input| input.as_value()),
|
||||
Some(TaggedValue::OptionalDAffine2(None))
|
||||
node.inputs.get(graphene_std::vector::fill::HasTransformInput::INDEX).and_then(|input| input.as_value()),
|
||||
Some(TaggedValue::HasTransform(HasTransform(false)))
|
||||
)
|
||||
}
|
||||
|
||||
@@ -985,20 +988,6 @@ 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,
|
||||
{
|
||||
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)
|
||||
}
|
||||
|
||||
/// 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
|
||||
|
||||
@@ -104,7 +104,7 @@ impl InternalNodeGraphUpdateSender {
|
||||
}
|
||||
|
||||
fn send_execution_response(&self, response: ExecutionResponse) {
|
||||
self.0.send(NodeGraphUpdate::ExecutionResponse(response)).expect("Failed to send response")
|
||||
self.0.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response")
|
||||
}
|
||||
|
||||
fn send_eyedropper_preview(&self, raster: Raster<CPU>) {
|
||||
@@ -179,6 +179,8 @@ impl Spawner for WasmSpawner {
|
||||
impl NodeRuntime {
|
||||
pub fn new(receiver: Receiver<GraphRuntimeRequest>, sender: Sender<NodeGraphUpdate>) -> Self {
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
// The box is a trait object, so `Box::default()` cannot name the concrete spawner.
|
||||
#[allow(clippy::box_default)]
|
||||
let spawner: Box<DynSpawner> = Box::new(TokioSpawner::new());
|
||||
#[cfg(target_family = "wasm")]
|
||||
let spawner: Box<DynSpawner> = Box::new(WasmSpawner);
|
||||
@@ -500,7 +502,9 @@ impl NodeRuntime {
|
||||
// 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.
|
||||
// SAFETY: `introspect_with`'s closure is higher-ranked over the batch's
|
||||
// lifetime, so the item cannot escape this read window, which the
|
||||
// frames outlive.
|
||||
let item = unsafe { GroupItem::from_resident(batch) };
|
||||
let bounds = graphene_std::renderer::graphic_list_bounding_box(&RunView::<Graphic>::new(&item)?, DAffine2::IDENTITY);
|
||||
let group = Graphic::Group(Group { row: None, content: item });
|
||||
@@ -512,7 +516,9 @@ impl NodeRuntime {
|
||||
// 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.
|
||||
// SAFETY: `introspect_with`'s closure is higher-ranked over the batch's
|
||||
// lifetime, so the item cannot escape this read window, which the
|
||||
// frames outlive.
|
||||
let item = unsafe { GroupItem::from_resident(batch) };
|
||||
let run = RunView::<Artboard>::new(&item)?;
|
||||
let bounds = artboard_clip_bounds(&run);
|
||||
@@ -522,7 +528,9 @@ impl NodeRuntime {
|
||||
}
|
||||
// Vector run: vector modifications
|
||||
else if type_id == std::any::TypeId::of::<Vector>() {
|
||||
// SAFETY: the batch is resident for the read.
|
||||
// SAFETY: `introspect_with`'s closure is higher-ranked over the batch's
|
||||
// lifetime, so the item cannot escape this read window, which the
|
||||
// frames outlive.
|
||||
let item = unsafe { GroupItem::from_resident(batch) };
|
||||
let run = RunView::<Vector>::new(&item)?;
|
||||
use graphene_std::core_types::lane::LaneSource;
|
||||
@@ -532,7 +540,9 @@ impl NodeRuntime {
|
||||
// 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.
|
||||
// SAFETY: `introspect_with`'s closure is higher-ranked over the batch's
|
||||
// lifetime, so the item cannot escape this read window, which the
|
||||
// frames outlive.
|
||||
let item = unsafe { GroupItem::from_resident(batch) };
|
||||
let run = RunView::<String>::new(&item)?;
|
||||
let bounds = graphene_std::renderer::text_list_bounding_box(&run, DAffine2::IDENTITY);
|
||||
@@ -544,10 +554,10 @@ impl NodeRuntime {
|
||||
Some(())
|
||||
}
|
||||
});
|
||||
if result.is_err() {
|
||||
if let Err(_error) = result {
|
||||
// TODO: Fix the root of the issue causing the spam of this warning (this at least temporarily disables it in release builds)
|
||||
#[cfg(debug_assertions)]
|
||||
warn!("Failed to introspect monitor node {}", result.unwrap_err());
|
||||
warn!("Failed to introspect monitor node {}", _error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+119
-131
@@ -1,173 +1,161 @@
|
||||
# Creating Nodes In Graphite
|
||||
# The Graphite Node Graph
|
||||
|
||||
## Purpose of Nodes
|
||||
Graphite is a node based image editor. Everything it renders comes from evaluating a graph of nodes, and this directory holds that system: the types nodes are built on, the node library, the macro that turns a plain Rust function into a node, and the compiler and executor that turn a saved document into a running graph.
|
||||
|
||||
Graphite is an image editor which is centered around a node based editing workflow, which allows operations to be visually connected in a graph. This is flexible as it allows all operations to be viewed or modified at any time without losing original data. The node system has been designed to be as general as possible with all data types being representable and a broad selection of nodes for a variety of use cases being planned.
|
||||
This is an orientation document, not a specification. It says what lives where and what the vocabulary means. The code is the ground truth, and the module level `//!` headers under `libraries/core-types/src/` carry the real design detail.
|
||||
|
||||
## The Document Graph
|
||||
## Crate map
|
||||
|
||||
The graph that is presented to users in the editor is known as the document graph, and is defined in the `NodeNetwork` struct. Each node that has been placed in this graph has the following properties:
|
||||
Foundations, in `libraries/`:
|
||||
|
||||
```rs
|
||||
pub struct DocumentNode {
|
||||
pub inputs: Vec<NodeInput>,
|
||||
pub call_argument: Type,
|
||||
pub implementation: DocumentNodeImplementation,
|
||||
pub skip_deduplication: bool,
|
||||
pub visible: bool,
|
||||
pub original_location: OriginalLocation,
|
||||
}
|
||||
```
|
||||
(Explanatory comments omitted; the actual definition is currently found in [`node-graph/graph-craft/src/document.rs`](https://github.com/GraphiteEditor/Graphite/blob/master/node-graph/graph-craft/src/document.rs))
|
||||
| Crate | Directory | What it is |
|
||||
| --- | --- | --- |
|
||||
| `core-types` | `libraries/core-types` | The `Node` trait, records, attributes, the arena, contexts, and the node registry. Everything else sits on it. |
|
||||
| `no-std-types` | `libraries/no-std-types` | `no_std` primitives shared with the GPU shader crates: color, blending, choice types. |
|
||||
| `graphene-hash` | `libraries/graphene-hash` | `CacheHash`, which hashes floats by bit pattern so cache keys stay stable. |
|
||||
| `graphic-types` | `libraries/graphic-types` | Document element types: `Graphic`, `Vector`, `Artboard`, and their attribute markers. |
|
||||
| `raster-types` | `libraries/raster-types` | `Image`, `Raster<CPU>` and `Raster<GPU>`, `Texture`, and the pixel traits. |
|
||||
| `vector-types` | `libraries/vector-types` | Vector geometry: `Vector`, subpaths, point and segment domains, gradients, styles. |
|
||||
| `rendering` | `libraries/rendering` | The `Render` trait and the SVG and Vello backends. |
|
||||
| `graphene-application-io` | `libraries/application-io` | Traits for reaching the host: GPU access, resource loading, `EditorApi`. |
|
||||
| `graphene-resource` | `libraries/resources` | Content addressed binary blobs and their async loading. |
|
||||
| `graphene-canvas-utils` | `libraries/canvas-utils` | HTML canvas helpers, and nothing at all off wasm. |
|
||||
| `wgpu-executor` | `libraries/wgpu-executor` | The GPU backend: wgpu context, pipeline and texture caches, the Vello renderer. |
|
||||
|
||||
Each `DocumentNode` is of a particular type, for example the "Opacity" node type. You can define your own type of document node in `editor/src/messages/portfolio/document/node_graph/node_graph_message_handler/document_node_types.rs`. A sample document node type definition for the opacity node is shown:
|
||||
The node library, in `nodes/`:
|
||||
|
||||
```rs
|
||||
DocumentNodeDefinition {
|
||||
name: "Opacity",
|
||||
category: "Image Adjustments",
|
||||
implementation: DocumentNodeImplementation::proto("graphene_core::raster::OpacityNode"),
|
||||
inputs: vec![
|
||||
DocumentInputType::value("Image", TaggedValue::ImageFrame(ImageFrame::empty()), true),
|
||||
DocumentInputType::value("Factor", TaggedValue::F32(100.), false),
|
||||
],
|
||||
outputs: vec![DocumentOutputType::new("Image", FrontendGraphDataType::Raster)],
|
||||
properties: node_properties::multiply_opacity,
|
||||
..Default::default()
|
||||
},
|
||||
```
|
||||
| Crate | Directory | What it is |
|
||||
| --- | --- | --- |
|
||||
| `graphene-core` | `nodes/gcore` | Core nodes: arithmetic, context modification, memoization, animation, and the pilot record nodes. |
|
||||
| `graphene-std` | `nodes/gstd` | The standard library. Re-exports every other node crate and adds the render pipeline, text, and platform IO nodes. |
|
||||
| `blending-nodes` | `nodes/blending` | Blend mode, opacity, and fill. |
|
||||
| `brush-nodes` | `nodes/brush` | Brush strokes, stamping, and brush rendering. |
|
||||
| `graphic-nodes` | `nodes/graphic` | Grouping and artboard construction over `Graphic`. |
|
||||
| `math-nodes` | `nodes/math` | The expression parser node plus arithmetic, random, and vector math. |
|
||||
| `path-bool-nodes` | `nodes/path-bool` | Boolean path operations on vector geometry. |
|
||||
| `raster-nodes` | `nodes/raster` | Color adjustments, blending, and filters. Written `no_std` capable so the kernels double as GPU shaders. |
|
||||
| `repeat-nodes` | `nodes/repeat` | Grid, linear, and circular repeats. |
|
||||
| `text-nodes` | `nodes/text` | Font loading, glyph shaping, text to path, and string operations. |
|
||||
| `transform-nodes` | `nodes/transform` | Translation, rotation, scale, skew, and footprint aware transforms. |
|
||||
| `vector-nodes` | `nodes/vector` | Shape generators, path operations, and vector modification. |
|
||||
|
||||
The identifier here must be the same as that of the proto-node which will be discussed soon (usually the path to the node implementation).
|
||||
Compiler and runtime:
|
||||
|
||||
> [!NOTE]
|
||||
> Nodes defined in `graphene_core` are re-exported by `graphene_std`. However if the strings for the type names do not match exactly then you will encounter an error.
|
||||
| Crate | Directory | What it is |
|
||||
| --- | --- | --- |
|
||||
| `graph-craft` | `graph-craft` | The document graph and its lowering: `NodeNetwork` and `DocumentNode` down to `ProtoNetwork`, plus type inference. |
|
||||
| `preprocessor` | `preprocessor` | The pass over a freshly loaded document: expands proto nodes into their definitions, injects scopes, resolves resource inputs. |
|
||||
| `interpreted-executor` | `interpreted-executor` | The dynamic executor. Instantiates a `ProtoNetwork` into a tree of boxed nodes and evaluates it. |
|
||||
| `node-macro` | `node-macro` | `#[node]` and friends. Generates the node struct, its `Node` impl, the registry entries, and the editor metadata. |
|
||||
| `graphene-cli` | `graphene-cli` | Headless CLI: load a document, compile it, run it, export the result. |
|
||||
|
||||
## Properties panel
|
||||
## Core concepts
|
||||
|
||||
The input names are shown in the graph when an input is exposed (with a dot in the properties panel). The default input is used when a node is first created or when a link is disconnected. An input is comprised from a `TaggedValue` (allowing serialization of a dynamic type with serde) in addition to an exposed boolean, which defines if the input is shown as a dot in the node graph UI by default. In the opacity node, the "Color" input is shown but the "Factor" input is hidden from the graph by default, allowing for a less cluttered graph.
|
||||
### Nodes
|
||||
|
||||
The properties field is a function that defines a number input, which can be seen by selecting the opacity node in the graph. The code for this property is shown below:
|
||||
`Node` lives in `libraries/core-types/src/node.rs` and has exactly one required method, `serve`. A node serves its output record through a frame claim its caller hands it, and returns a proof that only the claim's own closing methods can mint, so a served record is of the claimed layout by construction rather than by convention. Each node claims its frame out of the free space its caller left, so the frame space divides without bookkeeping.
|
||||
|
||||
```rs
|
||||
pub fn multiply_opacity(document_node: &DocumentNode, node_id: NodeId, _context: &mut NodePropertiesContext) -> Vec<LayoutGroup> {
|
||||
let factor = number_widget(document_node, node_id, 1, "Factor", NumberInput::default().min(0.).max(100.).unit("%"), true);
|
||||
Everything else on the trait has a default. `extent_at` and `extent` report how many items the node produces at a nesting level, `layout` reports the record layout, and `eval_batch` serves a whole range at once. The default `eval_batch` advertises no support and drivers fall back to per lane serves with copy out, so an override exists to beat that loop and never for correctness.
|
||||
|
||||
vec![LayoutGroup::Row { widgets: factor }]
|
||||
Kernels written with the macro do not see `serve`. They receive typed inputs and call `eval` on them, and the generated code handles the claim, the protocol, and status folding.
|
||||
|
||||
### Records
|
||||
|
||||
A record is what flows between nodes: the element at offset 0 plus one field per attribute written upstream. Its `Layout` is computed at wiring time from the upstream write set and is never serialized. Records of inline layouts live in the `RecordValue` itself, and larger ones live as per lane views on the evaluation's `Frames`, which the root owns and every node claims its own frame out of. Only generated and wiring code touches offsets, so a safe kernel cannot misalign a field.
|
||||
|
||||
`libraries/core-types/src/record/` is split by abstraction level, and each module's `//!` header states its job:
|
||||
|
||||
| Module | Concern |
|
||||
| --- | --- |
|
||||
| `layout` | Wiring time shape facts: the layout a record takes and the writes it folds from. |
|
||||
| `access` | Raw typed access to a record at a wiring proven layout. |
|
||||
| `frames` | The evaluation's record frame storage. |
|
||||
| `serve` | The serving protocol: a node's own frame claim and the proof it closes with. |
|
||||
| `input` | Consumer side bindings onto a record input, and the drivers they run. |
|
||||
| `route` | Producer side routing: a source's translation into the union layout. |
|
||||
| `promote` | Transient to persistent promotion of records and their parked payloads. |
|
||||
| `owned` | The owned crossing: deep copies that outlive the evaluation their content borrowed. |
|
||||
| `run` | Runs and groups: many records of one layout, resident or owned. |
|
||||
| `testkit` | Law test scaffolding over the record tier. |
|
||||
|
||||
Two words are used precisely throughout. An input is the consumer side of a connection, and a source is the producer side. Neither is called a wire; that word belongs to the editor UI.
|
||||
|
||||
### Attributes
|
||||
|
||||
An attribute is a named, typed channel that rides along with an element. A marker declares the name once, fixing its value type and its name specific default, and a census collects every declaration so name resolution, defaults, and diagnostics all happen at graph compile time. One name belongs to one marker, so a name can never mean two types. Declare markers with `core_types::attribute!`:
|
||||
|
||||
```rust
|
||||
core_types::attribute! {
|
||||
/// The measured length of an element.
|
||||
pub Length("length"): f64;
|
||||
/// A label parked in the arena by whoever writes it.
|
||||
pub Label("label"): &str;
|
||||
}
|
||||
```
|
||||
|
||||
## Graphene (proto node executor)
|
||||
Values are `Copy` and pack directly into record fields. Anything with drop glue rides the arena instead: the marker declares a reference value such as `&str`, the writing kernel parks the payload in the arena, and the record field carries a reference good for the evaluation.
|
||||
|
||||
The graphene crate (found in `gcore/`) and the graphene standard library (found in `gstd/`) is where actual implementation for nodes are located.
|
||||
In a kernel, `Attr<A>` as a parameter is a read, yielding the declared default where nothing upstream wrote it. `Attr<A>` in the return tuple is a write, and the same marker on both sides is a modify. `OwnedAttr<A>` carries a value across the evaluation boundary, and `RemoveAttr<A>` subtracts the attribute from the layout. See `libraries/core-types/src/attribute.rs`, and `nodes/gcore/src/record.rs` for worked examples of every form.
|
||||
|
||||
Implementing a node is done by defining a `struct` implementing the `Node` trait. The `Node` trait has a required function named `eval` that takes one generic input. A sample implementation for an opacity node acting on a color is seen below:
|
||||
### The arena
|
||||
|
||||
```rs
|
||||
use crate::{Color, Node};
|
||||
Two regions, both in `libraries/core-types/src/arena.rs`. The transient arena is reset at the top of every evaluation, so anything parked in it lives exactly as long as the evaluation that parked it. The persistent region backs promoted memo levels; it is flushed whole between evaluations and never during one, so no flush can land while a promoted value is still readable.
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct OpacityNode<OpacityMultiplierInput> {
|
||||
opacity_multiplier: OpacityMultiplierInput,
|
||||
}
|
||||
`Arena::move_park` is the promotion. It copies a payload's header into the receiving region, hands over the drop obligation, and tombstones the source entry in place. The heap the payload owns is neither copied nor freed, since ownership travels with the obligation, and a payload two records share moves once. Region sizes and the flush policy live in `interpreted-executor/src/dynamic_executor.rs`.
|
||||
|
||||
impl<'i, OpacityMultiplierInput: Node<'i, (), Output = f64> + 'i> Node<'i, Color> for OpacityNode<OpacityMultiplierInput> {
|
||||
type Output = Color;
|
||||
fn eval(&'i self, color: Color) -> Color {
|
||||
let opacity_multiplier = self.opacity_multiplier.eval(()) as f32 / 100.;
|
||||
Color::from_rgbaf32_unchecked(color.r(), color.g(), color.b(), color.a() * opacity_multiplier)
|
||||
}
|
||||
}
|
||||
```
|
||||
### Serving
|
||||
|
||||
The `eval` function can only take one input. To support more than one input, the node struct can store references to other nodes. This can be seen here, as the `opacity_multiplier` field, which is generic and is constrained to the trait `Node<'i, (), Output = f64>`. This means that it is a node with the input of `()` (no input is required to compute the opacity) and an output of an `f64`.
|
||||
Evaluating a graph is a walk of `serve` calls down from the root. The root claims the frame buffer, each node claims its own frame out of what its caller left, and status rides the `GPoll` return: `Final`, `Partial` for a result that is correct but incomplete, `Pending` for work not yet ready, `Error`, and `Fallback` for a usable value paired with the error that degraded it. `StatusCell` folds each input's status into the serving node's own, which is what lets a kernel be written as though its inputs simply returned values.
|
||||
|
||||
To compute the value when executing the `OpacityNode`, we need to call `self.opacity_multiplier.eval(())`. This evaluates the node that provides the `opacity_multiplier` input, with the input value of `()`— nothing. This occurs each time the opacity node is run.
|
||||
## Adding a node
|
||||
|
||||
To test this:
|
||||
```rs
|
||||
#[test]
|
||||
fn test_opacity_node() {
|
||||
let opacity_node = OpacityNode {
|
||||
opacity_multiplier: crate::value::CopiedNode(10_f64), // set opacity to 10%
|
||||
};
|
||||
assert_eq!(opacity_node.eval(Color::WHITE), Color::from_rgbaf32_unchecked(1., 1., 1., 0.1));
|
||||
}
|
||||
```
|
||||
Write a function and put `#[node_macro::node]` on it. The macro generates the node struct, the `Node` implementation, the registry entries, and the metadata the editor builds its catalog and properties panel from.
|
||||
|
||||
The `graphene_core::value::CopiedNode` is a node that, when evaluated, copies `10_f32` and returns it.
|
||||
```rust
|
||||
use core_types::Ctx;
|
||||
use core_types::attribute::{Attr, Opacity};
|
||||
|
||||
## Creating a new node
|
||||
|
||||
Instead of manually implementing the `Node` trait with complex generics, one can use the `node` macro, which can be applied to a function like `opacity`. This will generate the struct, implementation, node_registry entry, document node definition and properties panel entries:
|
||||
|
||||
```rs
|
||||
/// Scales the opacity attribute of every element passing through.
|
||||
#[node_macro::node(category("Raster: Adjustments"))]
|
||||
fn opacity(_input: (), #[default(424242)] color: Color, #[range] #[soft(0..100)] opacity_multiplier: f64) -> Color {
|
||||
let opacity_multiplier = opacity_multiplier as f32 / 100.;
|
||||
Color::from_rgbaf32_unchecked(color.r(), color.g(), color.b(), color.a() * opacity_multiplier)
|
||||
fn multiply_opacity(
|
||||
_: impl Ctx,
|
||||
/// The element and its current opacity.
|
||||
(element, opacity): (f64, Attr<Opacity>),
|
||||
/// The factor to scale the opacity by.
|
||||
#[default(1.)]
|
||||
#[range]
|
||||
#[soft(0..2)]
|
||||
factor: f64,
|
||||
) -> (f64, Attr<Opacity>) {
|
||||
(element, Attr(*opacity * factor))
|
||||
}
|
||||
```
|
||||
|
||||
## Additional Macro Options
|
||||
Reading that back: the first parameter is the evaluation context. A tuple parameter is a record input, binding the element alongside the attributes this kernel reads, while a plain parameter is an ordinary value input the user can set. The return tuple is the write set, and returning `Attr<Opacity>` after reading it makes this a modify rather than a fresh write.
|
||||
|
||||
The macro invocation can be extended with additional attributes. The currently supported attributes are (`name`, `path`, `skip_impl`, `category`). When using generics the `#[implementations()]` attribute can be used to automatically populate the node_registry for you. You can also use the `default`, `expose`, `soft`, `hard`, and `range` attributes to influence how the properties are generated. The `#[soft(a..b)]` and `#[hard(a..b)]` attributes set the slider's suggested extent and its enforced clamp, respectively (either endpoint may be omitted, e.g. `0..` or `..100`; both endpoints are inclusive, so there is no `..=` form), and `#[range]` renders the input as a draggable slider. Values typed into the input may exceed the soft extent but are clamped to the hard bounds, so `#[soft]` is only meaningful together with `#[range]`.
|
||||
Doc comments are not decoration. The one on the function becomes the node's description in the editor's catalog, and the one on each parameter becomes that input's description.
|
||||
|
||||
## Executing a document `NodeNetwork`
|
||||
Options on the invocation are `category`, `name`, `path`, `properties` (naming a function in `editor/src/messages/portfolio/document/node_graph/node_properties.rs` for a custom panel), `extent` (naming a function that computes the node's extent, for nodes that change the item count), and `skip_impl`.
|
||||
|
||||
When the document graph is executed, the following steps occur:
|
||||
- The `NodeNetwork` is flattened using `NodeNetwork::flatten`. This involves removing any `DocumentNodeImplementation::Network` - which allow for nested document node networks. Instead, all of the inner nodes are moved into a single node graph.
|
||||
- The `NodeNetwork` is converted into a proto-graph. Each node's inputs are stored as a list of node IDs in the `ConstructionArgs` struct in the `ProtoNode`. Converting a document graph into a proto graph is done with `NodeNetwork::into_proto_networks`.
|
||||
- The newly created `ProtoNode`s are then converted into the corresponding constructor functions using the mapping defined in `node-graph/interpreted-executor/src/node_registry.rs`. This is done by `BorrowTree::push_node`.
|
||||
- The constructor functions are run with the `ConstructionArgs` enum. Constructors generally evaluate the result of these inputs, e.g. if you have a `Pi` node that is used as the second input to an `Add` node, the `Add` node's constructor will evaluate the `Pi` node. This is visible if you place a log statement in the `Pi` node's implementation.
|
||||
- The resolved functions are stored in a `BorrowTree`, which allows previous proto-nodes to be referenced as inputs by later nodes. The `BorrowTree` ensures nodes can't be removed while being referenced by other nodes.
|
||||
Per parameter there are `#[default(..)]`, `#[expose]`, `#[name(..)]`, `#[widget(..)]`, and `#[implementations(..)]`, which enumerates the concrete type rows a generic node registers. For numbers, `#[range]` renders a draggable slider, `#[soft(a..b)]` sets its suggested extent, and `#[hard(a..b)]` sets the enforced clamp. Either endpoint may be omitted and both are inclusive, so there is no `..=` form. Typed values may exceed the soft extent but are clamped to the hard bounds, so `#[soft]` only means anything together with `#[range]`. The macro checks these and will reject a `#[range]` missing an end, or a `#[soft]` bound equal to its `#[hard]` counterpart.
|
||||
|
||||
The definition for the constructor of a node that applies the opacity transformation to each pixel of an image:
|
||||
```rs
|
||||
(
|
||||
// Matches against the string defined in the document node.
|
||||
ProtoNodeIdentifier::new("graphene_core::raster::OpacityNode"),
|
||||
// This function is run when converting the `ProtoNode` struct into the desired struct.
|
||||
|args| {
|
||||
Box::pin(async move {
|
||||
// Creates an instance of the struct that defines the node.
|
||||
let node = construct_node!(args, graphene_core::raster::OpacityNode<_>, [f64]).await;
|
||||
// Create a new map image node, that calls the `node` for each pixel.
|
||||
let map_node = graphene_std::raster::MapImageNode::new(graphene_core::value::ValueNode::new(node));
|
||||
// Wraps this in a type erased future `Box<Pin<dyn core::future::Future<Output = T> + 'n>>` - this allows it to work with async.
|
||||
let map_node = graphene_std::any::FutureWrapperNode::new(map_node);
|
||||
// The `DynAnyNode` downcasts its input from a `Box<dyn DynAny>` i.e. dynamically typed, to the desired statically typed input value. It then runs the wrapped node and converts the result back into a dynamically typed `Box<dyn DynAny>`.
|
||||
let any: DynAnyNode<Image<Color>, _, _> = graphene_std::any::DynAnyNode::new(graphene_core::value::ValueNode::new(map_node));
|
||||
// Nodes are stored as type erased, which means they are `Box<dyn NodeIo + Node>`. This allows us to create dynamic graphs, using dynamic dispatch so we do not have to know all node combinations at compile time.
|
||||
any.into_type_erased()
|
||||
})
|
||||
},
|
||||
// Defines the call argument, return value, and inputs.
|
||||
NodeIOTypes::new(concrete!(Image<Color>), concrete!(Image<Color>), vec![fn_type!((), f64)]),
|
||||
),
|
||||
```
|
||||
Registration is automatic. The macro emits a `ctor` constructor that inserts into `NODE_REGISTRY` and `NODE_METADATA` in `libraries/core-types/src/registry.rs` at process start, and `interpreted-executor/src/node_registry.rs` takes that table and adds a hand written set of conversion nodes to build the registry the compiler consumes. There is no separate definition table to edit; writing the function is the whole job. On wasm the `ctor` attribute is skipped and registration is driven explicitly instead.
|
||||
|
||||
Nodes in the borrow stack take a `Box<dyn DynAny>` as input and output another `Box<dyn DynAny>`, to allow for any type. To use a specific type, we must downcast the values that have been passed in.
|
||||
However the `OpacityNode` only works on one pixel at a time, so we first insert a `MapImageNode` to call the `OpacityNode` for every pixel in the image.
|
||||
Finally we call `.into_type_erased()` on the result and that is inserted into the borrow stack.
|
||||
## From a document to a result
|
||||
|
||||
We also need to add an implementation so that the user can change the opacity of just a single color. To simplify this process for raster nodes, a `raster_node!` macro is available which can simplify the definition of the opacity node to:
|
||||
```rs
|
||||
raster_node!(graphene_core::raster::OpacityNode<_>, params: [f64]),
|
||||
```
|
||||
A saved document arrives as a `NodeNetwork`. The preprocessor expands each proto node reference into the `DocumentNode` template built from its registry metadata, reconciling saved inputs against what the current definition expects, which is what lets old documents load against new node definitions. `NodeNetwork::flatten` then dissolves nested networks into one graph, `into_proto_networks` lowers it to a `ProtoNetwork`, and `TypingContext` resolves types against the registry. The executor pushes each `ProtoNode` into its `BorrowTree`, which keeps a node alive as long as anything references it, and `eval_root` resets the transient arena, sizes the frame buffer to the graph's need, and serves the output.
|
||||
|
||||
There is also the more general `register_node!` for nodes that do not need to run per pixel.
|
||||
```rs
|
||||
register_node!(graphene_core::transform_nodes::SetTransformNode<_>, input: Vector, params: [DAffine2]),
|
||||
```
|
||||
## Deeper reading
|
||||
|
||||
The design documentation for the record tier is the `//!` headers in the source. Read `libraries/core-types/src/record/mod.rs` first, then the submodule headers in the table above, then `node.rs`, `attribute.rs`, and `arena.rs`.
|
||||
|
||||
Two RFCs cover work adjacent to this system:
|
||||
|
||||
- [`rfcs/document-format.md`](rfcs/document-format.md), the `.gdd` on disk format and its CRDT delta model.
|
||||
- [`rfcs/fine-grained-context-caching.md`](rfcs/fine-grained-context-caching.md), a compilation pass that nullifies unused parts of the context to avoid needless cache invalidation.
|
||||
|
||||
## Debugging
|
||||
|
||||
Debugging inside your node can be done with the `log::debug!()` macro, for example `log::debug!("The opacity is {opacity_multiplier}");`.
|
||||
`log::debug!()` works inside a node body. For running a graph without the editor in the way, `graphene-cli` loads a document, compiles it, evaluates it, and can list every registered node.
|
||||
|
||||
We need a utility to easily view a graph as the various steps are applied. We also need a way to transparently see which constructors are being run, which nodes are being evaluated, and in what order.
|
||||
|
||||
## Conclusion
|
||||
|
||||
While we simplify the writing of nodes using the macro by hiding some of the details, creating nodes involves many files and concepts. We will work to continue making this system easier to use.
|
||||
|
||||
Any contributions you might have would be greatly appreciated. If any parts of this guide are outdated or difficult to understand, please feel free to ask for help in the Graphite Discord. We are very happy to answer any questions :)
|
||||
If any of this is wrong or unclear, please ask in the Graphite Discord. We are happy to help.
|
||||
@@ -315,7 +315,7 @@ pub enum DocumentNodeImplementation {
|
||||
Network(NodeNetwork),
|
||||
/// This describes a (document) node implemented as a proto node.
|
||||
///
|
||||
/// A proto node identifier which can be found in `node_registry.rs`.
|
||||
/// A proto node identifier, resolved against `NODE_REGISTRY` in `core-types/src/registry.rs`.
|
||||
#[serde(alias = "Unresolved")] // TODO: Eventually remove this alias document upgrade code
|
||||
ProtoNode(ProtoNodeIdentifier),
|
||||
/// The Extract variant is a tag which tells the compilation process to do something special: it invokes language-level functionality built for use by the ExtractNode to enable metaprogramming.
|
||||
|
||||
@@ -7,10 +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::registry::EdgeHandle;
|
||||
use core_types::registry::SourceHandle;
|
||||
use core_types::transform::Footprint;
|
||||
use core_types::uuid::NodeId;
|
||||
use core_types::value::{leveled_record_value_edge, record_value_edge};
|
||||
use core_types::value::{leveled_record_value_source, record_value_source};
|
||||
use core_types::{CacheHash, Color, ContextModification, MemoHash, Type, TypeDescriptor};
|
||||
use dyn_any::DynAny;
|
||||
pub use dyn_any::StaticType;
|
||||
@@ -266,7 +266,7 @@ macro_rules! tagged_value {
|
||||
}
|
||||
}
|
||||
|
||||
/// The record layout of this value's edge: leveled for the list-carrying
|
||||
/// The record layout of this value's source: 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> {
|
||||
@@ -309,13 +309,13 @@ macro_rules! tagged_value {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
/// Materializes the value as [`Self::to_dynany`] does, wrapped in a value source typed by [`Self::ty`].
|
||||
pub fn to_edge(self) -> Result<SourceHandle, String> {
|
||||
match self {
|
||||
// ===============
|
||||
// MANUAL VARIANTS
|
||||
// ===============
|
||||
Self::None => Ok(record_value_edge(())),
|
||||
Self::None => Ok(record_value_source(())),
|
||||
Self::TypeDefault(td) => {
|
||||
let name = td.name.as_ref();
|
||||
// The list-typed defaults serve an empty level; the rest construct
|
||||
@@ -323,7 +323,7 @@ macro_rules! tagged_value {
|
||||
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()));
|
||||
return Ok(leveled_record_value_source(Vec::<$element>::new()));
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -332,54 +332,54 @@ macro_rules! tagged_value {
|
||||
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()])); }
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<List<Vector>>()) { return Ok(leveled_record_value_source(vec![Vector::default()])); }
|
||||
check_level!(List<String>, String);
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<DocumentNode>()) { return Ok(record_value_edge(DocumentNode::default())); }
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<Resource>()) { return Ok(record_value_edge(Resource::default())); }
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<DocumentNode>()) { return Ok(record_value_source(DocumentNode::default())); }
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<Resource>()) { return Ok(record_value_source(Resource::default())); }
|
||||
Self::from_type_or_none(&Type::Concrete(td)).to_edge()
|
||||
}
|
||||
Self::F64Array(values) => Ok(leveled_record_value_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)),
|
||||
Self::F64Array(values) => Ok(leveled_record_value_source(values)),
|
||||
Self::Color(color) => Ok(leveled_record_value_source(color.into_iter().collect::<Vec<_>>())),
|
||||
Self::Gradient(stops) => Ok(leveled_record_value_source(vec![stops])),
|
||||
Self::BrushStrokes(strokes) => Ok(leveled_record_value_source(strokes)),
|
||||
// =======================
|
||||
// AUTO-GENERATED VARIANTS
|
||||
// =======================
|
||||
$( Self::$identifier(x) => Ok(record_value_edge(x)), )*
|
||||
$( Self::$identifier(x) => Ok(record_value_source(x)), )*
|
||||
// =======================
|
||||
// NON-SERIALIZED VARIANTS
|
||||
// =======================
|
||||
Self::RenderOutput(x) => Ok(record_value_edge(x)),
|
||||
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)),
|
||||
Self::ResourceHash(x) => Ok(record_value_edge(x)),
|
||||
Self::RenderOutput(x) => Ok(record_value_source(x)),
|
||||
Self::NodeIdPath(path) => Ok(record_value_source(path)),
|
||||
Self::DocumentNode(node) => Ok(record_value_source(node)),
|
||||
Self::ContextModification(modification) => Ok(record_value_source(modification)),
|
||||
Self::EditorApi(x) => Ok(record_value_source(x)),
|
||||
Self::ResourceHash(x) => Ok(record_value_source(x)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Evaluates a typed edge and converts the landed value into a tagged value, with the coverage of [`Self::try_from_any`].
|
||||
pub fn from_edge<'f>(handle: EdgeHandle, ctx: &Context<'f>, frames: &core_types::record::Frames<'f>) -> Result<GPoll<Self>, String> {
|
||||
/// Evaluates a typed source and converts the landed value into a tagged value, with the coverage of [`Self::try_from_any`].
|
||||
pub fn from_edge<'f>(handle: SourceHandle, ctx: &Context<'f>, frames: &core_types::record::Frames<'f>) -> Result<GPoll<Self>, String> {
|
||||
let ty = handle.ty().clone();
|
||||
// =======================
|
||||
// RECORD WIRES, WHICH LAND AS THEIR ELEMENT
|
||||
// =======================
|
||||
if ty == core_types::registry::record_edge_type::<()>() {
|
||||
if ty == core_types::registry::record_source_type::<()>() {
|
||||
let edge = handle.downcast_record::<()>().map_err(|e| format!("{e:?}"))?;
|
||||
return Ok(core_types::record::serve_edge(&edge, ctx, frames).map(|_| TaggedValue::None));
|
||||
return Ok(core_types::record::serve_input(&edge, ctx, frames).map(|_| TaggedValue::None));
|
||||
}
|
||||
$(
|
||||
if ty == core_types::registry::record_edge_type::<$ty>() {
|
||||
if ty == core_types::registry::record_source_type::<$ty>() {
|
||||
let layout = handle.layout().clone();
|
||||
let edge = handle.downcast_record::<$ty>().map_err(|e| format!("{e:?}"))?;
|
||||
return Ok(core_types::record::serve_edge(&edge, ctx, frames)
|
||||
return Ok(core_types::record::serve_input(&edge, ctx, frames)
|
||||
.map(|value| TaggedValue::$identifier(unsafe { core_types::record::read_element::<$ty>(layout.rec(&value)) })));
|
||||
}
|
||||
)*
|
||||
if ty == core_types::registry::record_edge_type::<RenderOutput>() {
|
||||
if ty == core_types::registry::record_source_type::<RenderOutput>() {
|
||||
let layout = handle.layout().clone();
|
||||
let edge = handle.downcast_record::<RenderOutput>().map_err(|e| format!("{e:?}"))?;
|
||||
return Ok(core_types::record::serve_edge(&edge, ctx, frames)
|
||||
return Ok(core_types::record::serve_input(&edge, ctx, frames)
|
||||
.map(|value| TaggedValue::RenderOutput(unsafe { core_types::record::read_element::<RenderOutput>(layout.rec(&value)) })));
|
||||
}
|
||||
Err(format!("Cannot convert edge of type {ty} to TaggedValue"))
|
||||
@@ -447,7 +447,7 @@ macro_rules! tagged_value {
|
||||
$( 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
|
||||
// Leveled inputs type by their element; each element name maps to the
|
||||
// same tagged default as its legacy list form.
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<Color>()) { return Some(TaggedValue::Color(Some(Color::default()))) }
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<GradientStops>()) { return Some(TaggedValue::Gradient(GradientStops::default())) }
|
||||
@@ -580,6 +580,7 @@ tagged_value! {
|
||||
StrokeJoin(vector::style::StrokeJoin),
|
||||
StrokeAlign(vector::style::StrokeAlign),
|
||||
PaintOrder(vector::style::PaintOrder),
|
||||
HasTransform(vector::style::HasTransform),
|
||||
GradientType(vector::style::GradientType),
|
||||
GradientSpreadMethod(vector::style::GradientSpreadMethod),
|
||||
ReferencePoint(vector::ReferencePoint),
|
||||
@@ -705,7 +706,7 @@ impl TaggedValue {
|
||||
|
||||
match ty {
|
||||
Type::Generic(_) => None,
|
||||
// A leveled wire's default is its element's default, as in `from_type`.
|
||||
// A leveled input's default is its element's default, as in `from_type`.
|
||||
Type::Record(inner) => TaggedValue::from_primitive_string(string, inner),
|
||||
Type::Concrete(concrete_type) => {
|
||||
let ty = concrete_type.id?;
|
||||
@@ -919,27 +920,27 @@ mod typedefault_dispatch {
|
||||
mod leveled_edges {
|
||||
use super::*;
|
||||
use core_types::descriptor;
|
||||
use core_types::registry::record_edge_type;
|
||||
use core_types::registry::record_source_type;
|
||||
|
||||
#[test]
|
||||
fn list_variants_produce_leveled_edges_typed_by_element() {
|
||||
let edge = TaggedValue::F64Array(vec![1., 2., 3.]).to_edge().unwrap();
|
||||
assert_eq!(edge.ty(), &record_edge_type::<f64>());
|
||||
assert_eq!(edge.ty(), &record_source_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.ty(), &record_source_type::<Color>());
|
||||
assert_eq!(edge.layout().depth, 1);
|
||||
|
||||
let edge = TaggedValue::TypeDefault(descriptor!(List<Graphic>)).to_edge().unwrap();
|
||||
assert_eq!(edge.ty(), &record_edge_type::<Graphic>());
|
||||
assert_eq!(edge.ty(), &record_source_type::<Graphic>());
|
||||
assert_eq!(edge.layout().depth, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_variants_keep_their_rank_zero_edges() {
|
||||
let edge = TaggedValue::Bool(true).to_edge().unwrap();
|
||||
assert_eq!(edge.ty(), &record_edge_type::<bool>());
|
||||
assert_eq!(edge.ty(), &record_source_type::<bool>());
|
||||
assert_eq!(edge.layout().depth, 0);
|
||||
}
|
||||
|
||||
@@ -961,7 +962,7 @@ mod leveled_edges {
|
||||
#[cfg(test)]
|
||||
mod record_defaults {
|
||||
use super::*;
|
||||
use core_types::registry::record_edge_type;
|
||||
use core_types::registry::record_source_type;
|
||||
|
||||
// The registry can present a record row first (wasm registration order),
|
||||
// so primitive defaults must parse through the record wrapping.
|
||||
@@ -969,7 +970,7 @@ mod record_defaults {
|
||||
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)));
|
||||
assert_eq!(TaggedValue::from_primitive_string("5", &record_source_type::<u32>()), Some(TaggedValue::U32(5)));
|
||||
assert_eq!(TaggedValue::from_primitive_string("true", &record_source_type::<bool>()), Some(TaggedValue::Bool(true)));
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,9 @@ 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
|
||||
.compute_layouts()
|
||||
.map_err(|errors| errors.iter().map(|error| format!("{:?}", error.error)).collect::<Vec<_>>().join("\n"))?;
|
||||
proto_network.generate_stable_node_ids();
|
||||
Ok(proto_network)
|
||||
})
|
||||
|
||||
@@ -70,11 +70,12 @@ impl core::fmt::Display for ProtoNetwork {
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
/// Defines the arguments used to construct the boxed node struct. This is used to call the constructor function in the `node_registry.rs` file - which is hidden behind a wall of macros.
|
||||
/// Defines the arguments used to construct the boxed node struct, passed to the
|
||||
/// constructor registered in `NODE_REGISTRY` (`core-types/src/registry.rs`).
|
||||
pub enum ConstructionArgs {
|
||||
/// A value of a type that is known, allowing serialization (serde::Deserialize is not object safe)
|
||||
Value(MemoHash<value::TaggedValue>),
|
||||
/// A list of nodes used as inputs to the constructor function in `node_registry.rs`.
|
||||
/// A list of nodes used as inputs to the registered constructor.
|
||||
/// The bool indicates whether to treat the node as lambda node.
|
||||
// TODO: use a struct for clearer naming.
|
||||
Nodes(Vec<NodeId>),
|
||||
@@ -377,7 +378,9 @@ impl ProtoNetwork {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn compute_layouts(&mut self) {
|
||||
pub fn compute_layouts(&mut self) -> Result<(), GraphErrors> {
|
||||
self.fold_attribute_names()?;
|
||||
let mut errors = GraphErrors::new();
|
||||
for index in 0..self.nodes.len() {
|
||||
let lane_invariant = self.nodes[index].1.lane_invariant_inputs;
|
||||
let layout = {
|
||||
@@ -387,6 +390,9 @@ impl ProtoNetwork {
|
||||
frame_bytes: layout.frame_bytes(),
|
||||
plan: Vec::new(),
|
||||
lane_invariant,
|
||||
named_writes: Vec::new(),
|
||||
named_reads: Vec::new(),
|
||||
named_read_defaults: Vec::new(),
|
||||
layout,
|
||||
}),
|
||||
ConstructionArgs::Nodes(inputs) => node.resolved.layout_meta.as_ref().and_then(|meta| {
|
||||
@@ -394,6 +400,10 @@ impl ProtoNetwork {
|
||||
.iter()
|
||||
.map(|input| self.nodes[input.0 as usize].1.resolved.layout.as_ref().map(|resolved| &resolved.layout))
|
||||
.collect();
|
||||
// A read meets the name's value type where the name was
|
||||
// written, so a disagreement upstream is caught here
|
||||
// rather than read as the wrong type at run time.
|
||||
errors.extend(read_type_conflicts(node, meta, &input_layouts));
|
||||
meta.sources.iter().all(|&source| input_layouts[source as usize].is_some()).then(|| core_types::record::RecordLayout {
|
||||
lane_invariant,
|
||||
..meta.resolve(&input_layouts)
|
||||
@@ -411,6 +421,79 @@ impl ProtoNetwork {
|
||||
self.nodes[index].1.resolved.layout = layout;
|
||||
}
|
||||
self.stack_need = self.fold_stack_peak();
|
||||
errors.is_empty().then_some(()).ok_or(errors)
|
||||
}
|
||||
|
||||
/// Resolves every name-from-input write against the constant its name
|
||||
/// input carries, leaving each node's meta indistinguishable from a marker
|
||||
/// node's. A name input that is not a constant is refused here, which is
|
||||
/// the whole of the no-runtime-names rule: past this point a name is a
|
||||
/// `&'static str` in a layout, so there is nowhere for one to be computed.
|
||||
fn fold_attribute_names(&mut self) -> Result<(), GraphErrors> {
|
||||
let mut errors = GraphErrors::new();
|
||||
for index in 0..self.nodes.len() {
|
||||
let Some(meta) = &self.nodes[index].1.resolved.layout_meta else { continue };
|
||||
if meta.named_writes.is_empty() && meta.named_reads.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let ConstructionArgs::Nodes(inputs) = &self.nodes[index].1.construction_args else {
|
||||
continue;
|
||||
};
|
||||
// Writes first, then reads: both draw their names the same way, and
|
||||
// the one-name-one-type check runs over them together.
|
||||
let sources: Vec<(u8, std::any::TypeId)> = meta
|
||||
.named_writes
|
||||
.iter()
|
||||
.map(|named| (named.name_input, named.template.type_id))
|
||||
.chain(meta.named_reads.iter().map(|named| (named.name_input, named.template.type_id)))
|
||||
.collect();
|
||||
let names: Vec<Result<&'static str, GraphErrorType>> = sources
|
||||
.iter()
|
||||
.map(
|
||||
|&(name_input, _)| match inputs.get(name_input as usize).map(|input| &self.nodes[input.0 as usize].1.construction_args) {
|
||||
Some(ConstructionArgs::Value(value)) => match &**value {
|
||||
value::TaggedValue::String(name) => Ok(core_types::attribute::intern_name(name)),
|
||||
other => Err(GraphErrorType::AttributeName(format!("an attribute name must be text, but input {} is {}", name_input + 1, other.ty()))),
|
||||
},
|
||||
_ => Err(GraphErrorType::AttributeName(format!(
|
||||
"input {} must be a constant, since attribute names resolve when the graph compiles rather than when it runs",
|
||||
name_input + 1
|
||||
))),
|
||||
},
|
||||
)
|
||||
.collect();
|
||||
let node = &self.nodes[index].1;
|
||||
let mut folded: Vec<(&'static str, std::any::TypeId)> = Vec::new();
|
||||
let mut failed = false;
|
||||
for (name, &(_, type_id)) in names.iter().zip(&sources) {
|
||||
match name {
|
||||
Err(error) => {
|
||||
errors.push(GraphError::new(node, error.clone()));
|
||||
failed = true;
|
||||
}
|
||||
Ok(name) => {
|
||||
if let Some(conflict) = one_name_one_type(name, type_id, &folded) {
|
||||
errors.push(GraphError::new(node, conflict));
|
||||
failed = true;
|
||||
}
|
||||
folded.push((name, type_id));
|
||||
}
|
||||
}
|
||||
}
|
||||
if failed {
|
||||
continue;
|
||||
}
|
||||
let writes = self.nodes[index].1.resolved.layout_meta.as_ref().expect("checked above").named_writes.len();
|
||||
let meta = self.nodes[index].1.resolved.layout_meta.as_mut().expect("checked above");
|
||||
for (position, name) in names.into_iter().enumerate() {
|
||||
let name = name.expect("every name resolved");
|
||||
match position < writes {
|
||||
true => meta.fold_name(position, name),
|
||||
false => meta.fold_read_name(name),
|
||||
}
|
||||
}
|
||||
}
|
||||
errors.is_empty().then_some(()).ok_or(errors)
|
||||
}
|
||||
|
||||
/// Peak record-stack bytes for evaluating [`output`](Self::output)'s cone. A node holds its
|
||||
@@ -736,9 +819,47 @@ impl ProtoNetwork {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
/// Reports each name-from-input read whose value type disagrees with the field
|
||||
/// the name already names on the input it reads. An absent field is no
|
||||
/// conflict: the read serves the name's forced default.
|
||||
fn read_type_conflicts(node: &ProtoNode, meta: &core_types::record::LayoutMeta, inputs: &[Option<&core_types::record::Layout>]) -> GraphErrors {
|
||||
meta.named_reads
|
||||
.iter()
|
||||
.zip(&meta.folded_read_names)
|
||||
.filter_map(|(read, name)| {
|
||||
let layout = inputs.get(read.input as usize).copied().flatten()?;
|
||||
let field = layout.fields.iter().find(|field| field.name == *name && field.level == read.template.level)?;
|
||||
(field.type_id != read.template.type_id).then(|| {
|
||||
GraphError::new(
|
||||
node,
|
||||
GraphErrorType::AttributeName(format!("attribute `{name}` is read at one value type but written at another, and one name carries one value type")),
|
||||
)
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Reports a folded name that disagrees with a type the same name already
|
||||
/// carries, over the census and the names this node folded together. One name
|
||||
/// means one value type everywhere, so the layouts a graph folds can never
|
||||
/// declare a field twice at two widths.
|
||||
fn one_name_one_type(name: &str, value_type: std::any::TypeId, folded: &[(&'static str, std::any::TypeId)]) -> Option<GraphErrorType> {
|
||||
let census = core_types::attribute::info(name);
|
||||
let declared = census
|
||||
.filter(|row| row.value_type != value_type)
|
||||
.map(|row| row.value_type_name.to_string())
|
||||
.or_else(|| folded.iter().find(|(other, ty)| *other == name && *ty != value_type).map(|_| "another type on this node".to_string()))?;
|
||||
Some(GraphErrorType::AttributeName(format!(
|
||||
"attribute `{name}` is already declared at {declared}, and one name carries one value type"
|
||||
)))
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum GraphErrorType {
|
||||
NodeNotFound(NodeId),
|
||||
/// A name-from-input attribute write whose name could not be resolved: it
|
||||
/// is not a constant, or it disagrees with the name's declared value type.
|
||||
AttributeName(String),
|
||||
UnexpectedGenerics {
|
||||
index: usize,
|
||||
inputs: Vec<Type>,
|
||||
@@ -763,6 +884,7 @@ impl Debug for GraphErrorType {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
GraphErrorType::NodeNotFound(id) => write!(f, "Input node {id} is not present in the typing context"),
|
||||
GraphErrorType::AttributeName(error) => write!(f, "{error}"),
|
||||
GraphErrorType::UnexpectedGenerics { index, inputs } => write!(f, "Generic inputs should not exist but found at {index}: {inputs:?}"),
|
||||
GraphErrorType::NoImplementations => write!(f, "No implementations found"),
|
||||
GraphErrorType::NoConstructor => write!(f, "No construct found for node"),
|
||||
@@ -1041,8 +1163,7 @@ fn valid_type(from: &Type, to: &Type) -> bool {
|
||||
// Graphite doesn't have subtyping currently, but it used to have it, and may do so again, so we make sure to compare types in this way to make things easier.
|
||||
// More details explained here: <https://github.com/GraphiteEditor/Graphite/issues/1741>
|
||||
(Type::Fn(in1, out1), Type::Fn(in2, out2)) => valid_type(out2, out1) && valid_type(in1, in2),
|
||||
// A lend edge is substitutable exactly when the lent values are.
|
||||
// A record edge is substitutable exactly when the elements are.
|
||||
// A record input is substitutable exactly when the elements are.
|
||||
(Type::Record(in1), Type::Record(in2)) => valid_type(in1, in2),
|
||||
// If either the proposed input or the allowed input are generic, we allow the substitution (meaning this is a valid subtype).
|
||||
// TODO: Add proper generic counting which is not based on the name
|
||||
|
||||
@@ -2,7 +2,7 @@ use crate::node_registry;
|
||||
use core_types::arena::Arena;
|
||||
use core_types::context::{ContextImpl, DynSlot, EvalScope, ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime, VarArg, VarArgLink, VarArgSlots};
|
||||
use core_types::gpoll::GPoll;
|
||||
use core_types::registry::EdgeHandle;
|
||||
use core_types::registry::SourceHandle;
|
||||
use core_types::runtime::{DynGraphRuntime, DynSpawner, GraphRuntime, NoopSpawner};
|
||||
use graph_craft::Type;
|
||||
use graph_craft::document::NodeId;
|
||||
@@ -33,6 +33,20 @@ fn over_budget(used: usize, budget: usize) -> bool {
|
||||
used >= budget / 8 * 7
|
||||
}
|
||||
|
||||
/// The deep element glue is filled by runtime registration: ctors at load
|
||||
/// natively, host-invoked exports on wasm. A lifetime-carrying element whose
|
||||
/// glue never registered takes the shallow clone-out path, which brands its
|
||||
/// arena borrows `'static` for a memo to hold across a reset, so a missed
|
||||
/// registration is caught here rather than at the first capture.
|
||||
fn assert_deep_element_glue() {
|
||||
for (name, registered) in [
|
||||
("graphic", core_types::record::has_deep_element_glue(std::any::TypeId::of::<graphic_types::Graphic<'static>>())),
|
||||
("artboard", core_types::record::has_deep_element_glue(std::any::TypeId::of::<graphic_types::Artboard<'static>>())),
|
||||
] {
|
||||
assert!(registered, "deep element glue for `{name}` is missing; run `__node_registry_deep_element_{name}` first");
|
||||
}
|
||||
}
|
||||
|
||||
fn new_arena(capacity: usize) -> Arena {
|
||||
Arena::new(capacity).unwrap_or_else(|| {
|
||||
log::error!("arena generations exhausted; continuing without frame caching");
|
||||
@@ -66,6 +80,7 @@ fn noop_runtime() -> Arc<DynGraphRuntime> {
|
||||
|
||||
impl Default for DynamicExecutor {
|
||||
fn default() -> Self {
|
||||
assert_deep_element_glue();
|
||||
Self {
|
||||
output: Default::default(),
|
||||
tree: Default::default(),
|
||||
@@ -96,6 +111,7 @@ pub struct ResolvedDocumentNodeTypesDelta {
|
||||
|
||||
impl DynamicExecutor {
|
||||
pub fn new(mut proto_network: ProtoNetwork) -> Result<Self, GraphErrors> {
|
||||
assert_deep_element_glue();
|
||||
let mut typing_context = TypingContext::new(&node_registry::NODE_REGISTRY);
|
||||
typing_context.update(&mut proto_network)?;
|
||||
let output = proto_network.output;
|
||||
@@ -173,18 +189,16 @@ impl DynamicExecutor {
|
||||
/// 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.
|
||||
/// rank-0 input yields its element and a leveled input its legacy list.
|
||||
pub fn introspect(&self, node_path: &[NodeId]) -> Result<Arc<dyn std::any::Any + Send + Sync + 'static>, IntrospectError> {
|
||||
let result = self.tree.introspect(node_path)?;
|
||||
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);
|
||||
return self.introspect_with(node_path, graphic_types::boundary::batch_to_legacy).map(Arc::from);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Re-evaluates the monitored edge at `node_path` with its stored context
|
||||
/// Re-evaluates the monitored input at `node_path` with its stored context
|
||||
/// snapshot and hands the resulting resident batch to `read`, inside the
|
||||
/// introspection window. The monitor stores only the context; the value is
|
||||
/// recreated against current source data, so a read right after an
|
||||
@@ -197,7 +211,7 @@ impl DynamicExecutor {
|
||||
let edge = self
|
||||
.tree
|
||||
.get_by_path(node_path)
|
||||
.and_then(EdgeHandle::record_edge)
|
||||
.and_then(SourceHandle::record_source)
|
||||
.ok_or_else(|| IntrospectError::PathNotFound(node_path.to_vec()))?;
|
||||
let arena = self.arena.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let persistent = self.persistent.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
@@ -219,10 +233,10 @@ impl DynamicExecutor {
|
||||
_ => None,
|
||||
}
|
||||
} else {
|
||||
match core_types::record::serve_edge(&edge, &ctx, &frames) {
|
||||
match core_types::record::serve_input(&edge, &ctx, &frames) {
|
||||
GPoll::Final(value) | GPoll::Partial(value) => {
|
||||
let rec = layout.rec(&value);
|
||||
// SAFETY: the serve produced one live record of the edge's layout.
|
||||
// SAFETY: the serve produced one live record of the input's layout.
|
||||
let batch = unsafe { core_types::node::RecordBatch::new(rec.ptr(), 1, layout) };
|
||||
read(layout, batch, &arena)
|
||||
}
|
||||
@@ -363,7 +377,7 @@ impl std::fmt::Display for IntrospectError {
|
||||
///
|
||||
/// # Fields
|
||||
///
|
||||
/// * `nodes`: A [`HashMap`] of [`NodeId`]s to tuples of [`EdgeHandle`] and [`Path`].
|
||||
/// * `nodes`: A [`HashMap`] of [`NodeId`]s to tuples of [`SourceHandle`] and [`Path`].
|
||||
/// This stores the actual node instances and their associated paths.
|
||||
///
|
||||
/// * `source_map`: A [`HashMap`] from [`Path`] to tuples of [`NodeId`] and [`NodeTypes`].
|
||||
@@ -373,7 +387,7 @@ impl std::fmt::Display for IntrospectError {
|
||||
#[derive(Default)]
|
||||
pub struct BorrowTree {
|
||||
/// A hashmap of node IDs and dynamically typed nodes.
|
||||
nodes: HashMap<NodeId, (EdgeHandle, Path)>,
|
||||
nodes: HashMap<NodeId, (SourceHandle, Path)>,
|
||||
/// A hashmap from the document path to the proto node ID.
|
||||
source_map: HashMap<Path, (NodeId, NodeTypes)>,
|
||||
/// The record-stack reserve, folded from the graph at construction.
|
||||
@@ -410,27 +424,27 @@ impl BorrowTree {
|
||||
Ok((new_nodes, old_nodes))
|
||||
}
|
||||
|
||||
fn node_deps(&self, nodes: &[NodeId]) -> Vec<EdgeHandle> {
|
||||
fn node_deps(&self, nodes: &[NodeId]) -> Vec<SourceHandle> {
|
||||
nodes.iter().map(|node| self.nodes.get(node).unwrap().0.duplicate()).collect()
|
||||
}
|
||||
|
||||
fn store_node(&mut self, node: EdgeHandle, id: NodeId, path: Path) {
|
||||
fn store_node(&mut self, node: SourceHandle, id: NodeId, path: Path) {
|
||||
self.nodes.insert(id, (node, path));
|
||||
}
|
||||
|
||||
/// Calls the `Node::serialize` for that specific node, returning for example the captured io record for a monitor node. The node path must match the document node path.
|
||||
/// Calls the `Node::serialize` for that specific node, returning for example the captured context snapshot for a monitor node. The node path must match the document node path.
|
||||
pub fn introspect(&self, node_path: &[NodeId]) -> Result<Arc<dyn std::any::Any + Send + Sync + 'static>, IntrospectError> {
|
||||
let (id, _) = self.source_map.get(node_path).ok_or_else(|| IntrospectError::PathNotFound(node_path.to_vec()))?;
|
||||
let (node, _path) = self.nodes.get(id).ok_or(IntrospectError::ProtoNodeNotFound(*id))?;
|
||||
node.serialize().ok_or(IntrospectError::NoData)
|
||||
}
|
||||
|
||||
pub fn get(&self, id: NodeId) -> Option<EdgeHandle> {
|
||||
pub fn get(&self, id: NodeId) -> Option<SourceHandle> {
|
||||
self.nodes.get(&id).map(|(node, _)| node.duplicate())
|
||||
}
|
||||
|
||||
/// The edge handle for the node at a document path.
|
||||
pub fn get_by_path(&self, node_path: &[NodeId]) -> Option<EdgeHandle> {
|
||||
pub fn get_by_path(&self, node_path: &[NodeId]) -> Option<SourceHandle> {
|
||||
let (id, _) = self.source_map.get(node_path)?;
|
||||
self.get(*id)
|
||||
}
|
||||
@@ -697,7 +711,7 @@ mod test {
|
||||
let scope = EvalScope::new(None, None, None, &generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
let frames = core_types::record::test_frames(layout.frame_bytes());
|
||||
let GPoll::Final(value) = core_types::record::serve_edge(&edge, &ctx, &frames) else {
|
||||
let GPoll::Final(value) = core_types::record::serve_input(&edge, &ctx, &frames) else {
|
||||
panic!("expected a final record");
|
||||
};
|
||||
assert_eq!(unsafe { core_types::record::read_element::<u32>(layout.rec(&value)) }, 2);
|
||||
@@ -705,7 +719,7 @@ mod test {
|
||||
|
||||
fn build_executor(mut network: ProtoNetwork) -> DynamicExecutor {
|
||||
network.resolve_types(&node_registry::NODE_REGISTRY).unwrap();
|
||||
network.compute_layouts();
|
||||
network.compute_layouts().unwrap();
|
||||
DynamicExecutor::new(network).unwrap()
|
||||
}
|
||||
|
||||
@@ -721,6 +735,193 @@ mod test {
|
||||
ProtoNode::value(ConstructionArgs::Value(TaggedValue::String(value.to_string()).into()), vec![])
|
||||
}
|
||||
|
||||
/// A record source, a constant name, and a value wired into the write node.
|
||||
fn write_attribute_network(name: &str, value: TaggedValue) -> ProtoNetwork {
|
||||
ProtoNetwork {
|
||||
stack_need: 0,
|
||||
inputs: vec![],
|
||||
output: NodeId(3),
|
||||
nodes: vec![
|
||||
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(7.).into()), vec![])),
|
||||
(NodeId(1), string_value(name)),
|
||||
(NodeId(2), ProtoNode::value(ConstructionArgs::Value(value.into()), vec![])),
|
||||
(NodeId(3), proto_node("graphic_nodes::graphic::WriteAttributeNode", vec![NodeId(0), NodeId(1), NodeId(2)])),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_constant_name_folds_into_the_written_layout() {
|
||||
let executor = build_executor(write_attribute_network("novel:count", TaggedValue::F64(2.5)));
|
||||
let arena = Arena::new(1 << 12).unwrap();
|
||||
let generations = [];
|
||||
let scope = EvalScope::new(None, None, None, &generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
let handle = executor.tree().get(NodeId(3)).unwrap();
|
||||
let layout = handle.layout().clone();
|
||||
let offset = layout.offset_of("novel:count", 0).expect("the folded name names a field of the output layout");
|
||||
let edge = handle.duplicate().downcast_record::<f64>().unwrap();
|
||||
let frames = core_types::record::test_frames(executor.tree().stack_need());
|
||||
let GPoll::Final(value) = core_types::record::serve_input(&edge, &ctx, &frames) else {
|
||||
panic!("expected a final record");
|
||||
};
|
||||
let rec = layout.rec(&value);
|
||||
assert_eq!(unsafe { rec.element::<f64>() }, 7., "the element passes through the write");
|
||||
assert_eq!(unsafe { rec.read::<f64>(offset) }, 2.5, "the value lands under the folded name");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_census_name_writes_at_its_declared_value_type() {
|
||||
let path = vec![NodeId(7), NodeId(8)];
|
||||
let executor = build_executor(write_attribute_network("editor:layer_path", TaggedValue::NodeIdPath(path.clone())));
|
||||
let arena = Arena::new(1 << 12).unwrap();
|
||||
let generations = [];
|
||||
let scope = EvalScope::new(None, None, None, &generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
let handle = executor.tree().get(NodeId(3)).unwrap();
|
||||
let layout = handle.layout().clone();
|
||||
let offset = layout.offset_of("editor:layer_path", 0).expect("a census name folds onto its census field");
|
||||
let edge = handle.duplicate().downcast_record::<f64>().unwrap();
|
||||
let frames = core_types::record::test_frames(executor.tree().stack_need());
|
||||
let GPoll::Final(value) = core_types::record::serve_input(&edge, &ctx, &frames) else {
|
||||
panic!("expected a final record");
|
||||
};
|
||||
assert_eq!(unsafe { layout.rec(&value).read::<&[NodeId]>(offset) }, path.as_slice());
|
||||
}
|
||||
|
||||
/// Reads `read_name` off a record that a write of `write_name` produced.
|
||||
fn read_attribute_network(write_name: &str, read_name: &str, value: TaggedValue) -> ProtoNetwork {
|
||||
read_attribute_network_over(TaggedValue::F64(7.), write_name, read_name, value)
|
||||
}
|
||||
|
||||
/// The same graph over any content element, which the read never looks at.
|
||||
fn read_attribute_network_over(content: TaggedValue, write_name: &str, read_name: &str, value: TaggedValue) -> ProtoNetwork {
|
||||
ProtoNetwork {
|
||||
stack_need: 0,
|
||||
inputs: vec![],
|
||||
output: NodeId(5),
|
||||
nodes: vec![
|
||||
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(content.into()), vec![])),
|
||||
(NodeId(1), string_value(write_name)),
|
||||
(NodeId(2), ProtoNode::value(ConstructionArgs::Value(value.into()), vec![])),
|
||||
(NodeId(3), proto_node("graphic_nodes::graphic::WriteAttributeNode", vec![NodeId(0), NodeId(1), NodeId(2)])),
|
||||
(NodeId(4), string_value(read_name)),
|
||||
(NodeId(5), proto_node("graphic_nodes::graphic::ReadNumberAttributeNode", vec![NodeId(3), NodeId(4)])),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
fn read_back(network: ProtoNetwork) -> f64 {
|
||||
let executor = build_executor(network);
|
||||
let arena = Arena::new(1 << 12).unwrap();
|
||||
let generations = [];
|
||||
let scope = EvalScope::new(None, None, None, &generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
let handle = executor.tree().get(NodeId(5)).unwrap();
|
||||
let layout = handle.layout().clone();
|
||||
let edge = handle.duplicate().downcast_record::<f64>().unwrap();
|
||||
let frames = core_types::record::test_frames(executor.tree().stack_need());
|
||||
let GPoll::Final(value) = core_types::record::serve_input(&edge, &ctx, &frames) else {
|
||||
panic!("expected a final record");
|
||||
};
|
||||
unsafe { core_types::record::read_element::<f64>(layout.rec(&value)) }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_named_read_serves_the_written_value() {
|
||||
assert_eq!(read_back(read_attribute_network("novel:count", "novel:count", TaggedValue::F64(2.5))), 2.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_absent_named_read_serves_the_forced_default() {
|
||||
// Nothing upstream writes `novel:absent`, so the read collapses to the
|
||||
// value type's default rather than reporting absence.
|
||||
assert_eq!(read_back(read_attribute_network("novel:count", "novel:absent", TaggedValue::F64(2.5))), 0.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_read_node_serves_every_content_element() {
|
||||
// The read never looks at the element, so one registry row covers any
|
||||
// upstream record wire rather than a row per element type.
|
||||
assert_eq!(read_back(read_attribute_network_over(TaggedValue::F64(7.), "novel:count", "novel:count", TaggedValue::F64(2.5))), 2.5);
|
||||
assert_eq!(
|
||||
read_back(read_attribute_network_over(TaggedValue::Bool(true), "novel:count", "novel:count", TaggedValue::F64(2.5))),
|
||||
2.5
|
||||
);
|
||||
assert_eq!(
|
||||
read_back(read_attribute_network_over(TaggedValue::DVec2(glam::DVec2::ONE), "novel:count", "novel:count", TaggedValue::F64(2.5))),
|
||||
2.5
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_census_named_read_round_trips_its_written_value() {
|
||||
// A declared name folds onto its census field, so the read resolves
|
||||
// against the same offset the write installed.
|
||||
assert_eq!(read_back(read_attribute_network("opacity", "opacity", TaggedValue::F64(0.5))), 0.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_absent_census_named_read_serves_the_census_default() {
|
||||
// `opacity` is declared `f64` defaulting to 1, so its absence reads as
|
||||
// the census default rather than the value type's.
|
||||
assert_eq!(read_back(read_attribute_network("novel:count", "opacity", TaggedValue::F64(2.5))), 1.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_named_read_disagreeing_with_its_write_is_refused() {
|
||||
// The name is written at a path upstream and read at `f64` here, which
|
||||
// is the one-name-one-type rule spanning a write and a read.
|
||||
let mut network = read_attribute_network("novel:count", "novel:count", TaggedValue::NodeIdPath(vec![NodeId(1)]));
|
||||
network.resolve_types(&node_registry::NODE_REGISTRY).unwrap();
|
||||
let errors = network.compute_layouts().expect_err("a name at two value types must be refused");
|
||||
assert!(
|
||||
errors.iter().any(|error| format!("{:?}", error.error).contains("one name carries one value type")),
|
||||
"the refusal names the one-name-one-type rule, got {errors:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_runtime_attribute_name_is_refused_when_the_graph_compiles() {
|
||||
// The outer node's name comes off another node rather than sitting on
|
||||
// the wire as text. It still types as a string, so only the fold can
|
||||
// reject it, which is the case the design rules out entirely.
|
||||
let mut network = ProtoNetwork {
|
||||
stack_need: 0,
|
||||
inputs: vec![],
|
||||
output: NodeId(6),
|
||||
nodes: vec![
|
||||
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(7.).into()), vec![])),
|
||||
(NodeId(1), string_value("novel:count")),
|
||||
(NodeId(2), string_value("inner:name")),
|
||||
(NodeId(3), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(1.).into()), vec![])),
|
||||
// Carries a string element, so its output types as a name.
|
||||
(NodeId(4), proto_node("graphic_nodes::graphic::WriteAttributeNode", vec![NodeId(1), NodeId(2), NodeId(3)])),
|
||||
(NodeId(5), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(2.5).into()), vec![])),
|
||||
(NodeId(6), proto_node("graphic_nodes::graphic::WriteAttributeNode", vec![NodeId(0), NodeId(4), NodeId(5)])),
|
||||
],
|
||||
};
|
||||
network.resolve_types(&node_registry::NODE_REGISTRY).unwrap();
|
||||
let errors = network.compute_layouts().expect_err("a non-constant name must be refused");
|
||||
assert!(
|
||||
errors.iter().any(|error| format!("{:?}", error.error).contains("must be a constant")),
|
||||
"the refusal names the constant requirement, got {errors:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_name_carries_one_value_type() {
|
||||
// `opacity` is declared `f64` in the census, so writing a path there is
|
||||
// a graph error rather than a second field of the same name.
|
||||
let mut network = write_attribute_network("opacity", TaggedValue::NodeIdPath(vec![NodeId(1)]));
|
||||
network.resolve_types(&node_registry::NODE_REGISTRY).unwrap();
|
||||
let errors = network.compute_layouts().expect_err("a name at two value types must be refused");
|
||||
assert!(
|
||||
errors.iter().any(|error| format!("{:?}", error.error).contains("one name carries one value type")),
|
||||
"the refusal names the one-name-one-type rule, got {errors:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_clone_node_clones_the_element_out_of_its_record_wire() {
|
||||
let network = ProtoNetwork {
|
||||
@@ -742,7 +943,7 @@ mod test {
|
||||
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 {
|
||||
let GPoll::Final(value) = core_types::record::serve_input(&edge, &ctx, &frames) else {
|
||||
panic!("the flipped clone must evaluate over record wires, got a non-final poll");
|
||||
};
|
||||
assert_eq!(unsafe { core_types::record::read_element::<f64>(layout.rec(&value)) }, 7.);
|
||||
@@ -769,7 +970,7 @@ mod test {
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
let edge = executor.tree().get(NodeId(2)).unwrap().downcast_record::<graphene_std::raster::color::Color>().unwrap();
|
||||
let frames = core_types::record::test_frames(executor.tree().stack_need());
|
||||
let result = core_types::record::serve_edge(&edge, &ctx, &frames);
|
||||
let result = core_types::record::serve_input(&edge, &ctx, &frames);
|
||||
// The empty raster level folds to an empty palette: past-end at lane 0.
|
||||
assert!(
|
||||
matches!(&result, GPoll::Error(error) if error.kind == core_types::gpoll::ErrorKind::PastEnd),
|
||||
@@ -788,7 +989,7 @@ mod test {
|
||||
|
||||
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_eq!(value.ty(), &core_types::registry::record_source_type::<f64>());
|
||||
assert_eq!(value.layout().depth, 0);
|
||||
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::F64(7.)));
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ use graphene_std::raster::GPU;
|
||||
#[cfg(feature = "gpu")]
|
||||
use graphene_std::SourceId;
|
||||
use graphene_std::raster::{CPU, Raster};
|
||||
use graphene_std::registry::{ConstructionError, EdgeHandle, NodeIOTypes, RegistryEntry};
|
||||
use graphene_std::registry::{ConstructionError, NodeIOTypes, RegistryEntry, SourceHandle};
|
||||
#[cfg(feature = "gpu")]
|
||||
use graphene_std::runtime::RuntimeHandle;
|
||||
|
||||
@@ -128,7 +128,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>> {
|
||||
.into_iter()
|
||||
.map(|entry| (graphene_std::graphic::to_graphic::IDENTIFIER.clone(), entry)),
|
||||
);
|
||||
// The transitional level bridge: a leveled wire materializes into the legacy
|
||||
// The transitional level bridge: a leveled input 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(
|
||||
@@ -217,7 +217,7 @@ mod node_registry_macros {
|
||||
io: NodeIOTypes::new(
|
||||
concrete!(Context),
|
||||
core_types::registry::record_type::<$to>(),
|
||||
vec![core_types::registry::record_edge_type::<$from>()],
|
||||
vec![core_types::registry::record_source_type::<$from>()],
|
||||
),
|
||||
constructor: |inputs| {
|
||||
if inputs.len() != 1 {
|
||||
@@ -227,7 +227,9 @@ mod node_registry_macros {
|
||||
let handle = inputs.next().unwrap();
|
||||
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>))
|
||||
Ok(SourceHandle::new_record::<$to>(
|
||||
std::sync::Arc::new(node) as std::sync::Arc<core_types::registry::ErasedRecordNode>
|
||||
))
|
||||
},
|
||||
},
|
||||
)
|
||||
@@ -284,10 +286,10 @@ mod node_registry_macros {
|
||||
concrete!(Context),
|
||||
core_types::registry::record_type::<$to>(),
|
||||
vec![
|
||||
core_types::registry::record_edge_type::<$from>(),
|
||||
core_types::registry::record_edge_type::<$convert>(),
|
||||
core_types::registry::record_edge_type::<RuntimeHandle>(),
|
||||
core_types::registry::record_edge_type::<SourceId>(),
|
||||
core_types::registry::record_source_type::<$from>(),
|
||||
core_types::registry::record_source_type::<$convert>(),
|
||||
core_types::registry::record_source_type::<RuntimeHandle>(),
|
||||
core_types::registry::record_source_type::<SourceId>(),
|
||||
],
|
||||
),
|
||||
constructor: |inputs| {
|
||||
@@ -314,7 +316,7 @@ mod node_registry_macros {
|
||||
&runtime_layout,
|
||||
&source_layout,
|
||||
);
|
||||
Ok(EdgeHandle::new_record::<$to>(std::sync::Arc::new(node) as std::sync::Arc<core_types::registry::ErasedRecordNode>))
|
||||
Ok(SourceHandle::new_record::<$to>(std::sync::Arc::new(node) as std::sync::Arc<core_types::registry::ErasedRecordNode>))
|
||||
},
|
||||
},
|
||||
)
|
||||
@@ -327,7 +329,7 @@ mod node_registry_macros {
|
||||
io: NodeIOTypes::new(
|
||||
concrete!(Context),
|
||||
core_types::registry::record_type::<$to>(),
|
||||
vec![core_types::registry::record_edge_type::<$from>(), core_types::registry::record_edge_type::<$convert>()],
|
||||
vec![core_types::registry::record_source_type::<$from>(), core_types::registry::record_source_type::<$convert>()],
|
||||
),
|
||||
constructor: |inputs| {
|
||||
if inputs.len() != 2 {
|
||||
@@ -344,7 +346,7 @@ mod node_registry_macros {
|
||||
&value_layout,
|
||||
&converter_layout,
|
||||
);
|
||||
Ok(EdgeHandle::new_record::<$to>(std::sync::Arc::new(node) as std::sync::Arc<core_types::registry::ErasedRecordNode>))
|
||||
Ok(SourceHandle::new_record::<$to>(std::sync::Arc::new(node) as std::sync::Arc<core_types::registry::ErasedRecordNode>))
|
||||
},
|
||||
},
|
||||
)
|
||||
@@ -367,7 +369,7 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// One wire kind: every row consumes and produces record wires. A plain
|
||||
/// One input kind: every row consumes and produces records. A plain
|
||||
/// io type here would need a bridge adapter, and those are gone.
|
||||
#[test]
|
||||
fn every_registry_row_is_record_typed() {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use std::any::TypeId;
|
||||
use std::cell::UnsafeCell;
|
||||
use std::collections::HashMap;
|
||||
use std::marker::PhantomData;
|
||||
@@ -26,11 +27,12 @@ pub struct Arena {
|
||||
/// 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)>>,
|
||||
/// the header's address in the receiving arena, the moved type's key and
|
||||
/// that arena's generation, so a payload two records share is moved once
|
||||
/// while a mistyped sharer, a sharer naming another destination, and a
|
||||
/// sharer whose destination has since flushed are all refused. Cleared by
|
||||
/// [`Arena::reset`], so a forwarding holds for one generation.
|
||||
forwarded: Mutex<HashMap<usize, (usize, TypeId, u64)>>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Arena {
|
||||
@@ -41,9 +43,9 @@ 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,
|
||||
/// The parked payload's static-type key, `None` where the park was
|
||||
/// allocated without one and so never moves.
|
||||
type_of: Option<TypeId>,
|
||||
drop_fn: unsafe fn(*mut u8),
|
||||
/// The park glue's estimate of the heap this payload owns, 0 where the
|
||||
/// glue cannot measure it, so the counter is a lower bound.
|
||||
@@ -52,6 +54,9 @@ struct DropEntry {
|
||||
|
||||
/// The glue a tombstoned entry carries: its payload was moved to another arena,
|
||||
/// which now owns the obligation.
|
||||
///
|
||||
/// # Safety
|
||||
/// None: the payload is neither read nor dropped, so any pointer is accepted.
|
||||
unsafe fn inert(_: *mut u8) {}
|
||||
|
||||
/// The entry parking `offset`, `None` where the arena holds no obligation for
|
||||
@@ -195,7 +200,7 @@ impl Arena {
|
||||
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 {
|
||||
} else if count.is_multiple_of(20000) {
|
||||
eprintln!("arena> {count} allocations, offset {}, this {size} bytes", self.offset.load(Ordering::Relaxed));
|
||||
}
|
||||
}
|
||||
@@ -214,18 +219,44 @@ impl Arena {
|
||||
/// [`Arena::alloc`] with the park glue's estimate of the heap `value` owns,
|
||||
/// which the region's own occupancy cannot see.
|
||||
pub fn alloc_sized<T: Send + Sync>(&self, value: T, retained: usize) -> Option<(&T, ArenaWeak<T>)> {
|
||||
self.alloc_stamped(value, retained, None)
|
||||
}
|
||||
|
||||
/// [`Arena::alloc_sized`] stamping the park's static-type key, which is what
|
||||
/// [`Arena::move_park`] matches on, so only a park allocated here can move.
|
||||
pub fn alloc_sized_keyed<T: Send + Sync + dyn_any::StaticTypeSized>(&self, value: T, retained: usize) -> Option<(&T, ArenaWeak<T>)> {
|
||||
self.alloc_stamped(value, retained, Some(TypeId::of::<T::Static>()))
|
||||
}
|
||||
|
||||
/// [`Arena::alloc_sized_keyed`] for park glue already holding the element's
|
||||
/// static form, which projects the key from the element type instead of
|
||||
/// from the value's own. Crate-private: a wrong key mistypes a move.
|
||||
pub(crate) fn alloc_sized_as<T: Send + Sync>(&self, value: T, retained: usize, type_of: TypeId) -> Option<(&T, ArenaWeak<T>)> {
|
||||
self.alloc_stamped(value, retained, Some(type_of))
|
||||
}
|
||||
|
||||
fn alloc_stamped<T: Send + Sync>(&self, value: T, retained: usize, type_of: Option<TypeId>) -> Option<(&T, ArenaWeak<T>)> {
|
||||
let offset = self.reserve(size_of::<T>(), align_of::<T>())?;
|
||||
// Built before the write so an unencodable offset drops `value` here
|
||||
// rather than stranding it in the arena without drop glue.
|
||||
let weak = ArenaWeak::new(self.generation(), offset)?;
|
||||
// SAFETY: `reserve` returned `offset`, so it is within the backbone.
|
||||
let ptr = unsafe { self.base().add(offset) }.cast::<T>();
|
||||
// SAFETY: freshly reserved, aligned, in-bounds, unaliased.
|
||||
unsafe { ptr.write(value) };
|
||||
if std::mem::needs_drop::<T>() {
|
||||
/// # Safety
|
||||
/// `p` must address the live `T` this entry was registered for.
|
||||
unsafe fn glue<T>(p: *mut u8) {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { p.cast::<T>().drop_in_place() }
|
||||
}
|
||||
self.drops.lock().unwrap().push(DropEntry { offset, size: size_of::<T>(), drop_fn: glue::<T>, retained });
|
||||
self.drops.lock().unwrap().push(DropEntry {
|
||||
offset,
|
||||
type_of,
|
||||
drop_fn: glue::<T>,
|
||||
retained,
|
||||
});
|
||||
self.retained_heap.fetch_add(retained, Ordering::Relaxed);
|
||||
}
|
||||
// SAFETY: initialized above; insert-only, so no `&mut` to it can exist.
|
||||
@@ -246,51 +277,71 @@ impl Arena {
|
||||
/// fan-out sharer's second move reaches the one header and the obligation
|
||||
/// is never duplicated.
|
||||
///
|
||||
/// A forwarding is to one destination generation, since the returned
|
||||
/// pointer is only the caller's to publish where it lands in the `dst` it
|
||||
/// named: a second move to another arena, or to one that has flushed since,
|
||||
/// is refused rather than answered with a foreign or freed header. The
|
||||
/// refusal reads as a decline, so the caller takes its clone path.
|
||||
///
|
||||
/// `dst` is credited `retained`, which is what a clone of the payload would
|
||||
/// have credited it, and this arena is debited what its own park recorded,
|
||||
/// so neither counter reads worse than it did before the move.
|
||||
///
|
||||
/// `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.
|
||||
/// The move republishes the payload at `T::Static`, which is the key both
|
||||
/// [`Arena::alloc_sized_keyed`] and this stamp, so a park and its move
|
||||
/// project the type exactly once each and agree by construction.
|
||||
///
|
||||
/// `None` where `src` is not this arena's park keyed to `T::Static`, where
|
||||
/// the type is zero-sized (whose parks share an offset and so cannot be
|
||||
/// told apart), or where `dst` refused the header.
|
||||
///
|
||||
/// # Safety
|
||||
/// `src` must address a live `T`, and 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(())?;
|
||||
/// `src` must address a live `T`, and `T` must own all of its content: the
|
||||
/// moved header may reference no storage of this arena, which is also what
|
||||
/// lets the payload be republished at `T::Static`. The key settles the
|
||||
/// type, so the caller owes no size or identity argument beyond those two.
|
||||
pub unsafe fn move_park<T: dyn_any::StaticTypeSized>(&self, src: *const u8, dst: &Arena, retained: usize) -> Option<*const T::Static>
|
||||
where
|
||||
T::Static: Send + Sync,
|
||||
{
|
||||
(size_of::<T::Static>() != 0).then_some(())?;
|
||||
let offset = (src as usize).checked_sub(self.base() as usize)?;
|
||||
(offset < self.buf.len()).then_some(())?;
|
||||
let type_of = TypeId::of::<T::Static>();
|
||||
let mut forwarded = self.forwarded.lock().unwrap();
|
||||
if let Some(&(moved, size)) = forwarded.get(&offset) {
|
||||
(size == size_of::<T>()).then_some(())?;
|
||||
return Some(moved as *const T);
|
||||
if let Some(&(moved, moved_type, moved_generation)) = forwarded.get(&offset) {
|
||||
(moved_type == type_of).then_some(())?;
|
||||
// Generations are globally unique, so the match is `dst` itself and
|
||||
// its current epoch; anything else declines.
|
||||
(moved_generation == dst.generation()).then_some(())?;
|
||||
return Some(moved as *const T::Static);
|
||||
}
|
||||
let mut entries = self.drops.lock().unwrap();
|
||||
let entry = entry_at(&entries, offset)?;
|
||||
(entries[entry].size == size_of::<T>()).then_some(())?;
|
||||
let slot = dst.alloc_scratch::<T>(1)?;
|
||||
let target = slot.as_mut_ptr().cast::<T>();
|
||||
(entries[entry].type_of == Some(type_of)).then_some(())?;
|
||||
let slot = dst.alloc_scratch::<T::Static>(1)?;
|
||||
let target = slot.as_mut_ptr().cast::<T::Static>();
|
||||
// SAFETY: the caller's contract on `src`, into a freshly reserved,
|
||||
// aligned, unaliased slot of the same type.
|
||||
unsafe { std::ptr::copy_nonoverlapping(src.cast::<T>(), target, 1) };
|
||||
unsafe { std::ptr::copy_nonoverlapping(src.cast::<T::Static>(), target, 1) };
|
||||
let parked = std::mem::replace(&mut entries[entry].retained, 0);
|
||||
entries[entry].drop_fn = inert;
|
||||
drop(entries);
|
||||
/// # Safety
|
||||
/// `p` must address the live `T` this entry was registered for.
|
||||
unsafe fn glue<T>(p: *mut u8) {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { p.cast::<T>().drop_in_place() }
|
||||
}
|
||||
dst.drops.lock().unwrap().push(DropEntry {
|
||||
offset: target as usize - dst.base() as usize,
|
||||
size: size_of::<T>(),
|
||||
drop_fn: glue::<T>,
|
||||
type_of: Some(type_of),
|
||||
drop_fn: glue::<T::Static>,
|
||||
retained,
|
||||
});
|
||||
dst.retained_heap.fetch_add(retained, Ordering::Relaxed);
|
||||
let _ = self.retained_heap.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| Some(current.saturating_sub(parked)));
|
||||
forwarded.insert(offset, (target as usize, size_of::<T>()));
|
||||
forwarded.insert(offset, (target as usize, type_of, dst.generation()));
|
||||
Some(target.cast_const())
|
||||
}
|
||||
|
||||
@@ -309,6 +360,7 @@ impl Arena {
|
||||
pub fn alloc_scratch<T: Send + Sync>(&self, len: usize) -> Option<&mut [MaybeUninit<T>]> {
|
||||
let size = size_of::<T>().checked_mul(len)?;
|
||||
let offset = self.reserve(size, align_of::<T>())?;
|
||||
// SAFETY: `reserve` returned `offset`, so it is within the backbone.
|
||||
let ptr = unsafe { self.base().add(offset) }.cast::<MaybeUninit<T>>();
|
||||
// SAFETY: exclusive region; lifetime tied to `&self`, and `reset` takes
|
||||
// `&mut self`, so the slice cannot outlive the generation.
|
||||
@@ -318,9 +370,13 @@ impl Arena {
|
||||
/// The generation-checked handle for a region this arena holds, `None` for
|
||||
/// a pointer from anywhere else. The handle keeps the region's provenance,
|
||||
/// so a cache stores one where it would otherwise launder an address.
|
||||
///
|
||||
/// The offset must sit below the bump watermark, not merely inside the
|
||||
/// backbone: [`ArenaWeak::upgrade`] hands out a `&T` at it, so only bytes a
|
||||
/// reservation already handed out may be minted into a handle.
|
||||
pub fn handle_at(&self, ptr: *const u8) -> Option<ArenaWeak<u8>> {
|
||||
let offset = (ptr as usize).checked_sub(self.base() as usize)?;
|
||||
(offset < self.buf.len()).then_some(())?;
|
||||
(offset < self.offset.load(Ordering::Acquire)).then_some(())?;
|
||||
ArenaWeak::new(self.generation(), offset)
|
||||
}
|
||||
|
||||
@@ -336,13 +392,14 @@ impl Arena {
|
||||
self.forwarded.get_mut().unwrap().clear();
|
||||
self.generation.store(PARKED_GENERATION, Ordering::Release);
|
||||
for entry in entries.into_iter().rev() {
|
||||
// Debited before the glue runs: a panicking destructor drops the
|
||||
// remaining entries unglued, so a hint subtracted afterwards would
|
||||
// strand on the counter for the arena's whole life.
|
||||
let retained = self.retained_heap.get_mut();
|
||||
*retained = retained.saturating_sub(entry.retained);
|
||||
// SAFETY: registered at alloc time; insert-only means the region was
|
||||
// never overwritten within this generation.
|
||||
unsafe { (entry.drop_fn)(base.add(entry.offset)) }
|
||||
// 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;
|
||||
@@ -524,6 +581,57 @@ mod tests {
|
||||
assert!(cell.load(&arena).is_none(), "a half-dropped generation must resolve no handle");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handles_mint_only_over_reserved_bytes() {
|
||||
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let (value, _) = arena.alloc(41u32).unwrap();
|
||||
let ptr = std::ptr::from_ref(value).cast::<u8>();
|
||||
assert!(arena.handle_at(ptr).is_some(), "a byte the bump handed out mints a handle");
|
||||
|
||||
let unreserved = ptr.wrapping_add(64);
|
||||
assert!(arena.contains(unreserved), "the fixture stays inside the backbone");
|
||||
assert!(arena.handle_at(unreserved).is_none(), "a byte past the watermark mints nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_forwarding_answers_only_the_destination_it_recorded() {
|
||||
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
struct Probe(#[allow(dead_code)] String);
|
||||
unsafe impl dyn_any::StaticType for Probe {
|
||||
type Static = Probe;
|
||||
}
|
||||
let transient = Arena::new(1024).unwrap();
|
||||
let mut first = Arena::new(1024).unwrap();
|
||||
let second = Arena::new(1024).unwrap();
|
||||
|
||||
let (parked, _) = transient.alloc_sized_keyed(Probe(String::from("shared by two records")), 21).unwrap();
|
||||
let src = std::ptr::from_ref(parked).cast::<u8>();
|
||||
unsafe { transient.move_park::<Probe>(src, &first, 21) }.unwrap();
|
||||
|
||||
assert!(unsafe { transient.move_park::<Probe>(src, &second, 21) }.is_none(), "a sharer naming another destination is refused");
|
||||
first.reset();
|
||||
assert!(unsafe { transient.move_park::<Probe>(src, &first, 21) }.is_none(), "a flushed destination is refused too");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_panicking_destructor_does_not_strand_the_retained_hint() {
|
||||
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
struct Bomb;
|
||||
impl Drop for Bomb {
|
||||
fn drop(&mut self) {
|
||||
panic!("payload destructor");
|
||||
}
|
||||
}
|
||||
let mut arena = Arena::new(1024).unwrap();
|
||||
arena.alloc_sized(Bomb, 64).unwrap();
|
||||
assert_eq!(arena.retained_heap(), 64);
|
||||
|
||||
let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| arena.reset()));
|
||||
assert!(unwound.is_err(), "the panic must propagate out of reset");
|
||||
assert_eq!(arena.retained_heap(), 0, "the hint is debited before the glue that panics");
|
||||
}
|
||||
|
||||
/// Held by every test that perturbs [`NEXT_GENERATION`], so a swapped-out counter
|
||||
/// is never observed by a concurrently constructing test.
|
||||
static COUNTER_GUARD: Mutex<()> = Mutex::new(());
|
||||
@@ -607,7 +715,7 @@ mod tests {
|
||||
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 (parked, _) = transient.alloc_sized_keyed(owned, length).unwrap();
|
||||
let src = std::ptr::from_ref(parked).cast::<u8>();
|
||||
|
||||
let moved = unsafe { transient.move_park::<String>(src, &persistent, length) }.unwrap();
|
||||
@@ -627,6 +735,9 @@ mod tests {
|
||||
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
static DROPS: AtomicU32 = AtomicU32::new(0);
|
||||
struct Probe(#[allow(dead_code)] String);
|
||||
unsafe impl dyn_any::StaticType for Probe {
|
||||
type Static = Probe;
|
||||
}
|
||||
impl Drop for Probe {
|
||||
fn drop(&mut self) {
|
||||
DROPS.fetch_add(1, Ordering::Relaxed);
|
||||
@@ -636,7 +747,7 @@ mod tests {
|
||||
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 (parked, _) = transient.alloc_sized_keyed(Probe(String::from("shared by two records")), 21).unwrap();
|
||||
let src = std::ptr::from_ref(parked).cast::<u8>();
|
||||
let first = unsafe { transient.move_park::<Probe>(src, &persistent, 21) }.unwrap();
|
||||
let second = unsafe { transient.move_park::<Probe>(src, &persistent, 21) }.unwrap();
|
||||
@@ -652,18 +763,30 @@ mod tests {
|
||||
#[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,
|
||||
struct Owner(#[allow(dead_code)] String);
|
||||
unsafe impl dyn_any::StaticType for Owner {
|
||||
type Static = Owner;
|
||||
}
|
||||
/// Owner's layout exactly, so only the type key tells the two apart.
|
||||
struct Twin(#[allow(dead_code)] String);
|
||||
unsafe impl dyn_any::StaticType for Twin {
|
||||
type Static = Twin;
|
||||
}
|
||||
let mut transient = Arena::new(1024).unwrap();
|
||||
let mut persistent = Arena::new(1024).unwrap();
|
||||
|
||||
let (parked, _) = transient.alloc(Owner { _first: String::from("a first member"), _tail: 0 }).unwrap();
|
||||
let (parked, _) = transient.alloc_sized_keyed(Owner(String::from("a keyed park")), 0).unwrap();
|
||||
let src = std::ptr::from_ref(parked).cast::<u8>();
|
||||
assert!(unsafe { transient.move_park::<String>(src, &persistent, 0) }.is_none(), "a park of another size is refused");
|
||||
assert!(
|
||||
unsafe { transient.move_park::<Twin>(src, &persistent, 0) }.is_none(),
|
||||
"a park of another type of the same size is refused"
|
||||
);
|
||||
unsafe { transient.move_park::<Owner>(src, &persistent, 0) }.unwrap();
|
||||
assert!(unsafe { transient.move_park::<String>(src, &persistent, 0) }.is_none(), "the forwarding refuses the same mistype");
|
||||
assert!(unsafe { transient.move_park::<Twin>(src, &persistent, 0) }.is_none(), "the forwarding refuses the same mistype");
|
||||
|
||||
let (unkeyed, _) = transient.alloc(Owner(String::from("an unkeyed park"))).unwrap();
|
||||
let src = std::ptr::from_ref(unkeyed).cast::<u8>();
|
||||
assert!(unsafe { transient.move_park::<Owner>(src, &persistent, 0) }.is_none(), "a park allocated without a key never moves");
|
||||
|
||||
transient.reset();
|
||||
persistent.reset();
|
||||
@@ -674,6 +797,9 @@ mod tests {
|
||||
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
static DROPS: AtomicU32 = AtomicU32::new(0);
|
||||
struct Probe(#[allow(dead_code)] String);
|
||||
unsafe impl dyn_any::StaticType for Probe {
|
||||
type Static = Probe;
|
||||
}
|
||||
impl Drop for Probe {
|
||||
fn drop(&mut self) {
|
||||
DROPS.fetch_add(1, Ordering::Relaxed);
|
||||
@@ -683,7 +809,7 @@ mod tests {
|
||||
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 (parked, _) = transient.alloc_sized_keyed(Probe(String::from("first generation")), 16).unwrap();
|
||||
let src = std::ptr::from_ref(parked).cast::<u8>();
|
||||
unsafe { transient.move_park::<Probe>(src, &persistent, 16) }.unwrap();
|
||||
assert_eq!(transient.forwarded.lock().unwrap().len(), 1, "the move tombstoned the entry it left");
|
||||
|
||||
@@ -20,15 +20,35 @@ use std::sync::{LazyLock, Mutex};
|
||||
|
||||
/// Declares an attribute name: one marker per name, fixing the value type and
|
||||
/// the name-specific default. Declare markers through the [`attribute!`]
|
||||
/// macro, which also registers them into the [`ATTRIBUTE_REGISTRY`].
|
||||
pub trait Attribute: 'static {
|
||||
/// macro, which also registers them into the [`ATTRIBUTE_REGISTRY`] and emits
|
||||
/// an impl meeting the obligations below.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// [`REPARK`](Self::REPARK) must be `Some` for every marker whose
|
||||
/// [`Value<'e>`](Self::Value) can carry a borrow shorter than `'static`. The
|
||||
/// plain-value arm of the census writer retypes the value [`from_stored`] hands
|
||||
/// it from the stored form's lifetime to the field's, which is only a relabel
|
||||
/// where the value borrows nothing; a re-parking marker instead writes a
|
||||
/// reference into the arena it is given.
|
||||
///
|
||||
/// [`from_stored`](Self::from_stored) must accept exactly the erased form
|
||||
/// [`read_erased`](Self::read_erased) produces, and [`read_erased`] must read
|
||||
/// its `ptr` as this marker's own `Value`. The two are each other's inverse
|
||||
/// across every persistence seam, so a marker that reads one type and stores
|
||||
/// another writes a value of the wrong type into the field.
|
||||
pub unsafe trait Attribute: 'static {
|
||||
/// The name as it appears in documents and diagnostics.
|
||||
const NAME: &'static str;
|
||||
/// The value type every read and write of this name shares. The lifetime
|
||||
/// is the evaluation the value flows in; non-reference values ignore it.
|
||||
/// The value outlives that evaluation, so its `'static` instantiation is
|
||||
/// the one the census registers and layouts stamp their type id from.
|
||||
type Value<'e>: Copy + Default + std::fmt::Debug + 'e;
|
||||
///
|
||||
/// `Send + Sync` because a record's bytes are these values: `RecordValue`
|
||||
/// is `Send + Sync` over whatever the field writes put there, and the write
|
||||
/// path never consults the census, so the bound has to sit here.
|
||||
type Value<'e>: Copy + Default + std::fmt::Debug + Send + Sync + 'e;
|
||||
/// The name-specific default, filled where an item lacks the attribute.
|
||||
/// Producing a value for any `'e` from no inputs, reference defaults can
|
||||
/// only point at `'static` data, which is what lets the census fill them
|
||||
@@ -48,7 +68,7 @@ pub trait Attribute: 'static {
|
||||
|
||||
/// Re-parks the owned clone [`Self::read_erased`] produced into fresh
|
||||
/// field storage; `None` for plain values, which ride the byte copy.
|
||||
const REPARK: Option<unsafe fn(&dyn AnyAttributeValue, *mut u8, &crate::arena::Arena) -> Option<()>> = None;
|
||||
const REPARK: Option<crate::list::ReparkFn> = None;
|
||||
}
|
||||
|
||||
/// A kernel-facing attribute value. A parameter `Attr<A>` is a read of `A`
|
||||
@@ -79,6 +99,45 @@ impl<'e, A: Attribute> std::fmt::Debug for Attr<'e, A> {
|
||||
}
|
||||
}
|
||||
|
||||
/// An attribute write that outlives the evaluation producing it: an async
|
||||
/// source's slot persists across generations, so a reference value cannot
|
||||
/// cross as itself. The value crosses deep-copied through the field glue and
|
||||
/// parks into the serving arena at every lift, which is why the copy is paid
|
||||
/// once per invocation rather than once per evaluation.
|
||||
pub struct OwnedAttr<A: Attribute>(Box<dyn AnyAttributeValue>, PhantomData<fn() -> A>);
|
||||
|
||||
impl<A: Attribute> OwnedAttr<A> {
|
||||
/// Deep-copies `value` out of the evaluation that produced it.
|
||||
pub fn new(value: A::Value<'_>) -> Self {
|
||||
// SAFETY: the read addresses a live local of the marker's value type.
|
||||
let erased = unsafe { A::read_erased((&raw const value).cast()) };
|
||||
OwnedAttr(crate::record::deepen_field_value(erased), PhantomData)
|
||||
}
|
||||
|
||||
/// Parks the copy into `arena` for one evaluation; `None` reports arena
|
||||
/// exhaustion.
|
||||
pub fn park<'e>(&self, arena: &'e crate::arena::Arena) -> Option<A::Value<'e>> {
|
||||
let resident = crate::record::replay_field_value(&*self.0, arena)?;
|
||||
let mut value = A::default();
|
||||
// SAFETY: the slot is a live field of the marker's value type, and the
|
||||
// stored value is the copy `new` took at that same type.
|
||||
unsafe { write_stored::<A>(resident.as_deref().unwrap_or(&*self.0), (&raw mut value).cast(), arena) }?;
|
||||
Some(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl<A: Attribute> Clone for OwnedAttr<A> {
|
||||
fn clone(&self) -> Self {
|
||||
OwnedAttr(self.0.clone(), PhantomData)
|
||||
}
|
||||
}
|
||||
|
||||
impl<A: Attribute> std::fmt::Debug for OwnedAttr<A> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_tuple(A::NAME).field(&self.0.display_string()).finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// A deletion of `A` in a node's return tuple: the name leaves the output
|
||||
/// layout, so downstream reads yield the declared default again. Functionally
|
||||
/// a write of the default; the value carries nothing.
|
||||
@@ -96,6 +155,278 @@ impl<A: Attribute> Default for RemoveAttr<A> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The value-type half of an attribute: everything [`Attribute`] declares
|
||||
/// except the name and its name-specific default. A name-generic write pairs
|
||||
/// one of these with a name taken from the graph, so the value type stays
|
||||
/// concrete in the signature while the name varies per instance.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// The obligations are [`Attribute`]'s, at this trait's value type:
|
||||
/// [`REPARK`](Self::REPARK) must be `Some` for every row whose
|
||||
/// [`Value<'e>`](Self::Value) can carry a borrow shorter than `'static`, and
|
||||
/// [`from_stored`](Self::from_stored) and [`read_erased`](Self::read_erased)
|
||||
/// must be each other's inverse.
|
||||
pub unsafe trait AttrValue: 'static {
|
||||
/// The value type every write of this row shares, as [`Attribute::Value`].
|
||||
type Value<'e>: Copy + Default + std::fmt::Debug + Send + Sync + 'e;
|
||||
|
||||
/// Borrows the value out of legacy list storage, as [`Attribute::from_stored`].
|
||||
fn from_stored<'a>(stored: &'a dyn std::any::Any) -> Option<Self::Value<'a>>;
|
||||
|
||||
/// # Safety
|
||||
/// `ptr` must point at a live field of this row's value type.
|
||||
unsafe fn read_erased(ptr: *const u8) -> Box<dyn AnyAttributeValue>;
|
||||
|
||||
/// Re-parks an owned clone into fresh field storage, as [`Attribute::REPARK`].
|
||||
const REPARK: Option<crate::list::ReparkFn> = None;
|
||||
}
|
||||
|
||||
/// The [`Attribute::NAME`] a [`Named`] marker carries before the compiler
|
||||
/// fills it. A layout never holds it: the fold replaces it with the
|
||||
/// instance's constant, and a node whose name input is not constant is
|
||||
/// refused at that same point.
|
||||
pub const NAMED_PLACEHOLDER: &str = "";
|
||||
|
||||
/// A name-generic attribute write. `X` is a placeholder that distinguishes
|
||||
/// name-generic attributes within one signature, so a node writing two of
|
||||
/// them takes two names; `V` fixes the value type. The name is absent by
|
||||
/// construction: it comes from the instance's constant text input, folded
|
||||
/// into the layout at graph compile time, so a computed name cannot exist.
|
||||
///
|
||||
/// Written `Named<X>` in parameter position, it declares where `X`'s name is
|
||||
/// wired: the macro gives that input constant text, and the kernel receives
|
||||
/// only the placeholder, since a folded name is a layout fact rather than a
|
||||
/// value the kernel needs.
|
||||
pub struct Named<X, V = Text>(PhantomData<fn() -> (X, V)>);
|
||||
|
||||
impl<X, V> Default for Named<X, V> {
|
||||
fn default() -> Self {
|
||||
Named(PhantomData)
|
||||
}
|
||||
}
|
||||
|
||||
/// The placeholders a signature distinguishes its name-generic attributes by.
|
||||
/// A node writing one name uses [`Name0`]; a second name on the same node
|
||||
/// takes [`Name1`], and so on, which is all the placeholder has to do.
|
||||
pub struct Name0;
|
||||
/// The second name-generic attribute in one signature. See [`Name0`].
|
||||
pub struct Name1;
|
||||
/// The third name-generic attribute in one signature. See [`Name0`].
|
||||
pub struct Name2;
|
||||
|
||||
// SAFETY: every obligation is discharged by `V`, which carries the same
|
||||
// contract at the same value type; only the name differs, and the compiler
|
||||
// fold replaces the placeholder before a layout sees it.
|
||||
unsafe impl<X: 'static, V: AttrValue> Attribute for Named<X, V> {
|
||||
const NAME: &'static str = NAMED_PLACEHOLDER;
|
||||
type Value<'e> = V::Value<'e>;
|
||||
|
||||
fn from_stored<'a>(stored: &'a dyn std::any::Any) -> Option<Self::Value<'a>> {
|
||||
V::from_stored(stored)
|
||||
}
|
||||
|
||||
unsafe fn read_erased(ptr: *const u8) -> Box<dyn AnyAttributeValue> {
|
||||
// SAFETY: the caller's contract, at `V`'s own value type.
|
||||
unsafe { V::read_erased(ptr) }
|
||||
}
|
||||
|
||||
const REPARK: Option<crate::list::ReparkFn> = V::REPARK;
|
||||
}
|
||||
|
||||
/// The value a name-generic write takes off the wire, and the row it lands
|
||||
/// in. A plain row is its own wire form; a reference row's wire form is the
|
||||
/// owned payload the kernel parks in the arena, so the field can carry a
|
||||
/// borrow of it for the evaluation.
|
||||
pub trait WireValue: 'static {
|
||||
/// The row this value is written at, fixing the field's value type.
|
||||
type Row: AttrValue;
|
||||
|
||||
/// Moves the value into `arena` where the row borrows it, or hands it back
|
||||
/// unchanged where the row stores it plainly. `None` reports exhaustion.
|
||||
fn park<'e>(self, arena: &'e crate::arena::Arena) -> Option<<Self::Row as AttrValue>::Value<'e>>;
|
||||
}
|
||||
|
||||
/// Declares [`WireValue`] rows. `for T` is a plain value, carried and stored
|
||||
/// as itself; `Wire => Row` parks `Wire`'s payload in the arena and stores the
|
||||
/// borrow `Row` names.
|
||||
#[macro_export]
|
||||
macro_rules! wire_value {
|
||||
() => {};
|
||||
(for $value:ty; $($rest:tt)*) => {
|
||||
impl $crate::attribute::WireValue for $value {
|
||||
type Row = $value;
|
||||
|
||||
fn park(self, _: &$crate::arena::Arena) -> ::core::option::Option<$value> {
|
||||
::core::option::Option::Some(self)
|
||||
}
|
||||
}
|
||||
|
||||
$crate::wire_value!($($rest)*);
|
||||
};
|
||||
($wire:ty => $row:ty; $($rest:tt)*) => {
|
||||
impl $crate::attribute::WireValue for $wire {
|
||||
type Row = $row;
|
||||
|
||||
fn park<'e>(self, arena: &'e $crate::arena::Arena) -> ::core::option::Option<<$row as $crate::attribute::AttrValue>::Value<'e>> {
|
||||
let (parked, _) = arena.alloc(self)?;
|
||||
::core::option::Option::Some(::std::borrow::Borrow::borrow(parked))
|
||||
}
|
||||
}
|
||||
|
||||
$crate::wire_value!($($rest)*);
|
||||
};
|
||||
}
|
||||
|
||||
wire_value! {
|
||||
for f64;
|
||||
for u32;
|
||||
for u64;
|
||||
for bool;
|
||||
for DVec2;
|
||||
for DAffine2;
|
||||
for crate::Color;
|
||||
for crate::blending::BlendMode;
|
||||
::std::vec::Vec<crate::uuid::NodeId> => NodeIdPath;
|
||||
::std::string::String => Text;
|
||||
}
|
||||
|
||||
/// Interns a folded attribute name for the `&'static str` a layout field
|
||||
/// holds. Census names never reach here; a document's novel names are finite
|
||||
/// and repeat across instances, so the leak is one allocation per name.
|
||||
pub fn intern_name(name: &str) -> &'static str {
|
||||
static NAMES: LazyLock<Mutex<std::collections::HashSet<&'static str>>> = LazyLock::new(|| Mutex::new(std::collections::HashSet::new()));
|
||||
let mut names = NAMES.lock().unwrap();
|
||||
if let Some(interned) = names.get(name) {
|
||||
return interned;
|
||||
}
|
||||
let interned: &'static str = Box::leak(name.to_owned().into_boxed_str());
|
||||
names.insert(interned);
|
||||
interned
|
||||
}
|
||||
|
||||
/// Declares [`AttrValue`] rows, the value types a name-generic attribute can
|
||||
/// be written at. `for T` implements the row on an existing plain value type;
|
||||
/// `Row: &T` and `Row: Option<&T>` declare a token naming a reference value,
|
||||
/// whose payload the writing kernel parks in the arena.
|
||||
///
|
||||
/// ```ignore
|
||||
/// core_types::named_value! {
|
||||
/// /// Plain rows, implemented on the value type itself.
|
||||
/// for f64;
|
||||
/// /// A reference row, whose token names the borrowed value.
|
||||
/// pub Text: &str;
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The `for T` arm implements this crate's trait on `T`, so rows over types
|
||||
/// this crate does not own are declared here rather than by a caller.
|
||||
#[macro_export]
|
||||
macro_rules! named_value {
|
||||
() => {};
|
||||
($(#[$meta:meta])* for $value:ty; $($rest:tt)*) => {
|
||||
// SAFETY: a plain value type cannot name `'e`, so no re-park is owed,
|
||||
// and the two glue fns below are each other's inverse at `$value`.
|
||||
unsafe impl $crate::attribute::AttrValue for $value {
|
||||
type Value<'e> = $value;
|
||||
|
||||
fn from_stored<'a>(stored: &'a dyn ::std::any::Any) -> ::core::option::Option<Self::Value<'a>> {
|
||||
stored.downcast_ref::<$value>().copied()
|
||||
}
|
||||
|
||||
unsafe fn read_erased(ptr: *const u8) -> ::std::boxed::Box<dyn $crate::list::AnyAttributeValue> {
|
||||
::std::boxed::Box::new(unsafe { ptr.cast::<$value>().read() })
|
||||
}
|
||||
}
|
||||
|
||||
$crate::named_value!($($rest)*);
|
||||
};
|
||||
($(#[$meta:meta])* $vis:vis $row:ident: Option<&$value:ty>; $($rest:tt)*) => {
|
||||
$(#[$meta])*
|
||||
$vis struct $row;
|
||||
|
||||
// SAFETY: the reference arm emits `REPARK`, and the two glue fns below
|
||||
// are each other's inverse at `Option<&$value>`.
|
||||
unsafe impl $crate::attribute::AttrValue for $row {
|
||||
type Value<'e> = ::core::option::Option<&'e $value>;
|
||||
|
||||
fn from_stored<'a>(stored: &'a dyn ::std::any::Any) -> ::core::option::Option<Self::Value<'a>> {
|
||||
stored
|
||||
.downcast_ref::<::core::option::Option<<$value as ::std::borrow::ToOwned>::Owned>>()
|
||||
.map(|owned| owned.as_ref().map(::std::borrow::Borrow::borrow))
|
||||
}
|
||||
|
||||
unsafe fn read_erased(ptr: *const u8) -> ::std::boxed::Box<dyn $crate::list::AnyAttributeValue> {
|
||||
::std::boxed::Box::new(unsafe { ptr.cast::<::core::option::Option<&$value>>().read() }.map(|value| <$value as ::std::borrow::ToOwned>::to_owned(value)))
|
||||
}
|
||||
|
||||
const REPARK: ::core::option::Option<$crate::list::ReparkFn> = {
|
||||
unsafe fn repark(value: &dyn $crate::list::AnyAttributeValue, dst: *mut u8, arena: &$crate::arena::Arena) -> ::core::option::Option<()> {
|
||||
let owned: &::core::option::Option<<$value as ::std::borrow::ToOwned>::Owned> =
|
||||
value.as_any().downcast_ref().expect("an optional reference row replays its owned clone");
|
||||
let parked = match owned {
|
||||
::core::option::Option::Some(owned) => {
|
||||
let (parked, _) = arena.alloc(<$value as ::std::borrow::ToOwned>::to_owned(::std::borrow::Borrow::borrow(owned)))?;
|
||||
::core::option::Option::Some(::std::borrow::Borrow::borrow(parked))
|
||||
}
|
||||
::core::option::Option::None => ::core::option::Option::None,
|
||||
};
|
||||
unsafe { dst.cast::<::core::option::Option<&$value>>().write(parked) };
|
||||
::core::option::Option::Some(())
|
||||
}
|
||||
::core::option::Option::Some(repark)
|
||||
};
|
||||
}
|
||||
|
||||
$crate::named_value!($($rest)*);
|
||||
};
|
||||
($(#[$meta:meta])* $vis:vis $row:ident: &$value:ty; $($rest:tt)*) => {
|
||||
$(#[$meta])*
|
||||
$vis struct $row;
|
||||
|
||||
// SAFETY: the reference arm emits `REPARK`, and the two glue fns below
|
||||
// are each other's inverse at `&$value`.
|
||||
unsafe impl $crate::attribute::AttrValue for $row {
|
||||
type Value<'e> = &'e $value;
|
||||
|
||||
fn from_stored<'a>(stored: &'a dyn ::std::any::Any) -> ::core::option::Option<Self::Value<'a>> {
|
||||
stored.downcast_ref::<<$value as ::std::borrow::ToOwned>::Owned>().map(::std::borrow::Borrow::borrow)
|
||||
}
|
||||
|
||||
unsafe fn read_erased(ptr: *const u8) -> ::std::boxed::Box<dyn $crate::list::AnyAttributeValue> {
|
||||
::std::boxed::Box::new(unsafe { ptr.cast::<&$value>().read() }.to_owned())
|
||||
}
|
||||
|
||||
const REPARK: ::core::option::Option<$crate::list::ReparkFn> = {
|
||||
unsafe fn repark(value: &dyn $crate::list::AnyAttributeValue, dst: *mut u8, arena: &$crate::arena::Arena) -> ::core::option::Option<()> {
|
||||
let owned: &<$value as ::std::borrow::ToOwned>::Owned = value.as_any().downcast_ref().expect("a reference row replays its owned clone");
|
||||
let (parked, _) = arena.alloc(<$value as ::std::borrow::ToOwned>::to_owned(::std::borrow::Borrow::borrow(owned)))?;
|
||||
unsafe { dst.cast::<&$value>().write(::std::borrow::Borrow::borrow(parked)) };
|
||||
::core::option::Option::Some(())
|
||||
}
|
||||
::core::option::Option::Some(repark)
|
||||
};
|
||||
}
|
||||
|
||||
$crate::named_value!($($rest)*);
|
||||
};
|
||||
}
|
||||
|
||||
named_value! {
|
||||
for f64;
|
||||
for u32;
|
||||
for u64;
|
||||
for bool;
|
||||
for DVec2;
|
||||
for DAffine2;
|
||||
for crate::Color;
|
||||
for crate::blending::BlendMode;
|
||||
/// A document node path, the value type of `editor:layer_path`.
|
||||
pub NodeIdPath: &[crate::uuid::NodeId];
|
||||
/// Free text, parked in the arena by the writing kernel.
|
||||
pub Text: &str;
|
||||
}
|
||||
|
||||
/// A census row: what is known about one declared attribute name.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct AttributeInfo {
|
||||
@@ -112,13 +443,25 @@ pub struct AttributeInfo {
|
||||
/// Writes a legacy stored value into a field of this marker, parking
|
||||
/// droppable payloads. A wrong-typed stored value leaves the field
|
||||
/// untouched; `None` reports arena exhaustion.
|
||||
///
|
||||
/// `dst` must address a live field of *this row's* value type: the glue
|
||||
/// writes its own `Value`'s worth of bytes there, so a caller resolving the
|
||||
/// field by [`name`](Self::name) checks [`size`](Self::size) and
|
||||
/// [`value_type`](Self::value_type) against the field first. The fields
|
||||
/// here are public and the struct is `Copy`, so a row is a claim about a
|
||||
/// marker rather than a proof about a field.
|
||||
pub write_stored: unsafe fn(&dyn AnyAttributeValue, *mut u8, &crate::arena::Arena) -> Option<()>,
|
||||
}
|
||||
|
||||
/// The default's object representation, staged through zeroed storage so a
|
||||
/// value with padding or an unused payload (`Option<f64>`'s `None`) hands the
|
||||
/// caller deterministic bytes rather than whatever the stack held.
|
||||
fn write_default_bytes<A: Attribute>(out: &mut [u8]) {
|
||||
assert_eq!(out.len(), size_of::<A::Value<'static>>());
|
||||
let value: A::Value<'static> = A::default();
|
||||
unsafe { std::ptr::copy_nonoverlapping((&raw const value).cast::<u8>(), out.as_mut_ptr(), size_of::<A::Value<'static>>()) };
|
||||
let mut staged = std::mem::MaybeUninit::<A::Value<'static>>::zeroed();
|
||||
staged.write(A::default());
|
||||
// SAFETY: the staging holds a live value of the type `out` is sized for.
|
||||
unsafe { std::ptr::copy_nonoverlapping(staged.as_ptr().cast::<u8>(), out.as_mut_ptr(), size_of::<A::Value<'static>>()) };
|
||||
}
|
||||
|
||||
fn field_write_at<A: Attribute>(level: u8) -> crate::record::FieldWrite
|
||||
@@ -128,12 +471,15 @@ where
|
||||
crate::record::FieldWrite::of::<A>(level)
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `dst` must address a live field of `A`'s value type.
|
||||
unsafe fn write_stored<A: Attribute>(stored: &dyn AnyAttributeValue, dst: *mut u8, arena: &crate::arena::Arena) -> Option<()> {
|
||||
if A::from_stored(stored.as_any()).is_none() {
|
||||
// A wrong-typed stored value reads as absent, so the field keeps its default.
|
||||
return Some(());
|
||||
}
|
||||
match A::REPARK {
|
||||
// SAFETY: the caller's contract; the glue is this marker's own.
|
||||
Some(repark) => unsafe { repark(stored, dst, arena) },
|
||||
None => {
|
||||
let value = A::from_stored(stored.as_any()).expect("checked above");
|
||||
@@ -212,7 +558,10 @@ macro_rules! attribute {
|
||||
$(#[$meta])*
|
||||
$vis struct $marker;
|
||||
|
||||
impl $crate::attribute::Attribute for $marker {
|
||||
// SAFETY: the reference-valued arms emit `REPARK`, the plain arm's value
|
||||
// type cannot name `'e`, and `read_erased` and `from_stored` are emitted
|
||||
// as each other's inverse.
|
||||
unsafe impl $crate::attribute::Attribute for $marker {
|
||||
const NAME: &'static str = $name;
|
||||
type Value<'e> = ::core::option::Option<&'e $value>;
|
||||
|
||||
@@ -251,7 +600,10 @@ macro_rules! attribute {
|
||||
$(#[$meta])*
|
||||
$vis struct $marker;
|
||||
|
||||
impl $crate::attribute::Attribute for $marker {
|
||||
// SAFETY: the reference-valued arms emit `REPARK`, the plain arm's value
|
||||
// type cannot name `'e`, and `read_erased` and `from_stored` are emitted
|
||||
// as each other's inverse.
|
||||
unsafe impl $crate::attribute::Attribute for $marker {
|
||||
const NAME: &'static str = $name;
|
||||
type Value<'e> = &'e $value;
|
||||
$(
|
||||
@@ -286,7 +638,10 @@ macro_rules! attribute {
|
||||
$(#[$meta])*
|
||||
$vis struct $marker;
|
||||
|
||||
impl $crate::attribute::Attribute for $marker {
|
||||
// SAFETY: the reference-valued arms emit `REPARK`, the plain arm's value
|
||||
// type cannot name `'e`, and `read_erased` and `from_stored` are emitted
|
||||
// as each other's inverse.
|
||||
unsafe impl $crate::attribute::Attribute for $marker {
|
||||
const NAME: &'static str = $name;
|
||||
type Value<'e> = $value;
|
||||
$(
|
||||
@@ -342,7 +697,7 @@ attribute! {
|
||||
/// 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.
|
||||
/// position its drag cage.
|
||||
pub EditorTextFrame("editor:text_frame"): DAffine2;
|
||||
/// Byte offset where a regex match begins ('Regex Find All' and 'Regex Capture' text nodes).
|
||||
pub Start("start"): u64;
|
||||
@@ -410,6 +765,27 @@ mod tests {
|
||||
assert_eq!(row.size, size_of::<&str>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_owned_reference_crossing_parks_into_the_serving_arena() {
|
||||
let owned = OwnedAttr::<Name>::new("crossing");
|
||||
let arena = crate::arena::Arena::new(1024).unwrap();
|
||||
assert_eq!(owned.park(&arena).unwrap(), "crossing");
|
||||
assert_eq!(owned.clone().park(&arena).unwrap(), "crossing", "the crossing parks again on every evaluation");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_owned_plain_crossing_rides_its_bytes() {
|
||||
let arena = crate::arena::Arena::new(64).unwrap();
|
||||
assert_eq!(OwnedAttr::<Opacity>::new(0.25).park(&arena).unwrap(), 0.25);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_exhausted_arena_refuses_an_owned_reference_crossing() {
|
||||
let owned = OwnedAttr::<Name>::new("too long for this arena");
|
||||
let arena = crate::arena::Arena::new(8).unwrap();
|
||||
assert!(owned.park(&arena).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reregistration_at_the_same_type_is_idempotent() {
|
||||
register::<Opacity>();
|
||||
@@ -421,7 +797,8 @@ mod tests {
|
||||
#[should_panic(expected = "two value types")]
|
||||
fn a_second_marker_at_a_different_type_panics() {
|
||||
struct Conflict;
|
||||
impl Attribute for Conflict {
|
||||
// SAFETY: `bool` borrows nothing, so the plain-value arm is the right one.
|
||||
unsafe impl Attribute for Conflict {
|
||||
const NAME: &'static str = "opacity";
|
||||
type Value<'e> = bool;
|
||||
|
||||
|
||||
@@ -244,7 +244,7 @@ impl IndexLevels {
|
||||
self.0 == u32::MAX
|
||||
}
|
||||
|
||||
/// The same requirement seen from outside an edge whose innermost `supplied`
|
||||
/// The same requirement seen from outside an input 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
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
use crate::gpoll::{Extent, GPoll};
|
||||
|
||||
/// A wired value input; `get` evaluates the edge and yields the typed element.
|
||||
/// A wired value input; `get` evaluates the input and yields the typed element.
|
||||
pub struct ValueIn<'a, T> {
|
||||
read: &'a dyn Fn() -> GPoll<T>,
|
||||
}
|
||||
@@ -21,9 +21,9 @@ impl<'a, T> ValueIn<'a, T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// An upstream edge's extents. For derived (per-copy) content the query runs
|
||||
/// An upstream input's extents. For derived (per-copy) content the query runs
|
||||
/// at the given copy's promoted context; `at` queries copy 0, the uniform
|
||||
/// default. For ordinary edges the copy is ignored.
|
||||
/// default. For ordinary inputs the copy is ignored.
|
||||
pub struct ExtentIn<'a> {
|
||||
query: &'a dyn Fn(u64, u8) -> GPoll<Extent>,
|
||||
}
|
||||
@@ -62,7 +62,7 @@ impl<'a, T> ListIn<'a, T> {
|
||||
(self.get)()
|
||||
}
|
||||
|
||||
/// The subject wire's total flat extent as a plain query.
|
||||
/// The subject input's total flat extent as a plain query.
|
||||
pub fn total(&self) -> GPoll<crate::gpoll::Extent> {
|
||||
(self.total)()
|
||||
}
|
||||
|
||||
@@ -208,7 +208,7 @@ impl Extent {
|
||||
}
|
||||
|
||||
/// 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,
|
||||
/// counts as one lane, so a scalar input joins a concat as a single item,
|
||||
/// and a lower-bound operand keeps the sum a lower bound.
|
||||
pub fn sum(a: GPoll<Extent>, b: GPoll<Extent>) -> GPoll<Extent> {
|
||||
let lanes = |extent| match extent {
|
||||
|
||||
@@ -85,6 +85,12 @@ pub trait AnyAttributeValue: std::any::Any + Send + Sync {
|
||||
fn into_attribute(self: Box<Self>, key: &str, preceding_defaults: usize) -> Box<dyn AnyAttribute>;
|
||||
}
|
||||
|
||||
/// Re-parks an owned attribute value into fresh field storage; `None` reports arena exhaustion.
|
||||
pub type ReparkFn = unsafe fn(&dyn AnyAttributeValue, *mut u8, &crate::arena::Arena) -> Option<()>;
|
||||
|
||||
/// Replays an owned attribute value into a serving arena; `Some(None)` is unchanged, `None` reports arena exhaustion.
|
||||
pub type FieldReplayFn = fn(&dyn AnyAttributeValue, &crate::arena::Arena) -> Option<Option<Box<dyn AnyAttributeValue>>>;
|
||||
|
||||
impl<T: Clone + Send + Sync + Default + Sized + Debug + PartialEq + CacheHash + 'static> AnyAttributeValue for T {
|
||||
/// Clones this value into a new boxed trait object.
|
||||
fn clone_box(&self) -> Box<dyn AnyAttributeValue> {
|
||||
@@ -336,21 +342,6 @@ impl AttributeDyn {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.0.len() == 0
|
||||
}
|
||||
|
||||
/// Builds a new attribute matching `target_len` items, taking values from this attribute (wrapping if shorter, truncating if longer).
|
||||
pub fn cloned_to_length(&self, key: &str, target_len: usize) -> Box<dyn AnyAttribute> {
|
||||
let mut result = self.0.new_with_defaults(0);
|
||||
let source_len = self.0.len();
|
||||
if source_len == 0 {
|
||||
pad_with_implicit_default(key, &mut result, target_len);
|
||||
return result;
|
||||
}
|
||||
for i in 0..target_len {
|
||||
let value = self.0.clone_value(i % source_len).expect("source_len > 0");
|
||||
result.push(value);
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for AttributeDyn {
|
||||
@@ -383,6 +374,7 @@ impl CacheHash for AttributeDyn {
|
||||
}
|
||||
}
|
||||
|
||||
// SAFETY: the type carries no lifetime, so it is its own static form.
|
||||
unsafe impl StaticType for AttributeDyn {
|
||||
type Static = Self;
|
||||
}
|
||||
@@ -426,6 +418,7 @@ impl CacheHash for AttributeValueDyn {
|
||||
}
|
||||
}
|
||||
|
||||
// SAFETY: as for AttributeDyn.
|
||||
unsafe impl StaticType for AttributeValueDyn {
|
||||
type Static = Self;
|
||||
}
|
||||
@@ -509,6 +502,7 @@ impl CacheHash for ListDyn {
|
||||
}
|
||||
}
|
||||
|
||||
// SAFETY: as for AttributeDyn.
|
||||
unsafe impl StaticType for ListDyn {
|
||||
type Static = Self;
|
||||
}
|
||||
@@ -784,13 +778,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) {
|
||||
@@ -1031,14 +1018,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) {
|
||||
@@ -1058,12 +1037,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)
|
||||
@@ -1219,6 +1192,8 @@ impl<T> ApplyTransform for List<T> {
|
||||
}
|
||||
}
|
||||
|
||||
// SAFETY: the list carries its lifetime only through T, so substituting T's
|
||||
// static form substitutes the list's and keeps the layout identical.
|
||||
unsafe impl<T: StaticTypeSized> StaticType for List<T> {
|
||||
type Static = List<T::Static>;
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ pub enum BatchStatus<'a> {
|
||||
/// 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
|
||||
/// No batch implementation behind this input; a driver answers with the
|
||||
/// per-lane serve and copy-out loop ([`crate::record::fill_frames`]).
|
||||
Unbatched,
|
||||
Pending,
|
||||
@@ -106,9 +106,10 @@ pub struct RecordBatchMut<'a> {
|
||||
|
||||
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.
|
||||
/// which serve in ascending order with no gaps, so the initialized prefix is
|
||||
/// a fact rather than a contract.
|
||||
pub(crate) fn new(scratch: &'a mut [MaybeUninit<u64>], len: usize, layout: &'a crate::record::Layout) -> Self {
|
||||
debug_assert!(len * layout.lane_stride() <= scratch.len() * 8);
|
||||
debug_assert!(len.checked_mul(layout.lane_stride()).is_some_and(|need| need <= scratch.len() * 8));
|
||||
Self { scratch, len, layout }
|
||||
}
|
||||
|
||||
@@ -135,19 +136,6 @@ impl<'a> RecordBatchMut<'a> {
|
||||
// SAFETY: the constructor's contract; the exclusive borrow is consumed.
|
||||
unsafe { RecordBatch::new(self.scratch.as_ptr().cast(), self.len, self.layout) }
|
||||
}
|
||||
|
||||
/// Lane `lane`'s frame for in-place writes through the layout's offsets.
|
||||
pub fn lane_ptr(&mut self, lane: usize) -> *mut u8 {
|
||||
assert!(lane < self.len, "lane {lane} out of bounds for a batch of {}", self.len);
|
||||
// SAFETY: in-bounds by the assert against the constructor's contract.
|
||||
unsafe { self.scratch.as_mut_ptr().cast::<u8>().add(lane * self.layout.lane_stride()) }
|
||||
}
|
||||
|
||||
/// Reclaims the raw buffer, e.g. to rebind it under a same-stride output
|
||||
/// layout for an in-place map.
|
||||
pub fn into_scratch(self) -> &'a mut [MaybeUninit<u64>] {
|
||||
self.scratch
|
||||
}
|
||||
}
|
||||
|
||||
/// One lane's record: its pointer paired with the batch's layout.
|
||||
@@ -224,8 +212,7 @@ impl<'a, T> Deref for Lane<'a, T> {
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// view over the [`RecordBatch`] the level was collected into.
|
||||
#[derive(Debug)]
|
||||
pub struct List<'a, T> {
|
||||
batch: RecordBatch<'a>,
|
||||
@@ -531,9 +518,9 @@ impl StatusCell {
|
||||
Self { no_partial: true, ..Self::new() }
|
||||
}
|
||||
|
||||
/// Claims the edge's own frame out of `frames`, serves through it, and
|
||||
/// Claims the input's own frame out of `frames`, serves through it, and
|
||||
/// folds the poll's status into the cell. The claim is the caller's, so
|
||||
/// the edge's frame is claimed exactly once per evaluation.
|
||||
/// the input's frame is claimed exactly once per evaluation.
|
||||
#[inline(always)]
|
||||
pub fn eval_input<'e, Input, N: Node<Input> + ?Sized>(&self, input_index: usize, node: &N, input: &Input, frames: &crate::record::Frames<'e>) -> Result<crate::record::RecordValue<'e>, Interrupt>
|
||||
where
|
||||
@@ -618,13 +605,13 @@ impl<'a, 'f, N> LazyInput<'a, 'f, N> {
|
||||
#[inline(always)]
|
||||
pub fn eval<'e, Input>(&self, ctx: &Input) -> Result<crate::record::RecordValue<'e>, Interrupt>
|
||||
where
|
||||
N: crate::record::DerivedRecordEdge<'e, Input>,
|
||||
N: crate::record::DerivedRecordInput<'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
|
||||
/// The input's composite extent, for kernels that split or shift indices
|
||||
/// over their sources.
|
||||
#[inline(always)]
|
||||
pub fn extent<'e, Input>(&self, ctx: &Input, at: Level) -> GPoll<Extent>
|
||||
@@ -643,7 +630,7 @@ mod tests {
|
||||
|
||||
use crate::arena::Arena;
|
||||
use crate::context::ExtractArena;
|
||||
use crate::record::{LiftedSource, serve_edge};
|
||||
use crate::record::{LiftedSource, serve_input};
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct TestInput<'a> {
|
||||
@@ -688,7 +675,7 @@ mod tests {
|
||||
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 {
|
||||
let GPoll::Final(value) = serve_input(&*erased, &input, &frames) else {
|
||||
panic!("the erased edge must serve a final record");
|
||||
};
|
||||
// SAFETY: the record was served at `layout`, whose element is the output.
|
||||
|
||||
@@ -44,7 +44,7 @@ impl<U, T: ListConvert<U> + Send> Convert<List<U>, ()> for List<T> {
|
||||
|
||||
/// Wraps each row's element into a type-erased attribute. Lets nodes that accept a source attribute
|
||||
/// from any `List<U>` express their signature as `AttributeDyn` and avoid monomorphizing
|
||||
/// over `U`; the compiler inserts this convert to bridge concrete-typed graph wires to the dyn input.
|
||||
/// over `U`; the compiler inserts this convert to bridge concrete-typed graph sources to the dyn input.
|
||||
impl<T: Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash + 'static> Convert<AttributeDyn, ()> for List<T> {
|
||||
fn convert(self, _: Footprint, _: ()) -> AttributeDyn {
|
||||
let values: Vec<T> = self.into_iter().map(|row| row.into_element()).collect();
|
||||
@@ -54,7 +54,7 @@ impl<T: Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash
|
||||
|
||||
/// Wraps a value into a type-erased attribute value. Lets nodes that take a per-item value source
|
||||
/// (such as `write_attribute`'s value-producing input) be generic over the destination list type
|
||||
/// alone, with the compiler-inserted convert handling each concrete value type at the wire level.
|
||||
/// alone, with the compiler-inserted convert handling each concrete value type at the input level.
|
||||
impl<T: Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash + 'static> Convert<AttributeValueDyn, ()> for T {
|
||||
fn convert(self, _: Footprint, _: ()) -> AttributeValueDyn {
|
||||
AttributeValueDyn(Box::new(self))
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,298 @@
|
||||
//! Raw typed access to a record at a wiring-proven layout.
|
||||
|
||||
use super::layout::element_parked;
|
||||
use crate::attribute;
|
||||
use crate::gpoll::GPoll;
|
||||
|
||||
/// A view of one record: a pointer whose layout is proven at wiring, borrowing
|
||||
/// the storage it points into for `'r`.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Rec<'r>(pub(in crate::record) *const u8, pub(in crate::record) std::marker::PhantomData<&'r u8>);
|
||||
|
||||
impl<'r> Rec<'r> {
|
||||
/// # Safety
|
||||
/// `ptr` must point to a live record of the layout the consumer resolved
|
||||
/// at wiring, valid for `'r` and until the owning slot is next written.
|
||||
pub unsafe fn new(ptr: *const u8) -> Self {
|
||||
Rec(ptr, std::marker::PhantomData)
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `offset` must be a field offset of the record's layout and `T` the
|
||||
/// field's type; both are proven at wiring. The record's base is aligned
|
||||
/// to its layout, so field reads are aligned.
|
||||
pub unsafe fn read<T: Copy>(self, offset: usize) -> T {
|
||||
unsafe { self.0.add(offset).cast::<T>().read() }
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `T` must be the record's element type; the element sits at offset 0.
|
||||
pub unsafe fn element<T: Copy>(self) -> T {
|
||||
unsafe { self.read(0) }
|
||||
}
|
||||
|
||||
pub fn ptr(self) -> *const u8 {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
/// An opaque record value: every non-empty record spills to a claimed frame
|
||||
/// and the value carries its pointer, while an empty record carries nothing.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct RecordValue<'e> {
|
||||
pub(in crate::record) ptr: *const u8,
|
||||
_lifetime: std::marker::PhantomData<&'e ()>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for RecordValue<'_> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str("RecordValue(..)")
|
||||
}
|
||||
}
|
||||
|
||||
// SAFETY: `element_write` requires the element `Send + Sync` and every field holds an
|
||||
// `Attribute::Value`, which the trait bounds `Send + Sync`, so the record bytes behind
|
||||
// the pointer are thread-safe; `'e` ties the pointer's validity to the shared arena and
|
||||
// record-stack discipline.
|
||||
unsafe impl Send for RecordValue<'_> {}
|
||||
// SAFETY: as `Send`.
|
||||
unsafe impl Sync for RecordValue<'_> {}
|
||||
|
||||
impl<'e> RecordValue<'e> {
|
||||
#[doc(hidden)]
|
||||
pub fn zeroed() -> Self {
|
||||
RecordValue {
|
||||
ptr: std::ptr::null(),
|
||||
_lifetime: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
/// The inline storage under construction; writes land in the value itself.
|
||||
#[doc(hidden)]
|
||||
pub fn as_mut_ptr(&mut self) -> *mut u8 {
|
||||
(&raw mut *self).cast()
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub fn spilled(rec: Rec<'_>) -> Self {
|
||||
RecordValue {
|
||||
ptr: rec.ptr(),
|
||||
_lifetime: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
/// Rebinds the eval lifetime, lengthening a derived scope's record back
|
||||
/// onto the outer evaluation's. Sound only because the record's bytes live
|
||||
/// in the outer caller's slot region: a derived context shortens the
|
||||
/// caller's frame space rather than owning any, so the frame the record
|
||||
/// sits in outlives the derivation, exactly as it outlives the arena
|
||||
/// borrow the derived context carries.
|
||||
pub(in crate::record) fn rebind<'a>(self) -> RecordValue<'a> {
|
||||
RecordValue {
|
||||
ptr: self.ptr,
|
||||
_lifetime: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads a declared attribute out of a record at a wiring-resolved offset,
|
||||
/// falling back to the marker's census default where the layout does not carry
|
||||
/// the name.
|
||||
///
|
||||
/// # Safety
|
||||
/// `rec` must be a live record of the layout `offset` was resolved against,
|
||||
/// and `offset`, where present, must be that layout's offset for `A` at the
|
||||
/// read's level. The census admits one value type per attribute name and
|
||||
/// panics on a conflicting declaration, so that field's bytes are a value of
|
||||
/// `A::Value`, differing from the read type only in `'e`, which must not
|
||||
/// outlive the evaluation a parked payload is arena-resident for.
|
||||
pub unsafe fn read_at<'e, A: attribute::Attribute>(rec: Rec<'_>, offset: Option<usize>) -> attribute::Attr<'e, A> {
|
||||
attribute::Attr(match offset {
|
||||
// SAFETY: the caller's contract.
|
||||
Some(offset) => unsafe { rec.read::<A::Value<'e>>(offset) },
|
||||
None => A::default(),
|
||||
})
|
||||
}
|
||||
|
||||
/// [`read_at`] for a name-generic read, whose marker carries the value type
|
||||
/// but not the name and so cannot know the name's own default. `absent` is
|
||||
/// that default's bytes, which the compiler takes from the census once the
|
||||
/// name is folded; without one the value type's default applies, which is
|
||||
/// exactly the rule for a name the census does not declare.
|
||||
///
|
||||
/// # Safety
|
||||
/// As [`read_at`]. `absent`, where present, must hold the object
|
||||
/// representation of `A::Value`, which the compiler takes from the census row
|
||||
/// for the folded name after checking that row's value type against `A`'s. A
|
||||
/// reference-valued default addresses `'static` data, so the value it yields
|
||||
/// outlives any evaluation.
|
||||
pub unsafe fn read_at_defaulting<'e, A: attribute::Attribute>(rec: Rec<'_>, offset: Option<usize>, absent: Option<&[u8]>) -> attribute::Attr<'e, A> {
|
||||
attribute::Attr(match (offset, absent) {
|
||||
// SAFETY: the caller's contract.
|
||||
(Some(offset), _) => unsafe { rec.read::<A::Value<'e>>(offset) },
|
||||
// SAFETY: the caller's contract; the bytes are unaligned storage, so
|
||||
// the value is read out rather than referenced in place.
|
||||
(None, Some(bytes)) => unsafe { bytes.as_ptr().cast::<A::Value<'e>>().read_unaligned() },
|
||||
(None, None) => A::default(),
|
||||
})
|
||||
}
|
||||
|
||||
/// The read-less [`DerivedLazyInput`] glue: the token alone.
|
||||
///
|
||||
/// # Safety
|
||||
/// `rec` must be a spilled record's frame.
|
||||
pub unsafe fn token_only<'e>(rec: Rec<'_>, _reads: &[Option<usize>]) -> RecordValue<'e> {
|
||||
RecordValue::spilled(rec)
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `offset` must be a field offset of the layout of the record under
|
||||
/// construction at `dst` and `T` the field's type; both are proven at wiring.
|
||||
pub unsafe fn write_field<T>(dst: *mut u8, offset: usize, value: T) {
|
||||
unsafe { dst.add(offset).cast::<T>().write(value) }
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// The record's element must be a `T` in the form [`element_parked`] picks,
|
||||
/// and the borrow is only valid while the record is.
|
||||
pub unsafe fn borrow_element<'e, T>(rec: Rec<'_>) -> &'e T {
|
||||
match element_parked::<T>() {
|
||||
true => unsafe { rec.element::<&T>() },
|
||||
false => unsafe { &*rec.ptr().cast::<T>() },
|
||||
}
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// The record's element must be a `T` in the form [`element_parked`] picks.
|
||||
pub unsafe fn read_element<T: Clone>(rec: Rec<'_>) -> T {
|
||||
unsafe { borrow_element::<T>(rec) }.clone()
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `dst` must be fresh element storage of a record whose element is `T`.
|
||||
/// `None` reports arena exhaustion for a parked element.
|
||||
pub unsafe fn write_element<T: Send + Sync + dyn_any::StaticTypeSized>(dst: *mut u8, value: T, arena: &crate::arena::Arena) -> Option<()> {
|
||||
unsafe { write_element_sized(dst, value, arena, 0) }
|
||||
}
|
||||
|
||||
/// [`write_element`] with the park glue's estimate of the heap `value` owns.
|
||||
///
|
||||
/// # Safety
|
||||
/// As [`write_element`].
|
||||
pub unsafe fn write_element_sized<T: Send + Sync + dyn_any::StaticTypeSized>(dst: *mut u8, value: T, arena: &crate::arena::Arena, retained: usize) -> Option<()> {
|
||||
// SAFETY: the caller's contract; `T::Static` is the element type's own key.
|
||||
unsafe { write_element_keyed(dst, value, arena, retained, std::any::TypeId::of::<T::Static>()) }
|
||||
}
|
||||
|
||||
/// [`write_element_sized`] for replay glue already holding the element's
|
||||
/// static form, whose key the element type it replays into supplies.
|
||||
///
|
||||
/// # Safety
|
||||
/// As [`write_element`], and `type_of` must be that element type's key, since
|
||||
/// a park carrying it is what [`Promotion::move_park`] moves at.
|
||||
pub(in crate::record) unsafe fn write_element_keyed<T: Send + Sync>(dst: *mut u8, value: T, arena: &crate::arena::Arena, retained: usize, type_of: std::any::TypeId) -> Option<()> {
|
||||
match element_parked::<T>() {
|
||||
true => {
|
||||
let (parked, _) = arena.alloc_sized_as(value, retained, type_of)?;
|
||||
unsafe { dst.cast::<&T>().write(parked) };
|
||||
Some(())
|
||||
}
|
||||
false => {
|
||||
unsafe { dst.cast::<T>().write(value) };
|
||||
Some(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Finishes a carried record frame: the element lands beside the fields
|
||||
/// already carried into `dst`, and inline frames copy out of the scratch
|
||||
/// bytes. Arena exhaustion of a parked element reports as an error poll.
|
||||
///
|
||||
/// # Safety
|
||||
/// `dst` must be the claimed frame (or inline scratch when `frame_bytes` is
|
||||
/// 0) of a record whose element is `T` and whose frame size is `frame_bytes`,
|
||||
/// with every carried field already written.
|
||||
pub(in crate::record) unsafe fn lift_poll_into<'e, T: Send + Sync + dyn_any::StaticTypeSized>(
|
||||
poll: GPoll<T>,
|
||||
dst: *mut u8,
|
||||
frame_bytes: usize,
|
||||
arena: &'e crate::arena::Arena,
|
||||
) -> GPoll<RecordValue<'e>> {
|
||||
let build = |element: T| {
|
||||
let written = unsafe { write_element(dst, element, arena) };
|
||||
written.map(|()| match frame_bytes {
|
||||
0 => unsafe { dst.cast::<RecordValue>().read() },
|
||||
_ => RecordValue::spilled(unsafe { Rec::new(dst.cast_const()) }),
|
||||
})
|
||||
};
|
||||
let exhausted = || {
|
||||
GPoll::Error(Box::new(crate::gpoll::GraphError {
|
||||
kind: crate::gpoll::ErrorKind::ArenaExhausted,
|
||||
trace: Vec::new(),
|
||||
}))
|
||||
};
|
||||
match poll {
|
||||
GPoll::Final(element) => build(element).map_or_else(exhausted, GPoll::Final),
|
||||
GPoll::Partial(element) => build(element).map_or_else(exhausted, GPoll::Partial),
|
||||
GPoll::Fallback(boxed) => {
|
||||
let (element, error) = *boxed;
|
||||
build(element).map_or_else(exhausted, |value| GPoll::Fallback(Box::new((value, error))))
|
||||
}
|
||||
GPoll::Pending => GPoll::Pending,
|
||||
GPoll::Error(error) => GPoll::Error(error),
|
||||
}
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `src` must be a record of the plan's source layout and `dst` a buffer of
|
||||
/// the plan's target layout; both are proven at wiring. The two records must
|
||||
/// not overlap: a plan routinely carries identity moves, so each entry copies
|
||||
/// non-overlapping and an aliasing pair is undefined on the first copy.
|
||||
pub unsafe fn apply_plan(src: Rec<'_>, dst: *mut u8, plan: &[(usize, usize, usize)]) {
|
||||
for &(from, to, size) in plan {
|
||||
unsafe { std::ptr::copy_nonoverlapping(src.ptr().add(from), dst.add(to), size) };
|
||||
}
|
||||
}
|
||||
|
||||
/// The value with its lifetimes substituted by `'static`, for erased storage
|
||||
/// whose reads re-bind a live lifetime.
|
||||
///
|
||||
/// # Safety
|
||||
/// The erased value's borrows must not be used past their real lifetimes: the
|
||||
/// stored form may only be read through a surface that re-binds a lifetime no
|
||||
/// longer than the borrows' own, or after deep glue replaced every borrow with
|
||||
/// owned content.
|
||||
pub unsafe fn erase_static<T: dyn_any::StaticTypeSized>(value: T) -> T::Static {
|
||||
let value = std::mem::ManuallyDrop::new(value);
|
||||
// SAFETY: `Static` is `Self` with lifetimes substituted, layout-identical
|
||||
// by `StaticTypeSized`'s contract.
|
||||
unsafe { std::ptr::read((&raw const value).cast::<T::Static>()) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn elements_write_and_read_in_their_picked_form() {
|
||||
let arena = crate::arena::Arena::new(256).unwrap();
|
||||
|
||||
let mut inline = [0u64; 2];
|
||||
unsafe { write_element(inline.as_mut_ptr().cast(), 4.5f64, &arena) }.unwrap();
|
||||
let rec = unsafe { Rec::new(inline.as_ptr().cast()) };
|
||||
assert_eq!(unsafe { *borrow_element::<f64>(rec) }, 4.5);
|
||||
assert_eq!(unsafe { read_element::<f64>(rec) }, 4.5);
|
||||
|
||||
let mut parked = [0u64; 2];
|
||||
unsafe { write_element(parked.as_mut_ptr().cast(), String::from("moved once"), &arena) }.unwrap();
|
||||
let rec = unsafe { Rec::new(parked.as_ptr().cast()) };
|
||||
assert_eq!(unsafe { borrow_element::<String>(rec) }.as_str(), "moved once");
|
||||
assert_eq!(unsafe { read_element::<String>(rec) }, "moved once");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn record_values_are_one_word() {
|
||||
assert_eq!(size_of::<RecordValue>(), 8);
|
||||
assert_eq!(align_of::<RecordValue>(), 8);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
//! The evaluation's record frame storage.
|
||||
|
||||
use super::access::RecordValue;
|
||||
use super::layout::Layout;
|
||||
use super::serve::{FrameClaim, SlotRun};
|
||||
|
||||
/// The evaluation's record frame space: a grow-only buffer the executor owns
|
||||
/// and lends by `&mut`, sized by the wiring-derived frame need, so exhaustion
|
||||
/// is an accounting failure the debug assertion catches rather than a hot-path
|
||||
/// branch. Frame bytes carry no drop glue, so growth and reuse are plain
|
||||
/// buffer operations.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct FrameArena {
|
||||
buf: Vec<u64>,
|
||||
}
|
||||
|
||||
impl FrameArena {
|
||||
pub fn new() -> Self {
|
||||
Self { buf: Vec::new() }
|
||||
}
|
||||
|
||||
/// Grows the buffer to hold `bytes`, the root's wiring-derived frame need.
|
||||
/// Grow-only, so repeated evaluations reuse one allocation.
|
||||
pub fn reserve(&mut self, bytes: usize) {
|
||||
let words = bytes.div_ceil(8).max(1);
|
||||
if self.buf.len() < words {
|
||||
self.buf.resize(words, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// The whole buffer as free space, for one evaluation.
|
||||
pub fn frames(&mut self) -> Frames<'_> {
|
||||
let base = self.buf.as_mut_ptr().cast::<u8>();
|
||||
Frames {
|
||||
base: std::cell::Cell::new(base),
|
||||
words: std::cell::Cell::new(self.buf.len()),
|
||||
bounds: (base as usize, self.buf.len() * 8),
|
||||
_lifetime: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The free frame space at one point of an evaluation. [`Self::claim`] splits
|
||||
/// a node's own frame off the front and the claim carries the remainder, so a
|
||||
/// node's inputs claim beyond its frame, one after another, and the space they
|
||||
/// used is free again once the claim dies: the release is the claim's
|
||||
/// lifetime, not a rewind contract. The cursor is shared through `&self` so
|
||||
/// the lazy inputs a kernel holds claim beyond each other rather than over each
|
||||
/// other. Covariant in `'e`, so a claim minted at the evaluation shortens onto
|
||||
/// a derived context's arena lifetime.
|
||||
pub struct Frames<'e> {
|
||||
base: std::cell::Cell<*mut u8>,
|
||||
words: std::cell::Cell<usize>,
|
||||
/// The whole buffer as (address, bytes), which stays fixed while claims
|
||||
/// advance the cursor, so a promote can range-check a reference against it.
|
||||
bounds: (usize, usize),
|
||||
_lifetime: std::marker::PhantomData<&'e ()>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Frames<'_> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Frames").field("free_words", &self.words.get()).finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'e> Frames<'e> {
|
||||
/// An independent cursor over the same free space: claims made through it
|
||||
/// are free again when it dies, so a repeated evaluation reuses one region.
|
||||
/// Two live cursors hand out the same region, so only one may be claimed
|
||||
/// from at a time.
|
||||
pub fn reborrow(&self) -> Frames<'e> {
|
||||
Frames {
|
||||
base: std::cell::Cell::new(self.base.get()),
|
||||
words: std::cell::Cell::new(self.words.get()),
|
||||
bounds: self.bounds,
|
||||
_lifetime: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
/// The whole frame buffer as (address, bytes), the range a promote treats
|
||||
/// as evaluation-lived.
|
||||
pub fn bounds(&self) -> (usize, usize) {
|
||||
self.bounds
|
||||
}
|
||||
|
||||
/// Runs claims against this space and gives it back on the guard's drop, so
|
||||
/// a loop that evaluates a subtree per iteration reuses the same region.
|
||||
pub fn scope(&self) -> FrameScope<'_, 'e> {
|
||||
FrameScope {
|
||||
frames: self,
|
||||
base: self.base.get(),
|
||||
words: self.words.get(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The words still free, the observable the frame accounting asserts on.
|
||||
pub fn free_words(&self) -> usize {
|
||||
self.words.get()
|
||||
}
|
||||
|
||||
/// Claims `layout`'s frame at the front of the free space; the claim
|
||||
/// carries the remainder, and an inline layout's record builds in the
|
||||
/// claim itself.
|
||||
pub fn claim<'l>(&self, layout: &'l Layout) -> FrameClaim<'e, 'l> {
|
||||
let frame = match layout.frame_bytes() {
|
||||
0 => None,
|
||||
bytes => Some(self.split(bytes)),
|
||||
};
|
||||
FrameClaim {
|
||||
layout,
|
||||
inline: RecordValue::zeroed(),
|
||||
frame,
|
||||
free: self.reborrow(),
|
||||
filled_fields: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Splits `bytes` (rounded to word alignment) off the front.
|
||||
fn split(&self, bytes: usize) -> *mut u8 {
|
||||
let words = bytes.div_ceil(8);
|
||||
debug_assert!(words <= self.words.get(), "record frame space exhausted: the root buffer must cover the graph's frame need");
|
||||
let frame = self.base.get();
|
||||
// SAFETY: the buffer covers the wiring-derived need, so the advanced
|
||||
// cursor stays within it.
|
||||
self.base.set(unsafe { frame.add(words * 8) });
|
||||
self.words.set(self.words.get() - words);
|
||||
frame
|
||||
}
|
||||
|
||||
/// A run of same-layout slots over caller scratch: lanes serve in place,
|
||||
/// each backed by its own region of the slab, and the collected proofs
|
||||
/// certify the filled prefix. `None` where the scratch cannot hold `len`
|
||||
/// lanes.
|
||||
pub fn run<'a>(&self, scratch: &'a mut [std::mem::MaybeUninit<u64>], len: usize, layout: &'a Layout) -> Option<SlotRun<'a>> {
|
||||
SlotRun::new(scratch, len, layout)
|
||||
}
|
||||
}
|
||||
|
||||
/// See [`Frames::scope`]. A forgotten guard leaks its region until the frame
|
||||
/// space itself dies, rather than releasing it.
|
||||
pub struct FrameScope<'s, 'e> {
|
||||
frames: &'s Frames<'e>,
|
||||
base: *mut u8,
|
||||
words: usize,
|
||||
}
|
||||
|
||||
impl<'e> std::ops::Deref for FrameScope<'_, 'e> {
|
||||
type Target = Frames<'e>;
|
||||
|
||||
fn deref(&self) -> &Frames<'e> {
|
||||
self.frames
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for FrameScope<'_, '_> {
|
||||
fn drop(&mut self) {
|
||||
self.frames.base.set(self.base);
|
||||
self.frames.words.set(self.words);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::record::layout::element_write;
|
||||
use crate::record::test_support::f64_field;
|
||||
|
||||
#[test]
|
||||
fn a_scope_releases_and_reuses_its_frames() {
|
||||
let layout = Layout::default().with_writes(0, element_write::<f64>(), &[f64_field("opacity")]);
|
||||
let mut frame_arena = FrameArena::new();
|
||||
frame_arena.reserve(1 << 10);
|
||||
let frames = frame_arena.frames();
|
||||
let free = frames.free_words();
|
||||
let mut addresses = Vec::new();
|
||||
for _ in 0..3 {
|
||||
let scope = frames.scope();
|
||||
let mut claim = scope.claim(&layout);
|
||||
addresses.push(claim.dst() as usize);
|
||||
drop(scope);
|
||||
assert_eq!(frames.free_words(), free, "the scope returns its claims");
|
||||
}
|
||||
assert!(addresses.windows(2).all(|pair| pair[0] == pair[1]), "each claim reuses the same region");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,524 @@
|
||||
//! Consumer-side bindings onto a record input, and the drivers they run.
|
||||
|
||||
use super::access::{Rec, RecordValue, read_element};
|
||||
use super::frames::Frames;
|
||||
use super::layout::Layout;
|
||||
use super::serve::{FrameClaim, Served, serve_input};
|
||||
use crate::gpoll::GPoll;
|
||||
use crate::node::Node;
|
||||
|
||||
/// A record input evaluable at a derived context, yielding the record at that
|
||||
/// context's lifetime. The lifetime is a trait parameter because a bound like
|
||||
/// `for<'d> Node<Derived<'d, C>>` cannot also say the derived context's arena
|
||||
/// is at `'d`: the equality binding `ExtractArena<ArenaRef = &'d Arena>` is an
|
||||
/// unconstrained position under a higher rank.
|
||||
pub trait DerivedRecordInput<'derived, C> {
|
||||
fn eval_derived(&self, cell: &crate::node::StatusCell, input_index: usize, ctx: &C, frames: &Frames<'derived>) -> Result<RecordValue<'derived>, crate::gpoll::Interrupt>;
|
||||
fn extent_at_derived(&self, ctx: &C, level: u8, frames: &Frames<'derived>) -> GPoll<crate::gpoll::Extent>;
|
||||
}
|
||||
|
||||
impl<'derived, C, N> DerivedRecordInput<'derived, C> for N
|
||||
where
|
||||
N: Node<C>,
|
||||
C: crate::context::ExtractArena<ArenaRef = &'derived crate::arena::Arena>,
|
||||
{
|
||||
fn eval_derived(&self, cell: &crate::node::StatusCell, input_index: usize, ctx: &C, frames: &Frames<'derived>) -> Result<RecordValue<'derived>, crate::gpoll::Interrupt> {
|
||||
cell.eval_input(input_index, self, ctx, frames)
|
||||
}
|
||||
|
||||
fn extent_at_derived(&self, ctx: &C, level: u8, frames: &Frames<'derived>) -> GPoll<crate::gpoll::Extent> {
|
||||
self.extent_at(ctx, level, frames)
|
||||
}
|
||||
}
|
||||
|
||||
/// Fills caller scratch with one frame per lane of `range`: the input serves
|
||||
/// into the lane's own region of the slab, and the lane's own frame space is
|
||||
/// free again at the next lane, so the frame peak stays at one lane's need and
|
||||
/// every lane's bytes are distinct.
|
||||
pub fn fill_frames<'a, 'e, C, N>(node: &'a N, input: &C, range: std::ops::Range<u64>, scratch: Option<&'a mut [std::mem::MaybeUninit<u64>]>, frames: &Frames<'e>) -> crate::node::BatchStatus<'a>
|
||||
where
|
||||
C: crate::context::InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||
N: Node<C>,
|
||||
{
|
||||
use crate::node::BatchStatus;
|
||||
let Some(scratch) = scratch else {
|
||||
return BatchStatus::NeedBuffer;
|
||||
};
|
||||
let Some(len) = range.end.checked_sub(range.start).and_then(|len| usize::try_from(len).ok()) else {
|
||||
return BatchStatus::InvalidRange;
|
||||
};
|
||||
let Some(mut run) = frames.run(scratch, len, node.layout()) else {
|
||||
return BatchStatus::InvalidRange;
|
||||
};
|
||||
let mut local = *input;
|
||||
let mut finality = crate::gpoll::Finality::AllFinal;
|
||||
let mut hint = crate::gpoll::Extent::AtLeast(range.end as usize);
|
||||
for lane in 0..len {
|
||||
local.set_index(range.start + lane as u64);
|
||||
let lane_frames = frames.scope();
|
||||
let slot = run.slot(lane, &lane_frames);
|
||||
let served = match node.serve(&local, slot) {
|
||||
GPoll::Final(served) => served,
|
||||
GPoll::Partial(served) => {
|
||||
finality = crate::gpoll::Finality::Partial;
|
||||
served
|
||||
}
|
||||
GPoll::Pending => return BatchStatus::Pending,
|
||||
GPoll::Fallback(boxed) => return BatchStatus::Error(boxed.1),
|
||||
// A lane past a lower-bound level ends the data: the fill comes
|
||||
// back short and the hint turns exact.
|
||||
GPoll::Error(error) if error.kind == crate::gpoll::ErrorKind::PastEnd => {
|
||||
hint = crate::gpoll::Extent::Exactly(range.start as usize + lane);
|
||||
break;
|
||||
}
|
||||
GPoll::Error(error) => return BatchStatus::Error(*error),
|
||||
};
|
||||
run.served(lane, &served);
|
||||
}
|
||||
BatchStatus::Filled(run.finish(), finality, hint)
|
||||
}
|
||||
|
||||
/// The driver a consumer runs on a record input: a resident batch returns with
|
||||
/// no allocation, a node's own batch impl gets `n * frame_bytes` of arena
|
||||
/// scratch, and an unbatched input falls back to the [`fill_frames`] loop.
|
||||
pub fn materialize_batch<'a, 'e, C, N>(node: &'a N, input: &'a C, range: std::ops::Range<u64>, arena: &'a crate::arena::Arena, frames: &Frames<'e>) -> crate::node::BatchStatus<'a>
|
||||
where
|
||||
C: crate::context::InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||
N: Node<C>,
|
||||
{
|
||||
use crate::node::BatchStatus;
|
||||
let Some(len) = range.end.checked_sub(range.start).and_then(|len| usize::try_from(len).ok()) else {
|
||||
return BatchStatus::InvalidRange;
|
||||
};
|
||||
// Checked: a wrapped product would size the scratch below the run.
|
||||
let Some(words) = len.checked_mul(node.layout().lane_stride()).map(|bytes| bytes / 8) else {
|
||||
return BatchStatus::InvalidRange;
|
||||
};
|
||||
let exhausted = || {
|
||||
BatchStatus::Error(crate::gpoll::GraphError {
|
||||
kind: crate::gpoll::ErrorKind::ArenaExhausted,
|
||||
trace: Vec::new(),
|
||||
})
|
||||
};
|
||||
match node.eval_batch(input, range.clone(), None, frames) {
|
||||
BatchStatus::Unbatched => match arena.alloc_scratch::<u64>(words) {
|
||||
Some(scratch) => fill_frames(node, input, range, Some(scratch), frames),
|
||||
None => exhausted(),
|
||||
},
|
||||
BatchStatus::NeedBuffer => match arena.alloc_scratch::<u64>(words) {
|
||||
Some(scratch) => node.eval_batch(input, range, Some(scratch), frames),
|
||||
None => exhausted(),
|
||||
},
|
||||
status => status,
|
||||
}
|
||||
}
|
||||
|
||||
/// The outcome of materializing a leveled input's whole flat span.
|
||||
pub enum LevelStatus<'a> {
|
||||
Batch(crate::node::RecordBatch<'a>, crate::gpoll::Finality),
|
||||
Pending,
|
||||
Error(crate::gpoll::GraphError),
|
||||
}
|
||||
|
||||
/// Evaluates a leveled input's whole flat span into one batch: an exact total
|
||||
/// fills once, a lower bound drains by guess-and-double until a short fill,
|
||||
/// each reply's hint seeding the next guess. The boundary consumers' driver;
|
||||
/// reducers inline the same protocol with their span offsets.
|
||||
pub fn materialize_level<'a, 'e, C, N>(node: &'a N, input: &'a C, arena: &'a crate::arena::Arena, frames: &Frames<'e>) -> LevelStatus<'a>
|
||||
where
|
||||
C: crate::context::InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||
N: Node<C>,
|
||||
{
|
||||
use crate::gpoll::{Extent, GraphError, Level};
|
||||
use crate::node::BatchStatus;
|
||||
let sized = match node.extent(input, Level::Total, frames) {
|
||||
GPoll::Final(Extent::Exactly(count)) => Ok(count),
|
||||
GPoll::Final(Extent::AtLeast(bound)) => Err(bound),
|
||||
GPoll::Pending => return LevelStatus::Pending,
|
||||
_ => return LevelStatus::Error(GraphError::new("materialize over a non-exact extent")),
|
||||
};
|
||||
match sized {
|
||||
Ok(count) => match materialize_batch(node, input, 0..count as u64, arena, frames) {
|
||||
BatchStatus::Lent(batch, finality, _) => LevelStatus::Batch(batch, finality),
|
||||
BatchStatus::Filled(batch, finality, _) => LevelStatus::Batch(batch.into_shared(), finality),
|
||||
BatchStatus::Pending => LevelStatus::Pending,
|
||||
BatchStatus::Error(error) => LevelStatus::Error(error),
|
||||
_ => LevelStatus::Error(GraphError::new("materialize batch failed")),
|
||||
},
|
||||
Err(bound) => {
|
||||
let mut guess = bound.max(16);
|
||||
loop {
|
||||
let (batch, finality, hint) = match materialize_batch(node, input, 0..guess as u64, arena, frames) {
|
||||
BatchStatus::Lent(batch, finality, hint) => (batch, finality, hint),
|
||||
BatchStatus::Filled(batch, finality, hint) => (batch.into_shared(), finality, hint),
|
||||
BatchStatus::Pending => return LevelStatus::Pending,
|
||||
BatchStatus::Error(error) => return LevelStatus::Error(error),
|
||||
_ => return LevelStatus::Error(GraphError::new("materialize batch failed")),
|
||||
};
|
||||
let filled = batch.len();
|
||||
if filled < guess {
|
||||
break LevelStatus::Batch(batch, finality);
|
||||
}
|
||||
match hint {
|
||||
Extent::Exactly(total) if total <= filled => break LevelStatus::Batch(batch, finality),
|
||||
Extent::Exactly(total) => guess = total,
|
||||
Extent::AtLeast(more) => guess = (guess * 2).max(more),
|
||||
Extent::Free => guess *= 2,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The raw lazy record input handed to a record-opaque kernel: the input plus
|
||||
/// its wiring-proven layout, the pairing the kernel's unsafe record
|
||||
/// operations rely on. The kernel must only pair the layout with values this
|
||||
/// input produced.
|
||||
pub struct RecordInput<'a, 'e, N> {
|
||||
node: &'a N,
|
||||
layout: &'a Layout,
|
||||
frames: &'a Frames<'e>,
|
||||
}
|
||||
|
||||
impl<'a, 'e, N> RecordInput<'a, 'e, N> {
|
||||
pub fn new(node: &'a N, layout: &'a Layout, frames: &'a Frames<'e>) -> Self {
|
||||
Self { node, layout, frames }
|
||||
}
|
||||
|
||||
pub fn layout(&self) -> &Layout {
|
||||
self.layout
|
||||
}
|
||||
|
||||
/// Serves the input through the kernel's own claim: the kernel's output
|
||||
/// layout is the input's, so the claim it was handed is the input's frame.
|
||||
pub fn serve<'l, C>(&self, ctx: &C, slot: FrameClaim<'e, 'l>) -> GPoll<Served<'e>>
|
||||
where
|
||||
N: Node<C>,
|
||||
C: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||
{
|
||||
self.node.serve(ctx, slot)
|
||||
}
|
||||
|
||||
/// [`materialize_level`] over the input: the input's whole flat span as one
|
||||
/// batch.
|
||||
pub fn materialize_level<'b, C>(&'b self, ctx: &'b C, arena: &'b crate::arena::Arena) -> LevelStatus<'b>
|
||||
where
|
||||
N: Node<C>,
|
||||
C: crate::context::InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||
{
|
||||
materialize_level(self.node, ctx, arena, self.frames)
|
||||
}
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `rec` must be a record of the layout the offsets were resolved against
|
||||
/// and `El` its element type; both are proven at wiring.
|
||||
unsafe fn element_only<El: Clone>(rec: Rec<'_>, _reads: &[Option<usize>]) -> El {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { read_element::<El>(rec) }
|
||||
}
|
||||
|
||||
/// The raw lazy input handed to a poll kernel whose input rides records while
|
||||
/// the kernel consumes the plain element.
|
||||
pub struct ElementInput<'a, 'e, Out, N> {
|
||||
node: &'a N,
|
||||
layout: &'a Layout,
|
||||
reads: &'a [Option<usize>],
|
||||
read: unsafe fn(Rec<'_>, &[Option<usize>]) -> Out,
|
||||
frames: &'a Frames<'e>,
|
||||
}
|
||||
|
||||
impl<'a, 'e, El: Clone, N> ElementInput<'a, 'e, El, N> {
|
||||
pub fn new(node: &'a N, layout: &'a Layout, frames: &'a Frames<'e>) -> Self {
|
||||
Self {
|
||||
node,
|
||||
layout,
|
||||
reads: &[],
|
||||
read: element_only::<El>,
|
||||
frames,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, 'e, Out, N> ElementInput<'a, 'e, Out, N> {
|
||||
/// `read` must be sound against the layout the offsets in `reads` were
|
||||
/// resolved from; the macro proves both at wiring.
|
||||
pub fn with_reads(node: &'a N, layout: &'a Layout, reads: &'a [Option<usize>], read: unsafe fn(Rec<'_>, &[Option<usize>]) -> Out, frames: &'a Frames<'e>) -> Self {
|
||||
Self { node, layout, reads, read, frames }
|
||||
}
|
||||
|
||||
/// The input's element at `ctx`, read out of a record claimed beyond the
|
||||
/// kernel's own frame; the claim dies with the call, so the record is free
|
||||
/// again at the next one.
|
||||
pub fn eval<'d, C>(&self, ctx: &C) -> GPoll<Out>
|
||||
where
|
||||
N: DerivedRecordInput<'d, C>,
|
||||
'e: 'd,
|
||||
{
|
||||
let cell = crate::node::StatusCell::new();
|
||||
let scope = self.frames.scope();
|
||||
match self.node.eval_derived(&cell, 0, ctx, &scope) {
|
||||
// SAFETY: the read copies out by value against the input's own layout.
|
||||
Ok(value) => cell.finish(unsafe { (self.read)(self.layout.rec(&value), self.reads) }),
|
||||
Err(interrupt) => interrupt.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The lazy input handed to a kernel whose input rides a record while
|
||||
/// the kernel consumes the plain element, or the element beside its declared
|
||||
/// attribute reads.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct ElementLazyInput<'a, 'e, Out, N> {
|
||||
node: &'a N,
|
||||
cell: &'a crate::node::StatusCell,
|
||||
input_index: usize,
|
||||
layout: &'a Layout,
|
||||
reads: &'a [Option<usize>],
|
||||
read: unsafe fn(Rec<'_>, &[Option<usize>]) -> Out,
|
||||
frames: &'a Frames<'e>,
|
||||
}
|
||||
|
||||
impl<'a, 'e, El: Clone, N> ElementLazyInput<'a, 'e, El, N> {
|
||||
pub fn new(node: &'a N, cell: &'a crate::node::StatusCell, input_index: usize, layout: &'a Layout, frames: &'a Frames<'e>) -> Self {
|
||||
Self {
|
||||
node,
|
||||
cell,
|
||||
input_index,
|
||||
layout,
|
||||
reads: &[],
|
||||
read: element_only::<El>,
|
||||
frames,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, 'e, Out, N> ElementLazyInput<'a, 'e, Out, N> {
|
||||
/// `read` must be sound against the layout the offsets in `reads` were
|
||||
/// resolved from; the macro proves both at wiring.
|
||||
pub fn with_reads(
|
||||
node: &'a N,
|
||||
cell: &'a crate::node::StatusCell,
|
||||
input_index: usize,
|
||||
layout: &'a Layout,
|
||||
reads: &'a [Option<usize>],
|
||||
read: unsafe fn(Rec<'_>, &[Option<usize>]) -> Out,
|
||||
frames: &'a Frames<'e>,
|
||||
) -> Self {
|
||||
Self {
|
||||
node,
|
||||
cell,
|
||||
input_index,
|
||||
layout,
|
||||
reads,
|
||||
read,
|
||||
frames,
|
||||
}
|
||||
}
|
||||
|
||||
/// The read copies the element and declared attributes out by value, so
|
||||
/// the record's claim dies with the call.
|
||||
pub fn eval<'d, C>(&self, ctx: &C) -> Result<Out, crate::gpoll::Interrupt>
|
||||
where
|
||||
N: DerivedRecordInput<'d, C>,
|
||||
'e: 'd,
|
||||
{
|
||||
let scope = self.frames.scope();
|
||||
let value = self.node.eval_derived(self.cell, self.input_index, ctx, &scope)?;
|
||||
// SAFETY: the reads are the input's own layout's, resolved at wiring.
|
||||
Ok(unsafe { (self.read)(self.layout.rec(&value), self.reads) })
|
||||
}
|
||||
}
|
||||
|
||||
/// The lazy record input handed to a kernel that evaluates its inputs under
|
||||
/// derived contexts: evaluating rebinds the record to the kernel's routing
|
||||
/// lifetime, so the value escapes the derivation scope.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct RecordLazyInput<'a, 'e, N> {
|
||||
node: &'a N,
|
||||
cell: &'a crate::node::StatusCell,
|
||||
input_index: usize,
|
||||
inner_levels: u8,
|
||||
frames: &'a Frames<'e>,
|
||||
}
|
||||
|
||||
impl<'a, 'e, N> RecordLazyInput<'a, 'e, N> {
|
||||
pub fn new(node: &'a N, cell: &'a crate::node::StatusCell, input_index: usize, inner_levels: u8, frames: &'a Frames<'e>) -> Self {
|
||||
Self {
|
||||
node,
|
||||
cell,
|
||||
input_index,
|
||||
inner_levels,
|
||||
frames,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn eval<'d, C>(&self, ctx: &C) -> Result<RecordValue<'e>, crate::gpoll::Interrupt>
|
||||
where
|
||||
N: DerivedRecordInput<'d, C>,
|
||||
'e: 'd,
|
||||
{
|
||||
Ok(self.node.eval_derived(self.cell, self.input_index, ctx, self.frames)?.rebind())
|
||||
}
|
||||
|
||||
/// The flat lane count of one copy: the product of the input's inner-level
|
||||
/// extents, queried uniform across copies (at copy 0). The dividend of a
|
||||
/// structure node's decompose-and-promote.
|
||||
pub fn inner_extent<B>(&self, ctx: &B) -> Result<u64, crate::gpoll::Interrupt>
|
||||
where
|
||||
B: crate::context::DeriveCtx,
|
||||
N: for<'d> DerivedRecordInput<'d, crate::context::Derived<'d, B>>,
|
||||
{
|
||||
inner_extent_of(self.node, ctx, 0, self.inner_levels, self.input_index, self.frames)
|
||||
}
|
||||
|
||||
/// The flat lane count of the copy at `copy`, for inputs whose inner
|
||||
/// extents vary per copy.
|
||||
pub fn inner_extent_at<B>(&self, ctx: &B, copy: u64) -> Result<u64, crate::gpoll::Interrupt>
|
||||
where
|
||||
B: crate::context::DeriveCtx,
|
||||
N: for<'d> DerivedRecordInput<'d, crate::context::Derived<'d, B>>,
|
||||
{
|
||||
inner_extent_of(self.node, ctx, copy, self.inner_levels, self.input_index, self.frames)
|
||||
}
|
||||
}
|
||||
|
||||
/// See [`RecordLazyInput::inner_extent`].
|
||||
fn inner_extent_of<B, N>(node: &N, ctx: &B, copy: u64, levels: u8, input_index: usize, frames: &Frames<'_>) -> Result<u64, crate::gpoll::Interrupt>
|
||||
where
|
||||
B: crate::context::DeriveCtx,
|
||||
N: for<'d> DerivedRecordInput<'d, crate::context::Derived<'d, B>>,
|
||||
{
|
||||
let mut frame = crate::context::IndexLink { index: 0, outer: None };
|
||||
let derived = ctx.push_level(&mut frame, copy, 0);
|
||||
let mut inner: u64 = 1;
|
||||
for level in 0..levels {
|
||||
match node.extent_at_derived(&derived, level, frames) {
|
||||
GPoll::Final(crate::gpoll::Extent::Exactly(count)) => inner *= count as u64,
|
||||
GPoll::Final(crate::gpoll::Extent::AtLeast(_)) => return probed_inner(node, ctx, copy, input_index, frames),
|
||||
GPoll::Pending => return Err(crate::gpoll::Interrupt::Pending),
|
||||
_ => return Err(crate::gpoll::GraphError::new("structure decomposition over a non-exact extent").into()),
|
||||
}
|
||||
}
|
||||
Ok(inner)
|
||||
}
|
||||
|
||||
/// The flat lane count of one copy of a lower-bound input, probed by
|
||||
/// evaluating lanes to the past-end signal. The probed records are
|
||||
/// discarded, and their statuses land in a scratch cell.
|
||||
fn probed_inner<B, N>(node: &N, ctx: &B, copy: u64, input_index: usize, frames: &Frames<'_>) -> Result<u64, crate::gpoll::Interrupt>
|
||||
where
|
||||
B: crate::context::DeriveCtx,
|
||||
N: for<'d> DerivedRecordInput<'d, crate::context::Derived<'d, B>>,
|
||||
{
|
||||
let cell = crate::node::StatusCell::new();
|
||||
let mut count: u64 = 0;
|
||||
loop {
|
||||
// The probed record is discarded, so the probe's claim is free again
|
||||
// at the next iteration.
|
||||
let probe_frames = frames.scope();
|
||||
let mut frame = crate::context::IndexLink { index: 0, outer: None };
|
||||
let probe = ctx.push_level(&mut frame, copy, count);
|
||||
let result = node.eval_derived(&cell, input_index, &probe, &probe_frames);
|
||||
match result {
|
||||
Ok(_) => count += 1,
|
||||
Err(crate::gpoll::Interrupt::Error(error)) if error.kind == crate::gpoll::ErrorKind::PastEnd => return Ok(count),
|
||||
Err(interrupt) => return Err(interrupt),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The derive-routing carrier beside its declared attribute reads: evaluating
|
||||
/// at a derived context yields the opaque row token and the read values in one
|
||||
/// step, so the kernel drives the per-copy eval while reads stay resolved
|
||||
/// against the source's wired layout.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct DerivedLazyInput<'a, 'e, Out, N> {
|
||||
node: &'a N,
|
||||
cell: &'a crate::node::StatusCell,
|
||||
input_index: usize,
|
||||
inner_levels: u8,
|
||||
reads: &'a [Option<usize>],
|
||||
read: unsafe fn(Rec<'_>, &[Option<usize>]) -> Out,
|
||||
frames: &'a Frames<'e>,
|
||||
}
|
||||
|
||||
impl<'a, 'e, Out, N> DerivedLazyInput<'a, 'e, Out, N> {
|
||||
/// `read` must be sound against the layout the offsets in `reads` were
|
||||
/// resolved from; the macro proves both at wiring.
|
||||
pub fn new(
|
||||
node: &'a N,
|
||||
cell: &'a crate::node::StatusCell,
|
||||
input_index: usize,
|
||||
inner_levels: u8,
|
||||
reads: &'a [Option<usize>],
|
||||
read: unsafe fn(Rec<'_>, &[Option<usize>]) -> Out,
|
||||
frames: &'a Frames<'e>,
|
||||
) -> Self {
|
||||
Self {
|
||||
node,
|
||||
cell,
|
||||
input_index,
|
||||
inner_levels,
|
||||
reads,
|
||||
read,
|
||||
frames,
|
||||
}
|
||||
}
|
||||
|
||||
/// The flat lane count of one copy; see [`RecordLazyInput::inner_extent`].
|
||||
pub fn inner_extent<B>(&self, ctx: &B) -> Result<u64, crate::gpoll::Interrupt>
|
||||
where
|
||||
B: crate::context::DeriveCtx,
|
||||
N: for<'d> DerivedRecordInput<'d, crate::context::Derived<'d, B>>,
|
||||
{
|
||||
inner_extent_of(self.node, ctx, 0, self.inner_levels, self.input_index, self.frames)
|
||||
}
|
||||
|
||||
pub fn eval<'d, C>(&self, ctx: &C) -> Result<Out, crate::gpoll::Interrupt>
|
||||
where
|
||||
N: DerivedRecordInput<'d, C>,
|
||||
'e: 'd,
|
||||
{
|
||||
let value: RecordValue<'e> = self.node.eval_derived(self.cell, self.input_index, ctx, self.frames)?.rebind();
|
||||
// SAFETY: declared reads imply a non-empty layout, so the record is
|
||||
// spilled and its pointer is the frame the offsets index into.
|
||||
Ok(unsafe { (self.read)(Rec::new(value.ptr), self.reads) })
|
||||
}
|
||||
}
|
||||
|
||||
/// A plain probe over a record input, cloning the element out of the parked
|
||||
/// reference when it carries drop glue. Registry constructors wrap a record
|
||||
/// input in one to feed a node's plain value input, keeping the input kind
|
||||
/// uniform.
|
||||
pub struct RecordExtract<El, N> {
|
||||
edge: N,
|
||||
layout: Layout,
|
||||
_marker: std::marker::PhantomData<fn() -> El>,
|
||||
}
|
||||
|
||||
impl<El, N> RecordExtract<El, N> {
|
||||
pub fn new(edge: N, layout: &Layout) -> Self {
|
||||
Self {
|
||||
edge,
|
||||
layout: layout.clone(),
|
||||
_marker: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<El: Clone + 'static, N> RecordExtract<El, N> {
|
||||
/// The input's element, copied out of its record.
|
||||
pub fn eval<'e, C>(&self, input: &C, frames: &Frames<'e>) -> GPoll<El>
|
||||
where
|
||||
N: Node<C>,
|
||||
C: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||
{
|
||||
// The element copies out by value, so the input's claim dies with
|
||||
// the scope.
|
||||
let scope = frames.scope();
|
||||
// SAFETY: the served value is a record of `self.layout`, whose element is
|
||||
// `El` by the wiring that built this extract.
|
||||
serve_input(&self.edge, input, &scope).map(|value| unsafe { read_element::<El>(self.layout.rec(&value)) })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,882 @@
|
||||
//! Wiring-time shape facts: the layout a record takes and the writes it folds from.
|
||||
|
||||
use super::access::{Rec, RecordValue, borrow_element, erase_static, read_element, write_element_keyed};
|
||||
use super::owned::deep_element_glue;
|
||||
use super::promote::{Promotion, retained_measure};
|
||||
use crate::attribute;
|
||||
|
||||
/// A field write declared at wiring, carrying the marker's erased-read glue
|
||||
/// so introspection and persistence never consult the census at runtime.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct FieldWrite {
|
||||
pub name: &'static str,
|
||||
pub level: u8,
|
||||
pub size: usize,
|
||||
pub align: usize,
|
||||
pub type_id: std::any::TypeId,
|
||||
pub read_erased: unsafe fn(*const u8) -> Box<dyn crate::list::AnyAttributeValue>,
|
||||
pub repark: Option<crate::list::ReparkFn>,
|
||||
/// Hashes the field's content. `None` means the stored bytes are the
|
||||
/// content, which holds for every unparked value.
|
||||
pub content_hash: Option<unsafe fn(*const u8, &mut dyn core::hash::Hasher)>,
|
||||
/// Compares two fields' content. `None` as for `content_hash`.
|
||||
pub content_eq: Option<unsafe fn(*const u8, *const u8) -> bool>,
|
||||
}
|
||||
|
||||
impl FieldWrite {
|
||||
pub fn of<A: crate::attribute::Attribute>(level: u8) -> Self
|
||||
where
|
||||
A::Value<'static>: graphene_hash::CacheHash + PartialEq + 'static,
|
||||
{
|
||||
/// # Safety
|
||||
/// `ptr` must address a live `V`.
|
||||
unsafe fn content_hash<V: graphene_hash::CacheHash>(ptr: *const u8, state: &mut dyn core::hash::Hasher) {
|
||||
let mut state = state;
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { &*ptr.cast::<V>() }.cache_hash(&mut state);
|
||||
}
|
||||
/// # Safety
|
||||
/// `a` and `b` must both address a live `V`.
|
||||
unsafe fn content_eq<V: PartialEq>(a: *const u8, b: *const u8) -> bool {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { *a.cast::<V>() == *b.cast::<V>() }
|
||||
}
|
||||
Self {
|
||||
name: A::NAME,
|
||||
level,
|
||||
size: size_of::<A::Value<'static>>(),
|
||||
align: align_of::<A::Value<'static>>(),
|
||||
type_id: std::any::TypeId::of::<A::Value<'static>>(),
|
||||
read_erased: A::read_erased,
|
||||
repark: A::REPARK,
|
||||
content_hash: Some(content_hash::<A::Value<'static>>),
|
||||
content_eq: Some(content_eq::<A::Value<'static>>),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One field of a [`Layout`]: a (name, level) key resolved to an offset.
|
||||
/// Levels are numbered innermost-out; only level 0 exists at rank 0.
|
||||
/// Equality is structural over the field's identity, its value type
|
||||
/// included; only the glue pointers are excluded, since fn-pointer identity
|
||||
/// is not guaranteed across codegen units and layout equality drives
|
||||
/// identity forwarding.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct FieldDesc {
|
||||
pub name: &'static str,
|
||||
pub level: u8,
|
||||
pub offset: usize,
|
||||
pub size: usize,
|
||||
pub align: usize,
|
||||
pub type_id: std::any::TypeId,
|
||||
pub read_erased: unsafe fn(*const u8) -> Box<dyn crate::list::AnyAttributeValue>,
|
||||
pub repark: Option<crate::list::ReparkFn>,
|
||||
/// Hashes the field's content. `None` means the stored bytes are the
|
||||
/// content, which holds for every unparked value.
|
||||
pub content_hash: Option<unsafe fn(*const u8, &mut dyn core::hash::Hasher)>,
|
||||
/// Compares two fields' content. `None` as for `content_hash`.
|
||||
pub content_eq: Option<unsafe fn(*const u8, *const u8) -> bool>,
|
||||
}
|
||||
|
||||
impl PartialEq for FieldDesc {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
(self.name, self.level, self.offset, self.size, self.align, self.type_id) == (other.name, other.level, other.offset, other.size, other.align, other.type_id)
|
||||
}
|
||||
}
|
||||
|
||||
impl FieldDesc {
|
||||
/// The write this field re-declares when a layout's fields fold into
|
||||
/// another layout.
|
||||
pub fn as_write(&self) -> FieldWrite {
|
||||
FieldWrite {
|
||||
name: self.name,
|
||||
level: self.level,
|
||||
size: self.size,
|
||||
align: self.align,
|
||||
type_id: self.type_id,
|
||||
read_erased: self.read_erased,
|
||||
repark: self.repark,
|
||||
content_hash: self.content_hash,
|
||||
content_eq: self.content_eq,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for FieldDesc {}
|
||||
|
||||
/// The element slot of a layout: its dimensions plus erased glue bound where
|
||||
/// the element type is statically known, so generic consumers read or
|
||||
/// deep-copy the element without it. Equality is structural over the
|
||||
/// element's identity, its type included; glue pointers are excluded for the
|
||||
/// same reason as [`FieldDesc`]'s.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct ElementWrite {
|
||||
pub size: usize,
|
||||
pub align: usize,
|
||||
pub parked: bool,
|
||||
pub type_id: std::any::TypeId,
|
||||
pub clone_out: unsafe fn(*const u8) -> Box<dyn std::any::Any + Send + Sync>,
|
||||
pub repark: unsafe fn(&(dyn std::any::Any + Send + Sync), *mut u8, &crate::arena::Arena) -> Option<()>,
|
||||
/// Moves a parked payload's header into the persistent region rather than
|
||||
/// cloning the heap it owns, returning the new header. `None` declines,
|
||||
/// which leaves the caller its clone path.
|
||||
pub park_move: unsafe fn(*const u8, &Promotion<'_>) -> Option<*const u8>,
|
||||
/// Hashes the element's content. `None` means the stored bytes are the
|
||||
/// content, which holds for every unparked element.
|
||||
pub content_hash: Option<unsafe fn(*const u8, &mut dyn core::hash::Hasher)>,
|
||||
/// Compares two elements' content. `None` as for `content_hash`.
|
||||
pub content_eq: Option<unsafe fn(*const u8, *const u8) -> bool>,
|
||||
}
|
||||
|
||||
impl PartialEq for ElementWrite {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
(self.size, self.align, self.parked, self.type_id) == (other.size, other.align, other.parked, other.type_id)
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for ElementWrite {}
|
||||
|
||||
impl Default for ElementWrite {
|
||||
fn default() -> Self {
|
||||
/// # Safety
|
||||
/// None: the empty element has no bytes, so nothing is read.
|
||||
unsafe fn clone_out(_ptr: *const u8) -> Box<dyn std::any::Any + Send + Sync> {
|
||||
Box::new(())
|
||||
}
|
||||
/// # Safety
|
||||
/// None: nothing is written, the empty element having no slot.
|
||||
unsafe fn repark(_value: &(dyn std::any::Any + Send + Sync), _dst: *mut u8, _arena: &crate::arena::Arena) -> Option<()> {
|
||||
Some(())
|
||||
}
|
||||
/// # Safety
|
||||
/// None: the move always declines, so `parked` is never read.
|
||||
unsafe fn park_move(_parked: *const u8, _promotion: &Promotion<'_>) -> Option<*const u8> {
|
||||
None
|
||||
}
|
||||
Self {
|
||||
size: 0,
|
||||
align: 0,
|
||||
parked: false,
|
||||
type_id: std::any::TypeId::of::<()>(),
|
||||
clone_out,
|
||||
repark,
|
||||
park_move,
|
||||
content_hash: None,
|
||||
content_eq: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The widest alignment a record may need. Frames are a `Vec<u64>`, lanes
|
||||
/// stride at a multiple of 8, and run slabs come from `alloc_scratch::<u64>`,
|
||||
/// so nothing below a record can promise more.
|
||||
pub const MAX_ALIGN: usize = 8;
|
||||
|
||||
/// A record layout: the element at offset 0, then the written attributes in
|
||||
/// canonical order (descending alignment, then size, then name, then level).
|
||||
/// Layouts are derived data, a pure function of the upstream write set.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Layout {
|
||||
pub depth: u8,
|
||||
pub element: ElementWrite,
|
||||
pub fields: Vec<FieldDesc>,
|
||||
pub size: usize,
|
||||
pub align: usize,
|
||||
}
|
||||
|
||||
impl Layout {
|
||||
pub fn offset_of(&self, name: &str, level: u8) -> Option<usize> {
|
||||
self.fields.iter().find(|field| field.name == name && field.level == level).map(|field| field.offset)
|
||||
}
|
||||
|
||||
pub fn frame_bytes(&self) -> usize {
|
||||
self.size.next_multiple_of(8)
|
||||
}
|
||||
|
||||
/// One batch lane's stride: a spilled record's frame, or the value itself
|
||||
/// for records this layout keeps inline (`size == 0`), whose payload rides
|
||||
/// in the `RecordValue`'s own storage exactly as [`Layout::rec`] resolves.
|
||||
pub fn lane_stride(&self) -> usize {
|
||||
match self.size == 0 {
|
||||
true => size_of::<RecordValue<'static>>(),
|
||||
false => self.frame_bytes(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves a value of this layout, which must be its wiring-proven one,
|
||||
/// to its record bytes. An empty record carries nothing and resolves to the
|
||||
/// value's own storage; every other record spills and rides the pointer.
|
||||
pub fn rec<'v>(&self, value: &'v RecordValue<'_>) -> Rec<'v> {
|
||||
match self.size == 0 {
|
||||
true => Rec((&raw const *value).cast(), std::marker::PhantomData),
|
||||
false => Rec(value.ptr, std::marker::PhantomData),
|
||||
}
|
||||
}
|
||||
|
||||
/// The union of this layout's fields and `writes` over `element` at
|
||||
/// `depth`, in canonical order. A (name, level) written at a different
|
||||
/// size is a type conflict and panics, as does an element or attribute
|
||||
/// wider than [`MAX_ALIGN`]; the census keeps declared names to one type,
|
||||
/// so these only fire on wiring bugs.
|
||||
pub fn with_writes(&self, depth: u8, element: ElementWrite, writes: &[FieldWrite]) -> Layout {
|
||||
let mut merged: Vec<FieldWrite> = self.fields.iter().map(FieldDesc::as_write).collect();
|
||||
for &write in writes {
|
||||
match merged.iter().find(|field| field.name == write.name && field.level == write.level) {
|
||||
Some(existing) => assert_eq!(existing.type_id, write.type_id, "attribute `{}` written at two different types", write.name),
|
||||
None => merged.push(write),
|
||||
}
|
||||
}
|
||||
assert!(element.align <= MAX_ALIGN, "a record element aligns to at most {MAX_ALIGN} bytes, but this one needs {}", element.align);
|
||||
for write in &merged {
|
||||
assert!(write.align <= MAX_ALIGN, "attribute `{}` aligns to at most {MAX_ALIGN} bytes, but needs {}", write.name, write.align);
|
||||
}
|
||||
merged.sort_by(|a, b| b.align.cmp(&a.align).then(b.size.cmp(&a.size)).then(a.name.cmp(b.name)).then(a.level.cmp(&b.level)));
|
||||
let mut offset = element.size;
|
||||
let mut align = element.align.max(1);
|
||||
let fields = merged
|
||||
.into_iter()
|
||||
.map(|write| {
|
||||
offset = offset.next_multiple_of(write.align.max(1));
|
||||
align = align.max(write.align);
|
||||
let desc = FieldDesc {
|
||||
name: write.name,
|
||||
level: write.level,
|
||||
offset,
|
||||
size: write.size,
|
||||
align: write.align,
|
||||
type_id: write.type_id,
|
||||
read_erased: write.read_erased,
|
||||
repark: write.repark,
|
||||
content_hash: write.content_hash,
|
||||
content_eq: write.content_eq,
|
||||
};
|
||||
offset += write.size;
|
||||
desc
|
||||
})
|
||||
.collect();
|
||||
Layout {
|
||||
depth,
|
||||
element,
|
||||
fields,
|
||||
size: offset,
|
||||
align,
|
||||
}
|
||||
}
|
||||
|
||||
/// This layout minus the named fields, offsets recomputed. Removing an
|
||||
/// absent name is a no-op: downstream reads yield the default either way.
|
||||
pub fn without(&self, removes: &[(&str, u8)]) -> Layout {
|
||||
let retained: Vec<FieldWrite> = self.fields.iter().filter(|field| !removes.contains(&(field.name, field.level))).map(FieldDesc::as_write).collect();
|
||||
Layout::default().with_writes(self.depth, self.element, &retained)
|
||||
}
|
||||
|
||||
/// The union of several layouts over the same element and depth.
|
||||
pub fn union(layouts: &[&Layout]) -> Layout {
|
||||
let first = layouts.first().expect("a union needs at least one layout");
|
||||
// A shallower source joins the union lifted: a scalar concatenates as
|
||||
// one lane, its fields sitting at the innermost level like any lane's.
|
||||
let depth = layouts.iter().map(|layout| layout.depth).max().unwrap_or(first.depth);
|
||||
let mut union = Layout::default().with_writes(depth, first.element, &[]);
|
||||
for layout in layouts {
|
||||
assert_eq!(union.element, layout.element, "union layouts must share the element");
|
||||
let writes: Vec<FieldWrite> = layout.fields.iter().map(FieldDesc::as_write).collect();
|
||||
union = union.with_writes(union.depth, union.element, &writes);
|
||||
}
|
||||
union
|
||||
}
|
||||
}
|
||||
|
||||
/// A field handle minted once against a layout: the marker's (name, level)
|
||||
/// resolved to a field index and offset, with the marker-to-type proof taken
|
||||
/// there. Resolving it against a layout re-checks that one index instead of
|
||||
/// scanning names, so a token paired with any other layout resolves to
|
||||
/// nothing rather than to the wrong bytes.
|
||||
pub struct FieldOffset<A: attribute::Attribute> {
|
||||
index: usize,
|
||||
offset: usize,
|
||||
level: u8,
|
||||
marker: std::marker::PhantomData<fn() -> A>,
|
||||
}
|
||||
|
||||
impl<A: attribute::Attribute> Clone for FieldOffset<A> {
|
||||
fn clone(&self) -> Self {
|
||||
*self
|
||||
}
|
||||
}
|
||||
|
||||
impl<A: attribute::Attribute> Copy for FieldOffset<A> {}
|
||||
|
||||
impl<A: attribute::Attribute> std::fmt::Debug for FieldOffset<A> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("FieldOffset").field("name", &A::NAME).field("offset", &self.offset).field("level", &self.level).finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl<A: attribute::Attribute> FieldOffset<A> {
|
||||
/// The marker's field at `level`, `None` where the layout does not carry
|
||||
/// it. Panics where the layout declares the name at another value type,
|
||||
/// which the census forbids.
|
||||
pub fn of(layout: &Layout, level: u8) -> Option<Self> {
|
||||
let (index, field) = layout.fields.iter().enumerate().find(|(_, field)| field.name == A::NAME && field.level == level)?;
|
||||
assert_eq!(field.type_id, std::any::TypeId::of::<A::Value<'static>>(), "attribute `{}` is declared at another value type", A::NAME);
|
||||
Some(Self {
|
||||
index,
|
||||
offset: field.offset,
|
||||
level,
|
||||
marker: std::marker::PhantomData,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn offset(self) -> usize {
|
||||
self.offset
|
||||
}
|
||||
|
||||
/// The offset this token names in `layout`, `None` unless `layout` is the
|
||||
/// one it was minted against. The field's value type is re-checked, so a
|
||||
/// resolved offset carries the marker-to-type proof into `layout`.
|
||||
pub fn resolve(self, layout: &Layout) -> Option<usize> {
|
||||
let field = layout.fields.get(self.index)?;
|
||||
let same = field.offset == self.offset && field.level == self.level && field.name == A::NAME && field.type_id == std::any::TypeId::of::<A::Value<'static>>();
|
||||
same.then_some(self.offset)
|
||||
}
|
||||
}
|
||||
|
||||
/// The stand-in fed to a kernel's unbounded `element: T` parameter. The type
|
||||
/// system forces the kernel to route it to the element position of its return
|
||||
/// tuple, so the passthrough is explicit in the signature while the lowering
|
||||
/// carries the element bytes untyped through the copy plan.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct ElToken;
|
||||
|
||||
/// The shared empty layout: `depth` 0, no element, no fields, so `frame_bytes`
|
||||
/// is 0. The `Node::layout` default returns it for element-only and test nodes,
|
||||
/// which carry no record.
|
||||
pub fn empty_layout() -> &'static Layout {
|
||||
static EMPTY: std::sync::OnceLock<Layout> = std::sync::OnceLock::new();
|
||||
EMPTY.get_or_init(Layout::default)
|
||||
}
|
||||
|
||||
/// A record node's output layout with the frame size and carrier copy plan derived from it.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct RecordLayout {
|
||||
pub layout: Layout,
|
||||
pub frame_bytes: usize,
|
||||
pub plan: Vec<(usize, usize, usize)>,
|
||||
/// Inputs whose value cannot change with the innermost index, as a bitmask
|
||||
/// over input positions. Empty is the safe default: an uninstalled layout
|
||||
/// rebinds every input per lane.
|
||||
pub lane_invariant: u32,
|
||||
/// The names the fold gave this node's name-from-input writes, in the
|
||||
/// order the signature declares its placeholders. A marker-only node
|
||||
/// leaves it empty; `set_layout` resolves its offsets through these
|
||||
/// instead of through a marker's `NAME`.
|
||||
pub named_writes: Vec<&'static str>,
|
||||
/// The offsets the fold resolved for this node's name-from-input reads, in
|
||||
/// placeholder order. `None` is an absent attribute, which the read serves
|
||||
/// as the name's forced default. Resolved in the compiler, where the folded
|
||||
/// name and the read input's finished layout sit together, so `set_layout`
|
||||
/// only copies the numbers into the read slots.
|
||||
pub named_reads: Vec<Option<usize>>,
|
||||
/// The census default's bytes for each absent name-from-input read whose
|
||||
/// name the census declares, in the same order. A name the census does not
|
||||
/// declare has `None` and reads as its value type's default, which is that
|
||||
/// case's own rule; a read that resolved to an offset needs no default.
|
||||
pub named_read_defaults: Vec<Option<Box<[u8]>>>,
|
||||
}
|
||||
|
||||
/// A write whose name comes from the graph rather than from a marker: the
|
||||
/// input carrying the name, and the field descriptor with every facet but the
|
||||
/// name already minted from the concrete value type.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct NamedWrite {
|
||||
/// The proto input position holding the name's constant text.
|
||||
pub name_input: u8,
|
||||
/// The write this becomes once the fold supplies the name.
|
||||
pub template: FieldWrite,
|
||||
}
|
||||
|
||||
impl NamedWrite {
|
||||
/// The template for a name-generic marker's write at `level`. Every facet
|
||||
/// but the name is the concrete value type's, exactly as for a census
|
||||
/// marker; [`FieldWrite::name`] holds the placeholder until the fold runs.
|
||||
pub fn of<X: 'static, V: crate::attribute::AttrValue>(name_input: u8, level: u8) -> Self
|
||||
where
|
||||
V::Value<'static>: graphene_hash::CacheHash + PartialEq + 'static,
|
||||
{
|
||||
Self {
|
||||
name_input,
|
||||
template: FieldWrite::of::<crate::attribute::Named<X, V>>(level),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A read whose name comes from the graph rather than from a marker. The
|
||||
/// compiler resolves it to an offset in the read input's own layout, where
|
||||
/// the folded name and that finished layout already sit together.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct NamedRead {
|
||||
/// The proto input the attribute is read from.
|
||||
pub input: u8,
|
||||
/// The proto input holding the name's constant text.
|
||||
pub name_input: u8,
|
||||
/// The read's field form, every facet but the name minted from the
|
||||
/// concrete value type, as for a write.
|
||||
pub template: FieldWrite,
|
||||
}
|
||||
|
||||
impl NamedRead {
|
||||
/// The template for a name-generic marker's read at `level`.
|
||||
pub fn of<X: 'static, V: crate::attribute::AttrValue>(input: u8, name_input: u8, level: u8) -> Self
|
||||
where
|
||||
V::Value<'static>: graphene_hash::CacheHash + PartialEq + 'static,
|
||||
{
|
||||
Self {
|
||||
input,
|
||||
name_input,
|
||||
template: FieldWrite::of::<crate::attribute::Named<X, V>>(level),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Declarative record-io metadata for a node type, emitted by the macro into
|
||||
/// its registry entry so the compiler can fold each input's layout without
|
||||
/// running the node's constructor. [`fold`](LayoutMeta::fold) reproduces the
|
||||
/// layout the constructor derives at wiring today; the compiler layout pass
|
||||
/// calls it over the proto graph instead.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct LayoutMeta {
|
||||
/// Input indices whose layouts union to form the base: `[]` writes a fresh
|
||||
/// record, `[i]` derives from a single carrier, `[i, j, ..]` unions routing
|
||||
/// sources.
|
||||
pub sources: Vec<u8>,
|
||||
/// Attributes read from each input. Unused by [`fold`](LayoutMeta::fold);
|
||||
/// recorded for later compiler analysis (read-offset resolution, per-name
|
||||
/// cache dependencies, residency).
|
||||
pub reads: Vec<InputReads>,
|
||||
/// The output element: a concrete write, or carried through from the base.
|
||||
pub element: ElementSpec,
|
||||
/// The attributes the node writes at its acting level.
|
||||
pub writes: Vec<FieldWrite>,
|
||||
/// The attributes the node writes under a name taken from the graph. The
|
||||
/// compiler fold turns each into a [`writes`](Self::writes) entry and
|
||||
/// empties this, so a folded meta is indistinguishable from a marker
|
||||
/// node's; one still carrying an entry has not been folded.
|
||||
pub named_writes: Vec<NamedWrite>,
|
||||
/// The names the fold gave [`named_writes`](Self::named_writes), in
|
||||
/// placeholder order. Empty until the fold runs.
|
||||
pub folded_names: Vec<&'static str>,
|
||||
/// The attributes the node reads under a name taken from the graph.
|
||||
pub named_reads: Vec<NamedRead>,
|
||||
/// The names the fold gave [`named_reads`](Self::named_reads), in
|
||||
/// placeholder order. Empty until the fold runs.
|
||||
pub folded_read_names: Vec<&'static str>,
|
||||
/// The attributes removed from the base layout, as `(name, level)`.
|
||||
pub removes: Vec<(&'static str, u8)>,
|
||||
/// The depth change the node applies: `0` for elementwise and flip nodes,
|
||||
/// `+1` for a creator, `-1` for a reducer.
|
||||
pub level_delta: i8,
|
||||
/// The materialized subject a reducer folds, as `(input, levels)`. The fold
|
||||
/// consumes the whole subject input, so only the node's own levels remain.
|
||||
pub folded: Option<(u8, u8)>,
|
||||
}
|
||||
|
||||
/// The attributes a node reads from one input, recorded on [`LayoutMeta`] for
|
||||
/// later compiler analysis. A read and a write of an attribute carry the same
|
||||
/// [`FieldWrite`] descriptor; the direction is the position on the node.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct InputReads {
|
||||
pub input: u8,
|
||||
pub reads: Vec<FieldWrite>,
|
||||
}
|
||||
|
||||
/// Where a node's output element comes from, for [`LayoutMeta`].
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum ElementSpec {
|
||||
/// The node writes this concrete element.
|
||||
Concrete(ElementWrite),
|
||||
/// The node carries the carrier's element through unchanged.
|
||||
Carried,
|
||||
}
|
||||
|
||||
impl LayoutMeta {
|
||||
/// Keeps input 0's layout but replaces its element.
|
||||
pub fn retype(element: ElementWrite) -> Self {
|
||||
Self {
|
||||
sources: vec![0],
|
||||
reads: Vec::new(),
|
||||
element: ElementSpec::Concrete(element),
|
||||
writes: Vec::new(),
|
||||
named_writes: Vec::new(),
|
||||
folded_names: Vec::new(),
|
||||
named_reads: Vec::new(),
|
||||
folded_read_names: Vec::new(),
|
||||
removes: Vec::new(),
|
||||
level_delta: 0,
|
||||
folded: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Folds the node's output layout from its inputs', reproducing what the
|
||||
/// node's constructor derives at wiring. `inputs` is indexed by proto-input
|
||||
/// position; [`sources`](LayoutMeta::sources) selects the base layouts, which
|
||||
/// union (empty writes a fresh record).
|
||||
pub fn fold(&self, inputs: &[Option<&Layout>]) -> Layout {
|
||||
let sources: Vec<&Layout> = self.sources.iter().map(|&i| inputs[i as usize].expect("layout fold source input has no layout")).collect();
|
||||
let base = match sources.as_slice() {
|
||||
[] => Layout::default(),
|
||||
sources => Layout::union(sources),
|
||||
}
|
||||
.without(&self.removes);
|
||||
let depth = match self.folded {
|
||||
// A fold consumes the whole subject input (a deeper input folds its
|
||||
// total flat span), so only the node's own levels remain.
|
||||
Some(_) => self.level_delta.max(0) as u8,
|
||||
None => (base.depth as i8 + self.level_delta).max(0) as u8,
|
||||
};
|
||||
let element = match &self.element {
|
||||
ElementSpec::Concrete(element) => *element,
|
||||
ElementSpec::Carried => base.element,
|
||||
};
|
||||
base.with_writes(depth, element, &self.writes)
|
||||
}
|
||||
|
||||
/// [`fold`](LayoutMeta::fold) with the frame size and carrier copy plan derived from it.
|
||||
pub fn resolve(&self, inputs: &[Option<&Layout>]) -> RecordLayout {
|
||||
let layout = self.fold(inputs);
|
||||
let frame_bytes = layout.frame_bytes();
|
||||
let plan = match self.sources.first() {
|
||||
Some(&source) if self.level_delta >= 0 => {
|
||||
let from = inputs[source as usize].expect("layout resolve source input has no layout");
|
||||
let carry_element = matches!(self.element, ElementSpec::Carried);
|
||||
let removes: Vec<(&str, u8)> = self.removes.clone();
|
||||
copy_plan(from, &layout, carry_element, &removes)
|
||||
}
|
||||
// A reducer collapses its carrier's levels, so it writes a fresh record rather than copying fields down.
|
||||
_ => Vec::new(),
|
||||
};
|
||||
// A named read resolves against the input it reads, whose layout is
|
||||
// finished by the time this node folds. An absent attribute stays
|
||||
// `None`, which the read serves as the name's forced default.
|
||||
let named_reads: Vec<Option<usize>> = self
|
||||
.named_reads
|
||||
.iter()
|
||||
.zip(&self.folded_read_names)
|
||||
.map(|(read, name)| inputs.get(read.input as usize).copied().flatten().and_then(|layout| layout.offset_of(name, read.template.level)))
|
||||
.collect();
|
||||
// An absent read serves the name's own default, which for a declared
|
||||
// name is the census's rather than the value type's. The census stages
|
||||
// it the same way it fills any absent field: as the declared default's
|
||||
// bytes. One name carries one value type, checked when the name folds,
|
||||
// so the size agreement below is a guard rather than a branch.
|
||||
let named_read_defaults = self
|
||||
.named_reads
|
||||
.iter()
|
||||
.zip(&self.folded_read_names)
|
||||
.zip(&named_reads)
|
||||
.map(|((read, name), offset)| {
|
||||
let row = offset.is_none().then(|| attribute::info(name))??;
|
||||
(row.value_type == read.template.type_id && row.size == read.template.size).then(|| {
|
||||
let mut bytes = vec![0u8; row.size];
|
||||
(row.write_default_bytes)(&mut bytes);
|
||||
bytes.into_boxed_slice()
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
RecordLayout {
|
||||
layout,
|
||||
frame_bytes,
|
||||
plan,
|
||||
lane_invariant: 0,
|
||||
named_writes: self.folded_names.clone(),
|
||||
named_reads,
|
||||
named_read_defaults,
|
||||
}
|
||||
}
|
||||
|
||||
/// Folds `name` into the name-from-input write at `index`, taking the
|
||||
/// census row's descriptor where the name is declared so a known name
|
||||
/// keeps its census default, and the template's otherwise. The write
|
||||
/// joins [`writes`](Self::writes) in placeholder order.
|
||||
pub fn fold_name(&mut self, index: usize, name: &'static str) {
|
||||
let named = self.named_writes[index];
|
||||
let census = attribute::info(name).map(|row| (row.field_write_at)(named.template.level));
|
||||
let write = match census {
|
||||
Some(write) if write.type_id == named.template.type_id => write,
|
||||
_ => FieldWrite { name, ..named.template },
|
||||
};
|
||||
self.writes.push(write);
|
||||
self.folded_names.push(name);
|
||||
}
|
||||
|
||||
/// Records the name of the name-from-input read at `index`. The offset
|
||||
/// itself waits for [`resolve`](Self::resolve), which is where the read
|
||||
/// input's finished layout arrives.
|
||||
pub fn fold_read_name(&mut self, name: &'static str) {
|
||||
self.folded_read_names.push(name);
|
||||
}
|
||||
}
|
||||
|
||||
/// Field-by-field carry from `from`'s layout into `to`'s, computed at
|
||||
/// wiring. The element copy is included when `carry_element` holds, which is
|
||||
/// exactly when the node does not write a concrete element itself. `removes`
|
||||
/// names the fields the node deletes, which are exactly the ones allowed to
|
||||
/// be absent from `to`.
|
||||
pub fn copy_plan(from: &Layout, to: &Layout, carry_element: bool, removes: &[(&str, u8)]) -> Vec<(usize, usize, usize)> {
|
||||
let mut plan = Vec::new();
|
||||
if carry_element {
|
||||
assert_eq!(from.element.size, to.element.size, "a carried element must keep its size");
|
||||
if from.element.size > 0 {
|
||||
plan.push((0, 0, from.element.size));
|
||||
}
|
||||
}
|
||||
for field in &from.fields {
|
||||
if removes.contains(&(field.name, field.level)) {
|
||||
continue;
|
||||
}
|
||||
let target = to.offset_of(field.name, field.level).expect("carried field missing from the output layout");
|
||||
plan.push((field.offset, target, field.size));
|
||||
}
|
||||
plan
|
||||
}
|
||||
|
||||
/// Whether elements of `T` move once into the arena and ride as references:
|
||||
/// records byte-copy their contents and never run drop glue, so a type is
|
||||
/// byte-carried exactly when it has none.
|
||||
pub const fn element_parked<T>() -> bool {
|
||||
std::mem::needs_drop::<T>()
|
||||
}
|
||||
|
||||
/// The element (size, align) a record input of `T` carries.
|
||||
pub fn element_dims<T>() -> (usize, usize) {
|
||||
match element_parked::<T>() {
|
||||
true => (size_of::<*const u8>(), align_of::<*const u8>()),
|
||||
false => (size_of::<T>(), align_of::<T>()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The element slot a record input of `T` carries, its erased glue bound at
|
||||
/// the statically-known type.
|
||||
pub fn element_write<T: Clone + Send + Sync + dyn_any::StaticTypeSized>() -> ElementWrite
|
||||
where
|
||||
T::Static: Clone + Send + Sync,
|
||||
{
|
||||
/// # Safety
|
||||
/// `ptr` must address a live element of `T` in the form [`element_parked`] picks.
|
||||
unsafe fn clone_out<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(ptr: *const u8) -> Box<dyn std::any::Any + Send + Sync>
|
||||
where
|
||||
T::Static: Clone + Send + Sync,
|
||||
{
|
||||
if let Some(deep) = deep_element_glue(std::any::TypeId::of::<T::Static>()) {
|
||||
// SAFETY: the caller's contract; the glue is registered for this element type.
|
||||
return unsafe { (deep.clone_out)(ptr) };
|
||||
}
|
||||
// SAFETY: a lifetime-carrying element type registers deep glue, so this
|
||||
// shallow path only erases borrow-free values. The registration is a
|
||||
// whole-program convention rather than something this call can check:
|
||||
// the executor asserts the in-tree types registered before it evaluates,
|
||||
// which is where a missed wasm registration export is caught.
|
||||
Box::new(unsafe { erase_static(read_element::<T>(Rec::new(ptr))) })
|
||||
}
|
||||
/// # Safety
|
||||
/// `dst` must be fresh element storage of a record whose element is `T`, and
|
||||
/// `value` must be the clone-out this glue produced for that element type.
|
||||
unsafe fn repark<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(value: &(dyn std::any::Any + Send + Sync), dst: *mut u8, arena: &crate::arena::Arena) -> Option<()>
|
||||
where
|
||||
T::Static: Clone + Send + Sync,
|
||||
{
|
||||
if let Some(deep) = deep_element_glue(std::any::TypeId::of::<T::Static>()) {
|
||||
// SAFETY: the caller's contract; the glue is registered for this element type.
|
||||
return unsafe { (deep.repark)(value, dst, arena) };
|
||||
}
|
||||
let retained = retained_measure(std::any::TypeId::of::<T::Static>()).map_or(0, |measure| measure(value));
|
||||
let value = value.downcast_ref::<T::Static>().expect("an element replays at its own type");
|
||||
// SAFETY: the caller's contract, keyed as this element's own parks are.
|
||||
unsafe { write_element_keyed(dst, value.clone(), arena, retained, std::any::TypeId::of::<T::Static>()) }
|
||||
}
|
||||
/// Declines for a type carrying deep glue, whose value may hold interiors
|
||||
/// the evaluation's arena owns and which a moved header may not reference.
|
||||
///
|
||||
/// # Safety
|
||||
/// `parked` must address a live payload of `T`.
|
||||
unsafe fn park_move<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(parked: *const u8, promotion: &Promotion<'_>) -> Option<*const u8>
|
||||
where
|
||||
T::Static: Clone + Send + Sync,
|
||||
{
|
||||
deep_element_glue(std::any::TypeId::of::<T::Static>()).is_none().then_some(())?;
|
||||
// SAFETY: the caller's contract, at the type the park was written with.
|
||||
let value: &(dyn std::any::Any + Send + Sync) = unsafe { &*parked.cast::<T::Static>() };
|
||||
let retained = retained_measure(std::any::TypeId::of::<T::Static>()).map_or(0, |measure| measure(value));
|
||||
// SAFETY: as above, and the decline above establishes that the payload
|
||||
// owns all of its content.
|
||||
unsafe { promotion.move_park::<T>(parked, retained) }.map(<*const T::Static>::cast)
|
||||
}
|
||||
let (size, align) = element_dims::<T>();
|
||||
ElementWrite {
|
||||
size,
|
||||
align,
|
||||
parked: element_parked::<T>(),
|
||||
type_id: std::any::TypeId::of::<T::Static>(),
|
||||
clone_out: clone_out::<T>,
|
||||
repark: repark::<T>,
|
||||
park_move: park_move::<T>,
|
||||
content_hash: None,
|
||||
content_eq: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// [`element_write`] plus the content hashing and equality glue, for element
|
||||
/// types that support them.
|
||||
pub fn element_write_hashed<T: Clone + Send + Sync + graphene_hash::CacheHash + PartialEq + dyn_any::StaticTypeSized>() -> ElementWrite
|
||||
where
|
||||
T::Static: Clone + Send + Sync,
|
||||
{
|
||||
/// # Safety
|
||||
/// `ptr` must address a live element of `T` in the form [`element_parked`] picks.
|
||||
unsafe fn content_hash<T: graphene_hash::CacheHash>(ptr: *const u8, state: &mut dyn core::hash::Hasher) {
|
||||
let mut state = state;
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { borrow_element::<T>(Rec::new(ptr)) }.cache_hash(&mut state);
|
||||
}
|
||||
/// # Safety
|
||||
/// `a` and `b` must each address a live element of `T` in that same form.
|
||||
unsafe fn content_eq<T: PartialEq>(a: *const u8, b: *const u8) -> bool {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { borrow_element::<T>(Rec::new(a)) == borrow_element::<T>(Rec::new(b)) }
|
||||
}
|
||||
ElementWrite {
|
||||
content_hash: Some(content_hash::<T>),
|
||||
content_eq: Some(content_eq::<T>),
|
||||
..element_write::<T>()
|
||||
}
|
||||
}
|
||||
|
||||
/// Selects [`element_write_hashed`] when the element type supports the
|
||||
/// content glue and [`element_write`] otherwise, by autoref method
|
||||
/// resolution: call `(&ElementWritePick::<T>(..)).element_write()` with both
|
||||
/// traits in scope.
|
||||
pub struct ElementWritePick<T>(pub std::marker::PhantomData<T>);
|
||||
|
||||
pub trait ElementWritePickHashed {
|
||||
fn element_write(&self) -> ElementWrite;
|
||||
}
|
||||
|
||||
impl<T: Clone + Send + Sync + graphene_hash::CacheHash + PartialEq + dyn_any::StaticTypeSized> ElementWritePickHashed for ElementWritePick<T>
|
||||
where
|
||||
T::Static: Clone + Send + Sync,
|
||||
{
|
||||
fn element_write(&self) -> ElementWrite {
|
||||
element_write_hashed::<T>()
|
||||
}
|
||||
}
|
||||
|
||||
pub trait ElementWritePickPlain {
|
||||
fn element_write(&self) -> ElementWrite;
|
||||
}
|
||||
|
||||
impl<T: Clone + Send + Sync + dyn_any::StaticTypeSized> ElementWritePickPlain for &ElementWritePick<T>
|
||||
where
|
||||
T::Static: Clone + Send + Sync,
|
||||
{
|
||||
fn element_write(&self) -> ElementWrite {
|
||||
element_write::<T>()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::record::test_support::{f64_field, sized_field};
|
||||
|
||||
#[test]
|
||||
fn canonical_order_and_offsets() {
|
||||
let layout = Layout::default().with_writes(0, element_write::<f64>(), &[sized_field("tint", 4, 4), f64_field("opacity"), sized_field("flag", 1, 1)]);
|
||||
assert_eq!(layout.offset_of("opacity", 0), Some(8));
|
||||
assert_eq!(layout.offset_of("tint", 0), Some(16));
|
||||
assert_eq!(layout.offset_of("flag", 0), Some(20));
|
||||
assert_eq!(layout.size, 21);
|
||||
assert_eq!(layout.align, 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "a record element aligns to at most 8 bytes")]
|
||||
fn an_over_aligned_element_is_refused_at_wiring() {
|
||||
Layout::default().with_writes(0, element_write::<u128>(), &[]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "attribute `wide` aligns to at most 8 bytes")]
|
||||
fn an_over_aligned_attribute_is_refused_at_wiring() {
|
||||
Layout::default().with_writes(0, element_write::<f64>(), &[sized_field("wide", 16, 16)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "two different types")]
|
||||
fn type_conflicts_panic() {
|
||||
let mut conflicting = sized_field("opacity", 8, 8);
|
||||
conflicting.type_id = std::any::TypeId::of::<u64>();
|
||||
let layout = Layout::default().with_writes(0, element_write::<f64>(), &[f64_field("opacity")]);
|
||||
layout.with_writes(0, element_write::<f64>(), &[conflicting]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_token_resolves_only_in_the_layout_it_was_minted_against() {
|
||||
use crate::attribute::{Attribute, Opacity, Transform};
|
||||
|
||||
let layout = Layout::default().with_writes(0, element_write::<f64>(), &[FieldWrite::of::<Opacity>(0)]);
|
||||
let token = FieldOffset::<Opacity>::of(&layout, 0).expect("the layout carries the marker");
|
||||
assert_eq!(token.resolve(&layout), layout.offset_of(Opacity::NAME, 0));
|
||||
|
||||
let shifted = Layout::default().with_writes(0, element_write::<f64>(), &[FieldWrite::of::<Transform>(0), FieldWrite::of::<Opacity>(0)]);
|
||||
assert_eq!(FieldOffset::<Opacity>::of(&shifted, 0).and_then(|token| token.resolve(&layout)), None);
|
||||
assert!(FieldOffset::<Opacity>::of(&Layout::default(), 0).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn union_is_order_independent() {
|
||||
let a = Layout::default().with_writes(0, element_write::<f64>(), &[f64_field("opacity")]);
|
||||
let b = Layout::default().with_writes(0, element_write::<f64>(), &[f64_field("length")]);
|
||||
assert_eq!(Layout::union(&[&a, &b]), Layout::union(&[&b, &a]));
|
||||
assert!(Layout::union(&[&a, &b]).offset_of("length", 0).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_element_write_pick_selects_the_content_glue_by_type() {
|
||||
use super::{ElementWritePickHashed as _, ElementWritePickPlain as _};
|
||||
|
||||
#[derive(Clone, dyn_any::DynAny)]
|
||||
struct Opaque;
|
||||
|
||||
let hashed = ElementWritePick::<String>(std::marker::PhantomData).element_write();
|
||||
assert!(hashed.content_hash.is_some() && hashed.content_eq.is_some());
|
||||
let plain = (&ElementWritePick::<Opaque>(std::marker::PhantomData)).element_write();
|
||||
assert!(plain.content_hash.is_none() && plain.content_eq.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn elements_ride_as_bytes_exactly_without_drop_glue() {
|
||||
assert!(!element_parked::<f64>());
|
||||
assert!(!element_parked::<[f64; 4]>());
|
||||
assert!(element_parked::<String>());
|
||||
assert!(element_parked::<std::sync::Arc<str>>());
|
||||
assert_eq!(element_dims::<[f64; 4]>(), (32, 8));
|
||||
assert_eq!(element_dims::<String>(), (8, 8));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layouts_resolve_spilled_values() {
|
||||
let small = Layout::default().with_writes(0, element_write::<f64>(), &[f64_field("opacity")]);
|
||||
assert_eq!(small.frame_bytes(), 16);
|
||||
let backing = [4f64, 0.5];
|
||||
let value = RecordValue::spilled(unsafe { Rec::new(backing.as_ptr().cast()) });
|
||||
assert_eq!(unsafe { small.rec(&value).element::<f64>() }, 4.);
|
||||
assert_eq!(unsafe { small.rec(&value).read::<f64>(small.offset_of("opacity", 0).unwrap()) }, 0.5);
|
||||
|
||||
let spilled = Layout::default().with_writes(0, element_write::<f64>(), &[f64_field("opacity"), f64_field("length")]);
|
||||
assert_eq!(spilled.frame_bytes(), 24);
|
||||
let record = [1f64, 2., 3.];
|
||||
let value = RecordValue::spilled(unsafe { Rec::new(record.as_ptr().cast()) });
|
||||
assert_eq!(unsafe { spilled.rec(&value).element::<f64>() }, 1.);
|
||||
assert_eq!(unsafe { spilled.rec(&value).read::<f64>(spilled.offset_of("length", 0).unwrap()) }, 2.);
|
||||
assert_eq!(unsafe { spilled.rec(&value).read::<f64>(spilled.offset_of("opacity", 0).unwrap()) }, 3.);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
//! The packed-record tier at rank 0. A record is the element at offset 0
|
||||
//! plus one field per written attribute; its [`Layout`] is computed at
|
||||
//! wiring from the upstream write set and never serialized. Records of
|
||||
//! inline layouts live in the [`RecordValue`] itself; larger ones live as
|
||||
//! per-lane views on the evaluation's [`Frames`], which the root owns and
|
||||
//! every node claims its own frame out of. Kernels route them as opaque
|
||||
//! [`RecordValue`]s that carry
|
||||
//! their provenance. Only generated or wiring code touches offsets, so a
|
||||
//! safe kernel cannot misalign a field.
|
||||
|
||||
mod access;
|
||||
mod frames;
|
||||
mod input;
|
||||
mod layout;
|
||||
mod owned;
|
||||
mod promote;
|
||||
mod route;
|
||||
mod run;
|
||||
mod serve;
|
||||
#[cfg(test)]
|
||||
mod test_support;
|
||||
mod testkit;
|
||||
|
||||
pub use access::{Rec, RecordValue, apply_plan, borrow_element, erase_static, read_at, read_at_defaulting, read_element, token_only, write_element, write_element_sized, write_field};
|
||||
pub use frames::{FrameArena, FrameScope, Frames};
|
||||
pub use input::{DerivedLazyInput, DerivedRecordInput, ElementInput, ElementLazyInput, LevelStatus, RecordExtract, RecordInput, RecordLazyInput, fill_frames, materialize_batch, materialize_level};
|
||||
pub use layout::{
|
||||
ElToken, ElementSpec, ElementWrite, ElementWritePick, ElementWritePickHashed, ElementWritePickPlain, FieldDesc, FieldOffset, FieldWrite, InputReads, Layout, LayoutMeta, NamedRead, NamedWrite,
|
||||
RecordLayout, copy_plan, element_dims, element_parked, element_write, element_write_hashed, empty_layout,
|
||||
};
|
||||
pub use owned::{OwnedRecord, deepen_field_value, has_deep_element_glue, register_deep_element_clone, register_deep_field_value, replay_field_value};
|
||||
pub use promote::{Promotion, assert_promoted, register_element_promote, register_field_promote, register_retained_heap};
|
||||
pub use route::{RecordSource, SourcePlan};
|
||||
pub use run::{Group, GroupItem, RunBuilder, RunColumn, RunView, run_to_owned_list};
|
||||
pub use serve::{FrameClaim, MaterializedSpan, Served, SlotRun, serve_input};
|
||||
pub use testkit::{LiftedSource, ServedRecord, capture, test_frames};
|
||||
@@ -0,0 +1,233 @@
|
||||
//! The owned crossing: deep copies that outlive the evaluation their content borrowed.
|
||||
|
||||
use super::access::Rec;
|
||||
use super::layout::Layout;
|
||||
use super::serve::FrameClaim;
|
||||
|
||||
/// Deep-copy overrides for element types whose plain clone borrows the
|
||||
/// evaluation's arena (a `Graphic` holding a group interior). The generic
|
||||
/// element glue consults this registry, so every layout carrying such an
|
||||
/// element deep-copies at memo and capture seams regardless of which
|
||||
/// constructor built the glue. The clone-out must produce a value of the
|
||||
/// element's own type that owns all of its content; the re-park restores that
|
||||
/// value's arena-resident form before parking it.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(in crate::record) struct DeepElementGlue {
|
||||
pub(in crate::record) clone_out: unsafe fn(*const u8) -> Box<dyn std::any::Any + Send + Sync>,
|
||||
pub(in crate::record) repark: unsafe fn(&(dyn std::any::Any + Send + Sync), *mut u8, &crate::arena::Arena) -> Option<()>,
|
||||
}
|
||||
|
||||
static DEEP_ELEMENT_CLONES: std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<std::any::TypeId, DeepElementGlue>>> = std::sync::LazyLock::new(Default::default);
|
||||
|
||||
/// Registers the deep copy-out and re-park pair for elements of `T`. Called
|
||||
/// at startup from the crate that owns the type.
|
||||
pub fn register_deep_element_clone<T: dyn_any::StaticTypeSized>(
|
||||
clone_out: unsafe fn(*const u8) -> Box<dyn std::any::Any + Send + Sync>,
|
||||
repark: unsafe fn(&(dyn std::any::Any + Send + Sync), *mut u8, &crate::arena::Arena) -> Option<()>,
|
||||
) {
|
||||
DEEP_ELEMENT_CLONES.lock().unwrap().insert(std::any::TypeId::of::<T::Static>(), DeepElementGlue { clone_out, repark });
|
||||
}
|
||||
|
||||
pub(in crate::record) fn deep_element_glue(type_id: std::any::TypeId) -> Option<DeepElementGlue> {
|
||||
DEEP_ELEMENT_CLONES.lock().unwrap().get(&type_id).copied()
|
||||
}
|
||||
|
||||
/// Whether elements of a type registered deep glue. The shallow clone path is
|
||||
/// only sound for types that did not need to, so a host that drives the
|
||||
/// registration itself checks the types it owes before it evaluates anything.
|
||||
pub fn has_deep_element_glue(type_id: std::any::TypeId) -> bool {
|
||||
DEEP_ELEMENT_CLONES.lock().unwrap().contains_key(&type_id)
|
||||
}
|
||||
|
||||
/// Deep-copy overrides for field values whose content borrows the
|
||||
/// evaluation's arena (a graphic list holding native groups), keyed by the
|
||||
/// field's owned value form. Consulted at the persistence seams only:
|
||||
/// `read_erased` itself stays shallow, since introspection reads captures in
|
||||
/// generation. Both halves decline when the value already owns all of its
|
||||
/// content, so group-free values pay no extra clone: `copy_out` returns
|
||||
/// `None` for unchanged, `replay` returns `Some(None)` for unchanged and
|
||||
/// `None` for arena exhaustion.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(in crate::record) struct DeepFieldGlue {
|
||||
pub(in crate::record) copy_out: fn(&dyn crate::list::AnyAttributeValue) -> Option<Box<dyn crate::list::AnyAttributeValue>>,
|
||||
pub(in crate::record) replay: crate::list::FieldReplayFn,
|
||||
}
|
||||
|
||||
static DEEP_FIELD_VALUES: std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<std::any::TypeId, DeepFieldGlue>>> = std::sync::LazyLock::new(Default::default);
|
||||
|
||||
/// Registers the deep copy-out and replay pair for field values of `T`.
|
||||
/// Called at startup from the crate that owns the type.
|
||||
pub fn register_deep_field_value<T: 'static>(copy_out: fn(&dyn crate::list::AnyAttributeValue) -> Option<Box<dyn crate::list::AnyAttributeValue>>, replay: crate::list::FieldReplayFn) {
|
||||
DEEP_FIELD_VALUES.lock().unwrap().insert(std::any::TypeId::of::<T>(), DeepFieldGlue { copy_out, replay });
|
||||
}
|
||||
|
||||
pub(in crate::record) fn deep_field_glue(type_id: std::any::TypeId) -> Option<DeepFieldGlue> {
|
||||
DEEP_FIELD_VALUES.lock().unwrap().get(&type_id).copied()
|
||||
}
|
||||
|
||||
/// The copy-out half over an erased field value: the owned form a value takes
|
||||
/// when it crosses out of the evaluation whose arena its content borrows. A
|
||||
/// value with no registered glue already owns everything and passes through.
|
||||
pub fn deepen_field_value(value: Box<dyn crate::list::AnyAttributeValue>) -> Box<dyn crate::list::AnyAttributeValue> {
|
||||
match deep_field_glue(value.as_any().type_id()) {
|
||||
Some(glue) => (glue.copy_out)(&*value).unwrap_or(value),
|
||||
None => value,
|
||||
}
|
||||
}
|
||||
|
||||
/// The replay half over an erased field value: `Some(None)` where the value
|
||||
/// already owns its content, `None` on arena exhaustion.
|
||||
pub fn replay_field_value(value: &dyn crate::list::AnyAttributeValue, arena: &crate::arena::Arena) -> Option<Option<Box<dyn crate::list::AnyAttributeValue>>> {
|
||||
match deep_field_glue(value.as_any().type_id()) {
|
||||
Some(glue) => (glue.replay)(value, arena),
|
||||
None => Some(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// A record deep-copied out of its evaluation: the packed bytes plus owned
|
||||
/// clones of every parked payload, replayable into a later evaluation's
|
||||
/// storage through the layout's erased glue. The layout stays with the
|
||||
/// holder, which proved it at wiring.
|
||||
pub struct OwnedRecord {
|
||||
pub(in crate::record) bytes: Box<[u8]>,
|
||||
pub(in crate::record) element: Option<Box<dyn std::any::Any + Send + Sync>>,
|
||||
/// Each copied field's index in the copy's layout, that field's declared
|
||||
/// value type, and the owned value. The type rides along so a replay can
|
||||
/// re-check the field it resolves rather than trusting the caller's claim.
|
||||
fields: Vec<(usize, std::any::TypeId, Box<dyn crate::list::AnyAttributeValue>)>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for OwnedRecord {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str("OwnedRecord(..)")
|
||||
}
|
||||
}
|
||||
|
||||
impl OwnedRecord {
|
||||
/// # Safety
|
||||
/// `rec` must be a live record of `layout`.
|
||||
pub unsafe fn copy_out(layout: &Layout, rec: Rec<'_>) -> OwnedRecord {
|
||||
// The element-to-field seam is never written, so the copy stays untyped:
|
||||
// a `&[u8]` over the frame would read those bytes.
|
||||
let mut staged = Vec::<u8>::with_capacity(layout.size);
|
||||
// SAFETY: the caller's contract sizes the record at `layout.size`, which
|
||||
// is the capacity just reserved, so the copy fills exactly the staging.
|
||||
let bytes = unsafe {
|
||||
std::ptr::copy_nonoverlapping(rec.ptr(), staged.as_mut_ptr(), layout.size);
|
||||
staged.set_len(layout.size);
|
||||
staged.into_boxed_slice()
|
||||
};
|
||||
// SAFETY: the caller's contract; a parked element sits at offset 0.
|
||||
let element = layout.element.parked.then(|| unsafe { (layout.element.clone_out)(rec.ptr()) });
|
||||
let fields = layout
|
||||
.fields
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, field)| field.repark.is_some())
|
||||
// SAFETY: the caller's contract; each field reads its own descriptor's offset.
|
||||
.map(|(index, field)| (index, field.type_id, deepen_field_value(unsafe { (field.read_erased)(rec.ptr().add(field.offset)) })))
|
||||
.collect();
|
||||
OwnedRecord { bytes, element, fields }
|
||||
}
|
||||
|
||||
/// Replays the copy into a caller's claim, re-parking droppable payloads
|
||||
/// against `arena`; `None` reports arena exhaustion. The claim's layout must
|
||||
/// be the one the copy was taken at, which the checks below establish rather
|
||||
/// than assume: the copy carries no layout of its own, so a mismatched claim
|
||||
/// would otherwise write past the frame or re-park a field through another
|
||||
/// field's glue.
|
||||
pub fn replay_into(&self, slot: &mut FrameClaim<'_, '_>, arena: &crate::arena::Arena) -> Option<()> {
|
||||
let layout = slot.layout;
|
||||
assert_eq!(self.bytes.len(), layout.size, "a replay lands in the layout the copy was taken at");
|
||||
assert_eq!(self.element.is_some(), layout.element.parked, "a replay lands in the layout the copy was taken at");
|
||||
for &(index, type_id, _) in &self.fields {
|
||||
let field = layout.fields.get(index).expect("a replay lands in the layout the copy was taken at");
|
||||
assert_eq!(field.type_id, type_id, "a replay lands in the layout the copy was taken at");
|
||||
}
|
||||
self.write_into(layout, slot.dst(), arena)
|
||||
}
|
||||
|
||||
/// `dst` is a claimed frame of `layout`, and `replay_into`'s asserts have
|
||||
/// established that `layout` is the one the copy was taken at.
|
||||
fn write_into(&self, layout: &Layout, dst: *mut u8, arena: &crate::arena::Arena) -> Option<()> {
|
||||
// SAFETY: the copy is `layout.size` bytes and the claim is a frame of it.
|
||||
unsafe { std::ptr::copy_nonoverlapping(self.bytes.as_ptr(), dst, self.bytes.len()) };
|
||||
if let Some(element) = &self.element {
|
||||
// SAFETY: the element was cloned out of this layout's own slot at offset 0.
|
||||
unsafe { (layout.element.repark)(&**element, dst, arena) }?;
|
||||
}
|
||||
for (index, _, value) in &self.fields {
|
||||
let field = &layout.fields[*index];
|
||||
let repark = field.repark.expect("copied fields carry re-park glue");
|
||||
let resident = replay_field_value(&**value, arena)?;
|
||||
// SAFETY: the asserts matched this index's field type, so the glue and
|
||||
// the value agree; the write lands in that field's own region.
|
||||
unsafe { repark(resident.as_deref().unwrap_or(&**value), dst.add(field.offset), arena) }?;
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::record::access::{read_element, write_element, write_field};
|
||||
use crate::record::frames::FrameArena;
|
||||
use crate::record::layout::{FieldWrite, element_write};
|
||||
|
||||
#[test]
|
||||
fn a_padded_layout_copies_out_without_reading_its_seam() {
|
||||
// A 4-byte element before an 8-aligned field leaves [4, 8) unwritten.
|
||||
let layout = Layout::default().with_writes(0, element_write::<u32>(), &[FieldWrite::of::<crate::attribute::Opacity>(0)]);
|
||||
let offset = layout.offset_of("opacity", 0).unwrap();
|
||||
assert_eq!((layout.element.size, offset), (4, 8), "the fixture needs the element-to-field seam");
|
||||
|
||||
let arena = crate::arena::Arena::new(1024).unwrap();
|
||||
let scratch = arena.alloc_scratch::<u64>(layout.frame_bytes().div_ceil(8)).unwrap();
|
||||
let base: *mut u8 = scratch.as_mut_ptr().cast();
|
||||
unsafe { write_element(base, 7u32, &arena) }.unwrap();
|
||||
unsafe { write_field::<f64>(base, offset, 0.5) };
|
||||
|
||||
let copy = unsafe { OwnedRecord::copy_out(&layout, Rec::new(base.cast_const())) };
|
||||
|
||||
let replay_arena = crate::arena::Arena::new(1024).unwrap();
|
||||
let mut frame_arena = FrameArena::new();
|
||||
frame_arena.reserve(layout.frame_bytes());
|
||||
let frames = frame_arena.frames();
|
||||
let mut slot = frames.claim(&layout);
|
||||
copy.replay_into(&mut slot, &replay_arena).unwrap();
|
||||
// SAFETY: the replay completes the record in the claimed frame.
|
||||
let value = unsafe { slot.finish() };
|
||||
let rec = layout.rec(&value);
|
||||
assert_eq!(unsafe { read_element::<u32>(rec) }, 7);
|
||||
assert_eq!(unsafe { rec.read::<f64>(offset) }, 0.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn owned_records_replay_re_parked_payloads_after_the_source_dies() {
|
||||
let layout = Layout::default().with_writes(0, element_write::<String>(), &[FieldWrite::of::<crate::attribute::Name>(0)]);
|
||||
let mut buffer = vec![0u64; layout.size.div_ceil(8)];
|
||||
let base: *mut u8 = buffer.as_mut_ptr().cast();
|
||||
|
||||
let copy = {
|
||||
let arena = crate::arena::Arena::new(1024).unwrap();
|
||||
unsafe { write_element(base, String::from("element"), &arena) }.unwrap();
|
||||
let (name, _) = arena.alloc(String::from("field")).unwrap();
|
||||
unsafe { write_field::<&str>(base, layout.offset_of("name", 0).unwrap(), name.as_str()) };
|
||||
unsafe { OwnedRecord::copy_out(&layout, Rec::new(base)) }
|
||||
};
|
||||
buffer.fill(u64::MAX);
|
||||
|
||||
let replay_arena = crate::arena::Arena::new(1024).unwrap();
|
||||
let mut frame_arena = FrameArena::new();
|
||||
frame_arena.reserve(layout.frame_bytes());
|
||||
let frames = frame_arena.frames();
|
||||
let mut slot = frames.claim(&layout);
|
||||
copy.replay_into(&mut slot, &replay_arena).unwrap();
|
||||
// SAFETY: the replay completes the record in the claimed frame.
|
||||
let value = unsafe { slot.finish() };
|
||||
let rec = layout.rec(&value);
|
||||
assert_eq!(unsafe { read_element::<String>(rec) }, "element");
|
||||
assert_eq!(unsafe { rec.read::<&str>(layout.offset_of("name", 0).unwrap()) }, "field");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,433 @@
|
||||
//! Transient-to-persistent promotion of records and their parked payloads.
|
||||
|
||||
use super::layout::Layout;
|
||||
use super::owned::{deepen_field_value, replay_field_value};
|
||||
use super::serve::MaterializedSpan;
|
||||
|
||||
/// The regions a promote dispatches on. A payload already living in the
|
||||
/// persistent region outlives every entry promoted into it and is shared; a
|
||||
/// payload in the transient arena or the frame buffer dies at the next reset
|
||||
/// and is cloned.
|
||||
///
|
||||
/// The dispatch is decidable only where the reference addresses the payload
|
||||
/// itself, which holds for parked elements and for a group interior's frames.
|
||||
/// A reference-valued attribute instead names storage whose owner the address
|
||||
/// alone does not identify, so those are never provenance-shared; they clone,
|
||||
/// or move where [`Arena::move_park`](crate::arena::Arena::move_park) confirms
|
||||
/// the reference is the transient arena's own park.
|
||||
///
|
||||
/// THE SHARING LAW: sharing a payload between persistent entries is sound
|
||||
/// because persistent invalidation is epochal, so every entry dies at one
|
||||
/// flush and no entry can outlive a payload another still names. Per-entry
|
||||
/// eviction would have to refcount the shared payloads before it could
|
||||
/// reclaim one entry's storage.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct Promotion<'a> {
|
||||
transient: &'a crate::arena::Arena,
|
||||
frames: (usize, usize),
|
||||
persistent: &'a crate::arena::Arena,
|
||||
}
|
||||
|
||||
impl<'a> Promotion<'a> {
|
||||
/// `frames` is the whole frame buffer as (address, bytes), from
|
||||
/// [`Frames::bounds`].
|
||||
pub fn new(transient: &'a crate::arena::Arena, frames: (usize, usize), persistent: &'a crate::arena::Arena) -> Self {
|
||||
Promotion { transient, frames, persistent }
|
||||
}
|
||||
|
||||
pub fn persistent(&self) -> &'a crate::arena::Arena {
|
||||
self.persistent
|
||||
}
|
||||
|
||||
/// Whether the reference dies with the evaluation, which is the promote's
|
||||
/// clone-or-share question. A null or byte-carried slot reads as neither
|
||||
/// region's and shares.
|
||||
pub fn evaluation_lived(&self, ptr: *const u8) -> bool {
|
||||
self.transient.contains(ptr) || (ptr as usize).wrapping_sub(self.frames.0) < self.frames.1
|
||||
}
|
||||
|
||||
/// Moves a transient payload's header into the persistent region instead of
|
||||
/// cloning the heap it owns: the heap travels with the drop obligation and
|
||||
/// is freed at the persistent flush, never at the transient reset. `None`
|
||||
/// where the header is not the transient arena's own park keyed to `T`'s
|
||||
/// static type or the region refused it, which leaves the caller its clone
|
||||
/// path.
|
||||
///
|
||||
/// The forwarding is the evaluation's, so a payload two records share moves
|
||||
/// once and both reach the one persistent header. The source header stays
|
||||
/// readable to the evaluation's remaining sharers, which are the only reads
|
||||
/// the move keeps sound: no read of it may outlive the persistent flush.
|
||||
///
|
||||
/// # Safety
|
||||
/// `parked` must address a live `T`, and `T` must own all of its content, a
|
||||
/// persistent header being allowed to reference no transient storage, which
|
||||
/// is also what lets it be republished at `T::Static`. The park's key
|
||||
/// settles the type, so the caller owes no identity argument.
|
||||
pub unsafe fn move_park<T: dyn_any::StaticTypeSized>(&self, parked: *const u8, retained: usize) -> Option<*const T::Static>
|
||||
where
|
||||
T::Static: Send + Sync,
|
||||
{
|
||||
// SAFETY: the caller's contract, forwarded to the parking arena.
|
||||
unsafe { self.transient.move_park::<T>(parked, self.persistent, retained) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Rewrites one promoted record's parked references in place: the lane bytes
|
||||
/// are already the persistent region's, and each reference whose payload dies
|
||||
/// with the evaluation is replaced by a clone parked there.
|
||||
///
|
||||
/// A parked element rides the arena slot its payload was written into, so the
|
||||
/// region holding it decides share against clone. A parked field's reference
|
||||
/// names storage the promote cannot attribute from the address alone, so it is
|
||||
/// never provenance-shared: it clones, or takes the route a registered
|
||||
/// [`FieldPromote`] states under the two-level sharing law.
|
||||
///
|
||||
/// # Safety
|
||||
/// `dst` must be a persistent image of a live record of `layout`.
|
||||
pub(in crate::record) unsafe fn promote_record(layout: &Layout, dst: *mut u8, promotion: &Promotion<'_>) -> Option<()> {
|
||||
if layout.element.parked {
|
||||
// SAFETY: a parked element slot holds one reference at offset 0.
|
||||
let parked = unsafe { dst.cast::<*const u8>().read() };
|
||||
if !promotion.persistent.contains(parked) {
|
||||
match element_promote_glue(layout.element.type_id) {
|
||||
// SAFETY: the slot images a parked element of this type.
|
||||
Some(promote) => unsafe { promote(dst.cast_const(), dst, promotion) }?,
|
||||
// SAFETY: as above; the header is the payload's own.
|
||||
None => match unsafe { (layout.element.park_move)(parked, promotion) } {
|
||||
// SAFETY: a parked element slot holds one reference at offset 0.
|
||||
Some(moved) => unsafe { dst.cast::<*const u8>().write(moved) },
|
||||
None => {
|
||||
// SAFETY: as above, and the clone owns its content.
|
||||
let owned = unsafe { (layout.element.clone_out)(dst.cast_const()) };
|
||||
// SAFETY: the clone is this element's own type, back into its slot.
|
||||
unsafe { (layout.element.repark)(&*owned, dst, promotion.persistent) }?;
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
for field in &layout.fields {
|
||||
let Some(repark) = field.repark else { continue };
|
||||
// SAFETY: a parked field slot holds one reference at its offset.
|
||||
let slot = unsafe { dst.add(field.offset) };
|
||||
if let Some(promote) = field_promote_glue(field.type_id) {
|
||||
// SAFETY: the slot images a parked field of this descriptor, and the
|
||||
// promoted reference is written back into that same slot.
|
||||
unsafe { promote(slot.cast_const(), slot, promotion) }?;
|
||||
continue;
|
||||
}
|
||||
// SAFETY: the slot images a parked field of this descriptor.
|
||||
let value = deepen_field_value(unsafe { (field.read_erased)(slot.cast_const()) });
|
||||
let resident = replay_field_value(&*value, promotion.persistent)?;
|
||||
// SAFETY: the replay produced this field's own value type.
|
||||
unsafe { repark(resident.as_deref().unwrap_or(&*value), slot, promotion.persistent) }?;
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Re-walks a promoted record and asserts no reference into the evaluation's
|
||||
/// storage survived, which is the postcondition every later hit and every
|
||||
/// shared interior relies on. The element's payload must sit in the persistent
|
||||
/// region itself; a field's payload is heap its owner holds, so the weaker
|
||||
/// range check is all that is decidable there.
|
||||
///
|
||||
/// # Safety
|
||||
/// `ptr` must be a live record of `layout`.
|
||||
pub unsafe fn assert_promoted(layout: &Layout, ptr: *const u8, promotion: &Promotion<'_>) {
|
||||
if layout.element.parked {
|
||||
// SAFETY: a parked element slot holds one reference at offset 0.
|
||||
let parked = unsafe { ptr.cast::<*const u8>().read() };
|
||||
assert!(promotion.persistent.contains(parked), "a promoted element kept a reference outside the persistent region");
|
||||
}
|
||||
for field in &layout.fields {
|
||||
if field.repark.is_none() {
|
||||
continue;
|
||||
}
|
||||
// SAFETY: a parked field slot holds one reference at its offset.
|
||||
let parked = unsafe { ptr.add(field.offset).cast::<*const u8>().read() };
|
||||
assert!(!promotion.evaluation_lived(parked), "a promoted field kept a reference into the evaluation");
|
||||
}
|
||||
}
|
||||
|
||||
/// The promote override for element types whose payload holds arena-resident
|
||||
/// interiors: the generic path clones through an owned intermediate, while a
|
||||
/// registered promote shares the interiors already living in the persistent
|
||||
/// region and copies only the rest.
|
||||
type ElementPromote = unsafe fn(*const u8, *mut u8, &Promotion<'_>) -> Option<()>;
|
||||
|
||||
static ELEMENT_PROMOTES: std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<std::any::TypeId, ElementPromote>>> = std::sync::LazyLock::new(Default::default);
|
||||
|
||||
/// Registers the promote for elements of `T`. Called at startup from the crate
|
||||
/// that owns the type. The promote must leave no reference the promotion calls
|
||||
/// evaluation-lived.
|
||||
pub fn register_element_promote<T: dyn_any::StaticTypeSized>(promote: ElementPromote) {
|
||||
ELEMENT_PROMOTES.lock().unwrap().insert(std::any::TypeId::of::<T::Static>(), promote);
|
||||
}
|
||||
|
||||
fn element_promote_glue(type_id: std::any::TypeId) -> Option<ElementPromote> {
|
||||
ELEMENT_PROMOTES.lock().unwrap().get(&type_id).copied()
|
||||
}
|
||||
|
||||
/// The deep field glue's third half, opt-in beside [`register_deep_field_value`]'s
|
||||
/// pair: a registered promote routes the field payload transient-to-persistent
|
||||
/// at the slot itself, so the promote never builds the owned form the other two
|
||||
/// halves round-trip through. Keyed by the field's stored type rather than its
|
||||
/// owned one, since the route runs before any erased read. The owned halves keep
|
||||
/// serving every other seam, [`OwnedRecord::copy_out`] and [`GroupItem::copy_out`]
|
||||
/// included.
|
||||
///
|
||||
/// THE TWO-LEVEL SHARING LAW, which a registrant must hold to: the field's own
|
||||
/// header is not provenance-shared, since a stored reference names storage whose
|
||||
/// owner the promote cannot attribute from the address alone; it clones, or moves
|
||||
/// where the payload owns all of its content and the transient arena confirms the
|
||||
/// reference is its own park. One level inside the payload, an interior that is
|
||||
/// arena-resident has decidable provenance and takes the Cow dispatch: an interior
|
||||
/// the persistent region already holds is shared pointer for pointer, and one that
|
||||
/// dies with the evaluation is copied or moved.
|
||||
type FieldPromote = unsafe fn(*const u8, *mut u8, &Promotion<'_>) -> Option<()>;
|
||||
|
||||
static FIELD_PROMOTES: std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<std::any::TypeId, FieldPromote>>> = std::sync::LazyLock::new(Default::default);
|
||||
|
||||
/// Registers the promote for fields stored as `T`. Called at startup from the
|
||||
/// crate that owns the type. The promote must leave no reference the promotion
|
||||
/// calls evaluation-lived.
|
||||
pub fn register_field_promote<T: 'static>(promote: FieldPromote) {
|
||||
FIELD_PROMOTES.lock().unwrap().insert(std::any::TypeId::of::<T>(), promote);
|
||||
}
|
||||
|
||||
fn field_promote_glue(type_id: std::any::TypeId) -> Option<FieldPromote> {
|
||||
FIELD_PROMOTES.lock().unwrap().get(&type_id).copied()
|
||||
}
|
||||
|
||||
/// The park glue's heap estimate for values of a type, keyed as the deep glue
|
||||
/// is. Consulted where a payload parks, so a region's retained heap is known
|
||||
/// without walking it.
|
||||
type RetainedMeasure = fn(&(dyn std::any::Any + Send + Sync)) -> usize;
|
||||
|
||||
static RETAINED_MEASURES: std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<std::any::TypeId, RetainedMeasure>>> = std::sync::LazyLock::new(Default::default);
|
||||
|
||||
/// Registers the retained-heap estimate for values of `T`. Called at startup
|
||||
/// from the crate that owns the type. The estimate is a hint: an unregistered
|
||||
/// type contributes 0, so a region's counter is a lower bound.
|
||||
pub fn register_retained_heap<T: dyn_any::StaticTypeSized>(measure: RetainedMeasure) {
|
||||
RETAINED_MEASURES.lock().unwrap().insert(std::any::TypeId::of::<T::Static>(), measure);
|
||||
}
|
||||
|
||||
pub(in crate::record) fn retained_measure(type_id: std::any::TypeId) -> Option<RetainedMeasure> {
|
||||
RETAINED_MEASURES.lock().unwrap().get(&type_id).copied()
|
||||
}
|
||||
|
||||
impl MaterializedSpan {
|
||||
/// Copies the batch into the persistent region as a copy-on-write over
|
||||
/// provenance: the frame bytes memcpy, and each parked reference is cloned
|
||||
/// only where it dies with the evaluation, so a layout carrying no parked
|
||||
/// slot reduces to the memcpy and a level whose payloads an upstream memo
|
||||
/// already published costs nothing beyond it. `None` where the region
|
||||
/// could not hold the copy, which leaves the caller with nothing to cache.
|
||||
///
|
||||
/// # Safety
|
||||
/// The batch's lanes must be live records of its layout.
|
||||
pub unsafe fn to_persistent(batch: &crate::node::RecordBatch<'_>, promotion: &Promotion<'_>) -> Option<MaterializedSpan> {
|
||||
let layout = batch.layout();
|
||||
let stride = layout.lane_stride();
|
||||
let len = batch.len();
|
||||
if len == 0 {
|
||||
return Some(MaterializedSpan {
|
||||
base: crate::arena::ArenaWeak::NULL,
|
||||
len: 0,
|
||||
});
|
||||
}
|
||||
let persistent = promotion.persistent();
|
||||
let slab = persistent.alloc_scratch::<u64>((len * stride).div_ceil(8))?;
|
||||
let base: *mut u8 = slab.as_mut_ptr().cast();
|
||||
for lane in 0..len {
|
||||
// SAFETY: the caller's contract on the lane, into the lane's own
|
||||
// region of the freshly reserved slab.
|
||||
let dst = unsafe { base.add(lane * stride) };
|
||||
// SAFETY: as above; `layout.size` bytes of a lane fit its own stride.
|
||||
unsafe { std::ptr::copy_nonoverlapping(batch.get(lane).rec().ptr(), dst, layout.size) };
|
||||
// SAFETY: the copy images a record of this layout.
|
||||
unsafe { promote_record(layout, dst, promotion) }?;
|
||||
}
|
||||
#[cfg(debug_assertions)]
|
||||
for lane in 0..len {
|
||||
// SAFETY: every lane was imaged and promoted above.
|
||||
unsafe { assert_promoted(layout, base.add(lane * stride).cast_const(), promotion) };
|
||||
}
|
||||
Some(MaterializedSpan {
|
||||
base: persistent.handle_at(base.cast_const())?,
|
||||
len,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::record::access::{borrow_element, write_element, write_element_sized};
|
||||
use crate::record::layout::element_write;
|
||||
use crate::record::test_support::f64_field;
|
||||
|
||||
#[test]
|
||||
fn a_pod_level_promotes_as_a_bare_memcpy() {
|
||||
let transient = crate::arena::Arena::new(4096).unwrap();
|
||||
let persistent = crate::arena::Arena::new(4096).unwrap();
|
||||
let layout = Layout::default().with_writes(1, element_write::<f64>(), &[f64_field("opacity")]);
|
||||
let stride = layout.lane_stride();
|
||||
|
||||
let mut buffer = vec![0u64; (4 * stride).div_ceil(8)];
|
||||
let base = buffer.as_mut_ptr().cast::<u8>();
|
||||
let bounds = (base as usize, buffer.len() * 8);
|
||||
for lane in 0..4usize {
|
||||
unsafe { base.add(lane * stride).cast::<f64>().write(lane as f64) };
|
||||
}
|
||||
let batch = unsafe { crate::node::RecordBatch::new(base.cast_const(), 4, &layout) };
|
||||
|
||||
let promotion = Promotion::new(&transient, bounds, &persistent);
|
||||
let span = unsafe { MaterializedSpan::to_persistent(&batch, &promotion) }.unwrap();
|
||||
|
||||
let slab = (4 * stride).div_ceil(8) * 8;
|
||||
assert_eq!(persistent.occupancy(), slab, "a layout with no parked slot allocates the slab and nothing else");
|
||||
assert_eq!(persistent.retained_heap(), 0, "no payload parked, so nothing is retained");
|
||||
let published = span.batch(&persistent, &layout).unwrap();
|
||||
for lane in 0..4usize {
|
||||
assert_eq!(unsafe { published.get(lane).rec().element::<f64>() }, lane as f64, "lane {lane}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_promoted_element_lands_in_the_persistent_region() {
|
||||
let transient = crate::arena::Arena::new(4096).unwrap();
|
||||
let persistent = crate::arena::Arena::new(4096).unwrap();
|
||||
let layout = Layout::default().with_writes(0, element_write::<String>(), &[]);
|
||||
|
||||
let mut buffer = vec![0u64; layout.frame_bytes().div_ceil(8)];
|
||||
let base = buffer.as_mut_ptr().cast::<u8>();
|
||||
let bounds = (base as usize, buffer.len() * 8);
|
||||
unsafe { write_element(base, String::from("parked in the evaluation"), &transient) }.unwrap();
|
||||
let source = unsafe { base.cast::<*const u8>().read() };
|
||||
assert!(transient.contains(source));
|
||||
|
||||
let batch = unsafe { crate::node::RecordBatch::new(base.cast_const(), 1, &layout) };
|
||||
let promotion = Promotion::new(&transient, bounds, &persistent);
|
||||
let span = unsafe { MaterializedSpan::to_persistent(&batch, &promotion) }.unwrap();
|
||||
|
||||
let published = span.batch(&persistent, &layout).unwrap();
|
||||
let promoted = unsafe { published.get(0).rec().ptr().cast::<*const u8>().read() };
|
||||
assert!(persistent.contains(promoted), "the promote re-parked the payload into the persistent region");
|
||||
assert_ne!(source, promoted, "an evaluation-lived payload gets its own persistent header");
|
||||
assert_eq!(unsafe { borrow_element::<String>(published.get(0).rec()) }, "parked in the evaluation");
|
||||
}
|
||||
|
||||
/// The measure production registers for `String`, without which a promote
|
||||
/// credits the region 0 and the counters cannot be observed to transfer.
|
||||
fn measure_strings() {
|
||||
register_retained_heap::<String>(|value| value.downcast_ref::<String>().map_or(0, String::len));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_promoted_payload_moves_its_heap_rather_than_cloning_it() {
|
||||
measure_strings();
|
||||
let mut transient = crate::arena::Arena::new(4096).unwrap();
|
||||
let persistent = crate::arena::Arena::new(4096).unwrap();
|
||||
let layout = Layout::default().with_writes(0, element_write::<String>(), &[]);
|
||||
|
||||
let mut buffer = vec![0u64; layout.frame_bytes().div_ceil(8)];
|
||||
let base = buffer.as_mut_ptr().cast::<u8>();
|
||||
let bounds = (base as usize, buffer.len() * 8);
|
||||
let owned = String::from("the obligation travels with the header");
|
||||
let (heap, length) = (owned.as_ptr(), owned.len());
|
||||
unsafe { write_element_sized(base, owned, &transient, length) }.unwrap();
|
||||
assert_eq!(transient.retained_heap(), length);
|
||||
|
||||
let batch = unsafe { crate::node::RecordBatch::new(base.cast_const(), 1, &layout) };
|
||||
let promotion = Promotion::new(&transient, bounds, &persistent);
|
||||
let span = unsafe { MaterializedSpan::to_persistent(&batch, &promotion) }.unwrap();
|
||||
|
||||
let published = span.batch(&persistent, &layout).unwrap();
|
||||
let served = unsafe { borrow_element::<String>(published.get(0).rec()) };
|
||||
assert_eq!(served.as_ptr(), heap, "the promote moved the header, so the served view names the pre-promote heap");
|
||||
assert_eq!(transient.retained_heap(), 0, "the transient counter gave the hint up");
|
||||
assert_eq!(persistent.retained_heap(), length, "and the persistent counter took it");
|
||||
|
||||
transient.reset();
|
||||
let published = span.batch(&persistent, &layout).unwrap();
|
||||
assert_eq!(
|
||||
unsafe { borrow_element::<String>(published.get(0).rec()) },
|
||||
"the obligation travels with the header",
|
||||
"the moved payload survives the transient reset"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_payload_two_records_share_promotes_to_one_persistent_header() {
|
||||
measure_strings();
|
||||
let transient = crate::arena::Arena::new(4096).unwrap();
|
||||
let mut persistent = crate::arena::Arena::new(4096).unwrap();
|
||||
let layout = Layout::default().with_writes(0, element_write::<String>(), &[]);
|
||||
let stride = layout.lane_stride();
|
||||
|
||||
let mut buffer = vec![0u64; (2 * stride).div_ceil(8)];
|
||||
let base = buffer.as_mut_ptr().cast::<u8>();
|
||||
let bounds = (base as usize, buffer.len() * 8);
|
||||
let length = "shared across lanes".len();
|
||||
unsafe { write_element_sized(base, String::from("shared across lanes"), &transient, length) }.unwrap();
|
||||
// A carried element byte-copies its park reference, so both lanes name the one park.
|
||||
let shared = unsafe { base.cast::<*const u8>().read() };
|
||||
unsafe { base.add(stride).cast::<*const u8>().write(shared) };
|
||||
|
||||
let batch = unsafe { crate::node::RecordBatch::new(base.cast_const(), 2, &layout) };
|
||||
let promotion = Promotion::new(&transient, bounds, &persistent);
|
||||
let span = unsafe { MaterializedSpan::to_persistent(&batch, &promotion) }.unwrap();
|
||||
|
||||
let published = span.batch(&persistent, &layout).unwrap();
|
||||
let first = unsafe { published.get(0).rec().ptr().cast::<*const u8>().read() };
|
||||
let second = unsafe { published.get(1).rec().ptr().cast::<*const u8>().read() };
|
||||
assert_eq!(first, second, "a payload two records share moves once");
|
||||
assert_eq!(persistent.retained_heap(), length, "and its hint transfers once");
|
||||
|
||||
persistent.reset();
|
||||
assert_eq!(persistent.retained_heap(), 0, "the flush frees the one header exactly once");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_persistent_element_is_shared_by_the_promote() {
|
||||
let transient = crate::arena::Arena::new(4096).unwrap();
|
||||
let persistent = crate::arena::Arena::new(4096).unwrap();
|
||||
let layout = Layout::default().with_writes(0, element_write::<String>(), &[]);
|
||||
|
||||
let mut buffer = vec![0u64; layout.frame_bytes().div_ceil(8)];
|
||||
let base = buffer.as_mut_ptr().cast::<u8>();
|
||||
let bounds = (base as usize, buffer.len() * 8);
|
||||
// The payload an upstream memo already published: the promote must
|
||||
// name it rather than copy it.
|
||||
unsafe { write_element(base, String::from("published upstream"), &persistent) }.unwrap();
|
||||
let upstream = unsafe { base.cast::<*const u8>().read() };
|
||||
let occupied = persistent.occupancy();
|
||||
|
||||
let batch = unsafe { crate::node::RecordBatch::new(base.cast_const(), 1, &layout) };
|
||||
let promotion = Promotion::new(&transient, bounds, &persistent);
|
||||
let span = unsafe { MaterializedSpan::to_persistent(&batch, &promotion) }.unwrap();
|
||||
|
||||
let published = span.batch(&persistent, &layout).unwrap();
|
||||
let promoted = unsafe { published.get(0).rec().ptr().cast::<*const u8>().read() };
|
||||
assert_eq!(upstream, promoted, "an already persistent payload is shared, pointer for pointer");
|
||||
assert_eq!(persistent.occupancy() - occupied, layout.frame_bytes(), "only the lane slab was allocated");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "a promoted element kept a reference outside the persistent region")]
|
||||
fn the_rewalk_catches_a_reference_the_promote_left_behind() {
|
||||
let transient = crate::arena::Arena::new(4096).unwrap();
|
||||
let persistent = crate::arena::Arena::new(4096).unwrap();
|
||||
let layout = Layout::default().with_writes(0, element_write::<String>(), &[]);
|
||||
|
||||
let mut buffer = vec![0u64; layout.frame_bytes().div_ceil(8)];
|
||||
let base = buffer.as_mut_ptr().cast::<u8>();
|
||||
let bounds = (base as usize, buffer.len() * 8);
|
||||
unsafe { write_element(base, String::from("never promoted"), &transient) }.unwrap();
|
||||
|
||||
let promotion = Promotion::new(&transient, bounds, &persistent);
|
||||
unsafe { assert_promoted(&layout, base.cast_const(), &promotion) };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
//! Producer-side routing: a source's translation into the union layout.
|
||||
|
||||
use super::access::{Rec, apply_plan};
|
||||
use super::frames::Frames;
|
||||
use super::layout::{Layout, copy_plan};
|
||||
use super::serve::{FrameClaim, Served, serve_input};
|
||||
use crate::attribute;
|
||||
use crate::gpoll::GPoll;
|
||||
use crate::node::Node;
|
||||
|
||||
/// The default bytes for a union field the source does not carry: the census
|
||||
/// default for declared names, zeroes otherwise.
|
||||
fn default_fill_bytes(name: &str, size: usize) -> Box<[u8]> {
|
||||
let mut bytes = vec![0u8; size].into_boxed_slice();
|
||||
if let Some(info) = attribute::info(name)
|
||||
&& info.size == size
|
||||
{
|
||||
(info.write_default_bytes)(&mut bytes);
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
/// A routing source's wiring-resolved translation: field moves into the
|
||||
/// union layout plus census default fill for union fields the source lacks.
|
||||
/// Absent when the source's layout already equals the union, in which case
|
||||
/// the record pointer forwards untouched.
|
||||
#[derive(Debug)]
|
||||
pub struct SourcePlan {
|
||||
moves: Vec<(usize, usize, usize)>,
|
||||
fills: Vec<(usize, Box<[u8]>)>,
|
||||
source: Layout,
|
||||
}
|
||||
|
||||
impl SourcePlan {
|
||||
pub fn new(source: &Layout, union: &Layout) -> Option<SourcePlan> {
|
||||
if source == union {
|
||||
return None;
|
||||
}
|
||||
let moves = copy_plan(source, union, true, &[]);
|
||||
let fills = union
|
||||
.fields
|
||||
.iter()
|
||||
.filter(|field| source.offset_of(field.name, field.level).is_none())
|
||||
.map(|field| (field.offset, default_fill_bytes(field.name, field.size)))
|
||||
.collect();
|
||||
Some(SourcePlan { moves, fills, source: source.clone() })
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `src` must be a record of this plan's source layout and `dst` a
|
||||
/// buffer of the plan's union layout that does not overlap `src`. The
|
||||
/// returned view borrows `dst`, so `'d` must not outlive it.
|
||||
pub unsafe fn translate<'d>(&self, src: Rec<'_>, dst: *mut u8) -> Rec<'d> {
|
||||
// SAFETY: the caller's contract; the plan's moves and fills name only
|
||||
// offsets of the layouts it was built from.
|
||||
unsafe {
|
||||
apply_plan(src, dst, &self.moves);
|
||||
for (offset, bytes) in &self.fills {
|
||||
std::ptr::copy_nonoverlapping(bytes.as_ptr(), dst.add(*offset), bytes.len());
|
||||
}
|
||||
Rec::new(dst)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A routing input's claimed source plus its wiring-resolved [`SourcePlan`].
|
||||
/// Evaluating it yields the source's record translated to the union layout
|
||||
/// (or forwarded untouched when the layouts already agree), so the kernel
|
||||
/// holds and returns record values without ever seeing the representation.
|
||||
/// A translation lands in the claim the caller minted, so the value survives
|
||||
/// sibling evaluations and its region is free again with that claim, which
|
||||
/// bounds claims at one per source evaluation the kernel performs.
|
||||
pub struct RecordSource<N> {
|
||||
edge: N,
|
||||
plan: Option<SourcePlan>,
|
||||
union: Layout,
|
||||
}
|
||||
|
||||
impl<N> RecordSource<N> {
|
||||
pub fn new(edge: N, source: &Layout, union: &Layout) -> Self {
|
||||
Self {
|
||||
edge,
|
||||
plan: SourcePlan::new(source, union),
|
||||
union: union.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<C, N> Node<C> for RecordSource<N>
|
||||
where
|
||||
N: Node<C>,
|
||||
{
|
||||
fn serve<'e, 'l>(&self, input: &C, mut slot: FrameClaim<'e, 'l>) -> GPoll<Served<'e>>
|
||||
where
|
||||
C: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||
{
|
||||
// The source's frame is claimed beyond this one and dies with the
|
||||
// claim; the translated union record stays.
|
||||
let Some(plan) = &self.plan else {
|
||||
return self.edge.serve(input, slot);
|
||||
};
|
||||
match serve_input(&self.edge, input, &slot.frames().reborrow()) {
|
||||
GPoll::Final(value) => {
|
||||
// SAFETY: the value came from this source, so it carries the
|
||||
// plan's source layout.
|
||||
unsafe { slot.translate(plan.source.rec(&value), plan) };
|
||||
// SAFETY: the translation completes the union record.
|
||||
GPoll::Final(unsafe { slot.finish_served() })
|
||||
}
|
||||
GPoll::Partial(value) => {
|
||||
// SAFETY: as for the final arm.
|
||||
unsafe { slot.translate(plan.source.rec(&value), plan) };
|
||||
// SAFETY: as for the final arm.
|
||||
GPoll::Partial(unsafe { slot.finish_served() })
|
||||
}
|
||||
GPoll::Fallback(boxed) => {
|
||||
let (value, error) = *boxed;
|
||||
// SAFETY: as for the final arm.
|
||||
unsafe { slot.translate(plan.source.rec(&value), plan) };
|
||||
// SAFETY: as for the final arm.
|
||||
GPoll::Fallback(Box::new((unsafe { slot.finish_served() }, error)))
|
||||
}
|
||||
GPoll::Pending => GPoll::Pending,
|
||||
GPoll::Error(error) => GPoll::Error(error),
|
||||
}
|
||||
}
|
||||
|
||||
fn extent_at<'x>(&self, input: &C, level: u8, frames: &Frames<'x>) -> GPoll<crate::gpoll::Extent>
|
||||
where
|
||||
C: crate::context::ExtractArena<ArenaRef = &'x crate::arena::Arena>,
|
||||
{
|
||||
self.edge.extent_at(input, level, frames)
|
||||
}
|
||||
|
||||
fn layout(&self) -> &Layout {
|
||||
&self.union
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::record::layout::element_write;
|
||||
use crate::record::test_support::f64_field;
|
||||
|
||||
#[test]
|
||||
fn translation_moves_fields_and_fills_census_defaults() {
|
||||
let source = Layout::default().with_writes(0, element_write::<f64>(), &[f64_field("length")]);
|
||||
let union = Layout::union(&[&source, &Layout::default().with_writes(0, element_write::<f64>(), &[f64_field("opacity")])]);
|
||||
|
||||
let plan = SourcePlan::new(&source, &union).unwrap();
|
||||
let record = [5f64, 7f64];
|
||||
let mut buffer = vec![0u64; union.size.div_ceil(8)];
|
||||
let translated = unsafe { plan.translate(Rec::new(record.as_ptr().cast()), buffer.as_mut_ptr().cast()) };
|
||||
assert_eq!(unsafe { translated.element::<f64>() }, 5.);
|
||||
assert_eq!(unsafe { translated.read::<f64>(union.offset_of("length", 0).unwrap()) }, 7.);
|
||||
assert_eq!(unsafe { translated.read::<f64>(union.offset_of("opacity", 0).unwrap()) }, 1.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identity_layouts_forward() {
|
||||
let layout = Layout::default().with_writes(0, element_write::<f64>(), &[f64_field("opacity")]);
|
||||
assert!(SourcePlan::new(&layout, &layout.clone()).is_none());
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,389 @@
|
||||
//! The serving protocol: a node's own frame claim and the proof it closes with.
|
||||
|
||||
use super::access::{Rec, RecordValue, apply_plan, lift_poll_into, write_element, write_field};
|
||||
use super::frames::Frames;
|
||||
use super::layout::{Layout, element_dims, element_parked};
|
||||
use super::route::SourcePlan;
|
||||
use crate::gpoll::GPoll;
|
||||
use crate::node::Node;
|
||||
|
||||
/// A claimed run of same-layout slots over the caller's scratch: [`Self::slot`]
|
||||
/// backs an ordinary claim's own region by the lane's region of the slab, so a
|
||||
/// lane serves in place with no staging copy, and [`Self::served`] records the
|
||||
/// proof. The filled prefix is the only readable part, which is what makes
|
||||
/// [`Self::finish`] safe.
|
||||
pub struct SlotRun<'a> {
|
||||
scratch: &'a mut [std::mem::MaybeUninit<u64>],
|
||||
layout: &'a Layout,
|
||||
len: usize,
|
||||
filled: usize,
|
||||
}
|
||||
|
||||
impl<'a> SlotRun<'a> {
|
||||
/// `None` where the scratch cannot hold `len` lanes. The products are
|
||||
/// checked: the stride is a multiple of 8, so a wrapped one would pass the
|
||||
/// capacity test vacuously.
|
||||
pub(in crate::record) fn new(scratch: &'a mut [std::mem::MaybeUninit<u64>], len: usize, layout: &'a Layout) -> Option<SlotRun<'a>> {
|
||||
let need = len.checked_mul(layout.lane_stride())?;
|
||||
let capacity = scratch.len().checked_mul(8)?;
|
||||
(capacity >= need).then_some(SlotRun { scratch, layout, len, filled: 0 })
|
||||
}
|
||||
|
||||
pub fn layout(&self) -> &'a Layout {
|
||||
self.layout
|
||||
}
|
||||
|
||||
/// Lane `lane`'s claim: its own frame is the lane's region of the slab and
|
||||
/// its free space is `frames`, so the lane's inputs claim beyond it.
|
||||
pub fn slot<'e>(&mut self, lane: usize, frames: &Frames<'e>) -> FrameClaim<'e, 'a> {
|
||||
assert!(lane < self.len, "lane {lane} out of bounds for a run of {}", self.len);
|
||||
let stride = self.layout.lane_stride();
|
||||
// SAFETY: in-bounds by the assert against the capacity check `new` made.
|
||||
let frame = unsafe { self.scratch.as_mut_ptr().cast::<u8>().add(lane * stride) };
|
||||
|
||||
FrameClaim {
|
||||
layout: self.layout,
|
||||
inline: RecordValue::zeroed(),
|
||||
frame: (self.layout.frame_bytes() != 0).then_some(frame),
|
||||
free: frames.reborrow(),
|
||||
filled_fields: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Records lane `lane` as served; the proof came from that lane's slot. An
|
||||
/// inline record rides the value's own storage, so it takes the one copy
|
||||
/// the run makes. Lanes serve in ascending order with no gaps, so the
|
||||
/// filled count is an initialized prefix rather than a high-water mark.
|
||||
pub fn served(&mut self, lane: usize, proof: &Served<'_>) {
|
||||
assert!(lane < self.len, "lane {lane} out of bounds for a run of {}", self.len);
|
||||
assert_eq!(lane, self.filled, "lane {lane} serves out of order after {} filled lanes", self.filled);
|
||||
if self.layout.size == 0 {
|
||||
let stride = self.layout.lane_stride();
|
||||
// SAFETY: in-bounds by the assert against the capacity check `new`
|
||||
// made, and the lane takes the whole inline record.
|
||||
unsafe { std::ptr::copy_nonoverlapping(self.layout.rec(proof.record()).ptr(), self.scratch.as_mut_ptr().cast::<u8>().add(lane * stride), stride) };
|
||||
}
|
||||
self.filled = lane + 1;
|
||||
}
|
||||
|
||||
/// The served lanes as the caller's exclusive batch.
|
||||
pub fn finish(self) -> crate::node::RecordBatchMut<'a> {
|
||||
crate::node::RecordBatchMut::new(self.scratch, self.filled, self.layout)
|
||||
}
|
||||
}
|
||||
|
||||
/// A node's own output frame, minted by its caller from the caller's frame
|
||||
/// space: the one closing surface for every exit. Writes land through it,
|
||||
/// [`Self::lift`] and [`Self::finish`] serve the record, and it carries the
|
||||
/// free space beyond the frame, so a node's inputs claim past it and their
|
||||
/// space is free again when the claim dies, on value, error, and pending exits
|
||||
/// alike with no per-exit ritual.
|
||||
pub struct FrameClaim<'e, 'l> {
|
||||
pub(in crate::record) layout: &'l Layout,
|
||||
pub(in crate::record) inline: RecordValue<'static>,
|
||||
pub(in crate::record) frame: Option<*mut u8>,
|
||||
pub(in crate::record) free: Frames<'e>,
|
||||
/// Set by the writes that fill the declared fields, so the safe closers can
|
||||
/// refuse a field-bearing frame that was never filled.
|
||||
pub(in crate::record) filled_fields: bool,
|
||||
}
|
||||
|
||||
impl<'e, 'l> FrameClaim<'e, 'l> {
|
||||
/// The free space beyond this claim's frame, which the node's own inputs
|
||||
/// claim from.
|
||||
pub fn frames(&mut self) -> &Frames<'e> {
|
||||
&mut self.free
|
||||
}
|
||||
|
||||
pub(in crate::record) fn dst(&mut self) -> *mut u8 {
|
||||
match self.frame {
|
||||
Some(frame) => frame,
|
||||
None => (&raw mut self.inline).cast(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Asserts the served element matches the wired layout, so a node whose
|
||||
/// layout never resolved (or resolved at another type) panics here
|
||||
/// instead of writing past its frame.
|
||||
fn check_element<T: dyn_any::StaticTypeSized>(&self) {
|
||||
let (size, _) = element_dims::<T>();
|
||||
assert!(
|
||||
self.layout.element.size == size && self.layout.element.parked == element_parked::<T>() && self.layout.element.type_id == std::any::TypeId::of::<T::Static>(),
|
||||
"the served element `{}` ({size} bytes) must match the wired layout ({} bytes)",
|
||||
std::any::type_name::<T>(),
|
||||
self.layout.element.size,
|
||||
);
|
||||
}
|
||||
|
||||
/// Carries the plan's fields from a source record into the frame.
|
||||
///
|
||||
/// # Safety
|
||||
/// `src` must be a live record of the plan's source layout, and the plan
|
||||
/// must be the wiring-resolved plan of this frame's layout. `src` must not
|
||||
/// overlap this frame; an input's frame is split off beyond the claim, so
|
||||
/// serving the source through [`Self::frames`] establishes it.
|
||||
pub unsafe fn carry(&mut self, src: Rec<'_>, plan: &[(usize, usize, usize)]) {
|
||||
unsafe { apply_plan(src, self.dst(), plan) };
|
||||
self.filled_fields = true;
|
||||
}
|
||||
|
||||
/// Writes a field at its wiring-resolved offset.
|
||||
///
|
||||
/// # Safety
|
||||
/// `offset` must be this layout's resolved offset for a field of `T`. A
|
||||
/// generated write offset defaults to 0 until `set_layout` installs it, so
|
||||
/// the debug assertion catches a serve that ran before the install.
|
||||
pub unsafe fn attr_at<T>(&mut self, offset: usize, value: T) {
|
||||
debug_assert!(
|
||||
self.layout.fields.iter().any(|field| field.offset == offset),
|
||||
"attribute write at an offset this layout does not carry; the layout must install before serving"
|
||||
);
|
||||
unsafe { write_field(self.dst(), offset, value) };
|
||||
self.filled_fields = true;
|
||||
}
|
||||
|
||||
/// Writes the element; `None` reports arena exhaustion for a parked
|
||||
/// element. Panics where the element does not match the wired layout.
|
||||
pub fn element<T: Send + Sync + dyn_any::StaticTypeSized>(&mut self, value: T, arena: &crate::arena::Arena) -> Option<()> {
|
||||
self.check_element::<T>();
|
||||
// SAFETY: the frame is this layout's fresh claim and the element
|
||||
// check pinned `T` to the layout's element slot.
|
||||
unsafe { write_element(self.dst(), value, arena) }
|
||||
}
|
||||
|
||||
/// Lifts a kernel's poll into the frame and closes it: the element
|
||||
/// writes on value polls, every poll keeps the frame claimed, and arena
|
||||
/// exhaustion of a parked element reports as an error poll. Panics where
|
||||
/// the element does not match the wired layout, or where a field-bearing
|
||||
/// layout closes on a frame no carry or field write ever filled, since the
|
||||
/// [`Served`] proof certifies the whole record and the fields would be the
|
||||
/// prior frame's bytes.
|
||||
pub fn lift<T: Send + Sync + dyn_any::StaticTypeSized>(mut self, poll: GPoll<T>, arena: &'e crate::arena::Arena) -> GPoll<RecordValue<'e>> {
|
||||
self.check_element::<T>();
|
||||
assert!(
|
||||
self.layout.fields.is_empty() || self.filled_fields,
|
||||
"a layout with {} fields must carry or write them before lifting",
|
||||
self.layout.fields.len()
|
||||
);
|
||||
let frame_bytes = self.layout.frame_bytes();
|
||||
let dst = self.dst();
|
||||
// SAFETY: the frame is this layout's fresh claim, the element check
|
||||
// pinned `T`, and the drop keeps the frame contract on every poll.
|
||||
unsafe { lift_poll_into(poll, dst, frame_bytes, arena) }
|
||||
}
|
||||
|
||||
/// Copies a complete record of this layout into the frame, for serving
|
||||
/// cached or published bytes.
|
||||
///
|
||||
/// # Safety
|
||||
/// `src` must point at a live record of this layout whose parked
|
||||
/// references outlive the serving evaluation.
|
||||
pub unsafe fn fill_copy(&mut self, src: *const u8) {
|
||||
unsafe { std::ptr::copy_nonoverlapping(src, self.dst(), self.layout.size) };
|
||||
self.filled_fields = true;
|
||||
}
|
||||
|
||||
/// The served record. The frame stays claimed for the consumer; the drop
|
||||
/// releases only what was claimed above it.
|
||||
///
|
||||
/// # Safety
|
||||
/// The frame must hold a complete record of the layout, written through
|
||||
/// the carry, element, and field writes.
|
||||
pub unsafe fn finish(mut self) -> RecordValue<'e> {
|
||||
match self.frame {
|
||||
Some(frame) => RecordValue::spilled(unsafe { Rec::new(frame.cast_const()) }),
|
||||
// SAFETY: the inline record is the value's own bytes.
|
||||
None => unsafe { (&raw mut self.inline).cast::<RecordValue<'e>>().read() },
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Self::lift`] with the proof-bearing return for [`Node::serve`].
|
||||
pub fn lift_served<T: Send + Sync + dyn_any::StaticTypeSized>(self, poll: GPoll<T>, arena: &'e crate::arena::Arena) -> GPoll<Served<'e>> {
|
||||
self.lift(poll, arena).map(|value| Served { value })
|
||||
}
|
||||
|
||||
/// [`Self::finish`] with the proof-bearing return for [`Node::serve`].
|
||||
///
|
||||
/// # Safety
|
||||
/// As [`Self::finish`].
|
||||
pub unsafe fn finish_served(self) -> Served<'e> {
|
||||
Served { value: unsafe { self.finish() } }
|
||||
}
|
||||
|
||||
/// Fills the frame from a record a forwarded input already served, and
|
||||
/// closes it: the source's frame sits above this claim and dies with its
|
||||
/// drop, so the served record is this claim's own.
|
||||
///
|
||||
/// # Safety
|
||||
/// `value` must be a live record of this frame's layout.
|
||||
pub unsafe fn forward(mut self, value: &RecordValue<'_>) -> Served<'e> {
|
||||
let src = self.layout.rec(value).ptr();
|
||||
unsafe {
|
||||
self.fill_copy(src);
|
||||
self.finish_served()
|
||||
}
|
||||
}
|
||||
|
||||
/// Translates a source record into the frame through a wiring-resolved plan.
|
||||
///
|
||||
/// # Safety
|
||||
/// `src` must be a live record of `plan`'s source layout, `plan` must
|
||||
/// translate into this frame's layout, and `src` must not overlap this
|
||||
/// frame, as [`Self::carry`] requires.
|
||||
pub unsafe fn translate(&mut self, src: Rec<'_>, plan: &SourcePlan) {
|
||||
unsafe { plan.translate(src, self.dst()) };
|
||||
self.filled_fields = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// A materialized run of lanes as the arena region its frames live in: the
|
||||
/// handle keeps the provenance the region was allocated with and carries the
|
||||
/// generation, so resolving it re-checks liveness where an address would have
|
||||
/// been trusted. The layout stays with the holder, which proved it at wiring.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct MaterializedSpan {
|
||||
pub(in crate::record) base: crate::arena::ArenaWeak<u8>,
|
||||
pub(in crate::record) len: usize,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for MaterializedSpan {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("MaterializedSpan").field("len", &self.len).finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl MaterializedSpan {
|
||||
/// `None` where the batch's frames are not this arena's, which is the
|
||||
/// caller's cue to re-materialize rather than cache.
|
||||
pub fn of(batch: &crate::node::RecordBatch<'_>, arena: &crate::arena::Arena) -> Option<MaterializedSpan> {
|
||||
match batch.len() {
|
||||
0 => Some(MaterializedSpan {
|
||||
base: crate::arena::ArenaWeak::NULL,
|
||||
len: 0,
|
||||
}),
|
||||
len => Some(MaterializedSpan {
|
||||
base: arena.handle_at(batch.get(0).rec().ptr())?,
|
||||
len,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// The span's lanes at `layout`, or `None` once the generation moved on.
|
||||
pub fn batch<'a>(&self, arena: &'a crate::arena::Arena, layout: &'a Layout) -> Option<crate::node::RecordBatch<'a>> {
|
||||
let base: *const u8 = match self.len {
|
||||
0 => std::ptr::NonNull::<u8>::dangling().as_ptr(),
|
||||
_ => self.base.upgrade(arena)?,
|
||||
};
|
||||
// SAFETY: the handle resolved in generation, so the region still holds
|
||||
// the lanes it was published with, packed at the layout's stride; an
|
||||
// empty span reads no lane.
|
||||
Some(unsafe { crate::node::RecordBatch::new(base, self.len, layout) })
|
||||
}
|
||||
|
||||
/// Lane `lane`'s record, or `None` past the span or once the generation
|
||||
/// moved on.
|
||||
pub fn lane(&self, arena: &crate::arena::Arena, lane: usize, layout: &Layout) -> Option<*const u8> {
|
||||
(lane < self.len).then_some(())?;
|
||||
let base: *const u8 = self.base.upgrade(arena)?;
|
||||
// SAFETY: in-bounds by the length check, at the layout the span was
|
||||
// published under.
|
||||
Some(unsafe { base.add(lane * layout.lane_stride()) })
|
||||
}
|
||||
}
|
||||
|
||||
/// The proof a record was served through a frame claim: mintable only by the
|
||||
/// claim's closing methods, so holding one means the record is of the
|
||||
/// claimed layout.
|
||||
pub struct Served<'e> {
|
||||
value: RecordValue<'e>,
|
||||
}
|
||||
|
||||
impl<'e> Served<'e> {
|
||||
pub fn value(self) -> RecordValue<'e> {
|
||||
self.value
|
||||
}
|
||||
|
||||
/// The served record in place, for producers that read it before passing
|
||||
/// the proof on.
|
||||
pub fn record(&self) -> &RecordValue<'e> {
|
||||
&self.value
|
||||
}
|
||||
}
|
||||
|
||||
/// Claims `node`'s own frame from `frames` and serves through it: the
|
||||
/// caller-side half of [`Node::serve`], for drivers that want the record
|
||||
/// rather than the proof.
|
||||
pub fn serve_input<'e, C, N>(node: &N, input: &C, frames: &Frames<'e>) -> GPoll<RecordValue<'e>>
|
||||
where
|
||||
N: Node<C> + ?Sized,
|
||||
C: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||
{
|
||||
let slot = frames.claim(node.layout());
|
||||
node.serve(input, slot).map(Served::value)
|
||||
}
|
||||
|
||||
/// A claim shortens onto a derived context's arena lifetime.
|
||||
#[cfg(test)]
|
||||
fn claim_shortens<'long: 'short, 'short, 'l>(claim: FrameClaim<'long, 'l>) -> FrameClaim<'short, 'l> {
|
||||
claim
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::record::frames::FrameArena;
|
||||
use crate::record::layout::element_write;
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "must match the wired layout")]
|
||||
fn a_mistyped_element_is_rejected_at_the_write() {
|
||||
let arena = crate::arena::Arena::new(256).unwrap();
|
||||
let layout = Layout::default().with_writes(0, element_write::<f64>(), &[]);
|
||||
let mut frame_arena = FrameArena::new();
|
||||
frame_arena.reserve(1 << 10);
|
||||
let frames = frame_arena.frames();
|
||||
frames.claim(&layout).element(1u32, &arena);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_refuses_a_lane_count_whose_stride_product_overflows() {
|
||||
let layout = Layout::default().with_writes(0, element_write::<f64>(), &[]);
|
||||
let mut scratch = [std::mem::MaybeUninit::<u64>::uninit(); 4];
|
||||
let mut frame_arena = FrameArena::new();
|
||||
frame_arena.reserve(64);
|
||||
let frames = frame_arena.frames();
|
||||
let wrapping = usize::MAX / layout.lane_stride() + 1;
|
||||
assert!(frames.run(&mut scratch, wrapping, &layout).is_none(), "a wrapped capacity product must not pass the check");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "serves out of order")]
|
||||
fn a_run_refuses_a_gapped_serve() {
|
||||
let arena = crate::arena::Arena::new(1024).unwrap();
|
||||
let layout = Layout::default().with_writes(0, element_write::<f64>(), &[]);
|
||||
let mut scratch = [std::mem::MaybeUninit::<u64>::uninit(); 8];
|
||||
let mut frame_arena = FrameArena::new();
|
||||
frame_arena.reserve(1 << 10);
|
||||
let frames = frame_arena.frames();
|
||||
let mut run = frames.run(&mut scratch, 3, &layout).unwrap();
|
||||
let lane_frames = frames.scope();
|
||||
let slot = run.slot(2, &lane_frames);
|
||||
let GPoll::Final(proof) = slot.lift_served(GPoll::Final(1.0f64), &arena) else {
|
||||
panic!("expected a final record");
|
||||
};
|
||||
run.served(2, &proof);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_claim_shortens_onto_a_derived_lifetime() {
|
||||
fn shorten<'long: 'short, 'short, 'l>(claim: FrameClaim<'long, 'l>) -> FrameClaim<'short, 'l> {
|
||||
claim_shortens(claim)
|
||||
}
|
||||
let layout = Layout::default().with_writes(0, element_write::<f64>(), &[]);
|
||||
let mut frame_arena = FrameArena::new();
|
||||
frame_arena.reserve(64);
|
||||
let frames = frame_arena.frames();
|
||||
let claim = shorten(frames.claim(&layout));
|
||||
assert_eq!(claim.layout, &layout);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
//! Shared fixtures for the record module family's tests.
|
||||
|
||||
use super::layout::FieldWrite;
|
||||
|
||||
unsafe fn unread(_: *const u8) -> Box<dyn crate::list::AnyAttributeValue> {
|
||||
unreachable!("layout-only test field")
|
||||
}
|
||||
|
||||
pub(super) fn sized_field(name: &'static str, size: usize, align: usize) -> FieldWrite {
|
||||
FieldWrite {
|
||||
name,
|
||||
level: 0,
|
||||
size,
|
||||
align,
|
||||
type_id: std::any::TypeId::of::<()>(),
|
||||
read_erased: unread,
|
||||
repark: None,
|
||||
content_hash: None,
|
||||
content_eq: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn f64_field(name: &'static str) -> FieldWrite {
|
||||
sized_field(name, 8, 8)
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
//! Law-test scaffolding over the record tier.
|
||||
|
||||
use super::frames::{FrameArena, Frames};
|
||||
use super::layout::{Layout, element_write};
|
||||
use super::owned::OwnedRecord;
|
||||
use super::serve::{FrameClaim, Served, serve_input};
|
||||
use crate::gpoll::GPoll;
|
||||
use crate::node::Node;
|
||||
|
||||
/// Law-test scaffolding: a frame space of `bytes`, leaked so a fixture holds
|
||||
/// it for the whole test without threading the buffer's own borrow. Production
|
||||
/// roots own their buffer and lend it by `&mut`.
|
||||
#[doc(hidden)]
|
||||
pub fn test_frames(bytes: usize) -> Frames<'static> {
|
||||
let arena: &'static mut FrameArena = Box::leak(Box::new(FrameArena::new()));
|
||||
arena.reserve(bytes);
|
||||
arena.frames()
|
||||
}
|
||||
|
||||
/// One record captured out of a poll: the deep copy plus the layout it was
|
||||
/// served at, so assertions read owned storage with no tie to the record
|
||||
/// stack. [`capture`] is the only constructor.
|
||||
pub struct ServedRecord {
|
||||
layout: Layout,
|
||||
record: OwnedRecord,
|
||||
}
|
||||
|
||||
impl ServedRecord {
|
||||
pub fn layout(&self) -> &Layout {
|
||||
&self.layout
|
||||
}
|
||||
|
||||
/// The element, cloned out of the capture. Panics unless `T` is the
|
||||
/// layout's element type.
|
||||
pub fn element<T: Clone + 'static>(&self) -> T {
|
||||
assert_eq!(std::any::TypeId::of::<T>(), self.layout.element.type_id, "the read type must match the layout's element type");
|
||||
match &self.record.element {
|
||||
Some(parked) => parked.downcast_ref::<T>().expect("the element parked at its own type").clone(),
|
||||
// SAFETY: the captured bytes image a record of this layout; a
|
||||
// byte-carried element is a `T` with no drop glue.
|
||||
None => unsafe { self.record.bytes.as_ptr().cast::<T>().read_unaligned() },
|
||||
}
|
||||
}
|
||||
|
||||
/// The marker's level-0 field value. Panics unless the layout declares
|
||||
/// the marker at its value type.
|
||||
pub fn attr<A: crate::attribute::Attribute>(&self) -> A::Value<'static>
|
||||
where
|
||||
A::Value<'static>: Copy + 'static,
|
||||
{
|
||||
self.field(A::NAME, 0)
|
||||
}
|
||||
|
||||
/// A field by name and level, for layouts whose fields are not census
|
||||
/// markers. Panics unless the field is declared at `T` and byte-carried;
|
||||
/// a parked field reads through replay, not the captured bytes.
|
||||
pub fn field<T: Copy + 'static>(&self, name: &str, level: u8) -> T {
|
||||
let field = self
|
||||
.layout
|
||||
.fields
|
||||
.iter()
|
||||
.find(|field| field.name == name && field.level == level)
|
||||
.expect("the layout carries the read field");
|
||||
assert_eq!(field.type_id, std::any::TypeId::of::<T>(), "the field was declared at this value type");
|
||||
assert!(field.repark.is_none(), "a parked field reads through replay, not the captured bytes");
|
||||
// SAFETY: the captured bytes image a record of this layout and the
|
||||
// field is byte-carried at `T`.
|
||||
unsafe { self.record.bytes.as_ptr().add(field.offset).cast::<T>().read_unaligned() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Polls `node` once and captures any served record: the record is
|
||||
/// deep-copied at the node's own declared layout inside a frame scope, so the
|
||||
/// result is owned and every claimed frame is free again. Assertion
|
||||
/// scaffolding for law tests; production consumers read served records in
|
||||
/// place.
|
||||
pub fn capture<'e, C, N>(node: &N, ctx: &C, frames: &Frames<'e>) -> GPoll<ServedRecord>
|
||||
where
|
||||
N: Node<C> + ?Sized,
|
||||
C: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||
{
|
||||
let scope = frames.scope();
|
||||
let layout = node.layout().clone();
|
||||
serve_input(node, ctx, &scope).map(|value| ServedRecord {
|
||||
// SAFETY: the poll served `value` at the node's declared layout and
|
||||
// nothing has claimed frames since.
|
||||
record: unsafe { OwnedRecord::copy_out(&layout, layout.rec(&value)) },
|
||||
layout: layout.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Law-test scaffolding: a kernel closure served onto an element-only record
|
||||
/// input (the element lands at offset 0, parked when it carries drop glue). No
|
||||
/// production path constructs one; value sources are
|
||||
/// [`crate::value::ValueSource`].
|
||||
pub struct LiftedSource<El, F> {
|
||||
kernel: F,
|
||||
layout: Layout,
|
||||
_marker: std::marker::PhantomData<fn() -> El>,
|
||||
}
|
||||
|
||||
impl<El: Clone + Send + Sync + dyn_any::StaticTypeSized, F> LiftedSource<El, F>
|
||||
where
|
||||
El::Static: Clone + Send + Sync,
|
||||
{
|
||||
pub fn new(kernel: F) -> Self {
|
||||
Self {
|
||||
kernel,
|
||||
layout: Layout::default().with_writes(0, element_write::<El>(), &[]),
|
||||
_marker: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<C, El, F> Node<C> for LiftedSource<El, F>
|
||||
where
|
||||
El: Send + Sync + dyn_any::StaticTypeSized,
|
||||
F: Fn(&C) -> GPoll<El>,
|
||||
{
|
||||
fn serve<'e, 'l>(&self, input: &C, slot: FrameClaim<'e, 'l>) -> GPoll<Served<'e>>
|
||||
where
|
||||
C: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||
{
|
||||
slot.lift_served((self.kernel)(input), input.arena())
|
||||
}
|
||||
|
||||
fn layout(&self) -> &Layout {
|
||||
&self.layout
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::record::layout::FieldWrite;
|
||||
|
||||
#[test]
|
||||
fn a_captured_frame_serves_its_writes() {
|
||||
use crate::attribute::{Attribute, Transform};
|
||||
use glam::{DAffine2, DVec2};
|
||||
|
||||
struct Fixture {
|
||||
layout: Layout,
|
||||
}
|
||||
|
||||
impl<C> Node<C> for Fixture {
|
||||
fn serve<'e, 'l>(&self, input: &C, mut slot: FrameClaim<'e, 'l>) -> GPoll<Served<'e>>
|
||||
where
|
||||
C: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||
{
|
||||
let offset = self.layout.offset_of(Transform::NAME, 0).expect("the fixture's layout carries the transform");
|
||||
if slot.element(String::from("parked"), crate::context::ExtractArena::arena(input)).is_none() {
|
||||
return GPoll::error("arena exhausted");
|
||||
}
|
||||
// SAFETY: the offset is this layout's own, at the marker's value type.
|
||||
unsafe { slot.attr_at(offset, DAffine2::from_translation(DVec2::new(3., 4.))) };
|
||||
// SAFETY: the writes above complete the record.
|
||||
GPoll::Final(unsafe { slot.finish_served() })
|
||||
}
|
||||
|
||||
fn layout(&self) -> &Layout {
|
||||
&self.layout
|
||||
}
|
||||
}
|
||||
|
||||
let layout = Layout::default().with_writes(0, element_write::<String>(), &[FieldWrite::of::<Transform>(0)]);
|
||||
let mut frame_arena = FrameArena::new();
|
||||
frame_arena.reserve(1 << 10);
|
||||
let frames = frame_arena.frames();
|
||||
let arena = crate::arena::Arena::new(1024).unwrap();
|
||||
let generations = [];
|
||||
let scope = crate::context::EvalScope::new(None, None, None, &generations, &arena);
|
||||
let ctx = crate::context::ContextImpl::root(&scope);
|
||||
let free = frames.free_words();
|
||||
let GPoll::Final(served) = capture(&Fixture { layout }, &ctx, &frames) else {
|
||||
panic!("the fixture serves finally");
|
||||
};
|
||||
assert_eq!(frames.free_words(), free, "capture returns every claimed slot");
|
||||
assert_eq!(served.element::<String>(), "parked");
|
||||
assert_eq!(served.attr::<Transform>(), DAffine2::from_translation(DVec2::new(3., 4.)));
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,7 @@ pub struct NodeMetadata {
|
||||
pub context_features: Vec<ContextFeature>,
|
||||
pub memoize: bool,
|
||||
pub inject_scope: bool,
|
||||
/// The macro appended its hidden `_runtime` and `_source` fields as the last two entries of `fields`.
|
||||
/// Set where `_runtime` and `_source` are the last two entries of `fields`.
|
||||
pub async_source_fields: bool,
|
||||
}
|
||||
|
||||
@@ -72,27 +72,27 @@ pub static NODE_METADATA: LazyLock<Mutex<HashMap<ProtoNodeIdentifier, NodeMetada
|
||||
|
||||
pub use crate::NodeIOTypes;
|
||||
|
||||
/// Element-independent by erasure; the wire's `Type::Record(El)` keeps element reads proven at wiring.
|
||||
/// Element-independent by erasure; the input's `Type::Record(El)` keeps element reads proven at wiring.
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub type ErasedRecordNode = dyn for<'c> Node<ContextImpl<'c>> + Send + Sync;
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub type ErasedRecordNode = dyn for<'c> Node<ContextImpl<'c>>;
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
type DynEdge = dyn std::any::Any + Send + Sync;
|
||||
type DynSource = dyn std::any::Any + Send + Sync;
|
||||
#[cfg(target_family = "wasm")]
|
||||
type DynEdge = dyn std::any::Any;
|
||||
type DynSource = dyn std::any::Any;
|
||||
|
||||
pub fn record_type<T: 'static>() -> Type {
|
||||
Type::Record(Box::new(concrete!(T)))
|
||||
}
|
||||
|
||||
pub fn record_edge_type<T: 'static>() -> Type {
|
||||
pub fn record_source_type<T: 'static>() -> Type {
|
||||
Type::Fn(Box::new(concrete!(Context)), Box::new(record_type::<T>()))
|
||||
}
|
||||
|
||||
/// The record edge type of a token row, generic over the element.
|
||||
pub fn generic_record_edge_type(name: &'static str) -> Type {
|
||||
/// The record source type of a token row, generic over the element.
|
||||
pub fn generic_record_source_type(name: &'static str) -> Type {
|
||||
Type::Fn(Box::new(concrete!(Context)), Box::new(Type::Record(Box::new(Type::Generic(std::borrow::Cow::Borrowed(name))))))
|
||||
}
|
||||
|
||||
@@ -108,12 +108,12 @@ pub enum ConstructionError {
|
||||
Type { expected: Box<Type>, found: Box<Type> },
|
||||
}
|
||||
|
||||
pub struct SharedEdge<N: ?Sized> {
|
||||
pub struct SharedSource<N: ?Sized> {
|
||||
ptr: std::ptr::NonNull<N>,
|
||||
own: std::sync::Arc<N>,
|
||||
}
|
||||
|
||||
impl<N: ?Sized> SharedEdge<N> {
|
||||
impl<N: ?Sized> SharedSource<N> {
|
||||
pub fn new(own: std::sync::Arc<N>) -> Self {
|
||||
Self {
|
||||
ptr: std::ptr::NonNull::from(&*own),
|
||||
@@ -127,25 +127,32 @@ impl<N: ?Sized> SharedEdge<N> {
|
||||
|
||||
/// 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.
|
||||
/// every mutation through `own` ends here, an unwinding one included.
|
||||
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
|
||||
// thread safe as the payload it shares.
|
||||
unsafe impl<N: ?Sized + Send + Sync> Send for SharedEdge<N> {}
|
||||
// SAFETY: as in Send.
|
||||
unsafe impl<N: ?Sized + Send + Sync> Sync for SharedEdge<N> {}
|
||||
/// Re-derives on the way out of an exclusive re-borrow, so a mutation that
|
||||
/// panics cannot leave the cached pointer retired for a caller that catches.
|
||||
struct Rederive<'a, N: ?Sized>(&'a mut SharedSource<N>);
|
||||
|
||||
impl<Input, N> Node<Input> for SharedEdge<N>
|
||||
impl<N: ?Sized> Drop for Rederive<'_, N> {
|
||||
fn drop(&mut self) {
|
||||
self.0.rederive();
|
||||
}
|
||||
}
|
||||
|
||||
// SAFETY: `ptr` is derived from the owned Arc and never mutated through, so the source is exactly as
|
||||
// thread safe as the payload it shares.
|
||||
unsafe impl<N: ?Sized + Send + Sync> Send for SharedSource<N> {}
|
||||
// SAFETY: as in Send.
|
||||
unsafe impl<N: ?Sized + Send + Sync> Sync for SharedSource<N> {}
|
||||
|
||||
impl<Input, N> Node<Input> for SharedSource<N>
|
||||
where
|
||||
N: Node<Input> + ?Sized,
|
||||
{
|
||||
/// 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>,
|
||||
@@ -188,48 +195,53 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
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) -> &crate::record::Layout,
|
||||
set_layout: fn(&mut DynEdge, crate::record::RecordLayout),
|
||||
pub struct SourceHandle {
|
||||
node: Box<DynSource>,
|
||||
share: fn(&DynSource) -> Box<DynSource>,
|
||||
serialize: fn(&DynSource) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>>,
|
||||
layout: fn(&DynSource) -> &crate::record::Layout,
|
||||
set_layout: fn(&mut DynSource, crate::record::RecordLayout),
|
||||
ty: Type,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for EdgeHandle {
|
||||
impl std::fmt::Debug for SourceHandle {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("EdgeHandle").field("ty", &self.ty).finish_non_exhaustive()
|
||||
f.debug_struct("SourceHandle").field("ty", &self.ty).finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
// SAFETY: wasm is single threaded, so the marker-free payload never actually crosses a thread.
|
||||
#[cfg(target_family = "wasm")]
|
||||
unsafe impl Send for EdgeHandle {}
|
||||
unsafe impl Send for SourceHandle {}
|
||||
// SAFETY: as in Send.
|
||||
#[cfg(target_family = "wasm")]
|
||||
unsafe impl Sync for EdgeHandle {}
|
||||
unsafe impl Sync for SourceHandle {}
|
||||
|
||||
impl EdgeHandle {
|
||||
#[cfg(all(target_family = "wasm", target_feature = "atomics"))]
|
||||
compile_error!("SourceHandle's wasm Send/Sync rest on a single-threaded build; a +atomics target needs the stored node bounded instead");
|
||||
|
||||
impl SourceHandle {
|
||||
pub fn new_record<T: 'static>(node: std::sync::Arc<ErasedRecordNode>) -> Self {
|
||||
Self::new_erased(node, record_edge_type::<T>())
|
||||
Self::new_erased(node, record_source_type::<T>())
|
||||
}
|
||||
|
||||
pub fn new_erased<N>(node: std::sync::Arc<N>, ty: Type) -> Self
|
||||
where
|
||||
N: ?Sized + 'static + for<'c> Node<ContextImpl<'c>>,
|
||||
SharedEdge<N>: WasmNotSend + WasmNotSync,
|
||||
SharedSource<N>: WasmNotSend + WasmNotSync,
|
||||
{
|
||||
Self {
|
||||
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| Node::<ContextImpl>::layout(edge.downcast_ref::<SharedEdge<N>>().expect("layout hook matches the stored edge type")),
|
||||
node: Box::new(SharedSource::new(node)),
|
||||
share: |edge| Box::new(edge.downcast_ref::<SharedSource<N>>().expect("share hook matches the stored edge type").share()),
|
||||
serialize: |edge| Node::<ContextImpl>::serialize(edge.downcast_ref::<SharedSource<N>>().expect("serialize hook matches the stored edge type")),
|
||||
layout: |edge| Node::<ContextImpl>::layout(edge.downcast_ref::<SharedSource<N>>().expect("layout hook matches the stored edge type")),
|
||||
set_layout: |edge, layout| {
|
||||
let shared = edge.downcast_mut::<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");
|
||||
let shared = edge.downcast_mut::<SharedSource<N>>().expect("set_layout hook matches the stored edge type");
|
||||
// The re-borrow below retires the cached pointer, so the rederive
|
||||
// is a guard: a panicking `set_layout` must not leave it stale.
|
||||
let guard = Rederive(shared);
|
||||
let node = std::sync::Arc::get_mut(&mut guard.0.own).expect("layout is installed before the node is shared");
|
||||
Node::<ContextImpl>::set_layout(node, layout);
|
||||
shared.rederive();
|
||||
},
|
||||
ty,
|
||||
}
|
||||
@@ -262,38 +274,38 @@ impl EdgeHandle {
|
||||
(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>())
|
||||
pub fn downcast_record<T: 'static>(self) -> Result<SharedSource<ErasedRecordNode>, ConstructionError> {
|
||||
self.downcast_erased(record_source_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)
|
||||
/// The erased record source, for callers that dispatch on the layout rather
|
||||
/// than a static element type. `None` for a source erased to another node type.
|
||||
pub fn record_source(self) -> Option<SharedSource<ErasedRecordNode>> {
|
||||
self.node.downcast::<SharedSource<ErasedRecordNode>>().ok().map(|edge| *edge)
|
||||
}
|
||||
|
||||
pub fn downcast_erased<N: ?Sized + 'static>(self, expected: Type) -> Result<SharedEdge<N>, ConstructionError> {
|
||||
pub fn downcast_erased<N: ?Sized + 'static>(self, expected: Type) -> Result<SharedSource<N>, ConstructionError> {
|
||||
let found = self.ty;
|
||||
self.node.downcast::<SharedEdge<N>>().map(|edge| *edge).map_err(|_| ConstructionError::Type {
|
||||
self.node.downcast::<SharedSource<N>>().map(|edge| *edge).map_err(|_| ConstructionError::Type {
|
||||
expected: Box::new(expected),
|
||||
found: Box::new(found),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub type NodeConstructor = fn(Vec<EdgeHandle>) -> Result<EdgeHandle, ConstructionError>;
|
||||
pub type NodeConstructor = fn(Vec<SourceHandle>) -> Result<SourceHandle, ConstructionError>;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct RegistryEntry {
|
||||
pub io: NodeIOTypes,
|
||||
pub constructor: NodeConstructor,
|
||||
/// Declarative record-io metadata for the compiler layout pass; `None` for
|
||||
/// nodes whose layout the pass does not yet fold (routing/opaque, hand-written
|
||||
/// nodes whose layout the pass does not fold (routing/opaque, hand-written
|
||||
/// rows), which keep the construction-time path.
|
||||
pub layout_meta: Option<crate::record::LayoutMeta>,
|
||||
}
|
||||
|
||||
pub fn construct(entry: &RegistryEntry, inputs: Vec<EdgeHandle>) -> Result<EdgeHandle, ConstructionError> {
|
||||
pub fn construct(entry: &RegistryEntry, inputs: Vec<SourceHandle>) -> Result<SourceHandle, ConstructionError> {
|
||||
if inputs.len() != entry.io.inputs.len() {
|
||||
return Err(ConstructionError::Arity {
|
||||
expected: entry.io.inputs.len(),
|
||||
@@ -326,7 +338,7 @@ mod tests {
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
|
||||
use crate::record::{FrameClaim, Layout, LiftedSource, Served, element_write, read_element, serve_edge};
|
||||
use crate::record::{FrameClaim, Layout, LiftedSource, Served, element_write, read_element, serve_input};
|
||||
|
||||
fn counting() -> LiftedSource<u32, impl for<'c> Fn(&ContextImpl<'c>) -> GPoll<u32>> {
|
||||
let count = AtomicU32::new(0);
|
||||
@@ -379,11 +391,11 @@ mod tests {
|
||||
|
||||
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));
|
||||
let handle = SourceHandle::new_erased(Arc::new(node) as Arc<ErasedRecordNode>, concrete!(String));
|
||||
assert_eq!(*handle.ty(), concrete!(String));
|
||||
|
||||
let wired = handle.downcast_erased::<ErasedRecordNode>(concrete!(String)).unwrap();
|
||||
let GPoll::Final(value) = serve_edge(&wired, &ctx, &frames) else {
|
||||
let GPoll::Final(value) = serve_input(&wired, &ctx, &frames) else {
|
||||
panic!("borrow-carrying output must serve through the erased edge");
|
||||
};
|
||||
// SAFETY: the record was served at `layout`, whose element is the borrow.
|
||||
@@ -392,8 +404,8 @@ mod tests {
|
||||
assert_eq!(held.len(), 4);
|
||||
}
|
||||
|
||||
/// Evaluates its content at three promoted index levels and serves the
|
||||
/// collected elements.
|
||||
/// Evaluates its content at three indices of one promoted level and serves
|
||||
/// the collected elements.
|
||||
struct RepeatNode<Node0, T> {
|
||||
content: Node0,
|
||||
inner: Layout,
|
||||
@@ -421,7 +433,7 @@ mod tests {
|
||||
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>>,
|
||||
Node0: for<'x> crate::record::DerivedRecordInput<'x, crate::context::Derived<'x, C>>,
|
||||
{
|
||||
fn serve<'e, 'l>(&self, input: &C, mut slot: FrameClaim<'e, 'l>) -> GPoll<Served<'e>>
|
||||
where
|
||||
@@ -466,7 +478,7 @@ mod tests {
|
||||
let erased: Box<ErasedRecordNode> = Box::new(nested);
|
||||
let frames = crate::record::test_frames(1 << 12);
|
||||
|
||||
let GPoll::Final(value) = serve_edge(&*erased, &ctx, &frames) else {
|
||||
let GPoll::Final(value) = serve_input(&*erased, &ctx, &frames) else {
|
||||
panic!("nested repeat must evaluate");
|
||||
};
|
||||
// SAFETY: the record was served at `layout`, whose element is the output.
|
||||
@@ -497,7 +509,7 @@ mod tests {
|
||||
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>>,
|
||||
Node0: for<'x> crate::record::DerivedRecordInput<'x, crate::context::Derived<'x, C>>,
|
||||
{
|
||||
fn serve<'e, 'l>(&self, input: &C, mut slot: FrameClaim<'e, 'l>) -> GPoll<Served<'e>>
|
||||
where
|
||||
@@ -545,7 +557,7 @@ mod tests {
|
||||
let graph = ShiftFootprintNode::new(shifted, shifted_layout);
|
||||
let layout = Node::<ContextImpl>::layout(&graph).clone();
|
||||
|
||||
let GPoll::Final(value) = serve_edge(&graph, &ctx, &frames) else {
|
||||
let GPoll::Final(value) = serve_input(&graph, &ctx, &frames) else {
|
||||
panic!("the footprint shift must reach the content");
|
||||
};
|
||||
// SAFETY: the record was served at `layout`, whose element is the resolution.
|
||||
@@ -554,29 +566,29 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn construct_checks_arity_and_types() {
|
||||
fn construct_strlen(args: Vec<EdgeHandle>) -> Result<EdgeHandle, ConstructionError> {
|
||||
fn construct_strlen(args: Vec<SourceHandle>) -> Result<SourceHandle, ConstructionError> {
|
||||
let mut args = args.into_iter();
|
||||
let value = args.next().ok_or(ConstructionError::Arity { expected: 1, got: 0 })?.downcast_record::<String>()?;
|
||||
drop(value);
|
||||
Ok(crate::value::record_value_edge(0u32))
|
||||
Ok(crate::value::record_value_source(0u32))
|
||||
}
|
||||
let entry = RegistryEntry {
|
||||
layout_meta: None,
|
||||
io: NodeIOTypes::new(concrete!(Context), record_type::<u32>(), vec![record_edge_type::<String>()]),
|
||||
io: NodeIOTypes::new(concrete!(Context), record_type::<u32>(), vec![record_source_type::<String>()]),
|
||||
constructor: construct_strlen,
|
||||
};
|
||||
|
||||
let owned = crate::value::record_value_edge("typed".to_string());
|
||||
let owned = crate::value::record_value_source("typed".to_string());
|
||||
assert!(construct(&entry, vec![owned]).is_ok());
|
||||
|
||||
assert_eq!(construct(&entry, vec![]).unwrap_err(), ConstructionError::Arity { expected: 1, got: 0 });
|
||||
|
||||
let mistyped = crate::value::record_value_edge(1.0f64);
|
||||
let mistyped = crate::value::record_value_source(1.0f64);
|
||||
assert_eq!(
|
||||
construct(&entry, vec![mistyped]).unwrap_err(),
|
||||
ConstructionError::Type {
|
||||
expected: Box::new(record_edge_type::<String>()),
|
||||
found: Box::new(record_edge_type::<f64>()),
|
||||
expected: Box::new(record_source_type::<String>()),
|
||||
found: Box::new(record_source_type::<f64>()),
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -590,19 +602,19 @@ mod tests {
|
||||
|
||||
let counting = counting();
|
||||
let layout = Node::<ContextImpl>::layout(&counting).clone();
|
||||
let handle = EdgeHandle::new_record::<u32>(Arc::new(counting) as Arc<ErasedRecordNode>);
|
||||
let handle = SourceHandle::new_record::<u32>(Arc::new(counting) as Arc<ErasedRecordNode>);
|
||||
let duplicate = handle.duplicate();
|
||||
assert_eq!(*duplicate.ty(), record_edge_type::<u32>());
|
||||
assert_eq!(*duplicate.ty(), record_source_type::<u32>());
|
||||
let frames = crate::record::test_frames(1 << 12);
|
||||
|
||||
let first = handle.downcast_record::<u32>().unwrap();
|
||||
let second = duplicate.downcast_record::<u32>().unwrap();
|
||||
// SAFETY: each record was served at `layout`, whose element is the count.
|
||||
let count = |value| unsafe { layout.rec(&value).element::<u32>() };
|
||||
assert_eq!(serve_edge(&first, &ctx, &frames).map(count), GPoll::Final(1));
|
||||
assert_eq!(serve_edge(&second, &ctx, &frames).map(count), GPoll::Final(2));
|
||||
assert_eq!(serve_input(&first, &ctx, &frames).map(count), GPoll::Final(1));
|
||||
assert_eq!(serve_input(&second, &ctx, &frames).map(count), GPoll::Final(2));
|
||||
|
||||
drop(first);
|
||||
assert_eq!(serve_edge(&second, &ctx, &frames).map(count), GPoll::Final(3));
|
||||
assert_eq!(serve_input(&second, &ctx, &frames).map(count), GPoll::Final(3));
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,9 @@ unsafe impl Send for RuntimeHandle {}
|
||||
#[cfg(target_family = "wasm")]
|
||||
unsafe impl Sync for RuntimeHandle {}
|
||||
|
||||
#[cfg(all(target_family = "wasm", target_feature = "atomics"))]
|
||||
compile_error!("RuntimeHandle's wasm Send/Sync rest on a single-threaded build; a +atomics target needs the payload bounded instead");
|
||||
|
||||
impl std::fmt::Debug for RuntimeHandle {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("RuntimeHandle").finish_non_exhaustive()
|
||||
@@ -102,6 +105,9 @@ unsafe impl<S> Send for GraphRuntime<S> {}
|
||||
#[cfg(target_family = "wasm")]
|
||||
unsafe impl<S> Sync for GraphRuntime<S> {}
|
||||
|
||||
#[cfg(all(target_family = "wasm", target_feature = "atomics"))]
|
||||
compile_error!("GraphRuntime's wasm Send/Sync are unbounded in S and rest on a single-threaded build; a +atomics target needs S bounded instead");
|
||||
|
||||
impl<S> GraphRuntime<S> {
|
||||
pub fn new(spawner: S) -> Self {
|
||||
Self {
|
||||
@@ -272,6 +278,9 @@ mod tests {
|
||||
plan: Vec::new(),
|
||||
layout: layout.clone(),
|
||||
lane_invariant: u32::MAX,
|
||||
named_writes: Vec::new(),
|
||||
named_reads: Vec::new(),
|
||||
named_read_defaults: Vec::new(),
|
||||
});
|
||||
RecordExtract::new(graph, &layout)
|
||||
}
|
||||
|
||||
@@ -69,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) => {
|
||||
@@ -244,7 +232,7 @@ pub enum Type {
|
||||
Fn(Box<Type>, Box<Type>),
|
||||
/// Represents a future which promises to return the inner type.
|
||||
Future(Box<Type>),
|
||||
/// A packed record wire over the element type; the layout stays node-resident metadata.
|
||||
/// A packed record input over the element type; the layout stays node-resident metadata.
|
||||
Record(Box<Type>),
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/// The node behind every value edge: clones its constant onto the record
|
||||
/// wire per evaluation.
|
||||
/// The node behind every value source: clones its constant onto the record
|
||||
/// input per evaluation.
|
||||
pub struct ValueSource<T> {
|
||||
value: T,
|
||||
layout: crate::record::Layout,
|
||||
@@ -33,15 +33,15 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
/// The native record edge of a constant.
|
||||
pub fn record_value_edge<T: Clone + Send + Sync + dyn_any::StaticTypeSized + 'static>(value: T) -> crate::registry::EdgeHandle
|
||||
/// The native record source of a constant.
|
||||
pub fn record_value_source<T: Clone + Send + Sync + dyn_any::StaticTypeSized + 'static>(value: T) -> crate::registry::SourceHandle
|
||||
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>)
|
||||
crate::registry::SourceHandle::new_record::<T>(std::sync::Arc::new(ValueSource::new(value)) as std::sync::Arc<crate::registry::ErasedRecordNode>)
|
||||
}
|
||||
|
||||
/// The node behind a leveled value edge: a constant list served as one level,
|
||||
/// The node behind a leveled value source: a constant list served as one level,
|
||||
/// one lane per item, with the list's length as the exact extent.
|
||||
pub struct LeveledValueSource<T> {
|
||||
values: Vec<T>,
|
||||
@@ -90,10 +90,10 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// The native record source of a constant level: the source type is the element's.
|
||||
pub fn leveled_record_value_source<T: Clone + Send + Sync + crate::CacheHash + PartialEq + dyn_any::StaticTypeSized + 'static>(values: Vec<T>) -> crate::registry::SourceHandle
|
||||
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>)
|
||||
crate::registry::SourceHandle::new_record::<T>(std::sync::Arc::new(LeveledValueSource::new(values)) as std::sync::Arc<crate::registry::ErasedRecordNode>)
|
||||
}
|
||||
@@ -238,8 +238,7 @@ impl_tuple!(A, B, C, D, E);
|
||||
impl_tuple!(A, B, C, D, E, F);
|
||||
|
||||
/// rustc-hash's polynomial hash with the state pinned to u64, so keys match across native and wasm targets.
|
||||
/// The state starts at a nonzero seed: zero-initialized fx absorbs leading zero words, which produced
|
||||
/// a real wrong-value memo hit in the prototype.
|
||||
/// The state starts at a nonzero seed, since zero-initialized fx absorbs leading zero words.
|
||||
#[derive(Clone)]
|
||||
pub struct FxHasher64 {
|
||||
hash: u64,
|
||||
|
||||
@@ -0,0 +1,418 @@
|
||||
//! The appearance model: an ordered list of paint passes ("coverages") stored in the `ATTR_APPEARANCE` attribute.
|
||||
//! Data uniform across all covers (the paint) rides the outer `List<Coverage>` so columnar presence holds,
|
||||
//! while cover-specific data rides the inner `Item<Cover>`, reusing `ATTR_TRANSFORM` for the stroke-authoring space.
|
||||
//!
|
||||
//! The interior is `'static`: the paint column stores `Graphic<'static>`.
|
||||
|
||||
use crate::Graphic;
|
||||
use crate::markers::ATTR_PAINT;
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::{Item, List};
|
||||
use vector_types::markers::{ATTR_ALIGN, ATTR_CAP, ATTR_DASH_OFFSET, ATTR_DASH_PATTERN, ATTR_JOIN, ATTR_JOIN_MITER_LIMIT, ATTR_WEIGHT};
|
||||
use vector_types::vector::style::Stroke;
|
||||
|
||||
/// The geometry-to-region operator a coverage applies before painting:
|
||||
/// the interior of the geometry (fill) or the region swept along its outline (stroke).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, CacheHash, dyn_any::DynAny)]
|
||||
pub enum Cover {
|
||||
#[default]
|
||||
Fill,
|
||||
Stroke,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Cover {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Fill => write!(f, "Fill"),
|
||||
Self::Stroke => write!(f, "Stroke"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One paint pass of an [`Appearance`]: a [`Cover`] plus its cover-specific parameters, carried as
|
||||
/// attributes on the inner item. Attributes for stroke parameters are ignored on fill coverages.
|
||||
#[derive(Clone, Debug, Default, dyn_any::DynAny)]
|
||||
pub struct Coverage(pub Item<Cover>);
|
||||
|
||||
// Item equality ignores attributes, but the stroke parameters live there.
|
||||
impl PartialEq for Coverage {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.0.element() == other.0.element()
|
||||
&& self
|
||||
.0
|
||||
.attributes()
|
||||
.iter()
|
||||
.map(|(key, value)| (key, value.display_string()))
|
||||
.eq(other.0.attributes().iter().map(|(key, value)| (key, value.display_string())))
|
||||
}
|
||||
}
|
||||
|
||||
impl CacheHash for Coverage {
|
||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
self.0.element().cache_hash(state);
|
||||
for (key, value) in self.0.attributes().iter() {
|
||||
std::hash::Hash::hash(key, state);
|
||||
std::hash::Hash::hash(&value.display_string(), state);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An item's ordered list of paint passes, stored in the `ATTR_APPEARANCE` attribute cell.
|
||||
/// Earlier coverages paint first, compositing below later ones. Each row's paint is the
|
||||
/// `ATTR_PAINT` attribute beside it.
|
||||
///
|
||||
/// The empty appearance is its elided attribute default form, and the state in which it is
|
||||
/// replaced by an inherited appearance from an outer level of the cascade.
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash, dyn_any::DynAny)]
|
||||
pub struct Appearance(pub List<Coverage>);
|
||||
|
||||
/// Where a newly inserted coverage lands in the paint order when no same-cover coverage exists to replace.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum CoverPlacement {
|
||||
/// The front of the list, painting first (below every existing pass).
|
||||
Below,
|
||||
/// The back of the list, painting last (above every existing pass).
|
||||
Above,
|
||||
}
|
||||
|
||||
impl Coverage {
|
||||
/// Creates a fill coverage with no parameters beyond its cover.
|
||||
pub fn new_fill() -> Self {
|
||||
Self(Item::new_from_element(Cover::Fill))
|
||||
}
|
||||
|
||||
/// Creates a stroke coverage, stamping only the parameters that differ from their implicit defaults.
|
||||
pub fn new_stroke(stroke: &Stroke) -> Self {
|
||||
let defaults = Stroke::default();
|
||||
let mut item = Item::new_from_element(Cover::Stroke);
|
||||
|
||||
if stroke.weight != defaults.weight {
|
||||
item.set_attribute(ATTR_WEIGHT, stroke.weight);
|
||||
}
|
||||
if !stroke.dash_lengths.is_empty() {
|
||||
item.set_attribute(ATTR_DASH_PATTERN, stroke.dash_lengths.clone());
|
||||
}
|
||||
if stroke.dash_offset != defaults.dash_offset {
|
||||
item.set_attribute(ATTR_DASH_OFFSET, stroke.dash_offset);
|
||||
}
|
||||
if stroke.cap != defaults.cap {
|
||||
item.set_attribute(ATTR_CAP, stroke.cap);
|
||||
}
|
||||
if stroke.join != defaults.join {
|
||||
item.set_attribute(ATTR_JOIN, stroke.join);
|
||||
}
|
||||
if stroke.join_miter_limit != defaults.join_miter_limit {
|
||||
item.set_attribute(ATTR_JOIN_MITER_LIMIT, stroke.join_miter_limit);
|
||||
}
|
||||
if stroke.align != defaults.align {
|
||||
item.set_attribute(ATTR_ALIGN, stroke.align);
|
||||
}
|
||||
if stroke.transform != defaults.transform {
|
||||
item.set_attribute(ATTR_TRANSFORM, stroke.transform);
|
||||
}
|
||||
|
||||
Self(item)
|
||||
}
|
||||
|
||||
/// This coverage's cover.
|
||||
pub fn cover(&self) -> Cover {
|
||||
*self.0.element()
|
||||
}
|
||||
|
||||
/// Extracts the stroke parameters into a [`Stroke`], falling back to the default for any absent attribute.
|
||||
/// Dash lengths are clamped to non-negative, matching what rendering accepts.
|
||||
pub fn stroke_params(&self) -> Stroke {
|
||||
let mut stroke = Stroke::default();
|
||||
for (key, value) in self.0.attributes().iter() {
|
||||
match key {
|
||||
ATTR_WEIGHT => stroke.weight = value.as_any().downcast_ref().copied().unwrap_or(stroke.weight),
|
||||
ATTR_DASH_PATTERN => {
|
||||
stroke.dash_lengths = value
|
||||
.as_any()
|
||||
.downcast_ref::<Vec<f64>>()
|
||||
.map(|lengths| lengths.iter().map(|length| length.max(0.)).collect())
|
||||
.unwrap_or(stroke.dash_lengths)
|
||||
}
|
||||
ATTR_DASH_OFFSET => stroke.dash_offset = value.as_any().downcast_ref().copied().unwrap_or(stroke.dash_offset),
|
||||
ATTR_CAP => stroke.cap = value.as_any().downcast_ref().copied().unwrap_or(stroke.cap),
|
||||
ATTR_JOIN => stroke.join = value.as_any().downcast_ref().copied().unwrap_or(stroke.join),
|
||||
ATTR_JOIN_MITER_LIMIT => stroke.join_miter_limit = value.as_any().downcast_ref().copied().unwrap_or(stroke.join_miter_limit),
|
||||
ATTR_ALIGN => stroke.align = value.as_any().downcast_ref().copied().unwrap_or(stroke.align),
|
||||
ATTR_TRANSFORM => stroke.transform = value.as_any().downcast_ref().copied().unwrap_or(stroke.transform),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
stroke
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds an appearance row, eliding the paint attribute when it is the default none-paint.
|
||||
fn cover_row(coverage: Coverage, paint: Graphic<'static>) -> Item<Coverage> {
|
||||
let mut row = Item::new_from_element(coverage);
|
||||
if paint != Graphic::default() {
|
||||
row.set_attribute(ATTR_PAINT, paint);
|
||||
}
|
||||
row
|
||||
}
|
||||
|
||||
impl Appearance {
|
||||
/// Creates an appearance holding a single coverage with the given paint.
|
||||
pub fn new_single(coverage: Coverage, paint: Graphic<'static>) -> Self {
|
||||
Self(List::new_from_item(cover_row(coverage, paint)))
|
||||
}
|
||||
|
||||
/// The number of coverages in this appearance.
|
||||
pub fn len(&self) -> usize {
|
||||
self.0.len()
|
||||
}
|
||||
|
||||
/// Whether this appearance holds no coverages, the undeclared state that defers to the cascade.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.0.is_empty()
|
||||
}
|
||||
|
||||
/// This appearance if it declares any coverages, or `None` for the undeclared (empty) state.
|
||||
pub fn declared(&self) -> Option<&Self> {
|
||||
(!self.is_empty()).then_some(self)
|
||||
}
|
||||
|
||||
/// Resolves the cascade for one item: its own declared appearance wins, while an undeclared
|
||||
/// (absent or empty) cell inherits the nearest ancestor's declared appearance.
|
||||
pub fn cascade<'a>(own: Option<&'a Self>, inherited: Option<&'a Self>) -> Option<&'a Self> {
|
||||
own.and_then(Self::declared).or(inherited)
|
||||
}
|
||||
|
||||
/// Iterates the coverages in paint order.
|
||||
pub fn covers(&self) -> impl Iterator<Item = &Coverage> {
|
||||
self.0.iter_element_values()
|
||||
}
|
||||
|
||||
/// The coverage at the given index in paint order.
|
||||
pub fn cover_at(&self, index: usize) -> Option<&Coverage> {
|
||||
self.0.element(index)
|
||||
}
|
||||
|
||||
/// The paint of the coverage at the given index, or `None` if the paint attribute is absent.
|
||||
pub fn paint_at(&self, index: usize) -> Option<&Graphic<'static>> {
|
||||
self.0.attribute::<Graphic<'static>>(ATTR_PAINT, index)
|
||||
}
|
||||
|
||||
/// The index of the first coverage of the given cover in paint order.
|
||||
pub fn first_index_of(&self, cover: Cover) -> Option<usize> {
|
||||
self.covers().position(|coverage| coverage.cover() == cover)
|
||||
}
|
||||
|
||||
/// The first coverage of the given cover in paint order.
|
||||
pub fn first_coverage_of(&self, cover: Cover) -> Option<&Coverage> {
|
||||
self.first_index_of(cover).and_then(|index| self.cover_at(index))
|
||||
}
|
||||
|
||||
/// The paint of the first coverage of the given cover, filtered to paint that draws something.
|
||||
pub fn first_paint_of(&self, cover: Cover) -> Option<&Graphic<'static>> {
|
||||
self.first_index_of(cover).and_then(|index| self.paint_at(index)).filter(|paint| !paint.is_empty())
|
||||
}
|
||||
|
||||
/// Iterates the coverages in paint order together with their paint, which is `None` when absent or drawing nothing.
|
||||
pub fn covers_with_paints(&self) -> impl Iterator<Item = (&Coverage, Option<&Graphic<'static>>)> {
|
||||
self.covers().enumerate().map(|(index, coverage)| (coverage, self.paint_at(index).filter(|paint| !paint.is_empty())))
|
||||
}
|
||||
|
||||
/// Gathers the renderer's per-item reads in one walk of the coverage list.
|
||||
pub fn fill_and_stroke(&self) -> FillAndStroke<'_> {
|
||||
let mut first_fill = None;
|
||||
let mut first_stroke = None;
|
||||
for (index, coverage) in self.covers().enumerate() {
|
||||
match coverage.cover() {
|
||||
Cover::Fill if first_fill.is_none() => first_fill = Some(index),
|
||||
Cover::Stroke if first_stroke.is_none() => first_stroke = Some((index, coverage)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let painted = |index| self.paint_at(index).filter(|paint| !paint.is_empty());
|
||||
FillAndStroke {
|
||||
stroke: first_stroke.map(|(_, coverage)| coverage.stroke_params()),
|
||||
fill_paint: first_fill.and_then(painted),
|
||||
stroke_paint: first_stroke.and_then(|(index, _)| painted(index)),
|
||||
stroke_below: first_stroke.zip(first_fill).is_some_and(|((stroke_index, _), fill_index)| stroke_index < fill_index),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether any coverage of the given cover exists, regardless of whether its paint draws anything.
|
||||
pub fn has_cover(&self, cover: Cover) -> bool {
|
||||
self.first_index_of(cover).is_some()
|
||||
}
|
||||
|
||||
/// Whether any coverage of the given cover has paint that draws something, i.e. paint that is
|
||||
/// present and not empty. A coverage whose paint is the none-paint exists but paints nothing.
|
||||
pub fn has_painted_cover(&self, cover: Cover) -> bool {
|
||||
self.covers()
|
||||
.enumerate()
|
||||
.any(|(index, coverage)| coverage.cover() == cover && self.paint_at(index).is_some_and(|paint| !paint.is_empty()))
|
||||
}
|
||||
|
||||
/// Replaces the first coverage of the incoming cover in place (keeping its position in the paint order),
|
||||
/// or inserts a new row at the requested end of the paint order if none exists.
|
||||
pub fn replace_or_insert(&mut self, coverage: Coverage, paint: Graphic<'static>, placement: CoverPlacement) {
|
||||
if let Some(index) = self.first_index_of(coverage.cover()) {
|
||||
if let Some(element) = self.0.element_mut(index) {
|
||||
*element = coverage;
|
||||
}
|
||||
self.0.set_attribute(ATTR_PAINT, index, paint);
|
||||
return;
|
||||
}
|
||||
|
||||
let row = cover_row(coverage, paint);
|
||||
match placement {
|
||||
CoverPlacement::Above => self.0.push(row),
|
||||
CoverPlacement::Below => {
|
||||
self.0 = std::iter::once(row).chain(std::mem::take(&mut self.0)).collect();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the paint of the first coverage of the given cover, leaving its other parameters untouched.
|
||||
/// Returns `false` without changing anything if no coverage of that cover exists.
|
||||
pub fn set_paint_of(&mut self, cover: Cover, paint: Graphic<'static>) -> bool {
|
||||
let Some(index) = self.first_index_of(cover) else { return false };
|
||||
self.0.set_attribute(ATTR_PAINT, index, paint);
|
||||
true
|
||||
}
|
||||
|
||||
/// Discards every coverage that is not of the given cover, preserving the survivors' paint order.
|
||||
pub fn retain_cover(&mut self, cover: Cover) {
|
||||
self.0 = std::mem::take(&mut self.0).into_iter().filter(|row| row.element().cover() == cover).collect();
|
||||
}
|
||||
}
|
||||
|
||||
/// The first fill and stroke of an appearance in the form rendering consumes: the stroke's parameters,
|
||||
/// each cover's first paint (filtered to paint that draws something), and their relative paint order.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct FillAndStroke<'a> {
|
||||
pub stroke: Option<Stroke>,
|
||||
pub fill_paint: Option<&'a Graphic<'static>>,
|
||||
pub stroke_paint: Option<&'a Graphic<'static>>,
|
||||
/// Whether the first stroke coverage sits before the first fill in the paint order, painting below it.
|
||||
pub stroke_below: bool,
|
||||
}
|
||||
|
||||
/// Stamps a coverage into the item's `ATTR_APPEARANCE` cell, creating the attribute if absent.
|
||||
/// The coverage replaces the first same-cover one in place, or lands at the placement end of the paint order.
|
||||
pub fn stamp_coverage<T>(item: &mut Item<T>, coverage: Coverage, paint: Graphic<'static>, placement: CoverPlacement) {
|
||||
item.attribute_mut_or_insert_default::<Appearance>(crate::markers::ATTR_APPEARANCE)
|
||||
.replace_or_insert(coverage, paint, placement);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use core_types::Color;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use vector_types::vector::style::{StrokeAlign, StrokeCap, StrokeJoin};
|
||||
|
||||
fn solid_paint(color: Color) -> Graphic<'static> {
|
||||
Graphic::Color(color)
|
||||
}
|
||||
|
||||
fn paint_color(appearance: &Appearance, index: usize) -> Option<Color> {
|
||||
let paint = appearance.paint_at(index)?;
|
||||
let Graphic::Color(color) = paint else { return None };
|
||||
Some(*color)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stroke_params_survive_the_attribute_round_trip() {
|
||||
let stroke = Stroke {
|
||||
weight: 3.,
|
||||
dash_lengths: vec![4., -2.],
|
||||
dash_offset: 1.5,
|
||||
cap: StrokeCap::Round,
|
||||
join: StrokeJoin::Bevel,
|
||||
join_miter_limit: 7.,
|
||||
align: StrokeAlign::Inside,
|
||||
transform: DAffine2::from_scale(DVec2::new(2., 3.)),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let coverage = Coverage::new_stroke(&stroke);
|
||||
assert_eq!(coverage.cover(), Cover::Stroke);
|
||||
|
||||
let extracted = coverage.stroke_params();
|
||||
assert_eq!(extracted.weight, 3.);
|
||||
assert_eq!(extracted.dash_lengths, vec![4., 0.], "negative dash lengths should clamp to zero on extraction");
|
||||
assert_eq!(extracted.dash_offset, 1.5);
|
||||
assert_eq!(extracted.cap, StrokeCap::Round);
|
||||
assert_eq!(extracted.join, StrokeJoin::Bevel);
|
||||
assert_eq!(extracted.join_miter_limit, 7.);
|
||||
assert_eq!(extracted.align, StrokeAlign::Inside);
|
||||
assert_eq!(extracted.transform, DAffine2::from_scale(DVec2::new(2., 3.)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_appearance_is_undeclared_and_defers_to_the_cascade() {
|
||||
let inherited = Appearance::new_single(Coverage::new_fill(), solid_paint(Color::BLACK));
|
||||
let empty = Appearance::default();
|
||||
|
||||
assert!(empty.declared().is_none(), "an empty appearance should be undeclared");
|
||||
assert!(inherited.declared().is_some(), "an appearance with a coverage should be declared");
|
||||
|
||||
assert_eq!(Appearance::cascade(Some(&empty), Some(&inherited)), Some(&inherited));
|
||||
assert_eq!(Appearance::cascade(None, Some(&inherited)), Some(&inherited));
|
||||
assert_eq!(Appearance::cascade(Some(&inherited), None), Some(&inherited));
|
||||
assert_eq!(Appearance::cascade(Some(&empty), None), None);
|
||||
assert_eq!(Appearance::cascade(None, None), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_valued_stroke_parameters_elide_to_absence() {
|
||||
let coverage = Coverage::new_stroke(&Stroke::default());
|
||||
assert_eq!(coverage.0.attributes().keys().count(), 0, "default parameters should stay absent");
|
||||
assert_eq!(coverage.stroke_params(), Stroke::default(), "absent attributes should read back as the defaults");
|
||||
|
||||
let coverage = Coverage::new_stroke(&Stroke::new(2.));
|
||||
let keys: Vec<_> = coverage.0.attributes().keys().collect();
|
||||
assert_eq!(keys, vec![ATTR_WEIGHT], "only the non-default weight should be stamped");
|
||||
assert_eq!(coverage.stroke_params().weight, 2.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replace_keeps_position_and_the_other_rows_paint() {
|
||||
let mut appearance = Appearance::default();
|
||||
appearance.replace_or_insert(Coverage::new_fill(), solid_paint(Color::RED), CoverPlacement::Above);
|
||||
appearance.replace_or_insert(Coverage::new_stroke(&Stroke::new(2.)), solid_paint(Color::BLACK), CoverPlacement::Above);
|
||||
|
||||
appearance.replace_or_insert(Coverage::new_fill(), solid_paint(Color::BLUE), CoverPlacement::Above);
|
||||
|
||||
assert_eq!(appearance.len(), 2, "replacement should not add a row");
|
||||
assert_eq!(appearance.cover_at(0).map(Coverage::cover), Some(Cover::Fill), "the fill should keep its position");
|
||||
assert_eq!(paint_color(&appearance, 0), Some(Color::BLUE));
|
||||
assert_eq!(paint_color(&appearance, 1), Some(Color::BLACK), "the stroke row's paint should be untouched");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn below_insertion_prepends_and_preserves_paint_columns() {
|
||||
let mut appearance = Appearance::default();
|
||||
appearance.replace_or_insert(Coverage::new_stroke(&Stroke::new(2.)), solid_paint(Color::BLACK), CoverPlacement::Above);
|
||||
appearance.replace_or_insert(Coverage::new_fill(), solid_paint(Color::RED), CoverPlacement::Below);
|
||||
|
||||
let covers: Vec<_> = appearance.covers().map(Coverage::cover).collect();
|
||||
assert_eq!(covers, vec![Cover::Fill, Cover::Stroke], "a below-placed fill should paint before the stroke");
|
||||
assert_eq!(paint_color(&appearance, 0), Some(Color::RED));
|
||||
assert_eq!(paint_color(&appearance, 1), Some(Color::BLACK), "the existing row's paint should survive the reorder");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn painted_cover_distinguishes_none_paint_from_absence() {
|
||||
let mut appearance = Appearance::default();
|
||||
appearance.replace_or_insert(Coverage::new_fill(), Graphic::default(), CoverPlacement::Above);
|
||||
|
||||
assert!(appearance.has_cover(Cover::Fill), "a none-painted coverage still exists");
|
||||
assert!(!appearance.has_painted_cover(Cover::Fill), "a none-painted coverage draws nothing");
|
||||
assert!(!appearance.has_cover(Cover::Stroke));
|
||||
assert!(!appearance.has_painted_cover(Cover::Stroke));
|
||||
|
||||
appearance.replace_or_insert(Coverage::new_fill(), solid_paint(Color::RED), CoverPlacement::Above);
|
||||
assert!(appearance.has_painted_cover(Cover::Fill));
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,7 @@ impl<'e> Artboard<'e> {
|
||||
Self(content)
|
||||
}
|
||||
|
||||
pub fn as_graphic_list(&self) -> &List<Graphic> {
|
||||
pub fn as_graphic_list(&self) -> &List<Graphic<'_>> {
|
||||
&self.0
|
||||
}
|
||||
|
||||
@@ -50,11 +50,13 @@ impl<'e> Artboard<'e> {
|
||||
/// # Safety
|
||||
/// `ptr` must point at a live parked `Artboard` element field.
|
||||
unsafe fn deep_clone_artboard(ptr: *const u8) -> Box<dyn std::any::Any + Send + Sync> {
|
||||
// SAFETY: the caller's contract.
|
||||
let artboard = unsafe { core_types::record::borrow_element::<Artboard>(core_types::record::Rec::new(ptr)) };
|
||||
let mut content = artboard.0.clone();
|
||||
for element in content.iter_element_values_mut() {
|
||||
*element = crate::graphic::map_groups_to_owned(element);
|
||||
}
|
||||
crate::graphic::map_attribute_groups_to_owned(&mut content);
|
||||
Box::new(Artboard(content))
|
||||
}
|
||||
|
||||
@@ -70,22 +72,27 @@ unsafe fn deep_repark_artboard(value: &(dyn std::any::Any + Send + Sync), dst: *
|
||||
for element in content.iter_element_values_mut() {
|
||||
*element = crate::graphic::map_groups_to_resident(element, arena)?;
|
||||
}
|
||||
crate::graphic::map_attribute_groups_to_resident(&mut content, arena)?;
|
||||
// SAFETY: the caller's contract on `dst`; the replayed content is an `Artboard`.
|
||||
unsafe { core_types::record::write_element(dst, Artboard(content), arena) }
|
||||
}
|
||||
|
||||
/// The promote for `Artboard` elements: as for `Graphic`, content groups the
|
||||
/// persistent region already holds are shared rather than copied, and
|
||||
/// group-free content moves its header instead of copying its heap.
|
||||
/// persistent region already holds are shared rather than copied, and content
|
||||
/// no group is reachable from moves its header instead of copying its heap.
|
||||
///
|
||||
/// # Safety
|
||||
/// `src` must point at a live parked `Artboard` element field, and `dst` at
|
||||
/// the element field the promoted reference is written to.
|
||||
unsafe fn promote_artboard(src: *const u8, dst: *mut u8, promotion: &core_types::record::Promotion<'_>) -> Option<()> {
|
||||
// SAFETY: the caller's contract on `src`.
|
||||
let artboard = unsafe { core_types::record::borrow_element::<Artboard>(core_types::record::Rec::new(src)) };
|
||||
if !crate::graphic::list_contains_groups(&artboard.0) {
|
||||
// SAFETY: a parked element slot holds one reference at offset 0, and
|
||||
// group-free content owns all of itself.
|
||||
// content no group is reachable from, elements and item attribute values
|
||||
// alike, owns all of itself.
|
||||
let header = unsafe { src.cast::<*const u8>().read() };
|
||||
// SAFETY: as above; the group-free check establishes the own-all-content half.
|
||||
if let Some(moved) = unsafe { promotion.move_park::<Artboard>(header, 0) } {
|
||||
// SAFETY: as above, into the promoted image's own element slot.
|
||||
unsafe { dst.cast::<*const Artboard>().write(moved) };
|
||||
@@ -97,6 +104,8 @@ unsafe fn promote_artboard(src: *const u8, dst: *mut u8, promotion: &core_types:
|
||||
let (element, attributes) = item.into_parts();
|
||||
content.push(core_types::list::Item::from_parts(crate::graphic::map_groups_to_persistent(&element, promotion)?, attributes));
|
||||
}
|
||||
crate::graphic::map_attribute_groups_to_persistent(&mut content, promotion)?;
|
||||
// SAFETY: the caller's contract on `dst`; the promoted content is an `Artboard`.
|
||||
unsafe { core_types::record::write_element(dst, Artboard(content), promotion.persistent()) }
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,8 @@ use glam::{DAffine2, DVec2};
|
||||
use vector_types::GradientStops;
|
||||
|
||||
/// The outcome of materializing a leveled wire into a group.
|
||||
// The group is the render path's success payload; boxing it would add a heap allocation per materialized level.
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
pub enum LevelGroup<'e> {
|
||||
Group(Group<'e>, Finality),
|
||||
Pending,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,156 @@
|
||||
//! The legacy bridge: record-backed groups rebuilt as owned legacy lists.
|
||||
|
||||
use super::{Graphic, detable_items};
|
||||
use crate::appearance::Appearance;
|
||||
use crate::markers::{ATTR_APPEARANCE, ATTR_EDITOR_MERGED_LAYERS, ATTR_PAINT};
|
||||
use core_types::Color;
|
||||
use core_types::list::{Item, List};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
use vector_types::{GradientStops, Vector};
|
||||
|
||||
/// One typed run as an owned list, elements cloned and every attribute copied
|
||||
/// through its erased read. Content keeps its native form; the legacy
|
||||
/// conversions layer their mapping on top.
|
||||
pub fn run_to_list<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(item: &core_types::record::GroupItem) -> Option<List<T>> {
|
||||
core_types::record::run_to_owned_list(item)
|
||||
}
|
||||
|
||||
/// Converts the group content the list's attribute values reach to legacy
|
||||
/// form, so a legacy product owns everything its attributes hold: the paint
|
||||
/// cells inside each appearance, and the merged-layers snapshot.
|
||||
pub fn map_paint_attrs_to_legacy<T>(list: &mut List<T>) {
|
||||
if let Some(appearances) = list.iter_attribute_values_mut::<Appearance>(ATTR_APPEARANCE) {
|
||||
for appearance in appearances {
|
||||
let Some(cells) = appearance.0.iter_attribute_values_mut::<Graphic>(ATTR_PAINT) else { continue };
|
||||
for cell in cells {
|
||||
*cell = map_groups_to_legacy(cell);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(values) = list.iter_attribute_values_mut::<Option<List<Graphic>>>(ATTR_EDITOR_MERGED_LAYERS) {
|
||||
for value in values.flatten() {
|
||||
for element in value.iter_element_values_mut() {
|
||||
*element = map_groups_to_legacy(element);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One typed run as a legacy list: [`run_to_list`] with the paint attribute
|
||||
/// contents converted to their legacy form.
|
||||
pub(crate) fn run_to_legacy_list<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(item: &core_types::record::GroupItem) -> Option<List<T>> {
|
||||
let mut list = run_to_list::<T>(item)?;
|
||||
map_paint_attrs_to_legacy(&mut list);
|
||||
Some(list)
|
||||
}
|
||||
|
||||
/// The graphic with every `Group` converted to its legacy form.
|
||||
pub fn map_groups_to_legacy<'out>(graphic: &Graphic<'_>) -> Graphic<'out> {
|
||||
match graphic {
|
||||
Graphic::Group(group) => group_to_legacy_graphic(group),
|
||||
Graphic::Graphic(children) => {
|
||||
let mut out = List::new();
|
||||
for item in children.clone().into_iter() {
|
||||
let (element, attributes) = item.into_parts();
|
||||
out.push(Item::from_parts(map_groups_to_legacy(&element), attributes));
|
||||
}
|
||||
map_paint_attrs_to_legacy(&mut out);
|
||||
Graphic::Graphic(out)
|
||||
}
|
||||
Graphic::Vector(vector) => Graphic::Vector(vector.clone()),
|
||||
Graphic::RasterCPU(raster) => Graphic::RasterCPU(raster.clone()),
|
||||
Graphic::RasterGPU(raster) => Graphic::RasterGPU(raster.clone()),
|
||||
Graphic::Color(color) => Graphic::Color(*color),
|
||||
Graphic::Gradient(gradient) => Graphic::Gradient(gradient.clone()),
|
||||
Graphic::Text(text) => Graphic::Text(text.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The group as one legacy graphic. A bare (row-less) wrap of a single typed
|
||||
/// run keeps the run's typed variant, matching the `Into<Graphic>` the
|
||||
/// pre-flip wrap applied; everything else becomes the legacy group list.
|
||||
pub fn group_to_legacy_graphic(group: &core_types::record::Group) -> Graphic<'static> {
|
||||
if group.row.is_none() {
|
||||
let item = &group.content;
|
||||
let typed = None
|
||||
.or_else(|| run_to_legacy_list::<Vector>(item).map(|list| detable_items(list, Graphic::Vector)))
|
||||
.or_else(|| run_to_legacy_list::<Raster<CPU>>(item).map(|list| detable_items(list, Graphic::RasterCPU)))
|
||||
.or_else(|| run_to_legacy_list::<Raster<GPU>>(item).map(|list| detable_items(list, Graphic::RasterGPU)))
|
||||
.or_else(|| run_to_legacy_list::<Color>(item).map(|list| detable_items(list, Graphic::Color)))
|
||||
.or_else(|| run_to_legacy_list::<GradientStops>(item).map(|list| detable_items(list, Graphic::Gradient)))
|
||||
.or_else(|| run_to_legacy_list::<String>(item).map(|list| detable_items(list, Graphic::Text)));
|
||||
if let Some(typed) = typed {
|
||||
return Graphic::Graphic(typed);
|
||||
}
|
||||
}
|
||||
Graphic::Graphic(group_to_legacy_list(group))
|
||||
}
|
||||
|
||||
/// The group as a legacy `List<Graphic>`: a `Graphic` run becomes the items,
|
||||
/// another typed run becomes one de-tabled leaf item per lane.
|
||||
pub fn group_to_legacy_list(group: &core_types::record::Group) -> List<Graphic<'static>> {
|
||||
let item = &group.content;
|
||||
if let Some(mut list) = run_to_legacy_list::<Graphic>(item) {
|
||||
for element in list.iter_element_values_mut() {
|
||||
*element = map_groups_to_legacy(element);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
None.or_else(|| run_to_legacy_list::<Vector>(item).map(|list| detable_items(list, Graphic::Vector)))
|
||||
.or_else(|| run_to_legacy_list::<Raster<CPU>>(item).map(|list| detable_items(list, Graphic::RasterCPU)))
|
||||
.or_else(|| run_to_legacy_list::<Raster<GPU>>(item).map(|list| detable_items(list, Graphic::RasterGPU)))
|
||||
.or_else(|| run_to_legacy_list::<Color>(item).map(|list| detable_items(list, Graphic::Color)))
|
||||
.or_else(|| run_to_legacy_list::<GradientStops>(item).map(|list| detable_items(list, Graphic::Gradient)))
|
||||
.or_else(|| run_to_legacy_list::<String>(item).map(|list| detable_items(list, Graphic::Text)))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod run_tests {
|
||||
use super::*;
|
||||
use crate::appearance::Coverage;
|
||||
use crate::graphic::test_support::{native_group_paint, unit_square_at};
|
||||
use crate::markers::Appearance as AppearanceMarker;
|
||||
use core_types::record::{FieldWrite, RunBuilder, element_write_hashed};
|
||||
use glam::DVec2;
|
||||
|
||||
#[test]
|
||||
fn a_legacy_list_owns_its_appearance_paint_content() {
|
||||
let inner_vector = unit_square_at(DVec2::ZERO);
|
||||
let source = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
// SAFETY: the erased native list serves only while `source` is live; the
|
||||
// deep glue under test replaces its borrows at the copy-out seam.
|
||||
let paint = unsafe { core_types::record::erase_static(native_group_paint(&inner_vector, &source)) };
|
||||
let appearance = Appearance::new_single(Coverage::new_fill(), Graphic::Graphic(paint.clone()));
|
||||
|
||||
let vector = unit_square_at(DVec2::new(4., 4.));
|
||||
let mut builder = RunBuilder::new(&source, element_write_hashed::<Vector>(), &[FieldWrite::of::<AppearanceMarker>(0)], 1).unwrap();
|
||||
let lane = builder.push(vector.clone()).unwrap();
|
||||
builder.attr::<AppearanceMarker>(lane, Some(&appearance));
|
||||
let item = builder.finish();
|
||||
let legacy = run_to_legacy_list::<Vector>(&item).expect("the run lowers to a legacy vector list");
|
||||
let expected = map_groups_to_legacy(paint.element(0).unwrap());
|
||||
drop(item);
|
||||
drop(paint);
|
||||
drop(source);
|
||||
|
||||
let served = legacy.attribute::<Appearance>(ATTR_APPEARANCE, 0).expect("the appearance rides the list");
|
||||
let cell = served.paint_at(0).expect("the fill coverage keeps its paint");
|
||||
let Graphic::Graphic(cell_rows) = cell else { panic!("the paint cell keeps the list form") };
|
||||
assert_eq!(cell_rows.element(0).unwrap(), &expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_list_keeps_native_group_elements() {
|
||||
let inner_vector = unit_square_at(DVec2::ZERO);
|
||||
let arena = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
let content = native_group_paint(&inner_vector, &arena);
|
||||
let element = content.element(0).unwrap();
|
||||
|
||||
let mut builder = RunBuilder::new(&arena, element_write_hashed::<Graphic>(), &[], 1).unwrap();
|
||||
builder.push(element.clone()).unwrap();
|
||||
let item = builder.finish();
|
||||
let list = run_to_list::<Graphic>(&item).expect("the run holds graphic lanes");
|
||||
assert!(matches!(list.element(0), Some(Graphic::Group(_))), "the list keeps the native group form");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,731 @@
|
||||
mod glue;
|
||||
mod legacy;
|
||||
mod paint;
|
||||
mod walk;
|
||||
|
||||
pub(crate) use glue::{list_contains_groups, map_attribute_groups_to_owned, map_attribute_groups_to_persistent, map_attribute_groups_to_resident};
|
||||
pub use glue::{map_groups_to_owned, map_groups_to_persistent, map_groups_to_resident};
|
||||
pub(crate) use legacy::run_to_legacy_list;
|
||||
pub use legacy::{group_to_legacy_graphic, group_to_legacy_list, map_groups_to_legacy, map_paint_attrs_to_legacy, run_to_list};
|
||||
pub use paint::{PaintColumns, PaintReach, bake_paint_transforms, is_paint_present, paint_cell_rows, vector_can_reduce_to_clip_path};
|
||||
pub use walk::{GraphicLevel, GraphicLevelColumn, RowStep, VectorRow, direct_vector_len, flatten_vector_rows, group_is_empty, lane_attributes, run_lane_attributes, walk_vector_rows};
|
||||
use walk::{group_all_clipped, group_bounding_box, group_is_fully_transparent, group_is_opaque, group_render_complexity};
|
||||
|
||||
use crate::appearance::Appearance;
|
||||
use crate::markers::ATTR_APPEARANCE;
|
||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::ops::{FromAnchorPosition, ListConvert};
|
||||
use core_types::render_complexity::RenderComplexity;
|
||||
use core_types::uuid::NodeId;
|
||||
use core_types::{ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color};
|
||||
use dyn_any::DynAny;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
use vector_types::GradientStops;
|
||||
pub use vector_types::Vector;
|
||||
|
||||
/// The possible forms of graphical content that can be rendered by the Render node into either an image or SVG syntax.
|
||||
/// A leaf holds its element directly; its attributes ride the containing
|
||||
/// lane. Multi-element content is a [`core_types::record::Group`] run, or
|
||||
/// transitionally the legacy `Graphic` list.
|
||||
#[derive(Clone, Debug, CacheHash, PartialEq, DynAny)]
|
||||
pub enum Graphic<'e> {
|
||||
Graphic(List<Graphic<'e>>),
|
||||
Vector(Vector),
|
||||
RasterCPU(Raster<CPU>),
|
||||
RasterGPU(Raster<GPU>),
|
||||
Color(Color),
|
||||
Gradient(GradientStops),
|
||||
Text(String),
|
||||
Group(core_types::record::Group<'e>),
|
||||
}
|
||||
|
||||
impl Default for Graphic<'_> {
|
||||
fn default() -> Self {
|
||||
Self::Graphic(List::new())
|
||||
}
|
||||
}
|
||||
|
||||
/// A typed legacy list as a legacy graphic list: each item de-tables to a
|
||||
/// leaf element, keeping its attributes on the containing lane.
|
||||
pub(in crate::graphic) fn detable_items<'e, T: Clone + Send + Sync + 'static>(list: List<T>, leaf: fn(T) -> Graphic<'e>) -> List<Graphic<'e>> {
|
||||
let mut out = List::new();
|
||||
for item in list.into_iter() {
|
||||
let (element, attributes) = item.into_parts();
|
||||
out.push(Item::from_parts(leaf(element), attributes));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The element-space coercion into `Graphic`: a leaf converts in place and a
|
||||
/// legacy list becomes a native group built over the arena, so the coercion
|
||||
/// never constructs a legacy interior.
|
||||
pub trait IntoGraphicElement: Clone + Send + Sync + CacheHash + 'static {
|
||||
/// `None` reports arena exhaustion.
|
||||
fn into_graphic_element(self, arena: &core_types::arena::Arena) -> Option<Graphic<'_>>;
|
||||
}
|
||||
|
||||
fn list_group<T: Clone + Send + Sync + CacheHash + PartialEq + dyn_any::StaticTypeSized>(list: List<T>, arena: &core_types::arena::Arena) -> Option<Graphic<'_>>
|
||||
where
|
||||
T::Static: Clone + Send + Sync,
|
||||
{
|
||||
Some(Graphic::Group(core_types::record::Group {
|
||||
row: None,
|
||||
content: core_types::record::GroupItem::from_list(list, arena)?,
|
||||
}))
|
||||
}
|
||||
|
||||
macro_rules! into_graphic_element {
|
||||
($($leaf:ident: $element:ty;)*) => {
|
||||
$(
|
||||
impl IntoGraphicElement for $element {
|
||||
fn into_graphic_element(self, _arena: &core_types::arena::Arena) -> Option<Graphic<'_>> {
|
||||
Some(Graphic::$leaf(self))
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoGraphicElement for List<$element> {
|
||||
fn into_graphic_element(self, arena: &core_types::arena::Arena) -> Option<Graphic<'_>> {
|
||||
list_group(self, arena)
|
||||
}
|
||||
}
|
||||
)*
|
||||
};
|
||||
}
|
||||
|
||||
into_graphic_element! {
|
||||
Vector: Vector;
|
||||
RasterCPU: Raster<CPU>;
|
||||
RasterGPU: Raster<GPU>;
|
||||
Color: Color;
|
||||
Gradient: GradientStops;
|
||||
Text: String;
|
||||
}
|
||||
|
||||
impl IntoGraphicElement for Graphic<'static> {
|
||||
fn into_graphic_element(self, _arena: &core_types::arena::Arena) -> Option<Graphic<'_>> {
|
||||
Some(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoGraphicElement for List<Graphic<'static>> {
|
||||
fn into_graphic_element(self, arena: &core_types::arena::Arena) -> Option<Graphic<'_>> {
|
||||
list_group(self, arena)
|
||||
}
|
||||
}
|
||||
|
||||
// Vector
|
||||
impl From<Vector> for Graphic<'_> {
|
||||
fn from(vector: Vector) -> Self {
|
||||
Graphic::Vector(vector)
|
||||
}
|
||||
}
|
||||
|
||||
// Raster<CPU>
|
||||
impl From<Raster<CPU>> for Graphic<'_> {
|
||||
fn from(raster: Raster<CPU>) -> Self {
|
||||
Graphic::RasterCPU(raster)
|
||||
}
|
||||
}
|
||||
|
||||
// Raster<GPU>
|
||||
impl From<Raster<GPU>> for Graphic<'_> {
|
||||
fn from(raster: Raster<GPU>) -> Self {
|
||||
Graphic::RasterGPU(raster)
|
||||
}
|
||||
}
|
||||
|
||||
// Color
|
||||
impl From<Color> for Graphic<'_> {
|
||||
fn from(color: Color) -> Self {
|
||||
Graphic::Color(color)
|
||||
}
|
||||
}
|
||||
// Note: List<Color> -> Option<Color> is in gcore (Color is defined there)
|
||||
|
||||
// GradientStops
|
||||
impl From<GradientStops> for Graphic<'_> {
|
||||
fn from(gradient: GradientStops) -> Self {
|
||||
Graphic::Gradient(gradient)
|
||||
}
|
||||
}
|
||||
|
||||
// String
|
||||
impl From<String> for Graphic<'_> {
|
||||
fn from(text: String) -> Self {
|
||||
Graphic::Text(text)
|
||||
}
|
||||
}
|
||||
|
||||
/// Deeply flattens a `List<Graphic>`, collecting only elements matching a specific variant (extracted by `extract_variant`)
|
||||
/// and discarding all other non-matching content. Recursion through `Graphic::Graphic` sub-`List`s composes transforms and opacity.
|
||||
fn flatten_graphic_list<T>(content: List<Graphic>, extract_variant: fn(Graphic) -> Option<List<T>>) -> List<T> {
|
||||
fn flatten_recursive<T>(output: &mut List<T>, current_graphic_list: List<Graphic>, extract_variant: fn(Graphic) -> Option<List<T>>, parent_layer_path: Option<&[NodeId]>) {
|
||||
for current_graphic_item in current_graphic_list.into_iter() {
|
||||
// Whether the parent carries each attribute: a structural fact (column presence), never a value comparison.
|
||||
// Flattening composes a parent attribute onto its children only when the parent has it,
|
||||
// so an absent parent attribute never invents a column the children didn't already have.
|
||||
let parent_has_transform = current_graphic_item.attribute::<DAffine2>(ATTR_TRANSFORM).is_some();
|
||||
let parent_has_opacity = current_graphic_item.attribute::<f64>(ATTR_OPACITY).is_some();
|
||||
let parent_has_fill = current_graphic_item.attribute::<f64>(ATTR_OPACITY_FILL).is_some();
|
||||
|
||||
let current_transform: DAffine2 = current_graphic_item.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let current_opacity: f64 = current_graphic_item.attribute_cloned_or(ATTR_OPACITY, 1.);
|
||||
let current_fill: f64 = current_graphic_item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.);
|
||||
let lane_layer_path: Option<Vec<NodeId>> = current_graphic_item.attribute::<Vec<NodeId>>(ATTR_EDITOR_LAYER_PATH).cloned();
|
||||
let parent_appearance = current_graphic_item.attribute::<Appearance>(ATTR_APPEARANCE).and_then(Appearance::declared).cloned();
|
||||
|
||||
let (element, attributes) = current_graphic_item.into_parts();
|
||||
match element {
|
||||
// Compose the parent's transform/opacity/fill onto each child, but only for attributes the parent carries.
|
||||
// A child lacking one is padded with the composition identity (`1.` for opacity/fill, identity for transform), so composing through it is a no-op.
|
||||
Graphic::Graphic(mut sub_list) => {
|
||||
if parent_has_transform {
|
||||
for v in sub_list.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM) {
|
||||
*v = current_transform * *v;
|
||||
}
|
||||
}
|
||||
if parent_has_opacity {
|
||||
for v in sub_list.iter_attribute_values_mut_or_default::<f64>(ATTR_OPACITY) {
|
||||
*v *= current_opacity;
|
||||
}
|
||||
}
|
||||
if parent_has_fill {
|
||||
for v in sub_list.iter_attribute_values_mut_or_default::<f64>(ATTR_OPACITY_FILL) {
|
||||
*v *= current_fill;
|
||||
}
|
||||
}
|
||||
// Appearance cascades into each child whose own is undeclared, since a declared child wins wholesale
|
||||
if let Some(appearance) = &parent_appearance {
|
||||
for v in sub_list.iter_attribute_values_mut_or_default::<Appearance>(ATTR_APPEARANCE) {
|
||||
if v.is_empty() {
|
||||
*v = appearance.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
flatten_recursive(output, sub_list, extract_variant, lane_layer_path.as_deref());
|
||||
}
|
||||
// A bridge row's native group flattens through its legacy lowering.
|
||||
Graphic::Group(group) => {
|
||||
let lowered = List::new_from_item(Item::from_parts(group_to_legacy_graphic(&group), attributes.clone()));
|
||||
flatten_recursive(output, lowered, extract_variant, parent_layer_path);
|
||||
}
|
||||
// A de-tabled leaf is one attr-less element; the extracted row rides with its containing lane's full attributes, paint included.
|
||||
// The enclosing group lane's own layer path overrides, one hop only, matching the native walk.
|
||||
other => {
|
||||
if let Some(typed_list) = extract_variant(other) {
|
||||
for item in typed_list.into_iter() {
|
||||
let mut row = Item::from_parts(item.into_element(), attributes.clone());
|
||||
if let Some(layer_path) = parent_layer_path {
|
||||
row.set_attribute(ATTR_EDITOR_LAYER_PATH, layer_path.to_vec());
|
||||
}
|
||||
output.push(row);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut output = List::new();
|
||||
flatten_recursive(&mut output, content, extract_variant, None);
|
||||
output
|
||||
}
|
||||
|
||||
/// Maps from a concrete element type to its corresponding `Graphic` enum variant,
|
||||
/// enabling type-directed casting of typed `List`s from a `Graphic` value.
|
||||
pub trait TryFromGraphic: Clone + Sized {
|
||||
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>>;
|
||||
}
|
||||
|
||||
impl TryFromGraphic for Vector {
|
||||
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
|
||||
if let Graphic::Vector(t) = graphic { Some(List::new_from_element(t)) } else { None }
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFromGraphic for Raster<CPU> {
|
||||
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
|
||||
if let Graphic::RasterCPU(t) = graphic { Some(List::new_from_element(t)) } else { None }
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFromGraphic for Color {
|
||||
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
|
||||
if let Graphic::Color(t) = graphic { Some(List::new_from_element(t)) } else { None }
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFromGraphic for GradientStops {
|
||||
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
|
||||
if let Graphic::Gradient(t) = graphic { Some(List::new_from_element(t)) } else { None }
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFromGraphic for String {
|
||||
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
|
||||
if let Graphic::Text(t) = graphic { Some(List::new_from_element(t)) } else { None }
|
||||
}
|
||||
}
|
||||
|
||||
// Local trait to convert types to List<Graphic> (avoids orphan rule issues)
|
||||
pub trait IntoGraphicList: Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash + 'static {
|
||||
fn into_graphic_list(self) -> List<Graphic<'static>>;
|
||||
|
||||
/// Deeply flattens any content of type `T` within a `List<Graphic>`, discarding all other content, and returning a flat `List<T>`.
|
||||
fn into_flattened_list<T: TryFromGraphic>(self) -> List<T>
|
||||
where
|
||||
Self: std::marker::Sized,
|
||||
{
|
||||
flatten_graphic_list(self.into_graphic_list(), T::try_from_graphic)
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoGraphicList for List<Graphic<'static>> {
|
||||
fn into_graphic_list(self) -> List<Graphic<'static>> {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoGraphicList for List<Vector> {
|
||||
fn into_graphic_list(self) -> List<Graphic<'static>> {
|
||||
detable_items(self, Graphic::Vector)
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoGraphicList for List<Raster<CPU>> {
|
||||
fn into_graphic_list(self) -> List<Graphic<'static>> {
|
||||
detable_items(self, Graphic::RasterCPU)
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoGraphicList for List<Raster<GPU>> {
|
||||
fn into_graphic_list(self) -> List<Graphic<'static>> {
|
||||
detable_items(self, Graphic::RasterGPU)
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoGraphicList for List<Color> {
|
||||
fn into_graphic_list(self) -> List<Graphic<'static>> {
|
||||
detable_items(self, Graphic::Color)
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoGraphicList for List<GradientStops> {
|
||||
fn into_graphic_list(self) -> List<Graphic<'static>> {
|
||||
detable_items(self, Graphic::Gradient)
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoGraphicList for List<String> {
|
||||
fn into_graphic_list(self) -> List<Graphic<'static>> {
|
||||
detable_items(self, Graphic::Text)
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoGraphicList for DAffine2 {
|
||||
fn into_graphic_list(self) -> List<Graphic<'static>> {
|
||||
List::new_from_element(Graphic::default())
|
||||
}
|
||||
}
|
||||
|
||||
// DAffine2
|
||||
impl From<DAffine2> for Graphic<'_> {
|
||||
fn from(_: DAffine2) -> Self {
|
||||
Graphic::default()
|
||||
}
|
||||
}
|
||||
|
||||
// DVec2
|
||||
impl From<DVec2> for Graphic<'_> {
|
||||
fn from(position: DVec2) -> Self {
|
||||
Graphic::Vector(Vector::from_anchor_position(position))
|
||||
}
|
||||
}
|
||||
// Note: List conversions handled by blanket impl in gcore
|
||||
|
||||
impl<'e> Graphic<'e> {
|
||||
pub fn as_graphic(&self) -> Option<&List<Graphic<'_>>> {
|
||||
match self {
|
||||
Graphic::Graphic(graphic) => Some(graphic),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_graphic_mut(&mut self) -> Option<&mut List<Graphic<'e>>> {
|
||||
match self {
|
||||
Graphic::Graphic(graphic) => Some(graphic),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_vector(&self) -> Option<&Vector> {
|
||||
match self {
|
||||
Graphic::Vector(vector) => Some(vector),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_raster(&self) -> Option<&Raster<CPU>> {
|
||||
match self {
|
||||
Graphic::RasterCPU(raster) => Some(raster),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_raster_mut(&mut self) -> Option<&mut Raster<CPU>> {
|
||||
match self {
|
||||
Graphic::RasterCPU(raster) => Some(raster),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A leaf carries no clipping attribute, which rides its containing lane.
|
||||
pub fn had_clip_enabled(&self) -> bool {
|
||||
fn all_clipped<T>(list: &List<T>) -> bool {
|
||||
list.iter_attribute_values_or_default::<bool>(ATTR_CLIPPING_MASK).all(|clip| clip)
|
||||
}
|
||||
|
||||
match self {
|
||||
Graphic::Graphic(list) => all_clipped(list),
|
||||
Graphic::Group(group) => group_all_clipped(group),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn can_reduce_to_clip_path(&self, inherited_appearance: Option<&Appearance>) -> bool {
|
||||
match self {
|
||||
Graphic::Vector(vector) => vector_can_reduce_to_clip_path(&core_types::lane::Single(vector), inherited_appearance),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_opaque(&self) -> bool {
|
||||
match self {
|
||||
Graphic::Graphic(list) => !list.is_empty() && list.iter_element_values().all(Graphic::is_opaque),
|
||||
// A bare leaf carries no paint attribute, which rides its lane, so
|
||||
// nothing here claims opacity.
|
||||
Graphic::Vector(_) => false,
|
||||
Graphic::Color(color) => color.is_opaque(),
|
||||
Graphic::Gradient(stops) => stops.iter().all(|stop| stop.color.is_opaque()),
|
||||
Graphic::RasterCPU(_) | Graphic::RasterGPU(_) | Graphic::Text(_) => false,
|
||||
Graphic::Group(group) => group_is_opaque(group),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_fully_transparent(&self) -> bool {
|
||||
match self {
|
||||
Graphic::Graphic(list) => list.iter_element_values().all(Graphic::is_fully_transparent),
|
||||
// A bare vector leaf carries no paint or stroke of its own, so it is invisible on its own
|
||||
Graphic::Vector(_) => true,
|
||||
Graphic::Color(color) => color.a() == 0.,
|
||||
Graphic::Gradient(stops) => stops.iter().all(|stop| stop.color.a() == 0.),
|
||||
Graphic::RasterCPU(_) | Graphic::RasterGPU(_) | Graphic::Text(_) => false,
|
||||
Graphic::Group(group) => group_is_fully_transparent(group),
|
||||
}
|
||||
}
|
||||
|
||||
/// True if this paint opaquely covers the entire fill region.
|
||||
/// Vector, Raster, and a nested Graphic may leave gaps, so they return false.
|
||||
pub fn covers_opaquely(&self) -> bool {
|
||||
matches!(self, Graphic::Color(_) | Graphic::Gradient(_)) && self.is_opaque()
|
||||
}
|
||||
|
||||
/// Whether the graphic holds no content: a leaf always holds its element.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
match self {
|
||||
Graphic::Graphic(list) => list.is_empty(),
|
||||
Graphic::Group(group) => group_is_empty(group),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl BoundingBox for Graphic<'_> {
|
||||
fn bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
|
||||
match self {
|
||||
Graphic::Vector(vector) => BoundingBox::bounding_box(vector, transform, include_stroke),
|
||||
Graphic::RasterCPU(raster) => raster.bounding_box(transform, include_stroke),
|
||||
Graphic::RasterGPU(raster) => raster.bounding_box(transform, include_stroke),
|
||||
Graphic::Graphic(list) => list.bounding_box(transform, include_stroke),
|
||||
Graphic::Color(color) => color.bounding_box(transform, include_stroke),
|
||||
Graphic::Gradient(gradient) => gradient.bounding_box(transform, include_stroke),
|
||||
Graphic::Text(text) => text.bounding_box(transform, include_stroke),
|
||||
Graphic::Group(group) => group_bounding_box(group, transform, include_stroke, false),
|
||||
}
|
||||
}
|
||||
|
||||
fn thumbnail_bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
|
||||
match self {
|
||||
Graphic::Vector(vector) => vector.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::RasterCPU(raster) => raster.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::RasterGPU(raster) => raster.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::Graphic(graphic) => graphic.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::Color(color) => color.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::Gradient(gradient) => gradient.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::Text(list) => list.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::Group(group) => group_bounding_box(group, transform, include_stroke, true),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'e> ListConvert<Graphic<'e>> for Vector {
|
||||
fn convert_item(self) -> Graphic<'e> {
|
||||
Graphic::Vector(self)
|
||||
}
|
||||
}
|
||||
impl<'e> ListConvert<Graphic<'e>> for Raster<CPU> {
|
||||
fn convert_item(self) -> Graphic<'e> {
|
||||
Graphic::RasterCPU(self)
|
||||
}
|
||||
}
|
||||
impl<'e> ListConvert<Graphic<'e>> for Raster<GPU> {
|
||||
fn convert_item(self) -> Graphic<'e> {
|
||||
Graphic::RasterGPU(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderComplexity for Graphic<'_> {
|
||||
fn render_complexity(&self) -> usize {
|
||||
match self {
|
||||
Self::Graphic(list) => list.render_complexity(),
|
||||
Self::Vector(list) => list.render_complexity(),
|
||||
Self::RasterCPU(list) => list.render_complexity(),
|
||||
Self::RasterGPU(list) => list.render_complexity(),
|
||||
Self::Color(list) => list.render_complexity(),
|
||||
Self::Gradient(list) => list.render_complexity(),
|
||||
Self::Text(list) => list.render_complexity(),
|
||||
Self::Group(group) => group_render_complexity(group),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Node definitions moved to graphic-nodes crate
|
||||
|
||||
pub trait AtIndex {
|
||||
type Output;
|
||||
fn at_index(&self, index: usize) -> Option<Self::Output>;
|
||||
fn at_index_from_end(&self, index: usize) -> Option<Self::Output>;
|
||||
}
|
||||
impl<T: Clone> AtIndex for Vec<T> {
|
||||
type Output = T;
|
||||
|
||||
fn at_index(&self, index: usize) -> Option<Self::Output> {
|
||||
self.get(index).cloned()
|
||||
}
|
||||
|
||||
fn at_index_from_end(&self, index: usize) -> Option<Self::Output> {
|
||||
if index == 0 || index > self.len() { None } else { self.get(self.len() - index).cloned() }
|
||||
}
|
||||
}
|
||||
impl<T: Clone> AtIndex for List<T> {
|
||||
type Output = List<T>;
|
||||
|
||||
fn at_index(&self, index: usize) -> Option<Self::Output> {
|
||||
self.clone_item(index).map(|item| {
|
||||
let mut result_list = Self::default();
|
||||
result_list.push(item);
|
||||
result_list
|
||||
})
|
||||
}
|
||||
|
||||
fn at_index_from_end(&self, index: usize) -> Option<Self::Output> {
|
||||
if index == 0 || index > self.len() { None } else { self.at_index(self.len() - index) }
|
||||
}
|
||||
}
|
||||
|
||||
pub trait OmitIndex {
|
||||
fn omit_index(&self, index: usize) -> Self;
|
||||
fn omit_index_from_end(&self, index: usize) -> Self;
|
||||
}
|
||||
impl<T: Clone> OmitIndex for Vec<T> {
|
||||
fn omit_index(&self, index: usize) -> Self {
|
||||
self.iter().enumerate().filter(|(i, _)| *i != index).map(|(_, v)| v.clone()).collect()
|
||||
}
|
||||
|
||||
fn omit_index_from_end(&self, index: usize) -> Self {
|
||||
if index == 0 || index > self.len() {
|
||||
return self.clone();
|
||||
}
|
||||
self.omit_index(self.len() - index)
|
||||
}
|
||||
}
|
||||
impl<T: Clone> OmitIndex for List<T> {
|
||||
fn omit_index(&self, index: usize) -> Self {
|
||||
let mut result = Self::default();
|
||||
for i in 0..self.len() {
|
||||
if i != index
|
||||
&& let Some(item) = self.clone_item(i)
|
||||
{
|
||||
result.push(item);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn omit_index_from_end(&self, index: usize) -> Self {
|
||||
if index == 0 || index > self.len() {
|
||||
return self.clone();
|
||||
}
|
||||
self.omit_index(self.len() - index)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use core_types::list::List;
|
||||
|
||||
fn vector_graphic() -> Graphic<'static> {
|
||||
Graphic::Vector(Vector::default())
|
||||
}
|
||||
|
||||
// Flattening must not invent attribute columns that neither the parent graphic nor the child carried
|
||||
#[test]
|
||||
fn flatten_does_not_invent_attributes() {
|
||||
let graphics = List::new_from_element(vector_graphic());
|
||||
let flattened: List<Vector> = graphics.into_flattened_list();
|
||||
for key in [ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, ATTR_EDITOR_LAYER_PATH] {
|
||||
assert!(!flattened.attribute_keys().any(|k| k == key), "flatten invented the `{key}` attribute");
|
||||
}
|
||||
}
|
||||
|
||||
// A parent attribute that is present must compose onto the flattened children
|
||||
#[test]
|
||||
fn flatten_propagates_present_attributes() {
|
||||
let mut graphics = List::new_from_element(vector_graphic());
|
||||
graphics.set_attribute(ATTR_OPACITY, 0, 0.5_f64);
|
||||
let flattened: List<Vector> = graphics.into_flattened_list();
|
||||
assert_eq!(flattened.attribute_cloned_or_default::<f64>(ATTR_OPACITY, 0), 0.5);
|
||||
|
||||
let mut group = List::new_from_element(Graphic::Graphic(List::new_from_element(vector_graphic())));
|
||||
group.set_attribute(ATTR_OPACITY, 0, 0.5_f64);
|
||||
let flattened: List<Vector> = group.into_flattened_list();
|
||||
assert_eq!(flattened.attribute_cloned_or_default::<f64>(ATTR_OPACITY, 0), 0.5);
|
||||
}
|
||||
|
||||
// A padded (empty) appearance cell is undeclared, so the parent's appearance cascades into it while a declared sibling keeps its own
|
||||
#[test]
|
||||
fn flatten_cascades_into_padded_empty_appearance_items() {
|
||||
use crate::appearance::Coverage;
|
||||
|
||||
let single = |color: Color| Appearance::new_single(Coverage::new_fill(), Graphic::Color(color));
|
||||
|
||||
// Declaring an appearance on item 0 forces the attribute, padding item 1 with the empty appearance
|
||||
let mut inner = List::new();
|
||||
inner.push(Item::new_from_element(vector_graphic()));
|
||||
inner.push(Item::new_from_element(vector_graphic()));
|
||||
inner.set_attribute(ATTR_APPEARANCE, 0, single(Color::BLACK));
|
||||
|
||||
let mut outer = List::new_from_element(Graphic::Graphic(inner));
|
||||
outer.set_attribute(ATTR_APPEARANCE, 0, single(Color::WHITE));
|
||||
|
||||
let flattened: List<Vector> = outer.into_flattened_list();
|
||||
let color_of = |index: usize| {
|
||||
let appearance = flattened.attribute::<Appearance>(ATTR_APPEARANCE, index)?;
|
||||
let Graphic::Color(color) = appearance.paint_at(0)? else { return None };
|
||||
Some(*color)
|
||||
};
|
||||
|
||||
assert_eq!(color_of(0), Some(Color::BLACK), "a declared item should keep its own appearance");
|
||||
assert_eq!(color_of(1), Some(Color::WHITE), "a padded item should inherit the parent appearance");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod graphic_is_opaque_tests {
|
||||
use vector_types::GradientStop;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn color_graphic(alpha: f64) -> Graphic<'static> {
|
||||
let color = Color::from_rgbaf32(1., 0., 0., alpha as f32).unwrap();
|
||||
Graphic::Color(color)
|
||||
}
|
||||
|
||||
fn gradient_graphic(gradient: GradientStops) -> Graphic<'static> {
|
||||
Graphic::Gradient(gradient)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opaque_color_is_opaque() {
|
||||
let g = color_graphic(1.);
|
||||
assert!(g.is_opaque());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transparent_color_is_not_opaque() {
|
||||
let g = color_graphic(0.5);
|
||||
assert!(!g.is_opaque());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_is_not_opaque() {
|
||||
let g = Graphic::Vector(Vector::default());
|
||||
assert!(!g.is_opaque());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_with_all_opaque_stops_is_opaque() {
|
||||
let color_1 = Color::from_rgbaf32(1., 0., 0., 1.).unwrap();
|
||||
let color_2 = Color::from_rgbaf32(1., 0., 0., 1.).unwrap();
|
||||
let gradient = GradientStops::new(vec![
|
||||
GradientStop {
|
||||
position: 0.,
|
||||
midpoint: 0.5,
|
||||
color: color_1,
|
||||
},
|
||||
GradientStop {
|
||||
position: 1.,
|
||||
midpoint: 0.5,
|
||||
color: color_2,
|
||||
},
|
||||
]);
|
||||
let g = gradient_graphic(gradient);
|
||||
assert!(g.is_opaque());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_with_transparent_stop_is_not_opaque() {
|
||||
let color_1 = Color::from_rgbaf32(1., 0., 0., 0.5).unwrap();
|
||||
let color_2 = Color::from_rgbaf32(1., 0., 0., 1.).unwrap();
|
||||
let gradient = GradientStops::new(vec![
|
||||
GradientStop {
|
||||
position: 0.,
|
||||
midpoint: 0.5,
|
||||
color: color_1,
|
||||
},
|
||||
GradientStop {
|
||||
position: 1.,
|
||||
midpoint: 0.5,
|
||||
color: color_2,
|
||||
},
|
||||
]);
|
||||
let g = gradient_graphic(gradient);
|
||||
assert!(!g.is_opaque());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test_support {
|
||||
use super::Graphic;
|
||||
use core_types::list::List;
|
||||
use core_types::record::{RunBuilder, element_write_hashed};
|
||||
use glam::DVec2;
|
||||
use vector_types::Vector;
|
||||
use vector_types::subpath::Subpath;
|
||||
use vector_types::vector::PointId;
|
||||
|
||||
pub(in crate::graphic) fn unit_square_at(corner: DVec2) -> Vector {
|
||||
Vector::from_subpath(Subpath::<PointId>::new_rectangle(corner, corner + DVec2::ONE))
|
||||
}
|
||||
|
||||
pub(in crate::graphic) fn native_group_paint<'a>(vector: &Vector, arena: &'a core_types::arena::Arena) -> List<Graphic<'a>> {
|
||||
let mut builder = RunBuilder::new(arena, element_write_hashed::<Vector>(), &[], 1).unwrap();
|
||||
builder.push(vector.clone()).unwrap();
|
||||
List::new_from_element(Graphic::Group(core_types::record::Group { row: None, content: builder.finish() }))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
//! The appearance cascade level: the declared appearance read as a lane column and threaded down to the elements it reaches.
|
||||
|
||||
use super::Graphic;
|
||||
use crate::appearance::Appearance;
|
||||
use crate::markers::Appearance as AppearanceMarker;
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
use core_types::attribute::Opacity;
|
||||
use core_types::lane::{LaneColumn, LaneSource};
|
||||
use core_types::list::{ItemAttributeValues, List};
|
||||
use glam::DAffine2;
|
||||
use vector_types::Vector;
|
||||
|
||||
/// Whether a normalized paint graphic list actually carries renderable paint.
|
||||
/// A 0-item list, or a list whose first graphic is empty, is treated as no paint.
|
||||
pub fn is_paint_present(graphic_list: &List<Graphic>) -> bool {
|
||||
graphic_list.element(0).is_some_and(|graphic| !graphic.is_empty())
|
||||
}
|
||||
|
||||
/// Whether every lane of a vector source draws as a plain clip path: fully
|
||||
/// opaque, fill absent or opaque, stroke invisible or fully transparent.
|
||||
pub fn vector_can_reduce_to_clip_path<S: LaneSource<Element = Vector>>(source: &S, inherited_appearance: Option<&Appearance>) -> bool {
|
||||
(0..source.lane_count()).all(|index| {
|
||||
if source.element(index).is_none() {
|
||||
return false;
|
||||
}
|
||||
let opacity: f64 = source.attr::<Opacity>(index);
|
||||
|
||||
let appearance = Appearance::cascade(source.attr::<AppearanceMarker>(index), inherited_appearance);
|
||||
let resolved = appearance.map(Appearance::fill_and_stroke).unwrap_or_default();
|
||||
|
||||
let fill_opaque_or_absent = resolved
|
||||
.fill_paint
|
||||
.and_then(paint_cell_rows)
|
||||
.is_none_or(|graphic_list| graphic_list.element(0).is_none_or(|graphic| graphic.is_opaque()));
|
||||
|
||||
let stroke_invisible_or_transparent = resolved.stroke.as_ref().is_none_or(|stroke| !stroke.has_renderable_stroke())
|
||||
|| resolved
|
||||
.stroke_paint
|
||||
.and_then(paint_cell_rows)
|
||||
.is_none_or(|graphic_list| graphic_list.element(0).is_none_or(|graphic| graphic.is_fully_transparent()));
|
||||
|
||||
opacity > 1. - f64::EPSILON && fill_opaque_or_absent && stroke_invisible_or_transparent
|
||||
})
|
||||
}
|
||||
|
||||
/// A source's declared appearance column, resolved once for per-lane reads.
|
||||
pub struct PaintColumns<'a, S: LaneSource + 'a> {
|
||||
appearance: S::Column<'a, AppearanceMarker>,
|
||||
}
|
||||
|
||||
impl<'a, S: LaneSource> PaintColumns<'a, S> {
|
||||
pub fn new(source: &'a S) -> Self {
|
||||
Self {
|
||||
appearance: source.column::<AppearanceMarker>(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The lane's own declared appearance; an absent or empty cell is undeclared.
|
||||
pub fn read_appearance(&self, lane: usize) -> Option<&'a Appearance> {
|
||||
self.appearance.try_get(lane).flatten().and_then(Appearance::declared)
|
||||
}
|
||||
}
|
||||
|
||||
/// The appearance cascade threading down the graphic levels: a lane's own
|
||||
/// declared appearance wins wholesale, an undeclared lane inherits the
|
||||
/// nearest ancestor's, at any depth. Only a fresh entry (a pattern's own
|
||||
/// render, or any standalone render root) starts without an inherited one.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct PaintReach<'a> {
|
||||
/// The cascade's resolved appearance: the nearest declared one at or above this lane.
|
||||
pub appearance: Option<&'a Appearance>,
|
||||
}
|
||||
|
||||
impl<'a> PaintReach<'a> {
|
||||
pub const NONE: Self = Self { appearance: None };
|
||||
|
||||
/// The lane's effective reach: its own declared appearance wins over the inherited one.
|
||||
pub fn for_lane<S: LaneSource>(self, columns: &PaintColumns<'a, S>, index: usize) -> Self {
|
||||
Self {
|
||||
appearance: Appearance::cascade(columns.read_appearance(index), self.appearance),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The paint a coverage row's cell holds, in the canonical `List<Graphic>` form the paint
|
||||
/// renderers consume: this crate's writers carry the list as one graphic cell, and a bare
|
||||
/// cell of any other form is treated as paint that draws nothing.
|
||||
pub fn paint_cell_rows<'a>(cell: &'a Graphic<'static>) -> Option<&'a List<Graphic<'static>>> {
|
||||
match cell {
|
||||
Graphic::Graphic(list) => Some(list).filter(|list| is_paint_present(list)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Bake the provided transform into the per-item transforms of the paint
|
||||
/// graphics inside the item's appearance coverage cells.
|
||||
pub fn bake_paint_transforms(attributes: &mut ItemAttributeValues, transform: DAffine2) {
|
||||
fn bake_graphic_paint_transform(graphics: &mut List<Graphic>, transform: DAffine2) {
|
||||
for item_transform in graphics.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM) {
|
||||
*item_transform = transform * *item_transform;
|
||||
}
|
||||
for graphic in graphics.iter_element_values_mut() {
|
||||
if let Graphic::Graphic(list) = graphic {
|
||||
bake_graphic_paint_transform(list, transform);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(appearance) = attributes.get_mut::<Appearance>(crate::markers::ATTR_APPEARANCE) {
|
||||
if let Some(cells) = appearance.0.iter_attribute_values_mut::<Graphic>(crate::markers::ATTR_PAINT) {
|
||||
for cell in cells {
|
||||
if let Graphic::Graphic(list) = cell {
|
||||
bake_graphic_paint_transform(list, transform);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod run_tests {
|
||||
use super::*;
|
||||
use crate::graphic::run_to_legacy_list;
|
||||
use crate::graphic::test_support::unit_square_at;
|
||||
use core_types::Color;
|
||||
use core_types::record::{FieldWrite, RunBuilder, RunView, element_write_hashed};
|
||||
use glam::DVec2;
|
||||
|
||||
#[test]
|
||||
fn a_run_serves_the_parked_appearance_reference() {
|
||||
use crate::appearance::Coverage;
|
||||
use core_types::lane::LaneSource;
|
||||
|
||||
let appearance = Appearance::new_single(Coverage::new_fill(), Graphic::Color(Color::BLACK));
|
||||
let vector = unit_square_at(DVec2::ZERO);
|
||||
|
||||
let arena = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
let mut builder = RunBuilder::new(&arena, element_write_hashed::<Vector>(), &[FieldWrite::of::<AppearanceMarker>(0)], 1).unwrap();
|
||||
let lane = builder.push(vector.clone()).unwrap();
|
||||
builder.attr::<AppearanceMarker>(lane, Some(&appearance));
|
||||
let item = builder.finish();
|
||||
let run = RunView::<Vector>::new(&item).expect("the run holds vector elements");
|
||||
|
||||
assert_eq!(run.attr::<AppearanceMarker>(0), Some(&appearance));
|
||||
|
||||
let legacy = run_to_legacy_list::<Vector>(&item).expect("the run lowers to a legacy vector list");
|
||||
assert_eq!(legacy.attr::<AppearanceMarker>(0), Some(&appearance));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reach_cascades_the_appearance_with_own_wins_arbitration() {
|
||||
use crate::appearance::Coverage;
|
||||
use crate::markers::ATTR_APPEARANCE;
|
||||
|
||||
let own = Appearance::new_single(Coverage::new_fill(), Graphic::Color(Color::BLACK));
|
||||
let inherited = Appearance::new_single(Coverage::new_fill(), Graphic::Color(Color::WHITE));
|
||||
|
||||
// Lane 0 declares its own appearance, lane 1 is padded with the empty (undeclared) one
|
||||
let mut list: List<Graphic<'static>> = List::new_from_element(Graphic::Vector(Vector::default()));
|
||||
list.push(core_types::list::Item::new_from_element(Graphic::Vector(Vector::default())));
|
||||
list.set_attribute(ATTR_APPEARANCE, 0, own.clone());
|
||||
|
||||
let columns = PaintColumns::new(&list);
|
||||
let ancestor = PaintReach { appearance: Some(&inherited) };
|
||||
|
||||
assert_eq!(ancestor.for_lane(&columns, 0).appearance, Some(&own), "a declared lane wins over the inherited appearance");
|
||||
assert_eq!(ancestor.for_lane(&columns, 1).appearance, Some(&inherited), "a padded lane inherits");
|
||||
assert_eq!(PaintReach::NONE.for_lane(&columns, 1).appearance, None, "no ancestor leaves an undeclared lane bare");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,570 @@
|
||||
//! The native-content walk: vector rows reached through a graphic's own storage, with no legacy conversion.
|
||||
|
||||
use super::Graphic;
|
||||
use super::paint::{PaintColumns, PaintReach};
|
||||
use crate::appearance::Appearance;
|
||||
use crate::markers::ATTR_APPEARANCE;
|
||||
use core_types::attribute::{Attribute, ClippingMask, EditorLayerPath, Opacity, OpacityFill, Transform};
|
||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::lane::LaneSource;
|
||||
use core_types::list::{AttributeValueDyn, Item, ItemAttributeValues, List};
|
||||
use core_types::record::FieldOffset;
|
||||
use core_types::render_complexity::RenderComplexity;
|
||||
use core_types::uuid::NodeId;
|
||||
use core_types::{ATTR_EDITOR_LAYER_PATH, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
use vector_types::{GradientStops, Vector};
|
||||
|
||||
/// One run's attribute tokens, minted once so the lane loops read at an offset.
|
||||
struct RunAttrs {
|
||||
transform: Option<FieldOffset<Transform>>,
|
||||
opacity: Option<FieldOffset<Opacity>>,
|
||||
opacity_fill: Option<FieldOffset<OpacityFill>>,
|
||||
clipping_mask: Option<FieldOffset<ClippingMask>>,
|
||||
}
|
||||
|
||||
impl RunAttrs {
|
||||
fn of(item: &core_types::record::GroupItem) -> Self {
|
||||
let layout = item.layout();
|
||||
Self {
|
||||
transform: FieldOffset::of(layout, 0),
|
||||
opacity: FieldOffset::of(layout, 0),
|
||||
opacity_fill: FieldOffset::of(layout, 0),
|
||||
clipping_mask: FieldOffset::of(layout, 0),
|
||||
}
|
||||
}
|
||||
|
||||
fn read_or<'i, A: Attribute>(item: &'i core_types::record::GroupItem, field: Option<FieldOffset<A>>, lane: usize, default: A::Value<'i>) -> A::Value<'i> {
|
||||
match field.and_then(|field| item.lanes().get(lane).try_attr_at(field)) {
|
||||
Some(value) => value,
|
||||
None => default,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn group_is_empty(group: &core_types::record::Group) -> bool {
|
||||
group.content.is_empty()
|
||||
}
|
||||
|
||||
pub(in crate::graphic) fn group_all_clipped(group: &core_types::record::Group) -> bool {
|
||||
let item = &group.content;
|
||||
let attrs = RunAttrs::of(item);
|
||||
(0..item.len()).all(|lane| RunAttrs::read_or(item, attrs.clipping_mask, lane, false))
|
||||
}
|
||||
|
||||
pub(in crate::graphic) fn group_is_opaque(group: &core_types::record::Group) -> bool {
|
||||
let item = &group.content;
|
||||
let attrs = RunAttrs::of(item);
|
||||
let lanes = item.typed_lanes::<Graphic>();
|
||||
!item.is_empty()
|
||||
&& (0..item.len()).all(|lane| {
|
||||
RunAttrs::read_or(item, attrs.opacity, lane, 1.) >= 1.
|
||||
&& RunAttrs::read_or(item, attrs.opacity_fill, lane, 1.) >= 1.
|
||||
&& lanes.as_ref().is_some_and(|lanes| lanes.element_ref(lane).is_opaque())
|
||||
})
|
||||
}
|
||||
|
||||
pub(in crate::graphic) fn group_is_fully_transparent(group: &core_types::record::Group) -> bool {
|
||||
let item = &group.content;
|
||||
let attrs = RunAttrs::of(item);
|
||||
let lanes = item.typed_lanes::<Graphic>();
|
||||
(0..item.len()).all(|lane| RunAttrs::read_or(item, attrs.opacity, lane, 1.) <= 0. || lanes.as_ref().is_some_and(|lanes| lanes.element_ref(lane).is_fully_transparent()))
|
||||
}
|
||||
|
||||
pub(in crate::graphic) fn group_bounding_box(group: &core_types::record::Group, transform: DAffine2, include_stroke: bool, thumbnail: bool) -> RenderBoundingBox {
|
||||
fn combine(combined: &mut Option<[DVec2; 2]>, any_infinite: &mut bool, bounds: RenderBoundingBox, thumbnail: bool) -> Option<RenderBoundingBox> {
|
||||
match bounds {
|
||||
RenderBoundingBox::None => None,
|
||||
RenderBoundingBox::Infinite if thumbnail => {
|
||||
*any_infinite = true;
|
||||
None
|
||||
}
|
||||
RenderBoundingBox::Infinite => Some(RenderBoundingBox::Infinite),
|
||||
RenderBoundingBox::Rectangle(bounds) => {
|
||||
*combined = Some(match *combined {
|
||||
Some(existing) => core_types::math::quad::Quad::combine_bounds(existing, bounds),
|
||||
None => bounds,
|
||||
});
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
fn typed_run<T: dyn_any::StaticTypeSized + BoundingBox>(item: &core_types::record::GroupItem, transform: DAffine2, include_stroke: bool, thumbnail: bool) -> Option<RenderBoundingBox> {
|
||||
let lanes = item.typed_lanes::<T>()?;
|
||||
let transform_offset = RunAttrs::of(item).transform;
|
||||
let mut combined = None;
|
||||
let mut any_infinite = false;
|
||||
for lane in 0..lanes.len() {
|
||||
let lane_transform = transform * RunAttrs::read_or(item, transform_offset, lane, DAffine2::IDENTITY);
|
||||
let element = lanes.element_ref(lane);
|
||||
let bounds = match thumbnail {
|
||||
true => element.thumbnail_bounding_box(lane_transform, include_stroke),
|
||||
false => element.bounding_box(lane_transform, include_stroke),
|
||||
};
|
||||
if let Some(short_circuit) = combine(&mut combined, &mut any_infinite, bounds, thumbnail) {
|
||||
return Some(short_circuit);
|
||||
}
|
||||
}
|
||||
Some(match (combined, any_infinite) {
|
||||
(Some(bounds), _) => RenderBoundingBox::Rectangle(bounds),
|
||||
(None, true) => RenderBoundingBox::Infinite,
|
||||
(None, false) => RenderBoundingBox::None,
|
||||
})
|
||||
}
|
||||
fn run_bounding_box(item: &core_types::record::GroupItem, transform: DAffine2, include_stroke: bool, thumbnail: bool) -> RenderBoundingBox {
|
||||
None.or_else(|| typed_run::<Graphic>(item, transform, include_stroke, thumbnail))
|
||||
.or_else(|| typed_run::<Vector>(item, transform, include_stroke, thumbnail))
|
||||
.or_else(|| typed_run::<Raster<CPU>>(item, transform, include_stroke, thumbnail))
|
||||
.or_else(|| typed_run::<Raster<GPU>>(item, transform, include_stroke, thumbnail))
|
||||
.or_else(|| typed_run::<Color>(item, transform, include_stroke, thumbnail))
|
||||
.or_else(|| typed_run::<GradientStops>(item, transform, include_stroke, thumbnail))
|
||||
.or_else(|| typed_run::<String>(item, transform, include_stroke, thumbnail))
|
||||
.unwrap_or(RenderBoundingBox::Infinite)
|
||||
}
|
||||
run_bounding_box(&group.content, transform, include_stroke, thumbnail)
|
||||
}
|
||||
|
||||
/// One step of the vector-row walk: continue to the next row or stop early.
|
||||
pub enum RowStep {
|
||||
Continue,
|
||||
Stop,
|
||||
}
|
||||
|
||||
/// The ancestor composition a flattened row inherits: transform, opacity and
|
||||
/// fill opacity multiply down, each composing only where some ancestor
|
||||
/// carries the attribute, matching the legacy flatten.
|
||||
#[derive(Clone, Copy)]
|
||||
struct FlattenScale {
|
||||
has_transform: bool,
|
||||
transform: DAffine2,
|
||||
has_opacity: bool,
|
||||
opacity: f64,
|
||||
has_fill_opacity: bool,
|
||||
fill_opacity: f64,
|
||||
}
|
||||
|
||||
impl FlattenScale {
|
||||
const ROOT: Self = Self {
|
||||
has_transform: false,
|
||||
transform: DAffine2::IDENTITY,
|
||||
has_opacity: false,
|
||||
opacity: 1.,
|
||||
has_fill_opacity: false,
|
||||
fill_opacity: 1.,
|
||||
};
|
||||
|
||||
fn composed<S: LaneSource>(self, source: &S, lane: usize) -> Self {
|
||||
let transform = source.try_attr::<Transform>(lane);
|
||||
let opacity = source.try_attr::<Opacity>(lane);
|
||||
let fill_opacity = source.try_attr::<OpacityFill>(lane);
|
||||
Self {
|
||||
has_transform: self.has_transform || transform.is_some(),
|
||||
transform: self.transform * transform.unwrap_or(DAffine2::IDENTITY),
|
||||
has_opacity: self.has_opacity || opacity.is_some(),
|
||||
opacity: self.opacity * opacity.unwrap_or(1.),
|
||||
has_fill_opacity: self.has_fill_opacity || fill_opacity.is_some(),
|
||||
fill_opacity: self.fill_opacity * fill_opacity.unwrap_or(1.),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A graphic level in either of its two storages, as one lane source.
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum GraphicLevel<'a> {
|
||||
Legacy(&'a List<Graphic<'a>>),
|
||||
Run(&'a core_types::record::GroupItem<'a>),
|
||||
}
|
||||
|
||||
pub enum GraphicLevelColumn<'a, A: Attribute> {
|
||||
Legacy(core_types::list::ListColumn<'a, A>),
|
||||
Run(core_types::record::RunColumn<'a, A>),
|
||||
}
|
||||
|
||||
impl<'a, A: Attribute> core_types::lane::LaneColumn<'a, A> for GraphicLevelColumn<'a, A> {
|
||||
fn try_get(&self, lane: usize) -> Option<A::Value<'a>> {
|
||||
match self {
|
||||
GraphicLevelColumn::Legacy(column) => column.try_get(lane),
|
||||
GraphicLevelColumn::Run(column) => column.try_get(lane),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> LaneSource for GraphicLevel<'a> {
|
||||
type Element = Graphic<'a>;
|
||||
type Column<'b, A: Attribute>
|
||||
= GraphicLevelColumn<'b, A>
|
||||
where
|
||||
Self: 'b;
|
||||
|
||||
fn lane_count(&self) -> usize {
|
||||
match self {
|
||||
GraphicLevel::Legacy(list) => list.len(),
|
||||
GraphicLevel::Run(item) => item.len(),
|
||||
}
|
||||
}
|
||||
|
||||
fn element(&self, lane: usize) -> Option<&Graphic<'a>> {
|
||||
match self {
|
||||
GraphicLevel::Legacy(list) => list.element(lane),
|
||||
GraphicLevel::Run(item) => {
|
||||
let lanes = item.typed_lanes::<Graphic>()?;
|
||||
if lane >= lanes.len() {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: the layout records the element type, and a parked
|
||||
// element stores its reference at offset 0.
|
||||
Some(unsafe { core_types::record::borrow_element::<Graphic>(item.lanes().get(lane).rec()) })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn column<A: Attribute>(&self) -> GraphicLevelColumn<'_, A> {
|
||||
match self {
|
||||
GraphicLevel::Legacy(list) => GraphicLevelColumn::Legacy(list.column::<A>()),
|
||||
GraphicLevel::Run(item) => GraphicLevelColumn::Run(core_types::record::RunColumn::of(item)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The lane's attributes as an owned set, read through the erased glue.
|
||||
pub fn run_lane_attributes(item: &core_types::record::GroupItem, lane: usize) -> ItemAttributeValues {
|
||||
let mut scratch: List<Vector> = List::new_from_element(Vector::default());
|
||||
for field in &item.layout().fields {
|
||||
// SAFETY: the offset comes from the item's own layout.
|
||||
let value = unsafe { (field.read_erased)(item.lanes().get(lane).rec().ptr().add(field.offset)) };
|
||||
scratch.set_attribute_value_dyn(field.name, 0, AttributeValueDyn(value));
|
||||
}
|
||||
scratch.clone_item_attributes(0)
|
||||
}
|
||||
|
||||
/// The lane's attributes as an owned set, from either level storage.
|
||||
pub fn lane_attributes(level: GraphicLevel<'_>, lane: usize) -> ItemAttributeValues {
|
||||
match level {
|
||||
GraphicLevel::Legacy(list) => list.clone_item_attributes(lane),
|
||||
GraphicLevel::Run(item) => run_lane_attributes(item, lane),
|
||||
}
|
||||
}
|
||||
|
||||
/// One flattened vector row served by [`walk_vector_rows`]: cheap probes
|
||||
/// first, the full row built on demand.
|
||||
pub struct VectorRow<'w> {
|
||||
source: RowSourceRef<'w>,
|
||||
scale: FlattenScale,
|
||||
layer_path: Option<&'w [NodeId]>,
|
||||
appearance: Option<&'w Appearance>,
|
||||
}
|
||||
|
||||
enum RowSourceRef<'w> {
|
||||
/// A de-tabled vector leaf on a graphic lane: the lane is the row.
|
||||
Lane(GraphicLevel<'w>, usize),
|
||||
/// A lane of a vector run.
|
||||
Run(&'w core_types::record::RunView<'w, Vector>, &'w core_types::record::GroupItem<'w>, usize),
|
||||
}
|
||||
|
||||
impl VectorRow<'_> {
|
||||
/// The row's vector, borrowed.
|
||||
pub fn element(&self) -> &Vector {
|
||||
match &self.source {
|
||||
RowSourceRef::Lane(level, index) => level.element(*index).and_then(Graphic::as_vector).expect("the walk visits vector lanes"),
|
||||
RowSourceRef::Run(run, _, index) => LaneSource::element(*run, *index).expect("the walk visits held lanes"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the built row will carry fill paint: a painted fill coverage on
|
||||
/// the row's resolved appearance.
|
||||
pub fn has_fill(&self) -> bool {
|
||||
let own = match &self.source {
|
||||
RowSourceRef::Lane(level, index) => level.attr::<crate::markers::Appearance>(*index),
|
||||
RowSourceRef::Run(run, _, index) => LaneSource::attr::<crate::markers::Appearance>(*run, *index),
|
||||
};
|
||||
Appearance::cascade(own, self.appearance).is_some_and(|appearance| appearance.has_painted_cover(crate::appearance::Cover::Fill))
|
||||
}
|
||||
|
||||
/// Builds the row at the end of `out`, applying the reach paint and the
|
||||
/// inherited composition.
|
||||
pub fn build_into(&self, out: &mut List<Vector>) {
|
||||
let index = out.len();
|
||||
match &self.source {
|
||||
RowSourceRef::Lane(level, lane) => {
|
||||
let vector = self.element().clone();
|
||||
out.push(Item::from_parts(vector, lane_attributes(*level, *lane)));
|
||||
}
|
||||
RowSourceRef::Run(run, item, lane) => {
|
||||
let vector = LaneSource::element(*run, *lane).expect("the walk visits held lanes").clone();
|
||||
out.push(Item::from_parts(vector, run_lane_attributes(item, *lane)));
|
||||
}
|
||||
}
|
||||
if self.scale.has_transform || out.attribute::<DAffine2>(ATTR_TRANSFORM, index).is_some() {
|
||||
let row_transform: DAffine2 = out.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
out.set_attribute(ATTR_TRANSFORM, index, self.scale.transform * row_transform);
|
||||
}
|
||||
if self.scale.has_opacity || out.attribute::<f64>(ATTR_OPACITY, index).is_some() {
|
||||
let row_opacity: f64 = out.attribute_cloned_or(ATTR_OPACITY, index, 1.);
|
||||
out.set_attribute(ATTR_OPACITY, index, self.scale.opacity * row_opacity);
|
||||
}
|
||||
if self.scale.has_fill_opacity || out.attribute::<f64>(ATTR_OPACITY_FILL, index).is_some() {
|
||||
let row_fill: f64 = out.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.);
|
||||
out.set_attribute(ATTR_OPACITY_FILL, index, self.scale.fill_opacity * row_fill);
|
||||
}
|
||||
if let Some(layer_path) = self.layer_path {
|
||||
out.set_attribute(ATTR_EDITOR_LAYER_PATH, index, layer_path.to_vec());
|
||||
}
|
||||
// The cascade's resolved appearance lands on a row whose own is undeclared, since a declared row wins wholesale
|
||||
if let Some(appearance) = self.appearance
|
||||
&& out.attribute::<Appearance>(ATTR_APPEARANCE, index).and_then(Appearance::declared).is_none()
|
||||
{
|
||||
out.set_attribute(ATTR_APPEARANCE, index, appearance.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn walk_rows_of_run(
|
||||
item: &core_types::record::GroupItem,
|
||||
scale: FlattenScale,
|
||||
layer_path: Option<&[NodeId]>,
|
||||
appearance: Option<&Appearance>,
|
||||
visit: &mut dyn FnMut(VectorRow<'_>) -> RowStep,
|
||||
) -> RowStep {
|
||||
let Some(run) = core_types::record::RunView::<Vector>::new(item) else {
|
||||
return RowStep::Continue;
|
||||
};
|
||||
for lane in 0..item.len() {
|
||||
if let RowStep::Stop = visit(VectorRow {
|
||||
source: RowSourceRef::Run(&run, item, lane),
|
||||
scale,
|
||||
layer_path,
|
||||
appearance,
|
||||
}) {
|
||||
return RowStep::Stop;
|
||||
}
|
||||
}
|
||||
RowStep::Continue
|
||||
}
|
||||
|
||||
/// Walks a graphic level into its flattened vector rows, matching the legacy
|
||||
/// flatten lowering: the appearance cascades with [`PaintReach`], ancestor
|
||||
/// transform, opacity and fill opacity compose down, the containing level's
|
||||
/// parent layer path overwrites its rows, and non-vector content is
|
||||
/// discarded. A de-tabled leaf's row is its lane, attributes included.
|
||||
pub fn walk_vector_rows(level: GraphicLevel<'_>, visit: &mut dyn FnMut(VectorRow<'_>) -> RowStep) {
|
||||
walk_vector_rows_impl(level, FlattenScale::ROOT, None, PaintReach::NONE, visit);
|
||||
}
|
||||
|
||||
fn walk_vector_rows_impl<'a>(
|
||||
level: GraphicLevel<'a>,
|
||||
scale: FlattenScale,
|
||||
parent_layer_path: Option<&'a [NodeId]>,
|
||||
inherited: PaintReach<'a>,
|
||||
visit: &mut dyn FnMut(VectorRow<'_>) -> RowStep,
|
||||
) -> RowStep {
|
||||
if let GraphicLevel::Run(item) = level {
|
||||
// A vector-typed run is already its rows.
|
||||
if item.typed_lanes::<Vector>().is_some() {
|
||||
return walk_rows_of_run(item, scale, parent_layer_path, inherited.appearance, visit);
|
||||
}
|
||||
}
|
||||
let columns = PaintColumns::new(&level);
|
||||
for index in 0..level.lane_count() {
|
||||
let Some(element) = level.element(index) else { continue };
|
||||
let reach = inherited.for_lane(&columns, index);
|
||||
let step = match element {
|
||||
Graphic::Vector(_) => visit(VectorRow {
|
||||
source: RowSourceRef::Lane(level, index),
|
||||
scale,
|
||||
layer_path: parent_layer_path,
|
||||
appearance: reach.appearance,
|
||||
}),
|
||||
Graphic::Graphic(children) => walk_vector_rows_impl(GraphicLevel::Legacy(children), scale.composed(&level, index), level.try_attr::<EditorLayerPath>(index), reach, visit),
|
||||
Graphic::Group(group) => {
|
||||
let item = &group.content;
|
||||
if item.typed_lanes::<Vector>().is_some() {
|
||||
walk_rows_of_run(item, scale.composed(&level, index), level.try_attr::<EditorLayerPath>(index), reach.appearance, visit)
|
||||
} else if item.typed_lanes::<Graphic>().is_some() {
|
||||
walk_vector_rows_impl(GraphicLevel::Run(item), scale.composed(&level, index), level.try_attr::<EditorLayerPath>(index), reach, visit)
|
||||
} else {
|
||||
RowStep::Continue
|
||||
}
|
||||
}
|
||||
_ => RowStep::Continue,
|
||||
};
|
||||
if let RowStep::Stop = step {
|
||||
return RowStep::Stop;
|
||||
}
|
||||
}
|
||||
RowStep::Continue
|
||||
}
|
||||
|
||||
/// The level's flattened vector rows as one owned list, the walk's collect
|
||||
/// form.
|
||||
pub fn flatten_vector_rows(level: GraphicLevel<'_>) -> List<Vector> {
|
||||
let mut out = List::new();
|
||||
walk_vector_rows(level, &mut |row| {
|
||||
row.build_into(&mut out);
|
||||
RowStep::Continue
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// The count [`map_groups_to_legacy`] would expose through [`Graphic::as_vector`],
|
||||
/// read from the run's lanes instead of materializing the legacy list. Mirrors
|
||||
/// [`group_to_legacy_graphic`]'s typed-run path, where `Vector` is tried first.
|
||||
pub fn direct_vector_len(graphic: &Graphic) -> usize {
|
||||
match graphic {
|
||||
Graphic::Vector(_) => 1,
|
||||
Graphic::Group(group) => match &group.row {
|
||||
None => group.content.typed_lanes::<Vector>().map_or(0, |lanes| lanes.len()),
|
||||
_ => 0,
|
||||
},
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::graphic) fn group_render_complexity(group: &core_types::record::Group) -> usize {
|
||||
fn typed_run<T: dyn_any::StaticTypeSized + RenderComplexity>(item: &core_types::record::GroupItem) -> Option<usize> {
|
||||
let lanes = item.typed_lanes::<T>()?;
|
||||
Some((0..lanes.len()).map(|lane| lanes.element_ref(lane).render_complexity()).sum())
|
||||
}
|
||||
let item = &group.content;
|
||||
None.or_else(|| typed_run::<Graphic>(item))
|
||||
.or_else(|| typed_run::<Vector>(item))
|
||||
.or_else(|| typed_run::<Raster<CPU>>(item))
|
||||
.or_else(|| typed_run::<Raster<GPU>>(item))
|
||||
.or_else(|| typed_run::<Color>(item))
|
||||
.or_else(|| typed_run::<GradientStops>(item))
|
||||
.or_else(|| typed_run::<String>(item))
|
||||
.unwrap_or(item.len())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod run_tests {
|
||||
use super::*;
|
||||
use crate::graphic::test_support::unit_square_at;
|
||||
use crate::graphic::{IntoGraphicList, map_groups_to_legacy, run_to_legacy_list};
|
||||
use core_types::record::{FieldWrite, RunBuilder, RunView, element_write_hashed};
|
||||
|
||||
#[test]
|
||||
fn the_vector_row_walk_matches_the_legacy_flatten() {
|
||||
use crate::appearance::Coverage;
|
||||
|
||||
let single = |color: Color| Appearance::new_single(Coverage::new_fill(), Graphic::Color(color));
|
||||
|
||||
let inner_vector = unit_square_at(DVec2::ZERO);
|
||||
let arena = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
let mut builder = RunBuilder::new(&arena, element_write_hashed::<Vector>(), &[], 1).unwrap();
|
||||
builder.push(inner_vector.clone()).unwrap();
|
||||
let inner_item = builder.finish();
|
||||
|
||||
let mut painted = List::new();
|
||||
painted.push(Item::new_from_element(Graphic::Vector(unit_square_at(DVec2::ZERO))));
|
||||
painted.push(Item::new_from_element(Graphic::Vector(unit_square_at(DVec2::ONE))));
|
||||
painted.set_attribute(core_types::ATTR_TRANSFORM, 0, DAffine2::from_translation(DVec2::new(1., 0.)));
|
||||
painted.set_attribute(core_types::ATTR_TRANSFORM, 1, DAffine2::from_translation(DVec2::new(0., 1.)));
|
||||
painted.set_attribute(ATTR_APPEARANCE, 1, single(Color::WHITE));
|
||||
|
||||
let mut nested = List::new_from_element(Graphic::Vector(unit_square_at(DVec2::new(2., 2.))));
|
||||
nested.set_attribute(core_types::ATTR_TRANSFORM, 0, DAffine2::from_scale(DVec2::splat(2.)));
|
||||
|
||||
let mut top = List::new();
|
||||
top.push(Item::new_from_element(Graphic::Graphic(painted)));
|
||||
top.push(Item::new_from_element(Graphic::Graphic(nested)));
|
||||
top.push(Item::new_from_element(Graphic::Group(core_types::record::Group { row: None, content: inner_item })));
|
||||
top.push(Item::new_from_element(Graphic::Color(Color::BLACK)));
|
||||
top.push(Item::new_from_element(Graphic::Vector(unit_square_at(DVec2::new(6., 0.)))));
|
||||
top.set_attribute(core_types::ATTR_TRANSFORM, 0, DAffine2::from_translation(DVec2::new(5., 5.)));
|
||||
top.set_attribute(core_types::ATTR_EDITOR_LAYER_PATH, 0, vec![core_types::uuid::NodeId(7)]);
|
||||
top.set_attribute(ATTR_APPEARANCE, 0, single(Color::BLACK));
|
||||
top.set_attribute(core_types::ATTR_OPACITY, 1, 0.5);
|
||||
top.set_attribute(core_types::ATTR_TRANSFORM, 2, DAffine2::from_scale(DVec2::splat(3.)));
|
||||
top.set_attribute(core_types::ATTR_TRANSFORM, 4, DAffine2::from_translation(DVec2::new(0., 7.)));
|
||||
top.set_attribute(core_types::ATTR_EDITOR_LAYER_PATH, 4, vec![core_types::uuid::NodeId(9)]);
|
||||
top.set_attribute(ATTR_APPEARANCE, 4, single(Color::WHITE));
|
||||
|
||||
let legacy = {
|
||||
let mut list = List::new();
|
||||
for item in top.clone().into_iter() {
|
||||
let (element, attributes) = item.into_parts();
|
||||
list.push(Item::from_parts(map_groups_to_legacy(&element), attributes));
|
||||
}
|
||||
list.into_flattened_list::<Vector>()
|
||||
};
|
||||
let native = flatten_vector_rows(GraphicLevel::Legacy(&top));
|
||||
assert_eq!(native.len(), legacy.len());
|
||||
for row in 0..native.len() {
|
||||
assert_eq!(
|
||||
native.attribute::<DAffine2>(core_types::ATTR_TRANSFORM, row),
|
||||
legacy.attribute::<DAffine2>(core_types::ATTR_TRANSFORM, row),
|
||||
"transform, row {row}"
|
||||
);
|
||||
assert_eq!(
|
||||
native.attribute::<f64>(core_types::ATTR_OPACITY, row),
|
||||
legacy.attribute::<f64>(core_types::ATTR_OPACITY, row),
|
||||
"opacity, row {row}"
|
||||
);
|
||||
assert_eq!(
|
||||
native.attribute::<Vec<core_types::uuid::NodeId>>(core_types::ATTR_EDITOR_LAYER_PATH, row),
|
||||
legacy.attribute::<Vec<core_types::uuid::NodeId>>(core_types::ATTR_EDITOR_LAYER_PATH, row),
|
||||
"layer path, row {row}"
|
||||
);
|
||||
assert_eq!(
|
||||
native.attribute::<Appearance>(ATTR_APPEARANCE, row),
|
||||
legacy.attribute::<Appearance>(ATTR_APPEARANCE, row),
|
||||
"appearance, row {row}"
|
||||
);
|
||||
}
|
||||
assert_eq!(native, legacy);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_and_its_legacy_list_agree_on_bounding_boxes() {
|
||||
let vectors = [unit_square_at(DVec2::ZERO), unit_square_at(DVec2::new(4., 4.))];
|
||||
let transforms = [DAffine2::from_translation(DVec2::new(1., 2.)), DAffine2::from_scale(DVec2::splat(3.))];
|
||||
|
||||
let arena = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
let mut builder = RunBuilder::new(&arena, element_write_hashed::<Vector>(), &[FieldWrite::of::<core_types::attribute::Transform>(0)], 2).unwrap();
|
||||
for (vector, transform) in vectors.iter().zip(transforms) {
|
||||
let lane = builder.push(vector.clone()).unwrap();
|
||||
builder.attr::<core_types::attribute::Transform>(lane, transform);
|
||||
}
|
||||
let item = builder.finish();
|
||||
let run = RunView::<Vector>::new(&item).expect("the run holds vector elements");
|
||||
let legacy = run_to_legacy_list::<Vector>(&item).expect("the run lowers to a legacy vector list");
|
||||
|
||||
let outer = DAffine2::from_angle(0.3);
|
||||
for include_stroke in [false, true] {
|
||||
let bounds = run.bounding_box(outer, include_stroke);
|
||||
assert_eq!(bounds, legacy.bounding_box(outer, include_stroke));
|
||||
assert!(matches!(bounds, RenderBoundingBox::Rectangle(_)));
|
||||
assert_eq!(run.thumbnail_bounding_box(outer, include_stroke), legacy.thumbnail_bounding_box(outer, include_stroke));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_walk_cascades_appearance_like_the_legacy_flatten() {
|
||||
use crate::appearance::Coverage;
|
||||
|
||||
let single = |color: Color| Appearance::new_single(Coverage::new_fill(), Graphic::Color(color));
|
||||
|
||||
let mut inner = List::new();
|
||||
inner.push(Item::new_from_element(Graphic::Vector(unit_square_at(DVec2::ZERO))));
|
||||
inner.push(Item::new_from_element(Graphic::Vector(unit_square_at(DVec2::ONE))));
|
||||
inner.set_attribute(ATTR_APPEARANCE, 0, single(Color::BLACK));
|
||||
|
||||
let mut top = List::new_from_element(Graphic::Graphic(inner));
|
||||
top.set_attribute(ATTR_APPEARANCE, 0, single(Color::WHITE));
|
||||
|
||||
let walked = flatten_vector_rows(GraphicLevel::Legacy(&top));
|
||||
let legacy: List<Vector> = top.clone().into_flattened_list();
|
||||
|
||||
let color_of = |list: &List<Vector>, index: usize| {
|
||||
let appearance = list.attribute::<Appearance>(ATTR_APPEARANCE, index)?;
|
||||
let Graphic::Color(color) = appearance.paint_at(0)? else { return None };
|
||||
Some(*color)
|
||||
};
|
||||
|
||||
for list in [&walked, &legacy] {
|
||||
assert_eq!(color_of(list, 0), Some(Color::BLACK), "a declared row keeps its own appearance");
|
||||
assert_eq!(color_of(list, 1), Some(Color::WHITE), "an undeclared row inherits the level's appearance");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
pub mod appearance;
|
||||
pub mod artboard;
|
||||
pub mod boundary;
|
||||
pub mod graphic;
|
||||
@@ -9,9 +10,10 @@ pub use raster_types;
|
||||
pub use vector_types;
|
||||
|
||||
// Re-export commonly used types at the crate root
|
||||
pub use appearance::{Appearance, Cover, CoverPlacement, Coverage, FillAndStroke, stamp_coverage};
|
||||
pub use artboard::Artboard;
|
||||
pub use graphic::{Graphic, IntoGraphicList, TryFromGraphic, Vector};
|
||||
pub use markers::{ATTR_EDITOR_MERGED_LAYERS, ATTR_FILL, ATTR_STROKE};
|
||||
pub use markers::{ATTR_APPEARANCE, ATTR_EDITOR_MERGED_LAYERS, ATTR_PAINT};
|
||||
|
||||
pub mod migrations {
|
||||
use crate::Vector;
|
||||
@@ -91,10 +93,11 @@ pub mod migrations {
|
||||
}
|
||||
|
||||
/// The legacy `fill` field is intentionally omitted because vector payload migration only
|
||||
/// recovers editable vector data. The fill/stroke paints are migrated from the the node inputs.
|
||||
/// recovers editable vector data. The stroke parses solely to validate the legacy shape.
|
||||
#[derive(serde::Deserialize)]
|
||||
#[cfg_attr(test, derive(Default, serde::Serialize))]
|
||||
pub(super) struct PathStyle {
|
||||
#[allow(dead_code)]
|
||||
pub stroke: Option<Stroke>,
|
||||
}
|
||||
|
||||
@@ -102,6 +105,7 @@ pub mod migrations {
|
||||
#[derive(serde::Deserialize)]
|
||||
#[cfg_attr(test, derive(Default, serde::Serialize))]
|
||||
pub(super) struct VectorData {
|
||||
#[allow(dead_code)]
|
||||
pub style: PathStyle,
|
||||
pub colinear_manipulators: Vec<[HandleId; 2]>,
|
||||
pub point_domain: PointDomain,
|
||||
@@ -134,7 +138,6 @@ pub mod migrations {
|
||||
|
||||
Ok(match VectorFormat::deserialize(deserializer)? {
|
||||
VectorFormat::OldVectorData(old) => Some(Vector {
|
||||
stroke: old.style.stroke,
|
||||
colinear_manipulators: old.colinear_manipulators,
|
||||
point_domain: old.point_domain,
|
||||
segment_domain: old.segment_domain,
|
||||
@@ -151,9 +154,12 @@ pub mod migrations {
|
||||
use vector_types::vector::style::Stroke;
|
||||
|
||||
#[test]
|
||||
fn preserves_stroke_from_old_vector_data_style() {
|
||||
fn recovers_geometry_from_old_vector_data_style() {
|
||||
use core_types::ops::FromAnchorPosition;
|
||||
|
||||
let old_vector = legacy::VectorData {
|
||||
style: legacy::PathStyle { stroke: Some(Stroke::new(12.)) },
|
||||
point_domain: Vector::from_anchor_position(glam::DVec2::new(3., 4.)).point_domain,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
@@ -166,22 +172,21 @@ pub mod migrations {
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.insert("fill".into(), serde_json::to_value(legacy::Fill::default()).unwrap());
|
||||
let migrated = migrate_to_optional_vector(value).unwrap().unwrap();
|
||||
let migrated = migrate_to_optional_vector(value).unwrap().expect("the legacy shape parses into a vector");
|
||||
|
||||
assert_eq!(migrated.stroke.unwrap().weight, 12.);
|
||||
assert_eq!(migrated.point_domain.positions(), [glam::DVec2::new(3., 4.)], "the geometry survives alongside the discarded style");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_stroke_from_current_vector_data() {
|
||||
let vector = Vector {
|
||||
stroke: Some(Stroke::new(12.)),
|
||||
..Default::default()
|
||||
};
|
||||
fn recovers_geometry_from_current_vector_data() {
|
||||
use core_types::ops::FromAnchorPosition;
|
||||
|
||||
let vector = Vector::from_anchor_position(glam::DVec2::new(3., 4.));
|
||||
|
||||
let value = serde_json::to_value(&vector).unwrap();
|
||||
let migrated = migrate_to_optional_vector(value).unwrap().unwrap();
|
||||
|
||||
assert_eq!(migrated.stroke.unwrap().weight, 12.);
|
||||
assert_eq!(migrated.point_domain.positions(), [glam::DVec2::new(3., 4.)]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,30 +1,104 @@
|
||||
//! 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`].
|
||||
//! The 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;
|
||||
/// The item's ordered list of paint passes. An absent or empty value is the undeclared
|
||||
/// state that inherits the nearest ancestor's appearance through the cascade, so both
|
||||
/// read as `None`. The stored form is the bare [`crate::appearance::Appearance`], the
|
||||
/// shape the appearance writers use, which the `attribute!` macro's optional-reference
|
||||
/// arm cannot express.
|
||||
pub struct Appearance;
|
||||
|
||||
// SAFETY: `read_erased` produces the bare owned appearance `from_stored` reads, `REPARK`
|
||||
// re-parks that same form, and the empty appearance collapses to the `None` default at
|
||||
// every read seam.
|
||||
unsafe impl Attribute for Appearance {
|
||||
const NAME: &'static str = "appearance";
|
||||
type Value<'e> = Option<&'e crate::appearance::Appearance>;
|
||||
|
||||
fn from_stored<'a>(stored: &'a dyn std::any::Any) -> Option<Self::Value<'a>> {
|
||||
stored.downcast_ref::<crate::appearance::Appearance>().map(crate::appearance::Appearance::declared)
|
||||
}
|
||||
|
||||
unsafe fn read_erased(ptr: *const u8) -> Box<dyn core_types::list::AnyAttributeValue> {
|
||||
Box::new(unsafe { ptr.cast::<Option<&crate::appearance::Appearance>>().read() }.cloned().unwrap_or_default())
|
||||
}
|
||||
|
||||
const REPARK: Option<core_types::list::ReparkFn> = {
|
||||
unsafe fn repark(value: &dyn core_types::list::AnyAttributeValue, dst: *mut u8, arena: &core_types::arena::Arena) -> Option<()> {
|
||||
let owned: &crate::appearance::Appearance = value.as_any().downcast_ref().expect("an appearance attribute replays its bare owned clone");
|
||||
let parked = match owned.is_empty() {
|
||||
true => None,
|
||||
false => {
|
||||
let (parked, _) = arena.alloc(owned.clone())?;
|
||||
Some(&*parked)
|
||||
}
|
||||
};
|
||||
// SAFETY: the slot is a live field of this marker's value type.
|
||||
unsafe { dst.cast::<Option<&crate::appearance::Appearance>>().write(parked) };
|
||||
Some(())
|
||||
}
|
||||
Some(repark)
|
||||
};
|
||||
}
|
||||
|
||||
core_types::attribute!(@register Appearance);
|
||||
|
||||
/// One coverage row's paint, a bare graphic riding the coverage list as a column. Absent
|
||||
/// or empty paint draws nothing, so both read as `None`; the stored form is the bare
|
||||
/// [`Graphic`], the shape [`crate::appearance`]'s row writers use.
|
||||
pub struct Paint;
|
||||
|
||||
// SAFETY: as for `Appearance`, at the bare `Graphic` stored form.
|
||||
unsafe impl Attribute for Paint {
|
||||
const NAME: &'static str = "paint";
|
||||
type Value<'e> = Option<&'e Graphic<'static>>;
|
||||
|
||||
fn from_stored<'a>(stored: &'a dyn std::any::Any) -> Option<Self::Value<'a>> {
|
||||
stored.downcast_ref::<Graphic<'static>>().map(|paint| (!paint.is_empty()).then_some(paint))
|
||||
}
|
||||
|
||||
unsafe fn read_erased(ptr: *const u8) -> Box<dyn core_types::list::AnyAttributeValue> {
|
||||
Box::new(unsafe { ptr.cast::<Option<&Graphic<'static>>>().read() }.cloned().unwrap_or_default())
|
||||
}
|
||||
|
||||
const REPARK: Option<core_types::list::ReparkFn> = {
|
||||
unsafe fn repark(value: &dyn core_types::list::AnyAttributeValue, dst: *mut u8, arena: &core_types::arena::Arena) -> Option<()> {
|
||||
let owned: &Graphic<'static> = value.as_any().downcast_ref().expect("a paint attribute replays its bare owned clone");
|
||||
let parked = match owned.is_empty() {
|
||||
true => None,
|
||||
false => {
|
||||
let (parked, _) = arena.alloc(owned.clone())?;
|
||||
Some(&*parked)
|
||||
}
|
||||
};
|
||||
// SAFETY: the slot is a live field of this marker's value type.
|
||||
unsafe { dst.cast::<Option<&Graphic<'static>>>().write(parked) };
|
||||
Some(())
|
||||
}
|
||||
Some(repark)
|
||||
};
|
||||
}
|
||||
|
||||
core_types::attribute!(@register Paint);
|
||||
|
||||
pub const ATTR_EDITOR_MERGED_LAYERS: &str = EditorMergedLayers::NAME;
|
||||
pub const ATTR_APPEARANCE: &str = Appearance::NAME;
|
||||
pub const ATTR_PAINT: &str = Paint::NAME;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
@@ -34,25 +108,13 @@ mod tests {
|
||||
|
||||
#[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>>>());
|
||||
}
|
||||
assert_eq!(info("editor:merged_layers").unwrap().value_type, TypeId::of::<Option<&'static List<Graphic>>>());
|
||||
assert_eq!(info("appearance").unwrap().value_type, TypeId::of::<Option<&'static crate::appearance::Appearance>>());
|
||||
assert_eq!(info("paint").unwrap().value_type, TypeId::of::<Option<&'static 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);
|
||||
assert_eq!(<Paint as Attribute>::default(), None);
|
||||
}
|
||||
}
|
||||
@@ -185,3 +185,60 @@ impl Display for BlendMode {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Mixes the two colors by the blend mode's own formula, leaving the alpha compositing to the caller.
|
||||
pub fn apply_blend_mode(foreground: crate::color::Color, background: crate::color::Color, blend_mode: BlendMode) -> crate::color::Color {
|
||||
use crate::color::Color;
|
||||
match blend_mode {
|
||||
// Normal group
|
||||
BlendMode::Normal => background.blend_rgb(foreground, Color::blend_normal),
|
||||
// Darken group
|
||||
BlendMode::Darken => background.blend_rgb(foreground, Color::blend_darken),
|
||||
BlendMode::Multiply => background.blend_rgb(foreground, Color::blend_multiply),
|
||||
BlendMode::ColorBurn => background.blend_rgb(foreground, Color::blend_color_burn),
|
||||
BlendMode::LinearBurn => background.blend_rgb(foreground, Color::blend_linear_burn),
|
||||
BlendMode::DarkerColor => background.blend_darker_color(foreground),
|
||||
// Lighten group
|
||||
BlendMode::Lighten => background.blend_rgb(foreground, Color::blend_lighten),
|
||||
BlendMode::Screen => background.blend_rgb(foreground, Color::blend_screen),
|
||||
BlendMode::ColorDodge => background.blend_rgb(foreground, Color::blend_color_dodge),
|
||||
BlendMode::LinearDodge => background.blend_rgb(foreground, Color::blend_linear_dodge),
|
||||
BlendMode::LighterColor => background.blend_lighter_color(foreground),
|
||||
// Contrast group
|
||||
BlendMode::Overlay => background.blend_rgb(foreground, Color::blend_overlay),
|
||||
BlendMode::SoftLight => background.blend_rgb(foreground, Color::blend_softlight),
|
||||
BlendMode::HardLight => background.blend_rgb(foreground, Color::blend_hardlight),
|
||||
BlendMode::VividLight => background.blend_rgb(foreground, Color::blend_vivid_light),
|
||||
BlendMode::LinearLight => background.blend_rgb(foreground, Color::blend_linear_light),
|
||||
BlendMode::PinLight => background.blend_rgb(foreground, Color::blend_pin_light),
|
||||
BlendMode::HardMix => background.blend_rgb(foreground, Color::blend_hard_mix),
|
||||
// Inversion group
|
||||
BlendMode::Difference => background.blend_rgb(foreground, Color::blend_difference),
|
||||
BlendMode::Exclusion => background.blend_rgb(foreground, Color::blend_exclusion),
|
||||
BlendMode::Subtract => background.blend_rgb(foreground, Color::blend_subtract),
|
||||
BlendMode::Divide => background.blend_rgb(foreground, Color::blend_divide),
|
||||
// Component group
|
||||
BlendMode::Hue => background.blend_hue(foreground),
|
||||
BlendMode::Saturation => background.blend_saturation(foreground),
|
||||
BlendMode::Color => background.blend_color(foreground),
|
||||
BlendMode::Luminosity => background.blend_luminosity(foreground),
|
||||
// The alpha-only utility modes mix no color, so the foreground passes through for the caller to composite
|
||||
BlendMode::Erase | BlendMode::Restore | BlendMode::MultiplyAlpha => foreground,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::color::Color;
|
||||
|
||||
#[test]
|
||||
fn overlay_is_hard_light_with_swapped_operands() {
|
||||
let a = Color::from_rgbaf32_unchecked(0.8, 0.3, 0.6, 1.);
|
||||
let b = Color::from_rgbaf32_unchecked(0.2, 0.7, 0.4, 1.);
|
||||
|
||||
let overlay = apply_blend_mode(a, b, BlendMode::Overlay);
|
||||
let swapped_hard_light = apply_blend_mode(b, a, BlendMode::HardLight);
|
||||
assert_eq!(overlay, swapped_hard_light);
|
||||
}
|
||||
}
|
||||
@@ -749,6 +749,11 @@ impl Color {
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-channel "Overlay" blend: hard light with its operands swapped.
|
||||
pub fn blend_overlay(c_b: f32, c_s: f32) -> f32 {
|
||||
Self::blend_hardlight(c_s, c_b)
|
||||
}
|
||||
|
||||
/// Per-channel "Hard Light" blend.
|
||||
pub fn blend_hardlight(c_b: f32, c_s: f32) -> f32 {
|
||||
if c_s <= 0.5 {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use crate::renderer::{RenderParams, format_transform_matrix, gradient_placement, transform_is_invertible};
|
||||
use crate::renderer::{RenderParams, composite_paint_colors, 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::attribute::{Opacity, OpacityFill, Transform};
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::list::List;
|
||||
use core_types::uuid::generate_uuid;
|
||||
@@ -52,13 +52,13 @@ 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 {
|
||||
/// The color paint attribute for a composited paint color.
|
||||
pub fn render_color_paint(color: Option<Color>, target: PaintTarget) -> String {
|
||||
let Some(color) = color else {
|
||||
return format!(r#" {}="none""#, target.paint_attr());
|
||||
};
|
||||
|
||||
let mut result = format!(r##" {}="#{}""##, target.paint_attr(), SRGBA8::from(*color).to_rgb_hex());
|
||||
let mut result = format!(r##" {}="#{}""##, target.paint_attr(), SRGBA8::from(color).to_rgb_hex());
|
||||
if color.a() < 1. {
|
||||
let _ = write!(result, r#" {}="{}""#, target.opacity_attr(), (color.a() * 1000.).round() / 1000.);
|
||||
}
|
||||
@@ -76,10 +76,10 @@ impl RenderExt for List<Color> {
|
||||
_element_transform: DAffine2,
|
||||
_stroke_transform: DAffine2,
|
||||
_bounds: DAffine2,
|
||||
_render_params: &RenderParams,
|
||||
render_params: &RenderParams,
|
||||
target: PaintTarget,
|
||||
) -> Self::Output {
|
||||
render_color_paint(self, target)
|
||||
render_color_paint(composite_paint_colors(self, |color| Some(*color), render_params.for_mask), target)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,16 +94,22 @@ impl RenderExt for List<GradientStops> {
|
||||
element_transform: DAffine2,
|
||||
_stroke_transform: DAffine2,
|
||||
_bounds: DAffine2,
|
||||
_render_params: &RenderParams,
|
||||
render_params: &RenderParams,
|
||||
_target: PaintTarget,
|
||||
) -> Self::Output {
|
||||
render_gradient_paint(self, svg_defs, item_transform, element_transform)
|
||||
render_gradient_paint(self, svg_defs, item_transform, element_transform, render_params.for_mask)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
pub fn render_gradient_paint<S: core_types::lane::LaneSource<Element = GradientStops>>(
|
||||
source: &S,
|
||||
svg_defs: &mut String,
|
||||
item_transform: DAffine2,
|
||||
element_transform: DAffine2,
|
||||
for_mask: bool,
|
||||
) -> u64 {
|
||||
let mut stop = String::new();
|
||||
|
||||
{
|
||||
@@ -112,7 +118,12 @@ pub fn render_gradient_paint<S: core_types::lane::LaneSource<Element = GradientS
|
||||
let local_gradient_transform: DAffine2 = source.attr::<Transform>(0);
|
||||
let spread_method: GradientSpreadMethod = source.attr::<SpreadMethod>(0);
|
||||
|
||||
// The paint's own opacity fades each emitted stop, a masker dropping the fill half as for a color paint
|
||||
let opacity_fill: f64 = if for_mask { 1. } else { source.attr::<OpacityFill>(0) };
|
||||
let paint_opacity = (source.attr::<Opacity>(0) * opacity_fill) as f32;
|
||||
|
||||
for (position, color, original_midpoint) in stops.interpolated_samples() {
|
||||
let color = if paint_opacity < 1. { color.with_alpha(color.a() * paint_opacity) } else { color };
|
||||
stop.push_str("<stop");
|
||||
if position != 0. {
|
||||
let _ = write!(stop, r#" offset="{}""#, (position * 1_000_000.).round() / 1_000_000.);
|
||||
@@ -202,7 +213,7 @@ impl RenderExt for Stroke {
|
||||
let stroke_join = (self.join != StrokeJoin::Miter).then_some(self.join);
|
||||
let stroke_join_miter_limit = (self.join_miter_limit != 4.).then_some(self.join_miter_limit);
|
||||
let stroke_align = (self.align != StrokeAlign::Center).then_some(self.align);
|
||||
let paint_order = (self.paint_order != PaintOrder::StrokeAbove || render_params.override_paint_order).then_some(PaintOrder::StrokeBelow);
|
||||
let paint_order = render_params.stroke_below.then_some(PaintOrder::StrokeBelow);
|
||||
|
||||
// Render the needed stroke attributes
|
||||
let mut attributes = String::new();
|
||||
@@ -251,9 +262,13 @@ impl RenderExt for List<Graphic<'_>> {
|
||||
let paint_attr = target.paint_attr();
|
||||
|
||||
match fill_graphic {
|
||||
Some(Graphic::Color(color)) => render_color_paint(&core_types::lane::LeafLane::new(self, 0, color), target),
|
||||
Some(Graphic::Color(_)) => {
|
||||
// The whole color stack collapses to the one composited color the fast path emits
|
||||
let composited = composite_paint_colors(self, |graphic| if let Graphic::Color(color) = graphic { Some(*color) } else { None }, render_params.for_mask);
|
||||
render_color_paint(composited, 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);
|
||||
let gradient_id = render_gradient_paint(&core_types::lane::LeafLane::new(self, 0, gradient), svg_defs, item_transform, element_transform, render_params.for_mask);
|
||||
format!(r##" {paint_attr}="url(#{gradient_id})""##)
|
||||
}
|
||||
Some(Graphic::Vector(_)) | Some(Graphic::RasterCPU(_)) | Some(Graphic::RasterGPU(_)) | Some(Graphic::Graphic(_)) | Some(Graphic::Text(_)) | Some(Graphic::Group(_)) => {
|
||||
|
||||
@@ -23,15 +23,16 @@ use dyn_any::DynAny;
|
||||
use glam::{DAffine2, DMat2, DVec2};
|
||||
use graphene_hash::CacheHashWrapper;
|
||||
use graphene_resource::Resource;
|
||||
use graphic_types::graphic::{PaintColumns, PaintOverlay, PaintReach, has_paint, is_paint_present, paint_graphics, set_paint_attribute, vector_can_reduce_to_clip_path};
|
||||
use graphic_types::markers::{EditorMergedLayers, Fill, Stroke};
|
||||
use graphic_types::appearance::{Appearance, Coverage};
|
||||
use graphic_types::graphic::{PaintColumns, PaintReach, is_paint_present, paint_cell_rows, vector_can_reduce_to_clip_path};
|
||||
use graphic_types::markers::{Appearance as AppearanceMarker, EditorMergedLayers};
|
||||
use graphic_types::raster_types::{BitmapMut, CPU, GPU, Image, Raster, Texture};
|
||||
use graphic_types::vector_types::gradient::{GradientStops, GradientType};
|
||||
use graphic_types::vector_types::markers::{GradientType as GradientTypeAttr, SpreadMethod};
|
||||
use graphic_types::vector_types::subpath::Subpath;
|
||||
use graphic_types::vector_types::vector::click_target::{ClickTarget, FreePoint};
|
||||
use graphic_types::vector_types::vector::style::{PaintOrder, RenderMode, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use graphic_types::{ATTR_FILL, Artboard, Graphic, Vector};
|
||||
use graphic_types::vector_types::vector::style::{RenderMode, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use graphic_types::{Artboard, Graphic, Vector};
|
||||
use kurbo::{Affine, BezPath, Cap, Join, Shape, StrokeOpts};
|
||||
use num_traits::Zero;
|
||||
use skrifa::instance::{LocationRef, NormalizedCoord, Size};
|
||||
@@ -207,6 +208,77 @@ pub struct RenderContext {
|
||||
pub resource_overrides: Vec<(peniko::ImageBrush, Texture)>,
|
||||
}
|
||||
|
||||
/// The single black-fill appearance a mask clone paints with, at full alpha so the mask fully covers the interior.
|
||||
fn black_fill_appearance() -> Appearance {
|
||||
Appearance::new_single(Coverage::new_fill(), Graphic::Graphic(List::new_from_element(Graphic::Color(Color::BLACK))))
|
||||
}
|
||||
|
||||
/// The alpha multiplier a paint row's opacity attributes apply when it serves as a paint.
|
||||
/// Fill opacity fades a paint just as opacity does, but a masker drops it so it cannot reach the content clipped to it.
|
||||
pub(crate) fn paint_row_opacity<T>(list: &List<T>, index: usize, for_mask: bool) -> f32 {
|
||||
let opacity_fill = if for_mask {
|
||||
1.
|
||||
} else {
|
||||
list.attribute_cloned_or::<f64>(core_types::ATTR_OPACITY_FILL, index, 1.)
|
||||
};
|
||||
|
||||
(list.attribute_cloned_or::<f64>(core_types::ATTR_OPACITY, index, 1.) * opacity_fill) as f32
|
||||
}
|
||||
|
||||
/// Composites one paint color over the stack beneath it, mixing by the blend mode and then source-over in straight alpha.
|
||||
fn composite_paint_over(over: Color, under: Color, blend_mode: BlendMode) -> Color {
|
||||
let (over_alpha, under_alpha) = (over.a(), under.a());
|
||||
|
||||
// These modes only move the backdrop's alpha, leaving its color alone
|
||||
match blend_mode {
|
||||
BlendMode::Erase => return under.with_alpha((under_alpha - over_alpha).clamp(0., 1.)),
|
||||
BlendMode::Restore => return under.with_alpha((under_alpha + over_alpha).clamp(0., 1.)),
|
||||
BlendMode::MultiplyAlpha => return under.with_alpha(under_alpha * over_alpha),
|
||||
_ => {}
|
||||
}
|
||||
|
||||
let result_alpha = over_alpha + under_alpha * (1. - over_alpha);
|
||||
if result_alpha <= 0. {
|
||||
return Color::TRANSPARENT;
|
||||
}
|
||||
|
||||
// The blend formulas read their backdrop premultiplied
|
||||
let premultiplied_under = Color::from_rgbaf32_unchecked(under.r() * under_alpha, under.g() * under_alpha, under.b() * under_alpha, under_alpha);
|
||||
let mixed = core_types::blending::apply_blend_mode(over, premultiplied_under, blend_mode);
|
||||
|
||||
// The mode only mixes where the backdrop has coverage, so its alpha interpolates each source channel from the raw color to the mixed color
|
||||
let source_channel = |over_channel: f32, mixed_channel: f32| over_channel * (1. - under_alpha) + mixed_channel * under_alpha;
|
||||
|
||||
let channel =
|
||||
|mixed_channel: f32, over_channel: f32, under_channel: f32| (source_channel(over_channel, mixed_channel) * over_alpha + under_channel * under_alpha * (1. - over_alpha)) / result_alpha;
|
||||
|
||||
Color::from_rgbaf32_unchecked(
|
||||
channel(mixed.r(), over.r(), under.r()),
|
||||
channel(mixed.g(), over.g(), under.g()),
|
||||
channel(mixed.b(), over.b(), under.b()),
|
||||
result_alpha,
|
||||
)
|
||||
}
|
||||
|
||||
/// Flattens a color paint into the single color the fast path emits, stacking the rows in paint order.
|
||||
/// `element_color` reads a row's color, `None` skipping rows of another element type.
|
||||
pub(crate) fn composite_paint_colors<T>(list: &List<T>, element_color: impl Fn(&T) -> Option<Color>, for_mask: bool) -> Option<Color> {
|
||||
let mut composited = None;
|
||||
|
||||
for index in 0..list.len() {
|
||||
let Some(color) = list.element(index).and_then(&element_color) else { continue };
|
||||
let faded = color.with_alpha(color.a() * paint_row_opacity(list, index, for_mask));
|
||||
|
||||
composited = Some(match composited {
|
||||
// The lowest paint has nothing beneath it, so its blend mode has nothing to act on
|
||||
None => faded,
|
||||
Some(under) => composite_paint_over(faded, under, list.attribute_cloned_or::<BlendMode>(core_types::ATTR_BLEND_MODE, index, BlendMode::default())),
|
||||
});
|
||||
}
|
||||
|
||||
composited
|
||||
}
|
||||
|
||||
#[derive(Default, Clone, Copy, Hash, graphene_hash::CacheHash)]
|
||||
pub enum RenderOutputType {
|
||||
#[default]
|
||||
@@ -230,7 +302,7 @@ pub struct RenderParams {
|
||||
/// Are we generating a mask for alignment? Used to prevent unnecessary transforms in masks
|
||||
pub alignment_parent_transform: Option<DAffine2>,
|
||||
pub aligned_strokes: bool,
|
||||
pub override_paint_order: bool,
|
||||
pub stroke_below: bool,
|
||||
/// Are we rendering for a pattern content
|
||||
pub inside_pattern: bool,
|
||||
pub artboard_background: Option<Color>,
|
||||
@@ -400,15 +472,20 @@ pub(crate) fn gradient_placement(transform: DAffine2, gradient_type: GradientTyp
|
||||
}
|
||||
}
|
||||
|
||||
fn create_peniko_gradient_brush<S: LaneSource<Element = GradientStops>>(gradient_list: &S, multiplied_transform: &DAffine2) -> Option<(peniko::Brush, DAffine2)> {
|
||||
fn create_peniko_gradient_brush<S: LaneSource<Element = GradientStops>>(gradient_list: &S, multiplied_transform: &DAffine2, for_mask: bool) -> Option<(peniko::Brush, DAffine2)> {
|
||||
let stops = gradient_list.element(0)?;
|
||||
|
||||
let gradient_type: GradientType = gradient_list.attr::<GradientTypeAttr>(0);
|
||||
let gradient_transform: DAffine2 = gradient_list.attr::<Transform>(0);
|
||||
let spread_method: GradientSpreadMethod = gradient_list.attr::<SpreadMethod>(0);
|
||||
|
||||
// The paint's own opacity fades each ramp stop, a masker dropping the fill half as for a color paint
|
||||
let opacity_fill: f64 = if for_mask { 1. } else { gradient_list.attr::<OpacityFill>(0) };
|
||||
let paint_opacity = (gradient_list.attr::<Opacity>(0) * opacity_fill) as f32;
|
||||
|
||||
let mut peniko_stops = peniko::ColorStops::new();
|
||||
for (position, color, _) in stops.interpolated_samples() {
|
||||
let color = if paint_opacity < 1. { color.with_alpha(color.a() * paint_opacity) } else { color };
|
||||
peniko_stops.push(peniko::ColorStop {
|
||||
offset: position as f32,
|
||||
color: peniko::color::DynamicColor::from_alpha_color(SRGBA8::from(color).to_peniko_color()),
|
||||
@@ -463,12 +540,9 @@ pub struct RenderMetadata {
|
||||
pub text_frames: HashMap<NodeId, DAffine2>,
|
||||
pub clip_targets: HashSet<NodeId>,
|
||||
pub vector_data: HashMap<NodeId, Arc<Vector>>,
|
||||
/// Per-layer `ATTR_FILL` row attribute, exposed so message handlers can read it.
|
||||
/// Per-layer resolved appearance snapshot, exposed so message handlers can read the paint.
|
||||
#[cfg_attr(feature = "serde", serde(skip))]
|
||||
pub fill_attributes: HashMap<NodeId, Arc<List<Graphic<'static>>>>,
|
||||
/// Per-layer `ATTR_STROKE` row attribute, exposed so message handlers can read it.
|
||||
#[cfg_attr(feature = "serde", serde(skip))]
|
||||
pub stroke_attributes: HashMap<NodeId, Arc<List<Graphic<'static>>>>,
|
||||
pub appearance_attributes: HashMap<NodeId, Arc<Appearance>>,
|
||||
pub backgrounds: Vec<Background>,
|
||||
}
|
||||
|
||||
@@ -492,8 +566,7 @@ impl RenderMetadata {
|
||||
text_frames,
|
||||
clip_targets,
|
||||
vector_data,
|
||||
fill_attributes,
|
||||
stroke_attributes,
|
||||
appearance_attributes,
|
||||
backgrounds,
|
||||
} = self;
|
||||
upstream_footprints.extend(other.upstream_footprints.iter());
|
||||
@@ -504,8 +577,7 @@ impl RenderMetadata {
|
||||
text_frames.extend(other.text_frames.iter());
|
||||
clip_targets.extend(other.clip_targets.iter());
|
||||
vector_data.extend(other.vector_data.iter().map(|(id, data)| (*id, data.clone())));
|
||||
fill_attributes.extend(other.fill_attributes.iter().map(|(id, data)| (*id, data.clone())));
|
||||
stroke_attributes.extend(other.stroke_attributes.iter().map(|(id, data)| (*id, data.clone())));
|
||||
appearance_attributes.extend(other.appearance_attributes.iter().map(|(id, data)| (*id, data.clone())));
|
||||
|
||||
// TODO: Find a better non O(n^2) way to merge backgrounds
|
||||
for background in &other.backgrounds {
|
||||
@@ -553,7 +625,7 @@ impl Render for Graphic<'_> {
|
||||
fn render_svg(&self, render: &mut SvgRender, render_params: &RenderParams) {
|
||||
match self {
|
||||
Graphic::Graphic(list) => list.render_svg(render, render_params),
|
||||
Graphic::Vector(vector) => render_vector_svg(&Single(vector), render, render_params),
|
||||
Graphic::Vector(vector) => render_vector_svg(&Single(vector), None, render, render_params),
|
||||
Graphic::RasterCPU(raster) => render_raster_cpu_svg(&Single(raster), render, render_params),
|
||||
Graphic::RasterGPU(_) => (),
|
||||
Graphic::Color(color) => render_color_svg(&Single(color), render, render_params),
|
||||
@@ -566,7 +638,7 @@ impl Render for Graphic<'_> {
|
||||
fn render_to_vello(&self, scene: &mut Scene, transform: DAffine2, context: &mut RenderContext, render_params: &RenderParams) {
|
||||
match self {
|
||||
Graphic::Graphic(list) => list.render_to_vello(scene, transform, context, render_params),
|
||||
Graphic::Vector(vector) => render_vector_vello(&Single(vector), scene, transform, context, render_params),
|
||||
Graphic::Vector(vector) => render_vector_vello(&Single(vector), None, scene, transform, context, render_params),
|
||||
Graphic::RasterCPU(raster) => render_raster_cpu_vello(&Single(raster), scene, transform, render_params),
|
||||
Graphic::RasterGPU(raster) => render_raster_gpu_vello(&Single(raster), scene, transform, context, render_params),
|
||||
Graphic::Color(color) => render_color_vello(&Single(color), scene, render_params),
|
||||
@@ -606,8 +678,8 @@ impl Render for Graphic<'_> {
|
||||
|
||||
fn render_element_svg<'a>(element: &'a Graphic, reach: PaintReach<'a>, render: &mut SvgRender, render_params: &RenderParams) {
|
||||
match element {
|
||||
Graphic::Vector(vector) if reach.applies() => render_vector_svg(&PaintOverlay::new(&Single(vector), reach.paint), render, render_params),
|
||||
Graphic::Graphic(inner) => render_graphic_svg_with(inner, reach.nested(), render, render_params),
|
||||
Graphic::Vector(vector) => render_vector_svg(&Single(vector), reach.appearance, render, render_params),
|
||||
Graphic::Graphic(inner) => render_graphic_svg_with(inner, reach, render, render_params),
|
||||
Graphic::Group(group) => render_group_svg(group, reach, render, render_params),
|
||||
_ => element.render_svg(render, render_params),
|
||||
}
|
||||
@@ -615,8 +687,8 @@ fn render_element_svg<'a>(element: &'a Graphic, reach: PaintReach<'a>, render: &
|
||||
|
||||
fn render_element_vello<'a>(element: &'a Graphic, reach: PaintReach<'a>, scene: &mut Scene, transform: DAffine2, context: &mut RenderContext, render_params: &RenderParams) {
|
||||
match element {
|
||||
Graphic::Vector(vector) if reach.applies() => render_vector_vello(&PaintOverlay::new(&Single(vector), reach.paint), scene, transform, context, render_params),
|
||||
Graphic::Graphic(inner) => render_graphic_vello_with(inner, reach.nested(), scene, transform, context, render_params),
|
||||
Graphic::Vector(vector) => render_vector_vello(&Single(vector), reach.appearance, scene, transform, context, render_params),
|
||||
Graphic::Graphic(inner) => render_graphic_vello_with(inner, reach, scene, transform, context, render_params),
|
||||
Graphic::Group(group) => render_group_vello(group, reach, scene, transform, context, render_params),
|
||||
_ => element.render_to_vello(scene, transform, context, render_params),
|
||||
}
|
||||
@@ -624,13 +696,12 @@ fn render_element_vello<'a>(element: &'a Graphic, reach: PaintReach<'a>, scene:
|
||||
|
||||
fn element_can_reduce_to_clip_path<'a>(element: &'a Graphic, reach: PaintReach<'a>) -> bool {
|
||||
match element {
|
||||
Graphic::Vector(vector) if reach.applies() => vector_can_reduce_to_clip_path(&PaintOverlay::new(&Single(vector), reach.paint)),
|
||||
Graphic::Vector(vector) => vector_can_reduce_to_clip_path(&Single(vector), reach.appearance),
|
||||
Graphic::Group(group) => match RunView::<Vector>::new(&group.content) {
|
||||
Some(run) if reach.applies() => vector_can_reduce_to_clip_path(&PaintOverlay::new(&run, reach.paint)),
|
||||
Some(run) => vector_can_reduce_to_clip_path(&run),
|
||||
Some(run) => vector_can_reduce_to_clip_path(&run, reach.appearance),
|
||||
None => false,
|
||||
},
|
||||
_ => element.can_reduce_to_clip_path(),
|
||||
_ => element.can_reduce_to_clip_path(reach.appearance),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -660,9 +731,8 @@ fn collect_element_metadata<'a>(
|
||||
}
|
||||
|
||||
match element {
|
||||
Graphic::Graphic(list) => collect_graphic_metadata_with(list, reach.nested(), metadata, footprint, element_id),
|
||||
Graphic::Vector(vector) if reach.applies() => collect_vector_metadata(&PaintOverlay::new(&Single(vector), reach.paint), metadata, footprint, element_id),
|
||||
Graphic::Vector(vector) => collect_vector_metadata(&Single(vector), metadata, footprint, element_id),
|
||||
Graphic::Graphic(list) => collect_graphic_metadata_with(list, reach, metadata, footprint, element_id),
|
||||
Graphic::Vector(vector) => collect_vector_metadata(&Single(vector), reach.appearance, metadata, footprint, element_id),
|
||||
Graphic::RasterCPU(raster) => collect_raster_metadata(&Single(raster), metadata, footprint, element_id),
|
||||
Graphic::RasterGPU(raster) => collect_raster_metadata(&Single(raster), metadata, footprint, element_id),
|
||||
Graphic::Color(_) => {}
|
||||
@@ -703,9 +773,8 @@ fn collect_group_row_metadata(group: &Group, metadata: &mut RenderMetadata, elem
|
||||
|
||||
fn add_element_upstream_click_targets<'a>(element: &'a Graphic, reach: PaintReach<'a>, click_targets: &mut Vec<ClickTarget>) {
|
||||
match element {
|
||||
Graphic::Graphic(list) => add_graphic_upstream_click_targets_with(list, reach.nested(), click_targets),
|
||||
Graphic::Vector(vector) if reach.applies() => add_vector_upstream_click_targets(&PaintOverlay::new(&Single(vector), reach.paint), click_targets),
|
||||
Graphic::Vector(vector) => add_vector_upstream_click_targets(&Single(vector), click_targets),
|
||||
Graphic::Graphic(list) => add_graphic_upstream_click_targets_with(list, reach, click_targets),
|
||||
Graphic::Vector(vector) => add_vector_upstream_click_targets(&Single(vector), reach.appearance, click_targets),
|
||||
Graphic::RasterCPU(_) | Graphic::RasterGPU(_) => add_raster_upstream_click_targets(click_targets),
|
||||
Graphic::Color(_) | Graphic::Gradient(_) => {}
|
||||
Graphic::Text(text) => add_text_upstream_click_targets(&Single(text), click_targets),
|
||||
@@ -715,9 +784,8 @@ fn add_element_upstream_click_targets<'a>(element: &'a Graphic, reach: PaintReac
|
||||
|
||||
fn add_element_upstream_outline_targets<'a>(element: &'a Graphic, reach: PaintReach<'a>, outlines: &mut Vec<ClickTarget>) {
|
||||
match element {
|
||||
Graphic::Graphic(list) => add_graphic_upstream_outline_targets_with(list, reach.nested(), outlines),
|
||||
Graphic::Vector(vector) if reach.applies() => add_vector_upstream_outline_targets(&PaintOverlay::new(&Single(vector), reach.paint), outlines),
|
||||
Graphic::Vector(vector) => add_vector_upstream_outline_targets(&Single(vector), outlines),
|
||||
Graphic::Graphic(list) => add_graphic_upstream_outline_targets_with(list, reach, outlines),
|
||||
Graphic::Vector(vector) => add_vector_upstream_outline_targets(&Single(vector), reach.appearance, outlines),
|
||||
Graphic::RasterCPU(_) | Graphic::RasterGPU(_) => add_raster_upstream_click_targets(outlines),
|
||||
Graphic::Color(_) | Graphic::Gradient(_) => {}
|
||||
Graphic::Text(text) => add_text_upstream_click_targets(&Single(text), outlines),
|
||||
@@ -730,12 +798,9 @@ fn add_element_upstream_outline_targets<'a>(element: &'a Graphic, reach: PaintRe
|
||||
fn render_group_svg<'a>(group: &'a Group, reach: PaintReach<'a>, render: &mut SvgRender, render_params: &RenderParams) {
|
||||
let item = &group.content;
|
||||
if let Some(run) = RunView::<Graphic>::new(item) {
|
||||
render_graphic_svg_with(&run, reach.into_group_graphics(), render, render_params)
|
||||
render_graphic_svg_with(&run, reach, render, render_params)
|
||||
} else if let Some(run) = RunView::<Vector>::new(item) {
|
||||
match reach.applies() {
|
||||
true => render_vector_svg(&PaintOverlay::new(&run, reach.paint), render, render_params),
|
||||
false => render_vector_svg(&run, render, render_params),
|
||||
}
|
||||
render_vector_svg(&run, reach.appearance, render, render_params)
|
||||
} else if let Some(run) = RunView::<Raster<CPU>>::new(item) {
|
||||
render_raster_cpu_svg(&run, render, render_params)
|
||||
} else if item.typed_lanes::<Raster<GPU>>().is_some() {
|
||||
@@ -751,12 +816,9 @@ fn render_group_svg<'a>(group: &'a Group, reach: PaintReach<'a>, render: &mut Sv
|
||||
fn render_group_vello<'a>(group: &'a Group, reach: PaintReach<'a>, scene: &mut Scene, transform: DAffine2, context: &mut RenderContext, render_params: &RenderParams) {
|
||||
let item = &group.content;
|
||||
if let Some(run) = RunView::<Graphic>::new(item) {
|
||||
render_graphic_vello_with(&run, reach.into_group_graphics(), scene, transform, context, render_params)
|
||||
render_graphic_vello_with(&run, reach, scene, transform, context, render_params)
|
||||
} else if let Some(run) = RunView::<Vector>::new(item) {
|
||||
match reach.applies() {
|
||||
true => render_vector_vello(&PaintOverlay::new(&run, reach.paint), scene, transform, context, render_params),
|
||||
false => render_vector_vello(&run, scene, transform, context, render_params),
|
||||
}
|
||||
render_vector_vello(&run, reach.appearance, scene, transform, context, render_params)
|
||||
} else if let Some(run) = RunView::<Raster<CPU>>::new(item) {
|
||||
render_raster_cpu_vello(&run, scene, transform, render_params)
|
||||
} else if let Some(run) = RunView::<Raster<GPU>>::new(item) {
|
||||
@@ -776,12 +838,9 @@ fn render_group_vello<'a>(group: &'a Group, reach: PaintReach<'a>, scene: &mut S
|
||||
fn collect_group_metadata<'a>(group: &'a Group, reach: PaintReach<'a>, metadata: &mut RenderMetadata, footprint: Footprint, element_id: Option<NodeId>) {
|
||||
let item = &group.content;
|
||||
if let Some(run) = RunView::<Graphic>::new(item) {
|
||||
collect_graphic_metadata_with(&run, reach.into_group_graphics(), metadata, footprint, element_id)
|
||||
collect_graphic_metadata_with(&run, reach, metadata, footprint, element_id)
|
||||
} else if let Some(run) = RunView::<Vector>::new(item) {
|
||||
match reach.applies() {
|
||||
true => collect_vector_metadata(&PaintOverlay::new(&run, reach.paint), metadata, footprint, element_id),
|
||||
false => collect_vector_metadata(&run, metadata, footprint, element_id),
|
||||
}
|
||||
collect_vector_metadata(&run, reach.appearance, metadata, footprint, element_id)
|
||||
} else if let Some(run) = RunView::<Raster<CPU>>::new(item) {
|
||||
collect_raster_metadata(&run, metadata, footprint, element_id)
|
||||
} else if let Some(run) = RunView::<Raster<GPU>>::new(item) {
|
||||
@@ -795,12 +854,9 @@ fn collect_group_metadata<'a>(group: &'a Group, reach: PaintReach<'a>, metadata:
|
||||
fn add_group_upstream_click_targets<'a>(group: &'a Group, reach: PaintReach<'a>, click_targets: &mut Vec<ClickTarget>) {
|
||||
let item = &group.content;
|
||||
if let Some(run) = RunView::<Graphic>::new(item) {
|
||||
add_graphic_upstream_click_targets_with(&run, reach.into_group_graphics(), click_targets)
|
||||
add_graphic_upstream_click_targets_with(&run, reach, click_targets)
|
||||
} else if let Some(run) = RunView::<Vector>::new(item) {
|
||||
match reach.applies() {
|
||||
true => add_vector_upstream_click_targets(&PaintOverlay::new(&run, reach.paint), click_targets),
|
||||
false => add_vector_upstream_click_targets(&run, click_targets),
|
||||
}
|
||||
add_vector_upstream_click_targets(&run, reach.appearance, click_targets)
|
||||
} else if item.typed_lanes::<Raster<CPU>>().is_some() || item.typed_lanes::<Raster<GPU>>().is_some() {
|
||||
add_raster_upstream_click_targets(click_targets)
|
||||
} else if let Some(run) = RunView::<String>::new(item) {
|
||||
@@ -811,12 +867,9 @@ fn add_group_upstream_click_targets<'a>(group: &'a Group, reach: PaintReach<'a>,
|
||||
fn add_group_upstream_outline_targets<'a>(group: &'a Group, reach: PaintReach<'a>, outlines: &mut Vec<ClickTarget>) {
|
||||
let item = &group.content;
|
||||
if let Some(run) = RunView::<Graphic>::new(item) {
|
||||
add_graphic_upstream_outline_targets_with(&run, reach.into_group_graphics(), outlines)
|
||||
add_graphic_upstream_outline_targets_with(&run, reach, outlines)
|
||||
} else if let Some(run) = RunView::<Vector>::new(item) {
|
||||
match reach.applies() {
|
||||
true => add_vector_upstream_outline_targets(&PaintOverlay::new(&run, reach.paint), outlines),
|
||||
false => add_vector_upstream_outline_targets(&run, outlines),
|
||||
}
|
||||
add_vector_upstream_outline_targets(&run, reach.appearance, outlines)
|
||||
} else if item.typed_lanes::<Raster<CPU>>().is_some() || item.typed_lanes::<Raster<GPU>>().is_some() {
|
||||
add_raster_upstream_click_targets(outlines)
|
||||
} else if let Some(run) = RunView::<String>::new(item) {
|
||||
@@ -1272,7 +1325,7 @@ impl Render for List<Graphic<'_>> {
|
||||
}
|
||||
}
|
||||
|
||||
fn render_vector_svg<S: LaneSource<Element = Vector>>(source: &S, render: &mut SvgRender, render_params: &RenderParams) {
|
||||
fn render_vector_svg<S: LaneSource<Element = Vector>>(source: &S, inherited_appearance: Option<&Appearance>, render: &mut SvgRender, render_params: &RenderParams) {
|
||||
for index in 0..source.lane_count() {
|
||||
let Some(vector) = source.element(index) else { continue };
|
||||
let item_transform: DAffine2 = source.attr::<Transform>(index);
|
||||
@@ -1280,8 +1333,13 @@ fn render_vector_svg<S: LaneSource<Element = Vector>>(source: &S, render: &mut S
|
||||
let opacity_attr: f64 = source.attr::<Opacity>(index);
|
||||
let opacity_fill_attr: f64 = source.attr::<OpacityFill>(index);
|
||||
|
||||
// The lane's paint: its own declared appearance, or the nearest ancestor's through the cascade
|
||||
let appearance = Appearance::cascade(source.attr::<AppearanceMarker>(index), inherited_appearance);
|
||||
let resolved = appearance.map(Appearance::fill_and_stroke).unwrap_or_default();
|
||||
let element_stroke = resolved.stroke.as_ref();
|
||||
|
||||
// Only consider strokes with non-zero weight, since default strokes with zero weight would prevent assigning the correct stroke transform
|
||||
let has_real_stroke = vector.stroke.as_ref().filter(|stroke| stroke.weight() > 0.);
|
||||
let has_real_stroke = element_stroke.filter(|stroke| stroke.weight() > 0.);
|
||||
let set_stroke_transform = has_real_stroke.map(|stroke| stroke.transform).filter(|transform| transform_is_invertible(*transform));
|
||||
let applied_stroke_transform = set_stroke_transform.unwrap_or(item_transform);
|
||||
let applied_stroke_transform = render_params.alignment_parent_transform.unwrap_or(applied_stroke_transform);
|
||||
@@ -1289,7 +1347,7 @@ fn render_vector_svg<S: LaneSource<Element = Vector>>(source: &S, render: &mut S
|
||||
let element_transform = element_transform.unwrap_or(DAffine2::IDENTITY);
|
||||
let layer_bounds = vector.bounding_box().unwrap_or_default();
|
||||
let transformed_bounds = vector.bounding_box_with_transform(applied_stroke_transform).unwrap_or_default();
|
||||
let stroke_layer_bounds = vector.stroke_inclusive_bounding_box_with_transform(DAffine2::IDENTITY).unwrap_or(layer_bounds);
|
||||
let stroke_layer_bounds = vector.stroke_inclusive_bounding_box_with_transform(DAffine2::IDENTITY, element_stroke).unwrap_or(layer_bounds);
|
||||
|
||||
let bounds_matrix = DAffine2::from_scale_angle_translation(layer_bounds[1] - layer_bounds[0], 0., layer_bounds[0]);
|
||||
let stroke_bounds_matrix = DAffine2::from_scale_angle_translation(stroke_layer_bounds[1] - stroke_layer_bounds[0], 0., stroke_layer_bounds[0]);
|
||||
@@ -1301,26 +1359,27 @@ fn render_vector_svg<S: LaneSource<Element = Vector>>(source: &S, render: &mut S
|
||||
path.push_str(bezpath.to_svg().as_str());
|
||||
}
|
||||
|
||||
let mask_type = if vector.stroke.as_ref().map(|x| x.align) == Some(StrokeAlign::Inside) {
|
||||
let mask_type = if element_stroke.map(|x| x.align) == Some(StrokeAlign::Inside) {
|
||||
MaskType::Clip
|
||||
} else {
|
||||
MaskType::Mask
|
||||
};
|
||||
|
||||
let fill_graphic_list = paint_graphics::<Fill, _>(source, index);
|
||||
let fill_graphic_list = resolved.fill_paint.and_then(paint_cell_rows);
|
||||
let fill_graphic = fill_graphic_list.and_then(|l| l.element(0));
|
||||
|
||||
let stroke_graphic_list = paint_graphics::<Stroke, _>(source, index);
|
||||
let stroke_graphic_list = resolved.stroke_paint.and_then(paint_cell_rows);
|
||||
let stroke_graphic = stroke_graphic_list.and_then(|l| l.element(0));
|
||||
|
||||
let path_is_closed = vector.stroke_bezier_paths().all(|path| path.closed());
|
||||
let can_draw_aligned_stroke = path_is_closed
|
||||
&& vector.stroke.as_ref().is_some_and(|stroke| stroke.has_renderable_stroke() && stroke.align.is_not_centered())
|
||||
&& element_stroke.is_some_and(|stroke| stroke.has_renderable_stroke() && stroke.align.is_not_centered())
|
||||
&& stroke_graphic.is_some_and(|graphic| !graphic.is_fully_transparent());
|
||||
let can_use_paint_order = !(fill_graphic.is_none_or(|graphic| !graphic.covers_opaquely()) || mask_type == MaskType::Clip);
|
||||
|
||||
let needs_separate_alignment_fill = can_draw_aligned_stroke && !can_use_paint_order;
|
||||
let wants_stroke_below = vector.stroke.as_ref().map(|s| s.paint_order) == Some(PaintOrder::StrokeBelow);
|
||||
// The paint order rides the coverage list's row order
|
||||
let wants_stroke_below = resolved.stroke_below;
|
||||
let override_paint_order = can_draw_aligned_stroke && can_use_paint_order;
|
||||
let use_face_fill = vector.use_face_fill();
|
||||
|
||||
@@ -1340,13 +1399,12 @@ fn render_vector_svg<S: LaneSource<Element = Vector>>(source: &S, render: &mut S
|
||||
let push_id = needs_separate_alignment_fill.then_some({
|
||||
let id = format!("alignment-{}", generate_uuid());
|
||||
|
||||
let mut cloned_vector = vector.clone();
|
||||
cloned_vector.stroke = None;
|
||||
let cloned_vector = vector.clone();
|
||||
|
||||
// The mask must draw at full alpha so the SVG `<mask>`/`<clipPath>` fully zeroes the path interior.
|
||||
// The wrapping SVG group (above) handles the user-set opacity.
|
||||
let mut mask_item = Item::new_from_element(cloned_vector).with_attribute(ATTR_TRANSFORM, item_transform);
|
||||
set_paint_attribute(mask_item.attributes_mut(), ATTR_FILL, List::new_from_element(Color::BLACK));
|
||||
mask_item.set_attribute(graphic_types::ATTR_APPEARANCE, black_fill_appearance());
|
||||
let vector_item = List::new_from_item(mask_item);
|
||||
|
||||
(id, mask_type, vector_item)
|
||||
@@ -1381,7 +1439,7 @@ fn render_vector_svg<S: LaneSource<Element = Vector>>(source: &S, render: &mut S
|
||||
if let Some((ref id, mask_type, ref vector_item)) = push_id {
|
||||
let mut svg = SvgRender::new();
|
||||
vector_item.render_svg(&mut svg, &render_params.for_alignment(applied_stroke_transform));
|
||||
let stroke = vector.stroke.as_ref().unwrap();
|
||||
let stroke = element_stroke.unwrap();
|
||||
// `push_id` is only `Some` when `can_draw_aligned_stroke`, which is gated on `path_is_closed`
|
||||
let (largest_scale, _) = singular_values(applied_stroke_transform);
|
||||
let inflation = stroke.max_aabb_inflation(true) * largest_scale;
|
||||
@@ -1406,11 +1464,9 @@ fn render_vector_svg<S: LaneSource<Element = Vector>>(source: &S, render: &mut S
|
||||
|
||||
let mut render_params = render_params.clone();
|
||||
render_params.aligned_strokes = can_draw_aligned_stroke;
|
||||
render_params.override_paint_order = override_paint_order;
|
||||
render_params.stroke_below = override_paint_order || wants_stroke_below;
|
||||
|
||||
let stroke_shape_attribute = vector
|
||||
.stroke
|
||||
.as_ref()
|
||||
let stroke_shape_attribute = element_stroke
|
||||
.map(|stroke| {
|
||||
if stroke_graphic_list.is_some_and(is_paint_present) {
|
||||
stroke.render(defs, item_transform, element_transform, applied_stroke_transform, bounds_matrix, &render_params, PaintTarget::Stroke)
|
||||
@@ -1421,7 +1477,7 @@ fn render_vector_svg<S: LaneSource<Element = Vector>>(source: &S, render: &mut S
|
||||
.unwrap_or_default();
|
||||
|
||||
// Need to avoid generating only paint attribute, otherwise SVG uses 1px width stroke as a fallback
|
||||
let stroke_visible = vector.stroke.as_ref().is_some_and(|stroke| stroke.has_renderable_stroke()) && stroke_graphic.is_some_and(|g| !g.is_fully_transparent());
|
||||
let stroke_visible = element_stroke.is_some_and(|stroke| stroke.has_renderable_stroke()) && stroke_graphic.is_some_and(|g| !g.is_fully_transparent());
|
||||
let stroke_attribute = if stroke_visible {
|
||||
stroke_graphic_list
|
||||
.map(|list| {
|
||||
@@ -1484,17 +1540,27 @@ fn render_vector_svg<S: LaneSource<Element = Vector>>(source: &S, render: &mut S
|
||||
}
|
||||
}
|
||||
|
||||
fn render_vector_vello<S: LaneSource<Element = Vector>>(source: &S, scene: &mut Scene, parent_transform: DAffine2, context: &mut RenderContext, render_params: &RenderParams) {
|
||||
fn render_vector_vello<S: LaneSource<Element = Vector>>(
|
||||
source: &S,
|
||||
inherited_appearance: Option<&Appearance>,
|
||||
scene: &mut Scene,
|
||||
parent_transform: DAffine2,
|
||||
context: &mut RenderContext,
|
||||
render_params: &RenderParams,
|
||||
) {
|
||||
for index in 0..source.lane_count() {
|
||||
use graphic_types::vector_types::vector;
|
||||
|
||||
let Some(element) = source.element(index) else { continue };
|
||||
let item_transform: DAffine2 = source.attr::<Transform>(index);
|
||||
let blend_mode_attr: BlendMode = source.attr::<BlendModeAttr>(index);
|
||||
let opacity_attr: f64 = source.attr::<Opacity>(index);
|
||||
let opacity_fill_attr: f64 = source.attr::<OpacityFill>(index);
|
||||
let multiplied_transform = parent_transform * item_transform;
|
||||
let has_real_stroke = element.stroke.as_ref().filter(|stroke| stroke.weight() > 0.);
|
||||
|
||||
// The lane's paint: its own declared appearance, or the nearest ancestor's through the cascade
|
||||
let appearance = Appearance::cascade(source.attr::<AppearanceMarker>(index), inherited_appearance);
|
||||
let resolved = appearance.map(Appearance::fill_and_stroke).unwrap_or_default();
|
||||
|
||||
let has_real_stroke = resolved.stroke.as_ref().filter(|stroke| stroke.weight() > 0.);
|
||||
let set_stroke_transform = has_real_stroke.map(|stroke| stroke.transform).filter(|transform| transform_is_invertible(*transform));
|
||||
let mut applied_stroke_transform = set_stroke_transform.unwrap_or(multiplied_transform);
|
||||
let mut element_transform = set_stroke_transform
|
||||
@@ -1518,8 +1584,8 @@ fn render_vector_vello<S: LaneSource<Element = Vector>>(source: &S, scene: &mut
|
||||
}
|
||||
}
|
||||
|
||||
let fill_graphic_list = paint_graphics::<Fill, _>(source, index);
|
||||
let stroke_graphic_list = paint_graphics::<Stroke, _>(source, index);
|
||||
let fill_graphic_list = resolved.fill_paint.and_then(paint_cell_rows);
|
||||
let stroke_graphic_list = resolved.stroke_paint.and_then(paint_cell_rows);
|
||||
|
||||
// If we're using opacity or a blend mode, we need to push a layer
|
||||
let blend_mode = match render_params.render_mode {
|
||||
@@ -1531,7 +1597,7 @@ fn render_vector_vello<S: LaneSource<Element = Vector>>(source: &S, scene: &mut
|
||||
// Whether the renderer will engage the stroke-alignment compositing trick (non-Center align on a fully closed path).
|
||||
// Used by both the blend-layer clip rect inflation below (as `max_aabb_inflation`'s `path_is_closed` arg, equivalent here since
|
||||
// the function ignores the arg for Center align) and the `SrcIn`/`SrcOut` aligned-stroke branch further down.
|
||||
let stroke = element.stroke.as_ref();
|
||||
let stroke = resolved.stroke.as_ref();
|
||||
let stroke_fully_transparent = stroke_graphic_list.is_none_or(|l| l.element(0).is_none_or(|g| g.is_fully_transparent()));
|
||||
let can_draw_aligned_stroke = !stroke_fully_transparent && stroke.is_some_and(|s| s.has_renderable_stroke() && s.align.is_not_centered()) && element.stroke_bezier_paths().all(|p| p.closed());
|
||||
|
||||
@@ -1555,7 +1621,8 @@ fn render_vector_vello<S: LaneSource<Element = Vector>>(source: &S, scene: &mut
|
||||
}
|
||||
|
||||
let use_layer = can_draw_aligned_stroke;
|
||||
let wants_stroke_below = stroke.is_some_and(|s| s.paint_order == vector::style::PaintOrder::StrokeBelow);
|
||||
// The paint order rides the coverage list's row order
|
||||
let wants_stroke_below = resolved.stroke_below;
|
||||
|
||||
let do_fill_path = |scene: &mut Scene, context: &mut RenderContext, path: &kurbo::BezPath, fill_rule: peniko::Fill| {
|
||||
let Some(fill_graphic) = fill_graphic_list else { return };
|
||||
@@ -1564,11 +1631,13 @@ fn render_vector_vello<S: LaneSource<Element = Vector>>(source: &S, scene: &mut
|
||||
let Some(paint) = fill_graphic.element(paint_index) else { continue };
|
||||
match paint {
|
||||
Graphic::Color(color) => {
|
||||
let fill = peniko::Brush::Solid(SRGBA8::from(*color).to_peniko_color());
|
||||
// The row's own opacity fades the pass, matching the composited SVG fast path
|
||||
let color = color.with_alpha(color.a() * paint_row_opacity(fill_graphic, paint_index, render_params.for_mask));
|
||||
let fill = peniko::Brush::Solid(SRGBA8::from(color).to_peniko_color());
|
||||
scene.fill(fill_rule, kurbo::Affine::new(element_transform.to_cols_array()), &fill, None, path);
|
||||
}
|
||||
Graphic::Gradient(gradient) => {
|
||||
let Some((brush, gradient_to_device)) = create_peniko_gradient_brush(&LeafLane::new(fill_graphic, paint_index, gradient), &multiplied_transform) else {
|
||||
let Some((brush, gradient_to_device)) = create_peniko_gradient_brush(&LeafLane::new(fill_graphic, paint_index, gradient), &multiplied_transform, render_params.for_mask) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
@@ -1644,12 +1713,15 @@ fn render_vector_vello<S: LaneSource<Element = Vector>>(source: &S, scene: &mut
|
||||
|
||||
match stroke_graphic {
|
||||
Graphic::Color(color) => {
|
||||
let brush = peniko::Brush::Solid(SRGBA8::from(*color).to_peniko_color());
|
||||
// The row's own opacity fades the pass, matching the composited SVG fast path
|
||||
let color = color.with_alpha(color.a() * paint_row_opacity(stroke_graphic_list, paint_index, render_params.for_mask));
|
||||
let brush = peniko::Brush::Solid(SRGBA8::from(color).to_peniko_color());
|
||||
|
||||
scene.stroke(&stroke, kurbo::Affine::new(element_transform.to_cols_array()), &brush, None, &path);
|
||||
}
|
||||
Graphic::Gradient(gradient) => {
|
||||
let Some((brush, gradient_to_device)) = create_peniko_gradient_brush(&LeafLane::new(stroke_graphic_list, paint_index, gradient), &multiplied_transform) else {
|
||||
let Some((brush, gradient_to_device)) = create_peniko_gradient_brush(&LeafLane::new(stroke_graphic_list, paint_index, gradient), &multiplied_transform, render_params.for_mask)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let inverse_element_transform = if transform_is_invertible(element_transform) {
|
||||
@@ -1681,13 +1753,12 @@ fn render_vector_vello<S: LaneSource<Element = Vector>>(source: &S, scene: &mut
|
||||
}
|
||||
_ => {
|
||||
if use_layer {
|
||||
let mut cloned_element = element.clone();
|
||||
cloned_element.stroke = None;
|
||||
let cloned_element = element.clone();
|
||||
|
||||
// The mask must draw at full alpha so `SrcOut` fully zeroes the path interior.
|
||||
// The outer opacity/blend layer (above) handles the user-set opacity.
|
||||
let mut mask_item = Item::new_from_element(cloned_element).with_attribute(ATTR_TRANSFORM, item_transform);
|
||||
set_paint_attribute(mask_item.attributes_mut(), ATTR_FILL, List::new_from_element(Color::BLACK));
|
||||
mask_item.set_attribute(graphic_types::ATTR_APPEARANCE, black_fill_appearance());
|
||||
let vector_list = List::new_from_item(mask_item);
|
||||
|
||||
let bounds = element.bounding_box_with_transform(multiplied_transform).unwrap_or(layer_bounds);
|
||||
@@ -1735,7 +1806,7 @@ fn render_vector_vello<S: LaneSource<Element = Vector>>(source: &S, scene: &mut
|
||||
Stroke,
|
||||
}
|
||||
|
||||
let order = match stroke.is_some_and(|stroke| !stroke.paint_order.is_default()) {
|
||||
let order = match stroke.is_some() && wants_stroke_below {
|
||||
true => [Op::Stroke, Op::Fill],
|
||||
false => [Op::Fill, Op::Stroke], // Default
|
||||
};
|
||||
@@ -1757,7 +1828,13 @@ fn render_vector_vello<S: LaneSource<Element = Vector>>(source: &S, scene: &mut
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_vector_metadata<S: LaneSource<Element = Vector>>(source: &S, metadata: &mut RenderMetadata, footprint: Footprint, caller_element_id: Option<NodeId>) {
|
||||
fn collect_vector_metadata<S: LaneSource<Element = Vector>>(
|
||||
source: &S,
|
||||
inherited_appearance: Option<&Appearance>,
|
||||
metadata: &mut RenderMetadata,
|
||||
footprint: Footprint,
|
||||
caller_element_id: Option<NodeId>,
|
||||
) {
|
||||
// Aggregate all items' targets per element_id so multi-item lists (e.g. 'Text' node with "Separate Glyphs" active) produce hit areas for every glyph.
|
||||
// Targets are baked relative to item 0's transform since `Graphic::collect_metadata` records that as `local_transforms[element_id]`.
|
||||
let item_zero_transform: DAffine2 = if source.lane_count() > 0 { source.attr::<Transform>(0) } else { DAffine2::IDENTITY };
|
||||
@@ -1776,6 +1853,10 @@ fn collect_vector_metadata<S: LaneSource<Element = Vector>>(source: &S, metadata
|
||||
let layer_path: &[NodeId] = source.attr::<EditorLayerPath>(index);
|
||||
let layer = layer_path.last().copied();
|
||||
|
||||
// The lane's paint: its own declared appearance, or the nearest ancestor's through the cascade
|
||||
let appearance = Appearance::cascade(source.attr::<AppearanceMarker>(index), inherited_appearance);
|
||||
let resolved = appearance.map(Appearance::fill_and_stroke).unwrap_or_default();
|
||||
|
||||
if let Some(element_id) = caller_element_id.or(layer) {
|
||||
// When recovering element_id from the item's editor:layer_path tag (because the caller
|
||||
// passed None), also store the transform metadata that Graphic::collect_metadata
|
||||
@@ -1791,12 +1872,12 @@ fn collect_vector_metadata<S: LaneSource<Element = Vector>>(source: &S, metadata
|
||||
let item_relative_transform = item_zero_inverse * transform;
|
||||
|
||||
let mut click_targets_unwrapped = Vec::new();
|
||||
extend_targets_from_vector(&mut click_targets_unwrapped, source, index, click_target_vector, item_relative_transform);
|
||||
extend_targets_from_vector(&mut click_targets_unwrapped, &resolved, click_target_vector, item_relative_transform);
|
||||
accumulated_click_targets.entry(element_id).or_default().extend(click_targets_unwrapped.into_iter().map(Arc::new));
|
||||
|
||||
// Outlines always use source geometry so the visual outline reflects actual letterforms
|
||||
let mut outlines_unwrapped = Vec::new();
|
||||
extend_targets_from_vector(&mut outlines_unwrapped, source, index, element, item_relative_transform);
|
||||
extend_targets_from_vector(&mut outlines_unwrapped, &resolved, element, item_relative_transform);
|
||||
accumulated_outlines.entry(element_id).or_default().extend(outlines_unwrapped.into_iter().map(Arc::new));
|
||||
|
||||
// Source geometry (not the click-target override) so editing tools work on letterforms.
|
||||
@@ -1806,11 +1887,8 @@ fn collect_vector_metadata<S: LaneSource<Element = Vector>>(source: &S, metadata
|
||||
if let std::collections::hash_map::Entry::Vacant(e) = metadata.vector_data.entry(element_id) {
|
||||
e.insert(Arc::new(element.clone()));
|
||||
|
||||
if let Some(fill_graphic) = source.attr::<Fill>(index).filter(|list| is_paint_present(list)) {
|
||||
metadata.fill_attributes.insert(element_id, Arc::new(fill_graphic.clone()));
|
||||
}
|
||||
if let Some(stroke_graphic) = source.attr::<Stroke>(index).filter(|list| is_paint_present(list)) {
|
||||
metadata.stroke_attributes.insert(element_id, Arc::new(stroke_graphic.clone()));
|
||||
if let Some(appearance) = appearance {
|
||||
metadata.appearance_attributes.insert(element_id, Arc::new(appearance.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1839,7 +1917,7 @@ fn collect_vector_metadata<S: LaneSource<Element = Vector>>(source: &S, metadata
|
||||
}
|
||||
}
|
||||
|
||||
fn add_vector_upstream_click_targets<S: LaneSource<Element = Vector>>(source: &S, click_targets: &mut Vec<ClickTarget>) {
|
||||
fn add_vector_upstream_click_targets<S: LaneSource<Element = Vector>>(source: &S, inherited_appearance: Option<&Appearance>, click_targets: &mut Vec<ClickTarget>) {
|
||||
for index in 0..source.lane_count() {
|
||||
let Some(element) = source.element(index) else { continue };
|
||||
let transform: DAffine2 = source.attr::<Transform>(index);
|
||||
@@ -1847,39 +1925,45 @@ fn add_vector_upstream_click_targets<S: LaneSource<Element = Vector>>(source: &S
|
||||
// Use click-target override geometry if the item provides one (e.g. 'Text' node's per-glyph bounding boxes)
|
||||
let vector = source.attr::<EditorClickTarget>(index).unwrap_or(element);
|
||||
|
||||
extend_targets_from_vector(click_targets, source, index, vector, transform);
|
||||
let appearance = Appearance::cascade(source.attr::<AppearanceMarker>(index), inherited_appearance);
|
||||
let resolved = appearance.map(Appearance::fill_and_stroke).unwrap_or_default();
|
||||
|
||||
extend_targets_from_vector(click_targets, &resolved, vector, transform);
|
||||
}
|
||||
}
|
||||
|
||||
fn add_vector_upstream_outline_targets<S: LaneSource<Element = Vector>>(source: &S, outlines: &mut Vec<ClickTarget>) {
|
||||
fn add_vector_upstream_outline_targets<S: LaneSource<Element = Vector>>(source: &S, inherited_appearance: Option<&Appearance>, outlines: &mut Vec<ClickTarget>) {
|
||||
// Source geometry only, ignoring `editor:click_target`, so outlines reflect actual letterforms
|
||||
for index in 0..source.lane_count() {
|
||||
let Some(element) = source.element(index) else { continue };
|
||||
let transform: DAffine2 = source.attr::<Transform>(index);
|
||||
|
||||
extend_targets_from_vector(outlines, source, index, element, transform);
|
||||
let appearance = Appearance::cascade(source.attr::<AppearanceMarker>(index), inherited_appearance);
|
||||
let resolved = appearance.map(Appearance::fill_and_stroke).unwrap_or_default();
|
||||
|
||||
extend_targets_from_vector(outlines, &resolved, element, transform);
|
||||
}
|
||||
}
|
||||
|
||||
impl Render for List<Vector> {
|
||||
fn render_svg(&self, render: &mut SvgRender, render_params: &RenderParams) {
|
||||
render_vector_svg(self, render, render_params)
|
||||
render_vector_svg(self, None, render, render_params)
|
||||
}
|
||||
|
||||
fn render_to_vello(&self, scene: &mut Scene, parent_transform: DAffine2, context: &mut RenderContext, render_params: &RenderParams) {
|
||||
render_vector_vello(self, scene, parent_transform, context, render_params)
|
||||
render_vector_vello(self, None, scene, parent_transform, context, render_params)
|
||||
}
|
||||
|
||||
fn collect_metadata(&self, metadata: &mut RenderMetadata, footprint: Footprint, caller_element_id: Option<NodeId>) {
|
||||
collect_vector_metadata(self, metadata, footprint, caller_element_id)
|
||||
collect_vector_metadata(self, None, metadata, footprint, caller_element_id)
|
||||
}
|
||||
|
||||
fn add_upstream_click_targets(&self, click_targets: &mut Vec<ClickTarget>) {
|
||||
add_vector_upstream_click_targets(self, click_targets)
|
||||
add_vector_upstream_click_targets(self, None, click_targets)
|
||||
}
|
||||
|
||||
fn add_upstream_outline_targets(&self, outlines: &mut Vec<ClickTarget>) {
|
||||
add_vector_upstream_outline_targets(self, outlines)
|
||||
add_vector_upstream_outline_targets(self, None, outlines)
|
||||
}
|
||||
|
||||
fn new_ids_from_hash(&mut self, reference: Option<NodeId>) {
|
||||
@@ -1891,15 +1975,15 @@ impl Render for List<Vector> {
|
||||
|
||||
/// Build one `CompoundPath` (non-zero fill rule, so holes like the inside of an "O" work
|
||||
/// correctly) plus one `FreePoint` per disconnected anchor, apply the transform, and append.
|
||||
fn extend_targets_from_vector<S: LaneSource<Element = Vector>>(targets: &mut Vec<ClickTarget>, source: &S, index: usize, geometry: &Vector, transform: DAffine2) {
|
||||
let filled = has_paint::<Fill, _>(source, index);
|
||||
fn extend_targets_from_vector(targets: &mut Vec<ClickTarget>, resolved: &graphic_types::appearance::FillAndStroke<'_>, geometry: &Vector, transform: DAffine2) {
|
||||
let filled = resolved.fill_paint.and_then(paint_cell_rows).is_some();
|
||||
|
||||
let mut subpaths: Vec<Subpath<_>> = geometry.stroke_bezier_paths().collect();
|
||||
let all_subpaths_closed = subpaths.iter().all(|subpath| subpath.closed());
|
||||
|
||||
// Inside/Outside-aligned strokes reach `weight` from the centerline rather than `weight / 2` per side,
|
||||
// so they need double the click inflation. Alignment is only honored by the renderer for fully-closed paths.
|
||||
let stroke_width = geometry.stroke.as_ref().map_or(0., |stroke| {
|
||||
let stroke_width = resolved.stroke.as_ref().map_or(0., |stroke| {
|
||||
if stroke.align.is_not_centered() && all_subpaths_closed {
|
||||
stroke.weight * 2.
|
||||
} else {
|
||||
@@ -2094,12 +2178,7 @@ fn collect_raster_metadata<S: LaneSource>(source: &S, metadata: &mut RenderMetad
|
||||
let transform: DAffine2 = source.attr::<Transform>(0);
|
||||
metadata.local_transforms.insert(element_id, transform);
|
||||
|
||||
// If this raster carries a snapshot of upstream graphic content (e.g. it was produced by Rasterize,
|
||||
// which destructively merges its inputs into pixels), recurse into that snapshot so the editor can
|
||||
// surface the original child layers' click targets (the same mechanism Boolean Operation uses).
|
||||
// The snapshot was captured before Rasterize shifted its input transforms to align with the rasterization
|
||||
// area, so the children are already in the coordinate space matching `footprint` here — we must NOT
|
||||
// multiply in `transform` (which is the rasterization area, not a layer-stack transform).
|
||||
// The snapshot's children already match `footprint`, so `transform` (the rasterization area) must not be applied.
|
||||
if let Some(upstream_nested_layers) = source.attr::<EditorMergedLayers>(0).filter(|layers| !layers.is_empty()) {
|
||||
upstream_nested_layers.collect_metadata(metadata, footprint, None);
|
||||
}
|
||||
@@ -2883,23 +2962,23 @@ impl Render for RunView<'_, Graphic<'_>> {
|
||||
|
||||
impl Render for RunView<'_, Vector> {
|
||||
fn render_svg(&self, render: &mut SvgRender, render_params: &RenderParams) {
|
||||
render_vector_svg(self, render, render_params)
|
||||
render_vector_svg(self, None, render, render_params)
|
||||
}
|
||||
|
||||
fn render_to_vello(&self, scene: &mut Scene, parent_transform: DAffine2, context: &mut RenderContext, render_params: &RenderParams) {
|
||||
render_vector_vello(self, scene, parent_transform, context, render_params)
|
||||
render_vector_vello(self, None, scene, parent_transform, context, render_params)
|
||||
}
|
||||
|
||||
fn collect_metadata(&self, metadata: &mut RenderMetadata, footprint: Footprint, caller_element_id: Option<NodeId>) {
|
||||
collect_vector_metadata(self, metadata, footprint, caller_element_id)
|
||||
collect_vector_metadata(self, None, metadata, footprint, caller_element_id)
|
||||
}
|
||||
|
||||
fn add_upstream_click_targets(&self, click_targets: &mut Vec<ClickTarget>) {
|
||||
add_vector_upstream_click_targets(self, click_targets)
|
||||
add_vector_upstream_click_targets(self, None, click_targets)
|
||||
}
|
||||
|
||||
fn add_upstream_outline_targets(&self, outlines: &mut Vec<ClickTarget>) {
|
||||
add_vector_upstream_outline_targets(self, outlines)
|
||||
add_vector_upstream_outline_targets(self, None, outlines)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3038,7 +3117,6 @@ impl SvgRenderAttrs<'_> {
|
||||
mod group_walk_tests {
|
||||
use super::*;
|
||||
use core_types::record::{FieldWrite, RunBuilder, element_write_hashed};
|
||||
use graphic_types::markers::Fill;
|
||||
use graphic_types::vector_types::vector::PointId;
|
||||
|
||||
fn unit_square_at(corner: DVec2) -> Vector {
|
||||
@@ -3049,6 +3127,11 @@ mod group_walk_tests {
|
||||
List::new_from_element(Graphic::Color(Color::from_rgbaf32(0.8, 0.2, 0.33, 1.).unwrap()))
|
||||
}
|
||||
|
||||
/// The appearance the fill node stamps, so test content mirrors node output.
|
||||
fn fill_appearance(paint: &List<Graphic<'static>>) -> Appearance {
|
||||
Appearance::new_single(Coverage::new_fill(), Graphic::Graphic(paint.clone()))
|
||||
}
|
||||
|
||||
fn rendered_svg(render: impl FnOnce(&mut SvgRender)) -> (String, String) {
|
||||
let mut svg_render = SvgRender::new();
|
||||
render(&mut svg_render);
|
||||
@@ -3061,9 +3144,10 @@ mod group_walk_tests {
|
||||
let paint = color_paint();
|
||||
let vectors = [unit_square_at(DVec2::ZERO), unit_square_at(DVec2::new(3., 1.))];
|
||||
let arena = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
let mut builder = RunBuilder::new(&arena, element_write_hashed::<Vector>(), &[FieldWrite::of::<Fill>(0)], 2).unwrap();
|
||||
let appearance = fill_appearance(&paint);
|
||||
let mut builder = RunBuilder::new(&arena, element_write_hashed::<Vector>(), &[FieldWrite::of::<AppearanceMarker>(0)], 2).unwrap();
|
||||
let lane = builder.push(vectors[0].clone()).unwrap();
|
||||
builder.attr::<Fill>(lane, Some(&paint));
|
||||
builder.attr::<AppearanceMarker>(lane, Some(&appearance));
|
||||
builder.push(vectors[1].clone()).unwrap();
|
||||
let item = builder.finish();
|
||||
let group = Group { row: None, content: item };
|
||||
@@ -3080,9 +3164,10 @@ mod group_walk_tests {
|
||||
let paint = color_paint();
|
||||
let inner = Graphic::Vector(unit_square_at(DVec2::ZERO));
|
||||
let arena = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
let mut builder = RunBuilder::new(&arena, element_write_hashed::<Graphic>(), &[FieldWrite::of::<Fill>(0)], 1).unwrap();
|
||||
let appearance = fill_appearance(&paint);
|
||||
let mut builder = RunBuilder::new(&arena, element_write_hashed::<Graphic>(), &[FieldWrite::of::<AppearanceMarker>(0)], 1).unwrap();
|
||||
let lane = builder.push(inner.clone()).unwrap();
|
||||
builder.attr::<Fill>(lane, Some(&paint));
|
||||
builder.attr::<AppearanceMarker>(lane, Some(&appearance));
|
||||
let item = builder.finish();
|
||||
let group = Group { row: None, content: item };
|
||||
|
||||
@@ -3099,9 +3184,10 @@ mod group_walk_tests {
|
||||
let paint = color_paint();
|
||||
let vectors = [unit_square_at(DVec2::ZERO)];
|
||||
let arena = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
let mut builder = RunBuilder::new(&arena, element_write_hashed::<Vector>(), &[FieldWrite::of::<Fill>(0)], 1).unwrap();
|
||||
let appearance = fill_appearance(&paint);
|
||||
let mut builder = RunBuilder::new(&arena, element_write_hashed::<Vector>(), &[FieldWrite::of::<AppearanceMarker>(0)], 1).unwrap();
|
||||
let lane = builder.push(vectors[0].clone()).unwrap();
|
||||
builder.attr::<Fill>(lane, Some(&paint));
|
||||
builder.attr::<AppearanceMarker>(lane, Some(&appearance));
|
||||
let item = builder.finish();
|
||||
let group = Group { row: None, content: item };
|
||||
|
||||
@@ -3116,7 +3202,14 @@ mod group_walk_tests {
|
||||
assert!(native.local_transforms.contains_key(&caller));
|
||||
assert!(native.upstream_footprints.contains_key(&caller));
|
||||
assert_eq!(native.vector_data.get(&caller).map(|vector| vector.as_ref()), Some(&vectors[0]));
|
||||
assert!(native.fill_attributes.get(&caller).is_some_and(|fill| matches!(fill.element(0), Some(Graphic::Color(_)))));
|
||||
assert!(
|
||||
native
|
||||
.appearance_attributes
|
||||
.get(&caller)
|
||||
.and_then(|appearance| appearance.first_paint_of(graphic_types::appearance::Cover::Fill))
|
||||
.and_then(paint_cell_rows)
|
||||
.is_some_and(|fill| matches!(fill.element(0), Some(Graphic::Color(_))))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -3124,9 +3217,10 @@ mod group_walk_tests {
|
||||
let paint = color_paint();
|
||||
let vectors = [unit_square_at(DVec2::ZERO), unit_square_at(DVec2::new(2., 2.))];
|
||||
let arena = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
let mut builder = RunBuilder::new(&arena, element_write_hashed::<Vector>(), &[FieldWrite::of::<Fill>(0)], 2).unwrap();
|
||||
let appearance = fill_appearance(&paint);
|
||||
let mut builder = RunBuilder::new(&arena, element_write_hashed::<Vector>(), &[FieldWrite::of::<AppearanceMarker>(0)], 2).unwrap();
|
||||
let lane = builder.push(vectors[0].clone()).unwrap();
|
||||
builder.attr::<Fill>(lane, Some(&paint));
|
||||
builder.attr::<AppearanceMarker>(lane, Some(&appearance));
|
||||
builder.push(vectors[1].clone()).unwrap();
|
||||
let item = builder.finish();
|
||||
let group = Group { row: None, content: item };
|
||||
@@ -3143,4 +3237,57 @@ mod group_walk_tests {
|
||||
Graphic::Group(group).add_upstream_outline_targets(&mut native_outlines);
|
||||
assert_eq!(native_outlines, legacy);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stacked_paint_colors_composite_in_straight_alpha() {
|
||||
// A half-transparent red over an opaque blue lands halfway between the two
|
||||
let mut list = List::new();
|
||||
list.push(Item::new_from_element(Color::from_rgbaf32_unchecked(0., 0., 1., 1.)));
|
||||
list.push(Item::new_from_element(Color::from_rgbaf32_unchecked(1., 0., 0., 0.5)));
|
||||
|
||||
let composited = composite_paint_colors(&list, |color| Some(*color), false).expect("a non-empty paint list composites to a color");
|
||||
|
||||
assert!((composited.r() - 0.5).abs() < 1e-5, "red was {}", composited.r());
|
||||
assert!((composited.g() - 0.).abs() < 1e-5, "green was {}", composited.g());
|
||||
assert!((composited.b() - 0.5).abs() < 1e-5, "blue was {}", composited.b());
|
||||
assert!((composited.a() - 1.).abs() < 1e-5, "alpha was {}", composited.a());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stacked_paint_blending_interpolates_by_backdrop_coverage() {
|
||||
// Multiply over half-covering black only half-multiplies the red
|
||||
let mut list = List::new();
|
||||
list.push(Item::new_from_element(Color::from_rgbaf32_unchecked(0., 0., 0., 0.5)));
|
||||
list.push(Item::new_from_element(Color::from_rgbaf32_unchecked(1., 0., 0., 1.)).with_attribute(core_types::ATTR_BLEND_MODE, BlendMode::Multiply));
|
||||
|
||||
let composited = composite_paint_colors(&list, |color| Some(*color), false).expect("a non-empty paint list composites to a color");
|
||||
|
||||
assert!((composited.r() - 0.5).abs() < 1e-5, "red was {}", composited.r());
|
||||
assert!((composited.a() - 1.).abs() < 1e-5, "alpha was {}", composited.a());
|
||||
|
||||
// Multiply over no backdrop at all leaves the source color untouched
|
||||
let mut list = List::new();
|
||||
list.push(Item::new_from_element(Color::TRANSPARENT));
|
||||
list.push(Item::new_from_element(Color::from_rgbaf32_unchecked(1., 0., 0., 1.)).with_attribute(core_types::ATTR_BLEND_MODE, BlendMode::Multiply));
|
||||
|
||||
let composited = composite_paint_colors(&list, |color| Some(*color), false).expect("a non-empty paint list composites to a color");
|
||||
|
||||
assert!((composited.r() - 1.).abs() < 1e-5, "red was {}", composited.r());
|
||||
assert!((composited.a() - 1.).abs() < 1e-5, "alpha was {}", composited.a());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_paint_rows_own_opacity_fades_its_color() {
|
||||
let mut list = List::new();
|
||||
list.push(Item::new_from_element(Color::from_rgbaf32_unchecked(1., 0., 0., 1.)));
|
||||
list.set_attribute(core_types::ATTR_OPACITY, 0, 0.5_f64);
|
||||
list.set_attribute(core_types::ATTR_OPACITY_FILL, 0, 0.5_f64);
|
||||
|
||||
let composited = composite_paint_colors(&list, |color| Some(*color), false).expect("a non-empty paint list composites to a color");
|
||||
assert!((composited.a() - 0.25).abs() < 1e-5, "both opacities fade the paint, alpha was {}", composited.a());
|
||||
|
||||
// A masker drops the fill opacity so it cannot reach the content clipped to it
|
||||
let masked = composite_paint_colors(&list, |color| Some(*color), true).expect("a non-empty paint list composites to a color");
|
||||
assert!((masked.a() - 0.5).abs() < 1e-5, "the mask keeps only the plain opacity, alpha was {}", masked.a());
|
||||
}
|
||||
}
|
||||
@@ -13,11 +13,39 @@ core_types::attribute! {
|
||||
/// 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>;
|
||||
/// Stroke coverage's line thickness. Absent when equal to the stroke default.
|
||||
pub Weight("weight"): f64;
|
||||
/// Stroke coverage's dash lengths, alternating dash and gap. Absent when the pattern is solid.
|
||||
pub DashPattern("dash_pattern"): Option<&Vec<f64>>;
|
||||
/// Stroke coverage's phase offset into the dash pattern. Absent when equal to the stroke default.
|
||||
pub DashOffset("dash_offset"): f64;
|
||||
/// Stroke coverage's shape at open endpoints. Absent when equal to the stroke default.
|
||||
pub Cap("cap"): crate::vector::style::StrokeCap;
|
||||
/// Stroke coverage's corner curvature. Absent when equal to the stroke default.
|
||||
pub Join("join"): crate::vector::style::StrokeJoin;
|
||||
/// Stroke coverage's miter-to-bevel conversion threshold. Absent when equal to the stroke default.
|
||||
pub JoinMiterLimit("join_miter_limit"): f64 = 4.;
|
||||
/// Stroke coverage's alignment to the path centerline. Absent when equal to the stroke default.
|
||||
pub Align("align"): crate::vector::style::StrokeAlign;
|
||||
}
|
||||
|
||||
// The value types a name-generic attribute can name here, so a compile-time
|
||||
// named write or read reaches this crate's enums like any other plain value.
|
||||
core_types::named_value! {
|
||||
for crate::gradient::GradientSpreadMethod;
|
||||
for crate::gradient::GradientType;
|
||||
}
|
||||
|
||||
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;
|
||||
pub const ATTR_WEIGHT: &str = Weight::NAME;
|
||||
pub const ATTR_DASH_PATTERN: &str = DashPattern::NAME;
|
||||
pub const ATTR_DASH_OFFSET: &str = DashOffset::NAME;
|
||||
pub const ATTR_CAP: &str = Cap::NAME;
|
||||
pub const ATTR_JOIN: &str = Join::NAME;
|
||||
pub const ATTR_JOIN_MITER_LIMIT: &str = JoinMiterLimit::NAME;
|
||||
pub const ATTR_ALIGN: &str = Align::NAME;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
@@ -30,6 +58,24 @@ mod tests {
|
||||
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>>());
|
||||
assert_eq!(info("weight").unwrap().value_type, TypeId::of::<f64>());
|
||||
assert_eq!(info("dash_pattern").unwrap().value_type, TypeId::of::<Option<&'static Vec<f64>>>());
|
||||
assert_eq!(info("dash_offset").unwrap().value_type, TypeId::of::<f64>());
|
||||
assert_eq!(info("cap").unwrap().value_type, TypeId::of::<crate::vector::style::StrokeCap>());
|
||||
assert_eq!(info("join").unwrap().value_type, TypeId::of::<crate::vector::style::StrokeJoin>());
|
||||
assert_eq!(info("join_miter_limit").unwrap().value_type, TypeId::of::<f64>());
|
||||
assert_eq!(info("align").unwrap().value_type, TypeId::of::<crate::vector::style::StrokeAlign>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stroke_parameter_defaults_match_the_stroke_struct() {
|
||||
let defaults = crate::vector::style::Stroke::default();
|
||||
assert_eq!(<Weight as Attribute>::default(), defaults.weight);
|
||||
assert_eq!(<DashOffset as Attribute>::default(), defaults.dash_offset);
|
||||
assert_eq!(<JoinMiterLimit as Attribute>::default(), defaults.join_miter_limit);
|
||||
assert_eq!(<Cap as Attribute>::default(), defaults.cap);
|
||||
assert_eq!(<Join as Attribute>::default(), defaults.join);
|
||||
assert_eq!(<Align as Attribute>::default(), defaults.align);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -47,7 +47,7 @@ impl MergeByDistanceExt for Vector {
|
||||
// Collect points and segments to delete at the end to avoid invalidating indices
|
||||
let mut points_to_delete = FxHashSet::default();
|
||||
let mut segments_to_delete = FxHashSet::default();
|
||||
for (mut collapse_set, average_pos) in collapse.into_iter().zip(average_position.into_iter()) {
|
||||
for (mut collapse_set, average_pos) in collapse.into_iter().zip(average_position) {
|
||||
// Remove any segments where both endpoints are in the collapse set
|
||||
segments_to_delete.extend(self.segment_domain.iter().filter_map(|(id, start_offset, end_offset, _)| {
|
||||
let start = self.point_domain.ids()[start_offset];
|
||||
|
||||
@@ -201,6 +201,15 @@ fn daffine2_identity() -> DAffine2 {
|
||||
DAffine2::IDENTITY
|
||||
}
|
||||
|
||||
/// Whether a fill's gradient placement transform is explicitly set, as opposed to derived
|
||||
/// from the content's bounding box at evaluation. A newtype so the node input's name is
|
||||
/// fixed in the document format ahead of the transform toggle's own arrival.
|
||||
#[repr(C)]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, graphene_hash::CacheHash, DynAny)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct HasTransform(pub bool);
|
||||
|
||||
#[repr(C)]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Debug, Clone, PartialEq, graphene_hash::CacheHash, DynAny)]
|
||||
@@ -221,8 +230,6 @@ pub struct Stroke {
|
||||
pub align: StrokeAlign,
|
||||
#[cfg_attr(feature = "serde", serde(default = "daffine2_identity"))]
|
||||
pub transform: DAffine2,
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub paint_order: PaintOrder,
|
||||
}
|
||||
|
||||
impl Stroke {
|
||||
@@ -236,7 +243,6 @@ impl Stroke {
|
||||
join_miter_limit: 4.,
|
||||
align: StrokeAlign::Center,
|
||||
transform: DAffine2::IDENTITY,
|
||||
paint_order: PaintOrder::StrokeAbove,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -273,7 +279,6 @@ impl Stroke {
|
||||
let skew = DAffine2::from_cols_array(&[1., 0., lerp(s_skew, t_skew), 1., 0., 0.]);
|
||||
trs * skew
|
||||
},
|
||||
paint_order: if time < 0.5 { self.paint_order } else { other.paint_order },
|
||||
}
|
||||
}
|
||||
|
||||
@@ -401,7 +406,6 @@ impl Default for Stroke {
|
||||
join_miter_limit: 4.,
|
||||
align: StrokeAlign::Center,
|
||||
transform: DAffine2::IDENTITY,
|
||||
paint_order: PaintOrder::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,6 @@ use crate::vector::vector_modification::VectorExt;
|
||||
use core::borrow::Borrow;
|
||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::render_complexity::RenderComplexity;
|
||||
use core_types::transform::Transform;
|
||||
use dyn_any::StaticType;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use kurbo::{Affine, BezPath, Rect, Shape};
|
||||
@@ -18,8 +17,6 @@ use std::collections::HashMap;
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct Vector {
|
||||
pub stroke: Option<Stroke>,
|
||||
|
||||
/// A list of all manipulator groups (referenced in `subpaths`) that have colinear handles (where they're locked at 180° angles from one another).
|
||||
/// This gets read in `graph_operation_message_handler.rs` by calling `inputs.as_mut_slice()` (search for the string `"Shape does not have both `subpath` and `colinear_manipulators` inputs"` to find it).
|
||||
pub colinear_manipulators: Vec<[HandleId; 2]>,
|
||||
@@ -35,7 +32,6 @@ unsafe impl StaticType for Vector {
|
||||
impl Default for Vector {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
stroke: Some(Stroke::new(0.)),
|
||||
colinear_manipulators: Vec::new(),
|
||||
point_domain: PointDomain::new(),
|
||||
segment_domain: SegmentDomain::new(),
|
||||
@@ -49,7 +45,6 @@ impl graphene_hash::CacheHash for Vector {
|
||||
self.point_domain.cache_hash(state);
|
||||
self.segment_domain.cache_hash(state);
|
||||
self.region_domain.cache_hash(state);
|
||||
self.stroke.cache_hash(state);
|
||||
self.colinear_manipulators.cache_hash(state);
|
||||
}
|
||||
}
|
||||
@@ -239,10 +234,10 @@ impl Vector {
|
||||
/// identity (`Inside` = 0, `Outside` = 2×weight): the renderer masks half of a centered double-width
|
||||
/// stroke, so its AABB matches the unmasked centered stroke's. For open paths the renderer always
|
||||
/// draws a centered `weight`-wide stroke regardless of the align attribute, so we mirror that here.
|
||||
pub fn stroke_inclusive_bounding_box_with_transform(&self, transform: DAffine2) -> Option<[DVec2; 2]> {
|
||||
pub fn stroke_inclusive_bounding_box_with_transform(&self, transform: DAffine2, stroke: Option<&Stroke>) -> Option<[DVec2; 2]> {
|
||||
let path_bounds = self.bounding_box_with_transform(transform);
|
||||
|
||||
let Some(stroke) = self.stroke.as_ref() else { return path_bounds };
|
||||
let Some(stroke) = stroke else { return path_bounds };
|
||||
// Stroke alignment is only honored by the renderer when every subpath is closed; open paths fall
|
||||
// back to drawing a Center-aligned `weight`-wide stroke. Match that behavior to keep bounds in sync.
|
||||
let aligned_renders = stroke.align != StrokeAlign::Center && self.stroke_bezier_paths().all(|p| p.closed());
|
||||
@@ -530,40 +525,14 @@ impl Vector {
|
||||
self.segment_domain.concat(&additional.segment_domain, transform_of_additional, &id_map);
|
||||
self.region_domain.concat(&additional.region_domain, transform_of_additional, &id_map);
|
||||
|
||||
// TODO: properly deal with fills such as gradients
|
||||
self.stroke = additional.stroke.clone();
|
||||
|
||||
self.colinear_manipulators.extend(additional.colinear_manipulators.iter().copied());
|
||||
}
|
||||
|
||||
pub fn set_stroke_transform(&mut self, transform: DAffine2) {
|
||||
if let Some(stroke) = &mut self.stroke {
|
||||
stroke.transform = transform;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl BoundingBox for Vector {
|
||||
fn bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
|
||||
if !include_stroke {
|
||||
// Just use the path bounds without stroke
|
||||
return match self.bounding_box_with_transform(transform) {
|
||||
Some(bounds) => RenderBoundingBox::Rectangle(bounds),
|
||||
None => RenderBoundingBox::None,
|
||||
};
|
||||
}
|
||||
|
||||
// Include stroke by adding offset based on stroke width
|
||||
let stroke = self.stroke.clone();
|
||||
let stroke_width = stroke.as_ref().map(|s| s.weight()).unwrap_or_default();
|
||||
let miter_limit = stroke.as_ref().map(|s| s.join_miter_limit).unwrap_or(1.);
|
||||
let scale = transform.scale_magnitudes();
|
||||
|
||||
// Use the full line width to account for different styles of stroke caps
|
||||
let offset = DVec2::splat(stroke_width * scale.x.max(scale.y) * miter_limit);
|
||||
|
||||
fn bounding_box(&self, transform: DAffine2, _include_stroke: bool) -> RenderBoundingBox {
|
||||
match self.bounding_box_with_transform(transform) {
|
||||
Some([a, b]) => RenderBoundingBox::Rectangle([a - offset, b + offset]),
|
||||
Some(bounds) => RenderBoundingBox::Rectangle(bounds),
|
||||
None => RenderBoundingBox::None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,21 +129,19 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Flipped nodes carry their kernel generics as struct parameters: record
|
||||
// edges no longer bind them through `Output`, so the struct must. A
|
||||
// ranked input's element generic is carried on any node kind for the
|
||||
// same reason: the materialized view monomorphizes the kernel per row.
|
||||
// Flipped kernels, ranked-input element generics, and the generics a
|
||||
// record-io node's secondary inputs name must be carried as struct parameters.
|
||||
let ctx_ident_for_flip = context_param(parsed).map(|ctx| ctx.ident.clone());
|
||||
let ranked_carries = |ident: &Ident| {
|
||||
regular_fields.iter().any(|field| match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, list_levels, .. }) => *list_levels > 0 && type_contains_ident(ty, ident),
|
||||
let carries_generic = |ident: &Ident| {
|
||||
regular_fields.iter().enumerate().any(|(index, field)| match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, list_levels, .. }) => (*list_levels > 0 || (record_io && index > 0)) && type_contains_ident(ty, ident),
|
||||
_ => false,
|
||||
})
|
||||
};
|
||||
let carried_generics: Vec<&syn::GenericParam> = fn_generics
|
||||
.iter()
|
||||
.filter(|param| match param {
|
||||
syn::GenericParam::Type(tp) => Some(&tp.ident) != ctx_ident_for_flip.as_ref() && !data_field_generic_idents.contains(&tp.ident) && (flip || ranked_carries(&tp.ident)),
|
||||
syn::GenericParam::Type(tp) => Some(&tp.ident) != ctx_ident_for_flip.as_ref() && !data_field_generic_idents.contains(&tp.ident) && (flip || carries_generic(&tp.ident)),
|
||||
_ => false,
|
||||
})
|
||||
.collect();
|
||||
@@ -199,7 +197,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
let field_pushed_levels: Vec<u8> = regular_fields
|
||||
.iter()
|
||||
.map(|field| match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { list_levels, .. }) if *list_levels > 0 => *list_levels as u8,
|
||||
ParsedFieldType::Regular(RegularParsedField { list_levels, .. }) if *list_levels > 0 => *list_levels,
|
||||
ParsedFieldType::Node(_) => pushed_levels,
|
||||
_ => 0,
|
||||
})
|
||||
@@ -242,6 +240,18 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
let slot = format_ident!("__read_{index}");
|
||||
quote!(pub(super) #slot: Option<usize>)
|
||||
}));
|
||||
// A name-generic read carries the folded name's own default beside its
|
||||
// offset, since its marker names the value type but not the name.
|
||||
state.extend(
|
||||
field_reads(&struct_regular_fields)
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, (_, read))| crate::parsing::named_marker(&read.marker).is_some())
|
||||
.map(|(index, _)| {
|
||||
let slot = format_ident!("__read_default_{index}");
|
||||
quote!(pub(super) #slot: Option<::std::boxed::Box<[u8]>>)
|
||||
}),
|
||||
);
|
||||
state.extend((0..node.output.shape.attrs.len()).map(|index| {
|
||||
let slot = format_ident!("__write_{index}");
|
||||
quote!(pub(super) #slot: usize)
|
||||
@@ -433,8 +443,8 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
register_metadata();
|
||||
}
|
||||
};
|
||||
// Record nodes construct through the generated `wire` fn, which resolves
|
||||
// offsets from the carrier layout; `new` cannot fill that state.
|
||||
// Record nodes construct through `new` with the carrier layout, which
|
||||
// resolves the offsets their reads and writes address.
|
||||
let routing_layout_param = (routing_generic.is_some() || opaque).then(|| quote!(__layout: &gcore::record::Layout,)).into_iter();
|
||||
let routing_layout_init = (routing_generic.is_some() || opaque).then(|| quote!(__layout: __layout.clone(),)).into_iter();
|
||||
// The lane-invariance mask arrives with the resolved layout, so `new` starts
|
||||
@@ -730,7 +740,7 @@ pub(crate) struct NodePlan {
|
||||
|
||||
/// The field and generic derivation shared by the struct/metadata side and the
|
||||
/// impl side, computed once in [`generate_node_code`] and passed to
|
||||
/// [`generate_node_impl`]. `regular_fields` is the carrier-skipped slice both
|
||||
/// [`generate_node_impl`]. `regular_fields` is the non-data field slice both
|
||||
/// sides agree on.
|
||||
pub(crate) struct NodeFields<'a> {
|
||||
pub(crate) data_fields: Vec<&'a ParsedField>,
|
||||
@@ -798,7 +808,9 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
// its generic stays a struct parameter.
|
||||
let record_token = match (kind, &node.output.shape.element) {
|
||||
(crate::codegen::ir::NodeKind::RecordIo, crate::codegen::ir::Element::Generic(ident)) if !gather_carrier => Some(ident.clone()),
|
||||
_ => None,
|
||||
// An opaque reading input's element is byte-carried the same way, even
|
||||
// though the output replaces it rather than carrying it through.
|
||||
_ => crate::codegen::classify::opaque_reading_carrier(parsed),
|
||||
};
|
||||
// The record-io write set, resolved from the output item and carrier input.
|
||||
let write_markers: Vec<&Type> = node.output.shape.attrs.iter().map(|attr| &attr.marker).collect();
|
||||
@@ -880,7 +892,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
})
|
||||
});
|
||||
let derive_routing = derives && routing_generic.is_some();
|
||||
// A kernel that holds records (a forwarded routing wire, or a lazy edge it
|
||||
// A kernel that holds records (a forwarded routing source, or a lazy input it
|
||||
// serves itself) names the record lifetime; unless it declared a serving
|
||||
// lifetime of its own, the context binds the arena at that lifetime.
|
||||
let kernel_lazy = parsed.fields.iter().any(|field| !field.is_data_field && matches!(field.ty, ParsedFieldType::Node(_)));
|
||||
@@ -937,7 +949,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
})
|
||||
.map(|param| match param {
|
||||
// Flipped kernels clone bare-typed elements out of their records,
|
||||
// so those generics carry the bound wire values satisfy; a
|
||||
// so those generics carry the bound input values satisfy; a
|
||||
// generic only nested in a field's type stays as declared.
|
||||
GenericParam::Type(type_param)
|
||||
if flip
|
||||
@@ -982,6 +994,11 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
let output_type = &parsed.output_type;
|
||||
let raw_lazy = matches!(*model, Dialect::Poll);
|
||||
let injected_name = |ident: &Ident| async_source && (ident == "_runtime" || ident == "_source");
|
||||
// A name input declares where a placeholder's name is wired and nothing
|
||||
// more: the name is spent resolving the layout when the graph compiles, so
|
||||
// it reaches neither the kernel's parameters nor its call. The wire input
|
||||
// stays, since the fold reads the constant off it.
|
||||
let kernel_omits = |field: &ParsedField| injected_name(&field.pat_ident.ident) || matches!(&field.ty, ParsedFieldType::Regular(RegularParsedField { name_source: Some(_), .. }));
|
||||
let where_predicates: Vec<TokenStream2> = parsed.where_clause.iter().flat_map(|clause| clause.predicates.iter()).map(|predicate| quote!(#predicate)).collect();
|
||||
|
||||
let NodeFields {
|
||||
@@ -1001,7 +1018,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
if routing_generic.as_ref().is_some_and(|generic| crate::codegen::classify::routing_source_output(source_ty, generic)) {
|
||||
let source_generic = format_ident!("__Source{index}");
|
||||
generics.push(quote! {
|
||||
#source_generic: for<'__derived> #core_types::record::DerivedRecordEdge<'__derived, #core_types::context::Derived<'__derived, #ctx_ident>>
|
||||
#source_generic: for<'__derived> #core_types::record::DerivedRecordInput<'__derived, #core_types::context::Derived<'__derived, #ctx_ident>>
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1009,7 +1026,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
if lazy_carrier && derives {
|
||||
let source_generic = format_ident!("__Source0");
|
||||
generics.push(quote! {
|
||||
#source_generic: for<'__derived> #core_types::record::DerivedRecordEdge<'__derived, #core_types::context::Derived<'__derived, #ctx_ident>>
|
||||
#source_generic: for<'__derived> #core_types::record::DerivedRecordInput<'__derived, #core_types::context::Derived<'__derived, #ctx_ident>>
|
||||
});
|
||||
}
|
||||
if flip {
|
||||
@@ -1017,7 +1034,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
if matches!(&field.ty, ParsedFieldType::Node(_)) {
|
||||
let source_generic = format_ident!("__Source{index}");
|
||||
let derived_extra = derives
|
||||
.then(|| quote!(+ for<'__derived> #core_types::record::DerivedRecordEdge<'__derived, #core_types::context::Derived<'__derived, #ctx_ident>>))
|
||||
.then(|| quote!(+ for<'__derived> #core_types::record::DerivedRecordInput<'__derived, #core_types::context::Derived<'__derived, #ctx_ident>>))
|
||||
.into_iter();
|
||||
generics.push(quote! {
|
||||
#source_generic: #core_types::node::Node<#ctx_ident> #(#derived_extra)*
|
||||
@@ -1030,7 +1047,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
if matches!(&field.ty, ParsedFieldType::Node(_)) && matches!(crate::codegen::ir::lazy_binding(&node, index), LazyBinding::Element) {
|
||||
let source_generic = format_ident!("__Source{index}");
|
||||
let derived_extra = derives
|
||||
.then(|| quote!(+ for<'__derived> #core_types::record::DerivedRecordEdge<'__derived, #core_types::context::Derived<'__derived, #ctx_ident>>))
|
||||
.then(|| quote!(+ for<'__derived> #core_types::record::DerivedRecordInput<'__derived, #core_types::context::Derived<'__derived, #ctx_ident>>))
|
||||
.into_iter();
|
||||
generics.push(quote! {
|
||||
#source_generic: #core_types::node::Node<#ctx_ident> #(#derived_extra)*
|
||||
@@ -1046,7 +1063,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
}
|
||||
}
|
||||
}
|
||||
// The record lifetime the kernel's wire types and arena bound name; the
|
||||
// The record lifetime the kernel's input types and arena bound name; the
|
||||
// impl infers it from the serving lifetime at every call.
|
||||
if wants_record_lifetime {
|
||||
generics.insert(0, quote!('__record));
|
||||
@@ -1061,7 +1078,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
quote!(#pat: &#ty)
|
||||
});
|
||||
|
||||
let derived_edge = quote!(for<'__derived> #core_types::record::DerivedRecordEdge<'__derived, #core_types::context::Derived<'__derived, #ctx_ident>>);
|
||||
let derived_edge = quote!(for<'__derived> #core_types::record::DerivedRecordInput<'__derived, #core_types::context::Derived<'__derived, #ctx_ident>>);
|
||||
let lazy_bound = || match derives {
|
||||
true => {
|
||||
let derived_edge = derived_edge.clone();
|
||||
@@ -1090,7 +1107,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
});
|
||||
quote!((#value_param #(, #read_pats)*): (#value_ty #(, #read_tys)*))
|
||||
};
|
||||
let kernel_params = regular_fields.iter().enumerate().filter(|(_, field)| !injected_name(&field.pat_ident.ident)).map(|(index, field)| {
|
||||
let kernel_params = regular_fields.iter().enumerate().filter(|(_, field)| !kernel_omits(field)).map(|(index, field)| {
|
||||
let pat = &field.pat_ident;
|
||||
match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) if ir::materialized_levels(&node, index) > 0 => {
|
||||
@@ -1134,10 +1151,10 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
let out = lazy_read_out(field, output_type);
|
||||
quote!(#pat: #core_types::record::DerivedLazyInput<'_, #frames_lifetime, #out, #source_generic>)
|
||||
}
|
||||
(LazyBinding::OpaqueRecord, _) => quote!(#pat: &#core_types::record::RecordEdgeInput<'_, #frames_lifetime, #source_generic>),
|
||||
(LazyBinding::OpaqueRecord, _) => quote!(#pat: &#core_types::record::RecordInput<'_, #frames_lifetime, #source_generic>),
|
||||
(LazyBinding::Element, true) => {
|
||||
let out = lazy_read_out(field, output_type);
|
||||
quote!(#pat: &#core_types::record::ElementEdge<'_, #frames_lifetime, #out, #source_generic>)
|
||||
quote!(#pat: &#core_types::record::ElementInput<'_, #frames_lifetime, #out, #source_generic>)
|
||||
}
|
||||
(LazyBinding::Element, false) => {
|
||||
let out = lazy_read_out(field, output_type);
|
||||
@@ -1158,7 +1175,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
|
||||
let node_bounds = regular_fields.iter().enumerate().zip(&node_generics).map(|((index, field), node_generic)| {
|
||||
let plain = quote!(#node_generic: #core_types::node::Node<#ctx_ident>);
|
||||
// A lazy edge the kernel evaluates at derived contexts needs the
|
||||
// A lazy input the kernel evaluates at derived contexts needs the
|
||||
// derived form: the derived context's arena binding is unnameable
|
||||
// under a higher rank.
|
||||
let derived = quote!(#node_generic: #derived_edge);
|
||||
@@ -1175,7 +1192,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
true => derived,
|
||||
false => plain,
|
||||
},
|
||||
// An element-consuming lazy secondary rides a record edge, derivable
|
||||
// An element-consuming lazy secondary rides a record input, derivable
|
||||
// when the kernel evaluates it at derived contexts.
|
||||
ParsedFieldType::Node(_) if record_io && matches!(ir::lazy_binding(&node, index), LazyBinding::Element) => match derives {
|
||||
true => derived_plus,
|
||||
@@ -1190,8 +1207,8 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
let bound = lazy_bound();
|
||||
quote!(#node_generic: #bound)
|
||||
}
|
||||
// Every wire is a record edge; a value input's element copies out of
|
||||
// the record its edge serves.
|
||||
// Every input is a record input; a value input's element copies out of
|
||||
// the record its source serves.
|
||||
ParsedFieldType::Regular(_) => plain,
|
||||
}
|
||||
});
|
||||
@@ -1204,7 +1221,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
lend_outlives.push(quote!(#inner: #lifetime));
|
||||
}
|
||||
|
||||
// The slot persists the plain value even on record wires, so the Clone
|
||||
// The slot persists the plain value even on record inputs, so the Clone
|
||||
// bound targets the slot type, not the (possibly lifted) trait output.
|
||||
let slot_ty = crate::codegen::classify::slot_static_type(&parsed.output_type);
|
||||
let mut async_bounds = match (async_fn, future_kernel) {
|
||||
@@ -1241,7 +1258,15 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
let read_binding = |slot: usize, read: &AttributeRead, rec: TokenStream2| {
|
||||
let pat = &read.pat_ident;
|
||||
let marker = &read.marker;
|
||||
let default_slot = format_ident!("__read_default_{slot}");
|
||||
let slot = format_ident!("__read_{slot}");
|
||||
// A name-generic marker carries the value type but not the name, so it
|
||||
// cannot know the name's own default; the compiler supplies it.
|
||||
if crate::parsing::named_marker(marker).is_some() {
|
||||
return quote! {
|
||||
let #pat = unsafe { #core_types::record::read_at_defaulting::<#marker>(#rec, self.#slot, self.#default_slot.as_deref()) };
|
||||
};
|
||||
}
|
||||
quote! {
|
||||
let #pat = unsafe { #core_types::record::read_at::<#marker>(#rec, self.#slot) };
|
||||
}
|
||||
@@ -1265,8 +1290,11 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
#[allow(unused_mut, unused_variables)]
|
||||
let mut __frame = __run.slot(__lane, &__lane_frames);
|
||||
};
|
||||
// A lazy edge claims beyond every input frame this node holds, and its
|
||||
// cursor is shared, so the edges a kernel drives claim past each other.
|
||||
// A lazy input claims beyond every input frame this node holds, and its
|
||||
// cursor is shared, so the inputs a kernel drives claim past each other.
|
||||
// The snapshot copies the cursor where it stands, so every frame the node
|
||||
// still reads after the kernel runs (the carrier's included) must have been
|
||||
// claimed before it.
|
||||
let lazy_frames_entry = quote! {
|
||||
let __lazy_frames = __frame.frames().reborrow();
|
||||
};
|
||||
@@ -1298,7 +1326,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
let non_exact = fail(quote!(#core_types::gpoll::GraphError::new(::std::concat!("reduce over a non-exact extent in ", ::std::stringify!(#fn_name)))));
|
||||
let batch_error = fail(quote!(__error));
|
||||
let batch_failed = fail(quote!(#core_types::gpoll::GraphError::new("reduce batch failed")));
|
||||
// A fold consumes the whole subject wire: a deeper wire's
|
||||
// A fold consumes the whole subject input: a deeper input's
|
||||
// total flat span, sized under the evaluation context, so a
|
||||
// fold inside a pushed level covers that copy's span. The
|
||||
// span caches per (lane-normalized context, generation):
|
||||
@@ -1371,7 +1399,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
let #name = unsafe { #core_types::node::List::<#ty>::new(__batch) };
|
||||
}
|
||||
}
|
||||
// A reading secondary input claims a record edge: the element and
|
||||
// A reading secondary input claims a record input: the element and
|
||||
// the declared reads copy out right after its eval.
|
||||
ValueBinding::ReadingSecondary => {
|
||||
let slot = format_ident!("__in_{index}");
|
||||
@@ -1400,9 +1428,8 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
let #name = unsafe { #core_types::record::borrow_element::<#ty>(self.#slot.rec(&#record_local)) };
|
||||
}
|
||||
}
|
||||
// A flip value or a routing non-source value rides a record edge; the
|
||||
// element copies out into `name`. The mark/rewind that reclaims the
|
||||
// record's frame is applied by the step lowering (see `reads_out`).
|
||||
// A flip value or a routing non-source value rides a record input; the
|
||||
// element copies out into `name`.
|
||||
ValueBinding::RecordElement => {
|
||||
let slot = format_ident!("__in_{index}");
|
||||
quote! {
|
||||
@@ -1413,8 +1440,8 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
let #name: #ty = unsafe { #core_types::record::read_element(self.#slot.rec(&#name)) };
|
||||
}
|
||||
}
|
||||
// A plain value rides a record edge like every other input; the
|
||||
// element copies out against the edge's own layout, except for a
|
||||
// A plain value rides a record input like every other input; the
|
||||
// element copies out against the input's own layout, except for a
|
||||
// routing source, whose record is what the kernel forwards.
|
||||
ValueBinding::Plain => {
|
||||
let read = (!routing_source(ty)).then(|| {
|
||||
@@ -1434,7 +1461,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
}
|
||||
},
|
||||
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => match (ir::lazy_binding(&node, index), raw_lazy) {
|
||||
// A raw poll edge is threaded straight through, so it does not bind here.
|
||||
// A raw poll input is threaded straight through, so it does not bind here.
|
||||
(LazyBinding::Generic, true) => quote!(),
|
||||
(LazyBinding::DeriveRouting, _) => quote! {
|
||||
let #name = #core_types::record::RecordLazyInput::new(&self.#name, &__cell, #index, self.__layout.depth.saturating_sub(#pushed_levels), &__lazy_frames);
|
||||
@@ -1459,13 +1486,13 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
let slot = format_ident!("__in_{index}");
|
||||
match field.attribute_reads.is_empty() {
|
||||
true => quote! {
|
||||
let #name = #core_types::record::ElementEdge::<#output_type, _>::new(&self.#name, &self.#slot, &__lazy_frames);
|
||||
let #name = #core_types::record::ElementInput::<#output_type, _>::new(&self.#name, &self.#slot, &__lazy_frames);
|
||||
},
|
||||
false => {
|
||||
let arr = format_ident!("__reads_{index}");
|
||||
let read_fn = format_ident!("__{}_read_{}", fn_name, index);
|
||||
quote! {
|
||||
let #name = #core_types::record::ElementEdge::with_reads(&self.#name, &self.#slot, &self.#arr, self::#read_fn, &__lazy_frames);
|
||||
let #name = #core_types::record::ElementInput::with_reads(&self.#name, &self.#slot, &self.#arr, self::#read_fn, &__lazy_frames);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1486,7 +1513,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
}
|
||||
}
|
||||
(LazyBinding::OpaqueRecord, _) => quote! {
|
||||
let #name = #core_types::record::RecordEdgeInput::new(&self.#name, &self.__layout, &__lazy_frames);
|
||||
let #name = #core_types::record::RecordInput::new(&self.#name, &self.__layout, &__lazy_frames);
|
||||
},
|
||||
(LazyBinding::Generic, false) => quote! {
|
||||
let #name = #core_types::node::LazyInput::new(&self.#name, &__cell, #index, &__lazy_frames);
|
||||
@@ -1495,7 +1522,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
}
|
||||
};
|
||||
|
||||
// A bind whose element copies out reclaims the edge's frame; a forwarded
|
||||
// A bind whose element copies out reclaims the input's frame; a forwarded
|
||||
// record must outlive the bind, so its frame stays.
|
||||
let _reads_out_at = |index: usize| match ®ular_fields[index].ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => !routing_source(ty) && ir::value_binding(&node, index).reads_out(),
|
||||
@@ -1517,10 +1544,10 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
(!tokens.is_empty()).then_some(tokens)
|
||||
};
|
||||
|
||||
let call_args = regular_fields.iter().enumerate().filter(|(_, field)| !injected_name(&field.pat_ident.ident)).map(|(index, field)| {
|
||||
let call_args = regular_fields.iter().enumerate().filter(|(_, field)| !kernel_omits(field)).map(|(index, field)| {
|
||||
let name = &field.pat_ident.ident;
|
||||
match &field.ty {
|
||||
// A lend param binds an owned edge; the kernel borrows the
|
||||
// A lend param binds an owned input; the kernel borrows the
|
||||
// evaluated value.
|
||||
ParsedFieldType::Regular(RegularParsedField { lend: Some(_), .. }) if !flip => quote!(&#name),
|
||||
ParsedFieldType::Regular(_) => quote!(#name),
|
||||
@@ -1533,10 +1560,9 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
});
|
||||
|
||||
// The extent override is the leveled `extent_at`; consumers query the
|
||||
// composite `extent(ctx, Level)`, which the trait derives from it. A node
|
||||
// without `extent = fn` keeps the scalar default (one item at every level).
|
||||
// composite `extent(ctx, Level)`, which the trait derives from it.
|
||||
// The typed extent surface: the node's inputs in declaration order (values
|
||||
// readable without unsafe, edges as per-level extent queries, derived
|
||||
// readable without unsafe, inputs as per-level extent queries, derived
|
||||
// content promoted per copy), then the level paired with the node's depth.
|
||||
let extent_impl = if let Some(path) = &parsed.attributes.extent {
|
||||
let mut arg_decls: Vec<TokenStream2> = Vec::new();
|
||||
@@ -1560,14 +1586,14 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
let #query = |__copy: u64, __lvl: u8| {
|
||||
let mut __frame = #core_types::context::IndexLink { index: 0, outer: None };
|
||||
let __derived = #core_types::context::DeriveCtx::push_level(__input, &mut __frame, __copy, 0);
|
||||
#core_types::record::DerivedRecordEdge::extent_at_derived(&self.#name, &__derived, __lvl, &__frames.scope())
|
||||
#core_types::record::DerivedRecordInput::extent_at_derived(&self.#name, &__derived, __lvl, &__frames.scope())
|
||||
};
|
||||
let #arg = #core_types::extent::ExtentIn::new(&#query);
|
||||
},
|
||||
_ => extent_edge(&query, &arg),
|
||||
},
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => match ir::value_binding(&node, index) {
|
||||
// A ranked input materializes whole (the wire's total flat
|
||||
// A ranked input materializes whole (the input's total flat
|
||||
// span, as in eval), so a data-dependent extent can walk
|
||||
// its lanes.
|
||||
ValueBinding::Materialized => {
|
||||
@@ -1605,17 +1631,17 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
};
|
||||
quote! {
|
||||
let #query = || {
|
||||
// The element copies out by value, so the edge's
|
||||
// The element copies out by value, so the input's
|
||||
// claim dies with the query.
|
||||
let __scope = __frames.scope();
|
||||
#core_types::record::serve_edge(&self.#name, __input, &__scope)
|
||||
#core_types::record::serve_input(&self.#name, __input, &__scope)
|
||||
.map(|__value| unsafe { #core_types::record::read_element::<#ty>(#layout.rec(&__value)) })
|
||||
};
|
||||
let #arg = #core_types::extent::ValueIn::new(&#query);
|
||||
}
|
||||
}
|
||||
// A carrier, lent, or materialized ranked input is a record
|
||||
// edge; its extents are the queryable quantity.
|
||||
// input; its extents are the queryable quantity.
|
||||
_ => extent_edge(&query, &arg),
|
||||
},
|
||||
};
|
||||
@@ -1652,7 +1678,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
let __query = |_: u64, __lvl: u8| {
|
||||
let __head = #core_types::context::DeriveCtx::index_head(__input);
|
||||
let __derived = #core_types::context::DeriveCtx::replaced(__input, __head.index);
|
||||
#core_types::record::DerivedRecordEdge::extent_at_derived(&self.#name, &__derived, __lvl, &__frames.scope())
|
||||
#core_types::record::DerivedRecordInput::extent_at_derived(&self.#name, &__derived, __lvl, &__frames.scope())
|
||||
};
|
||||
},
|
||||
_ => quote! {
|
||||
@@ -1718,12 +1744,17 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
let fn_where = &parsed.where_clause;
|
||||
let body = if level_delta > 0 { rewrite_emit(&parsed.body) } else { parsed.body.clone() };
|
||||
let vis = &parsed.vis;
|
||||
let kernel_fields: Vec<&&ParsedField> = regular_fields.iter().filter(|field| !injected_name(&field.pat_ident.ident)).collect();
|
||||
// The input index rides along: an async kernel's param type depends on the
|
||||
// field's value binding, which is indexed off the node's inputs.
|
||||
let kernel_indexed: Vec<(usize, &&ParsedField)> = regular_fields.iter().enumerate().filter(|(_, field)| !kernel_omits(field)).collect();
|
||||
let kernel_fields: Vec<&&ParsedField> = kernel_indexed.iter().map(|(_, field)| *field).collect();
|
||||
// A bare `Attr<M>` in the return type cannot elide its lifetime, so the
|
||||
// kernel gets a fresh one; reference-valued writes name their real
|
||||
// lifetime explicitly and pass through untouched. An async source's value
|
||||
// outlives the evaluation, so its writes are `'static` instead.
|
||||
let attr_injected = record_io.then(|| inject_attr_lifetimes(&parsed.output_type, if async_source { "'static" } else { "'__attr" })).flatten();
|
||||
let attr_injected = record_io
|
||||
.then(|| inject_attr_lifetimes(&parsed.output_type, if async_source { "'static" } else { "'__attr" }))
|
||||
.flatten();
|
||||
let attr_lifetime = (attr_injected.is_some() && !async_source).then(|| quote!('__attr,));
|
||||
let lane_injected = gather_carrier
|
||||
.then(|| crate::codegen::classify::inject_lane_lifetime(attr_injected.as_ref().unwrap_or(&parsed.output_type)))
|
||||
@@ -1758,12 +1789,18 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
};
|
||||
quote!(#pat: #ty)
|
||||
});
|
||||
let value_kernel_params = kernel_fields.iter().map(|field| {
|
||||
let value_kernel_params = kernel_indexed.iter().map(|(index, field)| {
|
||||
let pat = &field.pat_ident;
|
||||
let ParsedFieldType::Regular(RegularParsedField { ty, .. }) = &field.ty else {
|
||||
unreachable!("async source fields are eager values");
|
||||
};
|
||||
quote!(#pat: #ty)
|
||||
// A materialized level is a borrowed arena view, which cannot cross
|
||||
// into a `'static` future; the prologue snapshots it to the owned
|
||||
// legacy list and the kernel takes that instead.
|
||||
match ir::materialized_levels(&node, *index) > 0 {
|
||||
true => quote!(#pat: #core_types::list::List<#ty>),
|
||||
false => quote!(#pat: #ty),
|
||||
}
|
||||
});
|
||||
let params = snapshot_param.chain(data_kernel_params).chain(value_kernel_params);
|
||||
quote! {
|
||||
@@ -1811,6 +1848,17 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
.filter(|field| matches!(field.ty, ParsedFieldType::Regular(_)))
|
||||
.map(|field| &field.pat_ident.ident)
|
||||
.collect();
|
||||
let tail_form = if async_fn {
|
||||
Tail::SpawnAsyncFn
|
||||
} else if future_kernel {
|
||||
Tail::SpawnFuture
|
||||
} else {
|
||||
match ir::node_kind(&node) {
|
||||
ir::NodeKind::RecordIo => Tail::Record,
|
||||
ir::NodeKind::Flip => Tail::Flip,
|
||||
ir::NodeKind::Routing | ir::NodeKind::Opaque => Tail::Forward,
|
||||
}
|
||||
};
|
||||
// A carried tail claims the node's frame first, evaluates the carrier
|
||||
// beyond it, and carries its fields; every exit closes the frame through
|
||||
// `lift_poll_into`.
|
||||
@@ -1854,19 +1902,64 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
}
|
||||
})
|
||||
});
|
||||
// A record tail's carrier claim, the one the plan and the kernel read
|
||||
// `__src_rec` out of.
|
||||
let carrier_eval = (record_io && !skips_carrier && !lazy_carrier).then(|| {
|
||||
let name = ®ular_fields[0].pat_ident.ident;
|
||||
quote! {
|
||||
let __src = match __cell.eval_input(0, &self.#name, __input, __frame.frames()) {
|
||||
Ok(value) => value,
|
||||
Err(interrupt) => return interrupt.into()
|
||||
};
|
||||
let __src_rec = self.__carrier.rec(&__src);
|
||||
}
|
||||
});
|
||||
// The carrier's record stays claimed and readable through the kernel call, so
|
||||
// its claim runs before the lazy snapshot and the lazy handles claim past it
|
||||
// rather than over it. With no lazy input there is no snapshot and the claim
|
||||
// stays in the tail.
|
||||
let has_lazy = regular_fields.iter().any(|field| matches!(field.ty, ParsedFieldType::Node(_)));
|
||||
let hoisted_carrier = match (has_lazy, tail_form) {
|
||||
(false, _) => TokenStream2::new(),
|
||||
(true, Tail::Record) => carrier_eval.clone().unwrap_or_default(),
|
||||
(true, _) => carried_prelude.clone().unwrap_or_default(),
|
||||
};
|
||||
let carried_prelude = match has_lazy {
|
||||
true => None,
|
||||
false => carried_prelude,
|
||||
};
|
||||
let carrier_eval = match has_lazy {
|
||||
true => None,
|
||||
false => carrier_eval,
|
||||
};
|
||||
let lazy_entry = quote!(#hoisted_carrier #lazy_frames_entry);
|
||||
// Async slots persist plain values across evaluations; the source lifts
|
||||
// the slot value onto its record wire at every merge point, into the
|
||||
// the slot value onto its record input at every merge point, into the
|
||||
// carried frame when the node has a carrier.
|
||||
// A writing source stores the kernel's whole tuple as that plain value:
|
||||
// the lift writes the attributes through the claim, then lifts the
|
||||
// element, the shape the sync record tail closes with.
|
||||
// element, the shape the sync record tail closes with. An owned crossing
|
||||
// parks into the serving arena first, so its exhaustion is a poll.
|
||||
let source_writes = (record_io && async_source && !write_markers.is_empty()).then(|| {
|
||||
let binders: Vec<Ident> = (0..write_markers.len()).map(|index| format_ident!("__attr_{index}")).collect();
|
||||
let slots: Vec<Ident> = (0..write_markers.len()).map(|index| format_ident!("__write_{index}")).collect();
|
||||
let stores = node.output.shape.attrs.iter().enumerate().map(|(index, attr)| {
|
||||
let binder = &binders[index];
|
||||
let slot = format_ident!("__write_{index}");
|
||||
match attr.owned {
|
||||
false => quote!(unsafe { __frame.attr_at(self.#slot, #binder.0) };),
|
||||
true => quote! {
|
||||
let #binder = match #binder.park(#core_types::context::ExtractArena::arena(__input)) {
|
||||
::core::option::Option::Some(value) => value,
|
||||
::core::option::Option::None => return #core_types::gpoll::GPoll::arena_exhausted(),
|
||||
};
|
||||
unsafe { __frame.attr_at(self.#slot, #binder) };
|
||||
},
|
||||
}
|
||||
});
|
||||
quote! {
|
||||
.map(|(__element #(, #core_types::attribute::Attr(#binders))*)| {
|
||||
#(unsafe { __frame.attr_at(self.#slots, #binders) };)*
|
||||
__element
|
||||
.and_then(|(__element #(, #binders)*)| {
|
||||
#(#stores)*
|
||||
#core_types::gpoll::GPoll::Final(__element)
|
||||
})
|
||||
}
|
||||
});
|
||||
@@ -1946,26 +2039,16 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
Some(tuple_arg(regular_fields[0], quote!(#core_types::record::ElToken)))
|
||||
}
|
||||
.into_iter();
|
||||
let value_args = regular_fields.iter().skip(if skips_carrier { 0 } else { 1 }).map(|field| {
|
||||
let value_args = regular_fields.iter().skip(if skips_carrier { 0 } else { 1 }).filter(|field| !kernel_omits(field)).map(|field| {
|
||||
let name = &field.pat_ident.ident;
|
||||
match &field.ty {
|
||||
// A lend param binds an owned edge; the kernel borrows the
|
||||
// A lend param binds an owned input; the kernel borrows the
|
||||
// evaluated value.
|
||||
ParsedFieldType::Regular(RegularParsedField { lend: Some(_), .. }) => quote!(&#name),
|
||||
_ => tuple_arg(field, quote!(#name)),
|
||||
}
|
||||
});
|
||||
let record_kernel_call = quote!(self::#fn_name(__input #(, &self.#data_names)* #(, #carrier_arg)* #(, #value_args)*));
|
||||
let carrier_eval = (!skips_carrier && !lazy_carrier).then(|| {
|
||||
let name = ®ular_fields[0].pat_ident.ident;
|
||||
quote! {
|
||||
let __src = match __cell.eval_input(0, &self.#name, __input, __frame.frames()) {
|
||||
Ok(value) => value,
|
||||
Err(interrupt) => return interrupt.into()
|
||||
};
|
||||
let __src_rec = self.__carrier.rec(&__src);
|
||||
}
|
||||
});
|
||||
let carry = (!skips_carrier && !lazy_carrier).then(|| quote!(unsafe { __frame.carry(__src_rec, &self.__plan) };));
|
||||
// A lazy carrier's source record is the token the kernel returned; its
|
||||
// content frames sit above the claim and stay readable until its drop.
|
||||
@@ -2087,28 +2170,37 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
__cell.merge(__frame.lift_served(#core_types::gpoll::GPoll::Final(__kernel_value), #core_types::context::ExtractArena::arena(__input)))
|
||||
}
|
||||
});
|
||||
let tail_form = if async_fn {
|
||||
Tail::SpawnAsyncFn
|
||||
} else if future_kernel {
|
||||
Tail::SpawnFuture
|
||||
} else {
|
||||
match ir::node_kind(&node) {
|
||||
ir::NodeKind::RecordIo => Tail::Record,
|
||||
ir::NodeKind::Flip => Tail::Flip,
|
||||
ir::NodeKind::Routing | ir::NodeKind::Opaque => Tail::Forward,
|
||||
}
|
||||
};
|
||||
let lower_tail = |form: Tail| match form {
|
||||
Tail::Forward => lift.clone(),
|
||||
Tail::Record => record_tail.clone().expect("a record-io node has a record tail"),
|
||||
Tail::Flip => flip_tail.clone().expect("a flip node has a flip tail"),
|
||||
Tail::SpawnAsyncFn => {
|
||||
let kernel_value_names: Vec<&Ident> = kernel_fields.iter().map(|field| &field.pat_ident.ident).collect();
|
||||
// The level is still live here (the prologue materialized it into the
|
||||
// evaluation's arena), so the owned copy is taken before the future
|
||||
// is built, as the owned-attr crossing does.
|
||||
let kernel_value_args: Vec<TokenStream2> = kernel_indexed
|
||||
.iter()
|
||||
.map(|(index, field)| {
|
||||
let name = &field.pat_ident.ident;
|
||||
let ParsedFieldType::Regular(RegularParsedField { ty, .. }) = &field.ty else {
|
||||
return quote!(#name.clone());
|
||||
};
|
||||
match ir::materialized_levels(&node, *index) > 0 {
|
||||
true => quote! {
|
||||
match #core_types::record::run_to_owned_list::<#ty>(&#name.as_group_item()) {
|
||||
::core::option::Option::Some(__owned) => __owned,
|
||||
::core::option::Option::None => return #core_types::gpoll::GPoll::Error(::std::boxed::Box::new(
|
||||
#core_types::gpoll::GraphError::new(::std::concat!("the materialized level of ", ::std::stringify!(#name), " holds another element type")),
|
||||
)),
|
||||
}
|
||||
},
|
||||
false => quote!(#name.clone()),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let snapshot_binding = snapshot_ctx.then(|| quote!(let __snapshot = #core_types::context::CtxSnapshot::capture(__input);)).into_iter();
|
||||
let snapshot_arg = snapshot_ctx.then(|| quote!(__snapshot)).into_iter();
|
||||
let future_args = snapshot_arg
|
||||
.chain(data_names.iter().map(|name| quote!(self.#name.clone())))
|
||||
.chain(kernel_value_names.iter().map(|name| quote!(#name.clone())));
|
||||
let future_args = snapshot_arg.chain(data_names.iter().map(|name| quote!(self.#name.clone()))).chain(kernel_value_args);
|
||||
let completion = future_completion(&parsed.output_type);
|
||||
let tail = spawn_tail(completion, inflight.clone());
|
||||
let prelude = carried_prelude.iter();
|
||||
@@ -2215,10 +2307,10 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
let clamp = clamp_tokens(field);
|
||||
(field, quote!(#body #clamp))
|
||||
}),
|
||||
&lazy_frames_entry,
|
||||
&lazy_entry,
|
||||
);
|
||||
// The rebind path with nothing hoisted: every non-carrier input binds
|
||||
// fresh per lane, so an index-dependent edge reaches its own lane.
|
||||
// fresh per lane, so an index-dependent input reaches its own lane.
|
||||
let rebound_lane_binds: Vec<TokenStream2> = lazy_last(
|
||||
regular_fields
|
||||
.iter()
|
||||
@@ -2232,7 +2324,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
let clamp = clamp_tokens(field);
|
||||
(field, quote!(#body #clamp))
|
||||
}),
|
||||
&lazy_frames_entry,
|
||||
&lazy_entry,
|
||||
);
|
||||
// A hoisted value is moved into every lane's kernel call, so each
|
||||
// lane consumes a clone; view and borrow binds copy freely.
|
||||
@@ -2423,20 +2515,20 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(index, _)| ir::materialized_levels(&node, *index) == 0)
|
||||
.filter_map(|(_, field)| match &field.ty {
|
||||
.map(|(_, field)| match &field.ty {
|
||||
// The conditional arena-park moves a lend element once.
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, lend: Some(_), .. }) => Some({
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, lend: Some(_), .. }) => {
|
||||
let ty = &crate::codegen::classify::substitute_lifetimes(ty, "'static");
|
||||
quote!(#ty: ::core::marker::Send + ::core::marker::Sync + 'static)
|
||||
}),
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => Some({
|
||||
}
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => {
|
||||
let ty = &crate::codegen::classify::substitute_lifetimes(ty, "'static");
|
||||
quote!(#ty: ::core::clone::Clone)
|
||||
}),
|
||||
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => Some({
|
||||
}
|
||||
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => {
|
||||
let output_type = &crate::codegen::classify::substitute_lifetimes(output_type, "'static");
|
||||
quote!(#output_type: ::core::clone::Clone)
|
||||
}),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let out = crate::codegen::classify::substitute_lifetimes(&slot_value_type(&parsed.output_type), "'static");
|
||||
@@ -2454,15 +2546,50 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
self.__layout = __resolved.layout;
|
||||
})
|
||||
} else if record_io {
|
||||
let write_installs = write_markers.iter().enumerate().map(|(index, marker)| {
|
||||
let slot = format_ident!("__write_{index}");
|
||||
quote! {
|
||||
self.#slot = __resolved.layout.offset_of(<#marker as #core_types::attribute::Attribute>::NAME, 0).expect("a written attribute is always part of the wired layout");
|
||||
}
|
||||
});
|
||||
// A name-generic write has no marker name to look up: the compiler
|
||||
// folded its name out of the graph, so the offset resolves through the
|
||||
// name the resolved layout carries.
|
||||
let mut folded = 0usize;
|
||||
let write_installs: Vec<TokenStream2> = write_markers
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, marker)| {
|
||||
let slot = format_ident!("__write_{index}");
|
||||
let name = match crate::parsing::named_marker(marker).is_some() {
|
||||
true => {
|
||||
let position = folded;
|
||||
folded += 1;
|
||||
quote!(__resolved.named_writes[#position])
|
||||
}
|
||||
false => quote!(<#marker as #core_types::attribute::Attribute>::NAME),
|
||||
};
|
||||
quote! {
|
||||
self.#slot = __resolved.layout.offset_of(#name, 0).expect("a written attribute is always part of the wired layout");
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
// A name-generic read's offset was resolved against the input it reads,
|
||||
// which only the compiler sees, so installing it is a copy.
|
||||
let mut folded_read = 0usize;
|
||||
let read_installs: Vec<TokenStream2> = flat_reads
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, (_, read))| crate::parsing::named_marker(&read.marker).is_some())
|
||||
.map(|(slot, _)| {
|
||||
let default_slot = format_ident!("__read_default_{slot}");
|
||||
let slot = format_ident!("__read_{slot}");
|
||||
let position = folded_read;
|
||||
folded_read += 1;
|
||||
quote! {
|
||||
self.#slot = __resolved.named_reads[#position];
|
||||
self.#default_slot = __resolved.named_read_defaults[#position].clone();
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let plan = (!skips_carrier || gather_carrier).then(|| quote!(self.__plan = __resolved.plan;));
|
||||
Some(quote! {
|
||||
#(#write_installs)*
|
||||
#(#read_installs)*
|
||||
self.__frame_bytes = __resolved.frame_bytes;
|
||||
self.__lane_invariant = __resolved.lane_invariant;
|
||||
#plan
|
||||
@@ -2502,7 +2629,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
}
|
||||
None => quote!(#core_types::record::ElementSpec::Carried),
|
||||
};
|
||||
let layout_meta = crate::codegen::ir::layout_meta_tokens(&node, element_spec, core_types);
|
||||
let layout_meta = crate::codegen::ir::layout_meta_tokens(&node, element_spec, core_types, &[]);
|
||||
// A flipped shader node's struct and impl are std-gated; its layout meta must be too.
|
||||
let cfg = crate::shader_nodes::modify_cfg(&parsed.attributes);
|
||||
quote! {
|
||||
@@ -2518,8 +2645,11 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
|
||||
let record_wiring = record_io.then(|| {
|
||||
let layout_fn = format_ident!("{}_layout", fn_name);
|
||||
// A name-generic write is absent here: this free layout fn derives a
|
||||
// layout without a graph, and only the graph carries the name.
|
||||
let write_descs: Vec<TokenStream2> = write_markers
|
||||
.iter()
|
||||
.filter(|marker| crate::parsing::named_marker(marker).is_none())
|
||||
.map(|marker| quote!(#core_types::record::FieldWrite::of::<#marker>(0)))
|
||||
.collect();
|
||||
let remove_pairs: Vec<TokenStream2> = removes
|
||||
@@ -2556,7 +2686,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
}
|
||||
None => quote!(#core_types::record::ElementSpec::Carried),
|
||||
};
|
||||
let layout_meta = crate::codegen::ir::layout_meta_tokens(&node, element_spec, core_types);
|
||||
let layout_meta = crate::codegen::ir::layout_meta_tokens(&node, element_spec, core_types, &[]);
|
||||
let layout_meta_def = quote! {
|
||||
#vis fn #layout_meta_fn() -> #core_types::record::LayoutMeta {
|
||||
#layout_meta
|
||||
@@ -2583,6 +2713,12 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
let read_inits = flat_reads.iter().enumerate().map(|(slot, (owner, read))| {
|
||||
let marker = &read.marker;
|
||||
let slot = format_ident!("__read_{slot}");
|
||||
// A name-generic read has no marker name to look up here; the
|
||||
// compiler resolved its offset against the input's own layout, so
|
||||
// `set_layout` installs the number.
|
||||
if crate::parsing::named_marker(marker).is_some() {
|
||||
return quote!(let #slot = ::core::option::Option::None;);
|
||||
}
|
||||
let source = match !skips_carrier && *owner == 0 {
|
||||
true => quote!(__carrier_layout),
|
||||
false => format_ident!("__in_{owner}").to_token_stream(),
|
||||
@@ -2601,6 +2737,16 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
});
|
||||
let plan_default = (!skips_carrier || gather_carrier).then(|| quote!(__plan: ::std::vec::Vec::new(),)).into_iter();
|
||||
let read_names = (0..flat_reads.len()).map(|index| format_ident!("__read_{index}")).map(|slot| quote!(#slot,));
|
||||
// The folded name's default arrives with the layout, so the constructor
|
||||
// leaves the slot empty and `set_layout` fills it.
|
||||
let read_default_inits = flat_reads
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, (_, read))| crate::parsing::named_marker(&read.marker).is_some())
|
||||
.map(|(index, _)| {
|
||||
let slot = format_ident!("__read_default_{index}");
|
||||
quote!(#slot: ::core::option::Option::None,)
|
||||
});
|
||||
let write_defaults = (0..write_markers.len()).map(|index| format_ident!("__write_{index}")).map(|slot| quote!(#slot: 0,));
|
||||
let mat_cache_defaults = materialized_indices(®ular_fields, &node).into_iter().map(|index| {
|
||||
let slot = format_ident!("__mat_cache_{index}");
|
||||
@@ -2647,6 +2793,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
__frame_bytes: 0,
|
||||
__lane_invariant: 0,
|
||||
#(#read_names)*
|
||||
#(#read_default_inits)*
|
||||
#(#write_defaults)*
|
||||
#(#mat_cache_defaults)*
|
||||
#(#slot_default)*
|
||||
@@ -2684,7 +2831,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
EvalStep::Bind(index, field) => {
|
||||
let body = bind_body(*index, field, false, "e!(__frame.frames()));
|
||||
match matches!(field.ty, ParsedFieldType::Node(_)) && !std::mem::replace(&mut lazy_declared, true) {
|
||||
true => quote!(#lazy_frames_entry #body),
|
||||
true => quote!(#lazy_entry #body),
|
||||
false => body,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,7 +120,7 @@ pub(crate) fn routing_value_indices(regular_fields: &[&ParsedField], generic: &I
|
||||
}
|
||||
|
||||
/// The lazy inputs declaring attribute reads, with their indices into the
|
||||
/// unit-skipped regular fields.
|
||||
/// regular fields.
|
||||
pub(crate) fn lazy_read_fields<'a>(regular_fields: &[&'a ParsedField]) -> Vec<(usize, &'a ParsedField)> {
|
||||
regular_fields
|
||||
.iter()
|
||||
@@ -130,8 +130,8 @@ pub(crate) fn lazy_read_fields<'a>(regular_fields: &[&'a ParsedField]) -> Vec<(u
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The indices (into the unit-skipped regular fields) of value inputs whose
|
||||
/// reads resolve against their own wire rather than the carrier's.
|
||||
/// The indices (into the regular fields) of value inputs whose
|
||||
/// reads resolve against their own input rather than the carrier's.
|
||||
pub(crate) fn reading_secondary_indices(regular_fields: &[&ParsedField], skips_carrier: bool) -> Vec<usize> {
|
||||
regular_fields
|
||||
.iter()
|
||||
@@ -177,7 +177,7 @@ pub(crate) fn substitute_ident_types(ty: &Type, assignments: &[(Ident, Type)]) -
|
||||
}
|
||||
|
||||
/// Replaces the routing generic in a derive-routing kernel's return type with
|
||||
/// the routing record value, since the kernel's edges rebind to '__record.
|
||||
/// the routing record value, since the kernel's inputs rebind to '__record.
|
||||
pub(crate) fn substitute_routing_record(output: &Type, generic: &Ident, core_types: &TokenStream2) -> Type {
|
||||
struct Subst<'a> {
|
||||
generic: &'a Ident,
|
||||
@@ -266,6 +266,36 @@ pub(crate) fn contains_open_generic(parsed: &ParsedNodeFn, ty: &Type) -> bool {
|
||||
.any(|param| matches!(param, GenericParam::Type(type_param) if Some(&type_param.ident) != ctx_ident.as_ref() && type_contains_ident(ty, &type_param.ident)))
|
||||
}
|
||||
|
||||
/// The element generic of a primary input that is read but never looked at:
|
||||
/// declared as an unbounded passthrough, carrying attribute reads, and absent
|
||||
/// from everywhere else in the signature. Such a node maps its declared
|
||||
/// attributes onto a fresh element, so it accepts any upstream record wire and
|
||||
/// registers one generic row rather than a row per element type.
|
||||
///
|
||||
/// Inferred rather than marked: a generic with nowhere to go and nothing to be
|
||||
/// is opaque by construction, and the signature already says so.
|
||||
pub(crate) fn opaque_reading_carrier(parsed: &ParsedNodeFn) -> Option<Ident> {
|
||||
let carrier = parsed.fields.first()?;
|
||||
if carrier.is_data_field || carrier.attribute_reads.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let ParsedFieldType::Regular(RegularParsedField { ty, lend: None, implementations, .. }) = &carrier.ty else {
|
||||
return None;
|
||||
};
|
||||
if !implementations.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let token = unbounded_generic(parsed, ty)?;
|
||||
// A token that reaches the output or another input is a passthrough
|
||||
// element, which the node does carry; only one going nowhere is opaque.
|
||||
let escapes = type_contains_ident(&parsed.output_type, &token)
|
||||
|| parsed.fields.iter().skip(1).any(|field| match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => type_contains_ident(ty, &token),
|
||||
ParsedFieldType::Node(NodeParsedField { input_type, output_type, .. }) => type_contains_ident(input_type, &token) || type_contains_ident(output_type, &token),
|
||||
});
|
||||
(!escapes).then_some(token)
|
||||
}
|
||||
|
||||
pub(crate) fn unbounded_generic(parsed: &ParsedNodeFn, ty: &Type) -> Option<Ident> {
|
||||
let ident = bare_ident(ty)?.clone();
|
||||
let ctx_ident = context_param(parsed).map(|ctx| ctx.ident.clone());
|
||||
@@ -295,7 +325,7 @@ pub(crate) fn record_shape(parsed: &ParsedNodeFn) -> Option<RecordShape> {
|
||||
return None;
|
||||
}
|
||||
// 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.
|
||||
// writes it through the claim, and the reads have no input to bind against.
|
||||
if source && (has_reads || writes.is_none()) {
|
||||
return None;
|
||||
}
|
||||
@@ -306,13 +336,13 @@ pub(crate) fn record_shape(parsed: &ParsedNodeFn) -> Option<RecordShape> {
|
||||
// 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
|
||||
// Lazy secondaries are consumed as plain elements; raw record inputs 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)) {
|
||||
if parsed.fields.iter().skip(lazy_carrier as usize).any(unsupported_lazy_secondary) {
|
||||
return None;
|
||||
}
|
||||
let reads_well_placed = parsed.fields.iter().enumerate().all(|(index, field)| {
|
||||
@@ -362,6 +392,13 @@ pub(crate) fn record_shape(parsed: &ParsedNodeFn) -> Option<RecordShape> {
|
||||
None => (value, Vec::new(), Vec::new()),
|
||||
};
|
||||
match &token {
|
||||
// An opaque reading carrier never looks at its element, so it writes a
|
||||
// fresh one instead of passing the token through.
|
||||
Some(_) if opaque_reading_carrier(parsed).is_some() => {
|
||||
if contains_open_generic(parsed, &element) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(token) => {
|
||||
if !matches!(bare_ident(&element), Some(ident) if ident == token) {
|
||||
return None;
|
||||
@@ -423,10 +460,7 @@ pub(crate) fn flip_carrier(parsed: &ParsedNodeFn) -> bool {
|
||||
!(async_kernel && lend.is_some())
|
||||
}
|
||||
|
||||
/// Whether a plain node's lowering flips onto record wires: sync,
|
||||
/// 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.
|
||||
/// Whether any value input declares `IList` nesting, so the node materializes a ranked input.
|
||||
pub(crate) fn has_materialized_input(parsed: &ParsedNodeFn) -> bool {
|
||||
parsed
|
||||
.fields
|
||||
@@ -434,6 +468,7 @@ pub(crate) fn has_materialized_input(parsed: &ParsedNodeFn) -> bool {
|
||||
.any(|field| matches!(&field.ty, ParsedFieldType::Regular(RegularParsedField { list_levels, .. }) if *list_levels > 0))
|
||||
}
|
||||
|
||||
/// Whether a plain node's lowering flips onto record inputs.
|
||||
pub(crate) fn record_flip(parsed: &ParsedNodeFn) -> bool {
|
||||
if record_shape(parsed).is_some() || has_record_io(parsed) || routing_io(parsed).is_some() || record_opaque(parsed) {
|
||||
return false;
|
||||
@@ -467,7 +502,7 @@ pub(crate) fn record_flip(parsed: &ParsedNodeFn) -> bool {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
// A named lifetime is the serving lifetime: wire types substitute
|
||||
// A named lifetime is the serving lifetime: input types substitute
|
||||
// its erased projection in registry and layout contexts.
|
||||
GenericParam::Lifetime(_) => {}
|
||||
GenericParam::Const(_) => return false,
|
||||
@@ -520,7 +555,7 @@ pub(crate) fn is_served(ty: &Type) -> bool {
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// was handed, receives raw record inputs paired with the node's layout, and
|
||||
/// takes on the record APIs' unsafe contracts itself.
|
||||
pub(crate) fn record_opaque(parsed: &ParsedNodeFn) -> bool {
|
||||
is_served(&slot_value_type(&parsed.output_type))
|
||||
@@ -577,7 +612,7 @@ pub(crate) fn routing_io(parsed: &ParsedNodeFn) -> Option<RoutingIo> {
|
||||
}
|
||||
}
|
||||
}
|
||||
(sources > 0).then(|| RoutingIo { generic: ident })
|
||||
(sources > 0).then_some(RoutingIo { generic: ident })
|
||||
}
|
||||
|
||||
pub(crate) fn bare_ident(ty: &Type) -> Option<&Ident> {
|
||||
@@ -723,7 +758,7 @@ pub(crate) fn type_disqualifies(ty: &Type) -> bool {
|
||||
visitor.found
|
||||
}
|
||||
|
||||
/// The wire type with every named serving lifetime replaced: `'static` for
|
||||
/// The input 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.
|
||||
@@ -749,7 +784,7 @@ pub(crate) fn substitute_lifetimes(ty: &Type, replacement: &str) -> Type {
|
||||
ty
|
||||
}
|
||||
|
||||
/// The serving lifetime a wire type names, so a materialized binding can tie
|
||||
/// The serving lifetime an input 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 {
|
||||
|
||||
@@ -6,16 +6,28 @@ use syn::spanned::Spanned;
|
||||
use syn::{GenericParam, Ident, Type};
|
||||
|
||||
pub(crate) fn entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, data_field_generic_idents: &[Ident], regular_fields: &[&ParsedField]) -> TokenStream2 {
|
||||
// A data-field generic is monomorphized by hand, so those nodes carry their own rows.
|
||||
if !data_field_generic_idents.is_empty() {
|
||||
return quote!();
|
||||
}
|
||||
match crate::codegen::ir::node_kind(&crate::codegen::ir::build(parsed)) {
|
||||
let entries = 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),
|
||||
};
|
||||
// Validation already rejects a generic input without implementations, so an
|
||||
// empty row set here is an emitter gap, not an unregistered shape.
|
||||
if entries.is_empty() && !parsed.attributes.skip_impl {
|
||||
emit_error!(
|
||||
parsed.fn_name.span(),
|
||||
"no registry rows were generated for `{}`, so a document cannot resolve it",
|
||||
parsed.fn_name;
|
||||
help = "give every generic input an #[implementations(...)] list, or mark the node skip_impl if it registers its rows by hand"
|
||||
);
|
||||
}
|
||||
entries
|
||||
}
|
||||
|
||||
/// The registry rows of a flipped plain node: every wire is a record wire,
|
||||
/// The registry rows of a flipped plain node: every input is a record input,
|
||||
/// inputs resolve their layouts off the claimed handles, and the output is an
|
||||
/// element-only record of the kernel's return type.
|
||||
fn flip_entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields: &[&ParsedField]) -> TokenStream2 {
|
||||
@@ -100,7 +112,7 @@ fn flip_entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, regular_field
|
||||
}
|
||||
}
|
||||
let alias_params: Vec<&GenericParam> = candidate_params.iter().zip(&kept).filter(|(_, kept)| **kept).map(|(param, _)| *param).collect();
|
||||
let alias_param_idents: Vec<Ident> = alias_params.iter().map(|param| param_ident(param)).collect();
|
||||
let alias_param_idents: Vec<Ident> = alias_params.iter().map(param_ident).collect();
|
||||
let alias_param_tokens: Vec<TokenStream2> = alias_params.iter().map(|param| quote!(#param)).collect();
|
||||
let output_alias = format_ident!("__{}_output", fn_name);
|
||||
let alias_def = match alias_param_tokens.is_empty() {
|
||||
@@ -130,7 +142,7 @@ fn flip_entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, regular_field
|
||||
};
|
||||
let assignment_types = assignment_types.iter();
|
||||
let turbofish = quote!(::<#(#node_underscores,)* #(#assignment_types,)*>);
|
||||
let input_types = row.iter().map(|ty| quote!(gcore::registry::record_edge_type::<#ty>()));
|
||||
let input_types = row.iter().map(|ty| quote!(gcore::registry::record_source_type::<#ty>()));
|
||||
let downcasts = names.iter().zip(row.iter()).enumerate().map(|(index, (name, ty))| {
|
||||
let handle = format_ident!("__handle_{index}");
|
||||
let layout = format_ident!("__layout_{index}");
|
||||
@@ -145,7 +157,7 @@ fn flip_entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, regular_field
|
||||
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);
|
||||
let layout_meta = crate::codegen::ir::layout_meta_tokens(&node, element_spec, &core_types, &assignments);
|
||||
Some(quote! {
|
||||
gcore::registry::RegistryEntry {
|
||||
layout_meta: Some(#layout_meta),
|
||||
@@ -161,7 +173,7 @@ fn flip_entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, regular_field
|
||||
let mut inputs = inputs.into_iter();
|
||||
#(#downcasts)*
|
||||
let __node = #struct_name #turbofish::new(#(#names,)* #(#layout_args)*);
|
||||
Ok(gcore::registry::EdgeHandle::new_record::<#row_output>(::std::sync::Arc::new(__node) as ::std::sync::Arc<gcore::registry::ErasedRecordNode>))
|
||||
Ok(gcore::registry::SourceHandle::new_record::<#row_output>(::std::sync::Arc::new(__node) as ::std::sync::Arc<gcore::registry::ErasedRecordNode>))
|
||||
},
|
||||
}
|
||||
})
|
||||
@@ -179,20 +191,20 @@ fn flip_entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, regular_field
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// Which record an input claims and how its value is recovered. Base slots
|
||||
/// are the record inputs whose layouts form the output; value slots are record
|
||||
/// inputs read for their layout.
|
||||
enum SlotKind {
|
||||
/// A generic record edge whose element is only known at runtime; the runtime
|
||||
/// A generic record input 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.
|
||||
/// A concrete record input read for its layout only.
|
||||
Value(Type),
|
||||
/// A record edge whose element extracts to the node's plain value input.
|
||||
/// A record input whose element extracts to the node's plain value input.
|
||||
Extracted(Type),
|
||||
/// A ranked record edge consumed whole; no layout rides to the constructor.
|
||||
/// A ranked record input consumed whole; no layout rides to the constructor.
|
||||
Ranked(Type),
|
||||
}
|
||||
|
||||
@@ -203,7 +215,7 @@ impl SlotKind {
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// instance covers the input, each input's 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;
|
||||
@@ -212,8 +224,8 @@ fn single_row_entries(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields
|
||||
let core_types = quote!(gcore);
|
||||
let lend = |field: &ParsedField| matches!(&field.ty, ParsedFieldType::Regular(RegularParsedField { lend: Some(_), .. }));
|
||||
|
||||
// A subject is its record edge (concrete carrier or erased generic); a
|
||||
// non-subject value rides a record edge when it reads its layout.
|
||||
// A subject is its record input (concrete carrier or erased generic); a
|
||||
// non-subject value rides a record input when it reads its layout.
|
||||
let slots: Option<Vec<SlotKind>> = regular_fields
|
||||
.iter()
|
||||
.enumerate()
|
||||
@@ -228,7 +240,7 @@ fn single_row_entries(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields
|
||||
}
|
||||
match &field.ty {
|
||||
// An element-consuming lazy secondary of a record node rides a
|
||||
// record edge with a layout slot, like a reading secondary.
|
||||
// record input 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) =>
|
||||
{
|
||||
@@ -241,8 +253,8 @@ fn single_row_entries(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields
|
||||
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.
|
||||
// One input kind: a record node's plain value still rides a
|
||||
// record input, 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");
|
||||
@@ -261,27 +273,34 @@ fn single_row_entries(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields
|
||||
// (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
|
||||
let ranked = |index: usize| matches!(®ular_fields[index].ty, ParsedFieldType::Regular(RegularParsedField { list_levels, .. }) if *list_levels > 0);
|
||||
// A record-io node's plain secondary reaches the constructor concrete, so its generic monomorphizes the row like a ranked element does.
|
||||
let record_secondary =
|
||||
|index: usize| matches!(ir::node_kind(&node), ir::NodeKind::RecordIo) && index > 0 && !node.inputs[index].subject && matches!(®ular_fields[index].ty, ParsedFieldType::Regular(_));
|
||||
let names_generic = |index: usize, generic: &Ident| match ®ular_fields[index].ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => crate::codegen::type_contains_ident(ty, generic),
|
||||
_ => false,
|
||||
};
|
||||
let solves_generic = |index: usize, generic: &Ident| match ®ular_fields[index].ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, implementations, .. }) => !implementations.is_empty() && generic_extractable(ty, generic),
|
||||
_ => false,
|
||||
};
|
||||
let carried_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,
|
||||
})
|
||||
})
|
||||
.filter(|ident| (0..regular_fields.len()).any(|index| (ranked(index) || record_secondary(index)) && names_generic(index, ident)))
|
||||
.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,
|
||||
})
|
||||
// Ranked sources come first, so a generic a ranked input already carries keeps sourcing its rows from that input.
|
||||
let carried_source = |generic: &Ident| {
|
||||
(0..regular_fields.len())
|
||||
.find(|&index| ranked(index) && solves_generic(index, generic))
|
||||
.or_else(|| (0..regular_fields.len()).find(|&index| record_secondary(index) && solves_generic(index, generic)))
|
||||
};
|
||||
let carried: Option<Vec<(Ident, usize)>> = ranked_generic_idents.iter().map(|ident| ranked_source(ident).map(|index| (ident.clone(), index))).collect();
|
||||
let carried: Option<Vec<(Ident, usize)>> = carried_generic_idents.iter().map(|ident| carried_source(ident).map(|index| (ident.clone(), index))).collect();
|
||||
let Some(carried) = carried else {
|
||||
return quote!();
|
||||
};
|
||||
@@ -299,7 +318,7 @@ fn single_row_entries(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields
|
||||
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"),
|
||||
_ => unreachable!("carried sources are regular fields"),
|
||||
};
|
||||
generic_assignment(&field_ty, &row_ty, generic).map(|ty| (generic.clone(), ty))
|
||||
})
|
||||
@@ -339,8 +358,8 @@ fn single_row_entries(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields
|
||||
}
|
||||
|
||||
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>()),
|
||||
SlotKind::BaseGeneric(name) => quote!(gcore::registry::generic_record_source_type(#name)),
|
||||
SlotKind::BaseConcrete(ty) | SlotKind::Value(ty) | SlotKind::Extracted(ty) | SlotKind::Ranked(ty) => quote!(gcore::registry::record_source_type::<#ty>()),
|
||||
});
|
||||
|
||||
let downcasts = names.iter().zip(&slots).enumerate().map(|(index, (name, slot))| {
|
||||
@@ -359,7 +378,7 @@ fn single_row_entries(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields
|
||||
let #layout = #handle.layout().clone();
|
||||
let #name = #handle.downcast_record::<#value_ty>()?;
|
||||
},
|
||||
// The node reads the element off the edge's own layout, so
|
||||
// The node reads the element off the input'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>()?;
|
||||
@@ -378,11 +397,11 @@ fn single_row_entries(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields
|
||||
.collect();
|
||||
|
||||
let carried_meta = || {
|
||||
let meta = ir::layout_meta_tokens(&node, quote!(gcore::record::ElementSpec::Carried), &core_types);
|
||||
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
|
||||
// The output type 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 {
|
||||
@@ -394,7 +413,7 @@ fn single_row_entries(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields
|
||||
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)))),
|
||||
quote!(Ok(gcore::registry::SourceHandle::new_record::<#element>(::std::sync::Arc::new(__node)))),
|
||||
),
|
||||
None => {
|
||||
let name = match &node.output.shape.element {
|
||||
@@ -404,7 +423,7 @@ fn single_row_entries(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields
|
||||
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))),
|
||||
quote!(Ok(gcore::registry::SourceHandle::new_erased(::std::sync::Arc::new(__node) as ::std::sync::Arc<gcore::registry::ErasedRecordNode>, #base_ty))),
|
||||
)
|
||||
}
|
||||
};
|
||||
@@ -413,7 +432,25 @@ fn single_row_entries(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields
|
||||
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())))
|
||||
// A name-generic write names its value type through a wired
|
||||
// generic, which only the row resolves, so such a node's
|
||||
// meta is emitted per row instead of shared across them.
|
||||
let named = node.output.shape.attrs.iter().any(|attr| crate::parsing::named_marker(&attr.marker).is_some());
|
||||
let meta = match named {
|
||||
false => quote!(Some(self::#layout_meta_fn())),
|
||||
true => {
|
||||
let element_spec = match &node.output.shape.element {
|
||||
ir::Element::Concrete(element) => {
|
||||
let ty = substitute_ident_types(element, assignments);
|
||||
quote!(gcore::record::ElementSpec::Concrete({ use gcore::record::{ElementWritePickHashed as _, ElementWritePickPlain as _}; (&gcore::record::ElementWritePick::<#ty>(::core::marker::PhantomData)).element_write() }))
|
||||
}
|
||||
_ => quote!(gcore::record::ElementSpec::Carried),
|
||||
};
|
||||
let meta = ir::layout_meta_tokens(&node, element_spec, &core_types, assignments);
|
||||
quote!(Some(#meta))
|
||||
}
|
||||
};
|
||||
(quote!(), quote!(#carrier_arg #(#value_layout_args)*), meta)
|
||||
}
|
||||
ir::NodeKind::Routing => {
|
||||
let source_layouts = base_indices.iter().map(|index| format_ident!("__layout_{index}"));
|
||||
@@ -510,3 +547,122 @@ pub(crate) fn implementation_rows(parsed: &ParsedNodeFn, regular_fields: &[&Pars
|
||||
let row_count = candidates.iter().map(|types| types.len()).max().unwrap_or(1).max(1);
|
||||
Some((0..row_count).map(|row| candidates.iter().map(|types| types[row.min(types.len() - 1)].clone()).collect()).collect())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::parsing::parse_node_fn;
|
||||
|
||||
/// The macro's own pipeline up to the entries emitter, so a test node's rows
|
||||
/// match what `#[node]` would generate.
|
||||
fn entries_of(attr: TokenStream2, item: TokenStream2) -> String {
|
||||
let mut parsed = parse_node_fn(attr, item).unwrap();
|
||||
parsed.replace_impl_trait_in_input();
|
||||
if parsed.injects_async_source_fields() {
|
||||
parsed.inject_async_source_fields("e!(gcore));
|
||||
}
|
||||
let regular_fields: Vec<&ParsedField> = parsed.fields.iter().filter(|field| !field.is_data_field).collect();
|
||||
let data_field_generic_idents: Vec<Ident> = parsed
|
||||
.fn_generics
|
||||
.iter()
|
||||
.filter_map(|param| match param {
|
||||
GenericParam::Type(type_param) => Some(type_param.ident.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.filter(|ident| {
|
||||
parsed
|
||||
.fields
|
||||
.iter()
|
||||
.any(|field| field.is_data_field && matches!(&field.ty, ParsedFieldType::Regular(RegularParsedField { ty, .. }) if crate::codegen::type_contains_ident(ty, ident)))
|
||||
})
|
||||
.collect();
|
||||
entries_tokens(&parsed, &format_ident!("TestNode"), &data_field_generic_idents, ®ular_fields).to_string()
|
||||
}
|
||||
|
||||
/// A record-io async source whose only generic sits on a plain secondary:
|
||||
/// the shape the rasterize node has. One row per implementation, or the
|
||||
/// node never reaches the registry.
|
||||
#[test]
|
||||
fn record_io_source_rows_an_implementations_generic_secondary() {
|
||||
let entries = entries_of(
|
||||
quote!(category("")),
|
||||
quote!(
|
||||
async fn rasterize<T: Send + Clone>(
|
||||
_: impl Ctx,
|
||||
_: (),
|
||||
#[implementations(List<Vector>, List<Raster<CPU>>, List<Graphic>, List<Color>, List<GradientStops>)] data: List<T>,
|
||||
footprint: Footprint,
|
||||
canvas: CanvasHandle,
|
||||
) -> (Raster<CPU>, Attr<Transform>, OwnedAttr<EditorMergedLayers>) {
|
||||
todo!()
|
||||
}
|
||||
),
|
||||
);
|
||||
assert!(entries.contains("fn rasterize_entries"), "a registrable record-io source must emit its entries fn");
|
||||
for element in ["Vector", "Raster < CPU >", "Graphic", "Color", "GradientStops"] {
|
||||
let row = format!("record_source_type :: < List < {element} > > ()");
|
||||
assert!(entries.contains(&row), "the implementations row {element} is missing: {entries}");
|
||||
}
|
||||
assert_eq!(entries.matches("constructor :").count(), 5, "one row per implementation");
|
||||
assert!(!entries.contains("< T >"), "every row instantiates the carried generic");
|
||||
}
|
||||
|
||||
/// The same shape without implementations stays unregistered: nothing names
|
||||
/// the rows, so a silent empty emission is the intended answer.
|
||||
#[test]
|
||||
fn record_io_source_without_implementations_stays_unregistered() {
|
||||
let entries = entries_of(
|
||||
quote!(category(""), skip_impl),
|
||||
quote!(
|
||||
async fn rasterize_open<T: Send + Clone>(_: impl Ctx, _: (), data: List<T>) -> (Raster<CPU>, Attr<Transform>) {
|
||||
todo!()
|
||||
}
|
||||
),
|
||||
);
|
||||
assert!(entries.is_empty(), "an unsourced generic secondary registers nothing: {entries}");
|
||||
}
|
||||
|
||||
/// A ranked element generic keeps sourcing its rows from the ranked input.
|
||||
#[test]
|
||||
fn ranked_generic_still_rows_from_its_ranked_input() {
|
||||
let entries = entries_of(
|
||||
quote!(category("")),
|
||||
quote!(
|
||||
fn count<T: Send + Clone>(_: impl Ctx, _: (), #[implementations(IList<f64>, IList<u32>)] items: IList<T>) -> (u32, Attr<Opacity>) {
|
||||
todo!()
|
||||
}
|
||||
),
|
||||
);
|
||||
assert!(entries.contains("fn count_entries"), "a ranked record-io node still emits: {entries}");
|
||||
assert_eq!(entries.matches("constructor :").count(), 2, "one row per ranked implementation");
|
||||
}
|
||||
|
||||
/// An async source's materialized input crosses the future boundary as an
|
||||
/// owned snapshot: the prologue materializes the level while the evaluation
|
||||
/// is live, bridges it to the legacy list, and the kernel takes that.
|
||||
#[test]
|
||||
fn async_source_takes_a_materialized_input_as_an_owned_list() {
|
||||
let generated = crate::parsing::new_node_fn(
|
||||
quote!(category("")),
|
||||
quote!(
|
||||
async fn rasterize<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(
|
||||
_: impl Ctx,
|
||||
_: (),
|
||||
#[implementations(Vector, Raster<CPU>, Graphic)] data: IList<T>,
|
||||
footprint: Footprint,
|
||||
) -> (Raster<CPU>, Attr<Transform>) {
|
||||
todo!()
|
||||
}
|
||||
),
|
||||
)
|
||||
.expect("the async materialized shape generates")
|
||||
.to_string();
|
||||
assert!(generated.contains("data : :: core_types :: list :: List < T >"), "the kernel takes the owned legacy list: {generated}");
|
||||
assert!(generated.contains("run_to_owned_list"), "the prologue snapshots the materialized level: {generated}");
|
||||
assert!(generated.contains("record :: materialize_batch"), "the level still materializes in the prologue: {generated}");
|
||||
for element in ["Vector", "Raster < CPU >", "Graphic"] {
|
||||
let row = format!("record_source_type :: < {element} > ()");
|
||||
assert!(generated.contains(&row), "the row carries the leveled element {element}: {generated}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
//! The intent IR: a node built from its signature, from which lowering derives.
|
||||
// Fields below the `Node` root are read by the IR's own tests only.
|
||||
#![allow(dead_code)]
|
||||
|
||||
use crate::codegen::classify::{Dialect, RoutingIo, bare_ident, context_param, dialect, flip_carrier, generic_assignment, generic_extractable, is_served, record_shape, routing_io, slot_value_type};
|
||||
@@ -13,7 +14,6 @@ pub(crate) fn build(parsed: &ParsedNodeFn) -> Node {
|
||||
let generic_idents: Vec<Ident> = generics.iter().map(|generic| generic.ident.clone()).collect();
|
||||
let fields: Vec<&ParsedField> = parsed.fields.iter().filter(|field| !field.is_data_field).collect();
|
||||
Node {
|
||||
kernel: Kernel { fn_name: parsed.fn_name.clone() },
|
||||
monomorphizations: monomorphizations(parsed, &fields, &generic_idents),
|
||||
inputs: inputs(parsed, &fields, &generic_idents),
|
||||
output: output(parsed, &generic_idents),
|
||||
@@ -48,7 +48,7 @@ fn generics(parsed: &ParsedNodeFn) -> Vec<Generic> {
|
||||
|
||||
fn inputs(parsed: &ParsedNodeFn, fields: &[&ParsedField], generics: &[Ident]) -> Vec<Input> {
|
||||
let routing = routing_io(parsed);
|
||||
let carrier_subject = flip_carrier(parsed) || record_shape(parsed).map_or(false, |shape| !shape.skips_carrier());
|
||||
let carrier_subject = flip_carrier(parsed) || record_shape(parsed).is_some_and(|shape| !shape.skips_carrier());
|
||||
fields
|
||||
.iter()
|
||||
.enumerate()
|
||||
@@ -67,6 +67,10 @@ fn inputs(parsed: &ParsedNodeFn, fields: &[&ParsedField], generics: &[Ident]) ->
|
||||
shape: item_shape(&element, depth, &field.attribute_reads, generics),
|
||||
subject: subject(index, field, carrier_subject, routing.as_ref()),
|
||||
lend: matches!(&field.ty, ParsedFieldType::Regular(RegularParsedField { lend: Some(_), .. })),
|
||||
name_source: match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { name_source, .. }) => name_source.clone(),
|
||||
ParsedFieldType::Node(_) => None,
|
||||
},
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
@@ -96,9 +100,16 @@ fn output(parsed: &ParsedNodeFn, generics: &[Ident]) -> Output {
|
||||
shape: ItemShape {
|
||||
element: element_of(&element, generics),
|
||||
depth,
|
||||
attrs: writes.into_iter().map(|marker| LevelAttr { marker, level: 0 }).collect(),
|
||||
attrs: writes
|
||||
.into_iter()
|
||||
.map(|write| LevelAttr {
|
||||
marker: write.marker,
|
||||
level: 0,
|
||||
owned: write.owned,
|
||||
})
|
||||
.collect(),
|
||||
},
|
||||
removes: removes.into_iter().map(|marker| LevelAttr { marker, level: 0 }).collect(),
|
||||
removes: removes.into_iter().map(|marker| LevelAttr { marker, level: 0, owned: false }).collect(),
|
||||
gathers,
|
||||
}
|
||||
}
|
||||
@@ -158,6 +169,7 @@ fn item_shape(element: &Type, depth: u8, reads: &[AttributeRead], generics: &[Id
|
||||
.map(|read| LevelAttr {
|
||||
marker: read.marker.clone(),
|
||||
level: 0,
|
||||
owned: false,
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
@@ -253,16 +265,24 @@ fn ilist_inner(ty: &Type) -> Option<Type> {
|
||||
|
||||
/// Emits the `LayoutMeta` literal from the IR. `element_spec` is supplied by the
|
||||
/// caller since it is the one row-dependent facet; the rest folds from the node.
|
||||
pub(crate) fn layout_meta_tokens(node: &Node, element_spec: TokenStream2, core_types: &TokenStream2) -> TokenStream2 {
|
||||
/// `assignments` binds the row's concrete types to the signature's generics,
|
||||
/// which a name-generic write needs: its value type is written as a projection
|
||||
/// through the wired generic, so only the row resolves it.
|
||||
pub(crate) fn layout_meta_tokens(node: &Node, element_spec: TokenStream2, core_types: &TokenStream2, assignments: &[(Ident, Type)]) -> TokenStream2 {
|
||||
let sources = layout_sources(node).into_iter().map(|index| index as u8);
|
||||
let reads = node.inputs.iter().enumerate().filter_map(|(index, input)| {
|
||||
(matches!(input.evaluation, Evaluation::Eager) && !input.shape.attrs.is_empty()).then(|| {
|
||||
let reads = node
|
||||
.inputs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, input)| matches!(input.evaluation, Evaluation::Eager) && !input.shape.attrs.is_empty())
|
||||
.map(|(index, input)| {
|
||||
let descs = field_writes(&input.shape.attrs, core_types);
|
||||
let index = index as u8;
|
||||
quote!(#core_types::record::InputReads { input: #index, reads: ::std::vec![#(#descs),*] })
|
||||
})
|
||||
});
|
||||
});
|
||||
let writes = field_writes(&node.output.shape.attrs, core_types);
|
||||
let named_writes = named_field_writes(node, core_types, assignments);
|
||||
let named_reads = named_field_reads(node, core_types, assignments);
|
||||
let removes = node.output.removes.iter().map(|attr| {
|
||||
let marker = &attr.marker;
|
||||
let level = attr.level;
|
||||
@@ -279,6 +299,10 @@ pub(crate) fn layout_meta_tokens(node: &Node, element_spec: TokenStream2, core_t
|
||||
reads: ::std::vec![#(#reads),*],
|
||||
element: #element_spec,
|
||||
writes: ::std::vec![#(#writes),*],
|
||||
named_writes: ::std::vec![#(#named_writes),*],
|
||||
folded_names: ::std::vec![],
|
||||
named_reads: ::std::vec![#(#named_reads),*],
|
||||
folded_read_names: ::std::vec![],
|
||||
removes: ::std::vec![#(#removes),*],
|
||||
level_delta: #level_delta,
|
||||
folded: #folded,
|
||||
@@ -343,6 +367,7 @@ pub(crate) fn folded_subject(node: &Node) -> Option<(u8, u8)> {
|
||||
fn field_writes(attrs: &[LevelAttr], core_types: &TokenStream2) -> Vec<TokenStream2> {
|
||||
attrs
|
||||
.iter()
|
||||
.filter(|attr| crate::parsing::named_marker(&attr.marker).is_none())
|
||||
.map(|attr| {
|
||||
let marker = &attr.marker;
|
||||
let level = attr.level;
|
||||
@@ -351,6 +376,102 @@ fn field_writes(attrs: &[LevelAttr], core_types: &TokenStream2) -> Vec<TokenStre
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Emits one `NamedWrite` per name-generic write, pairing the template minted
|
||||
/// from the concrete value type with the input its placeholder's name sits at.
|
||||
fn named_field_writes(node: &Node, core_types: &TokenStream2, assignments: &[(Ident, Type)]) -> Vec<TokenStream2> {
|
||||
node.output
|
||||
.shape
|
||||
.attrs
|
||||
.iter()
|
||||
.filter_map(|attr| {
|
||||
let (placeholder, value) = crate::parsing::named_marker(&attr.marker)?;
|
||||
let value = qualify_projection(node, &crate::codegen::classify::substitute_ident_types(&value, assignments), assignments);
|
||||
// Only a row resolves a value type written through a generic, so
|
||||
// the row-free meta omits the write rather than naming a type that
|
||||
// is not in scope there.
|
||||
if node.generics.iter().any(|generic| mentions_ident(&value, &generic.ident)) {
|
||||
return None;
|
||||
}
|
||||
let input = name_input(node, &placeholder)? as u8;
|
||||
let level = attr.level;
|
||||
Some(quote!(#core_types::record::NamedWrite::of::<#placeholder, #value>(#input, #level)))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Emits one `NamedRead` per name-generic read, pairing the template minted
|
||||
/// from the concrete value type with the input read and the input its
|
||||
/// placeholder's name sits at.
|
||||
fn named_field_reads(node: &Node, core_types: &TokenStream2, assignments: &[(Ident, Type)]) -> Vec<TokenStream2> {
|
||||
node.inputs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(input, source)| source.shape.attrs.iter().map(move |attr| (input, attr)))
|
||||
.filter_map(|(input, attr)| {
|
||||
let (placeholder, value) = crate::parsing::named_marker(&attr.marker)?;
|
||||
let value = qualify_projection(node, &crate::codegen::classify::substitute_ident_types(&value, assignments), assignments);
|
||||
if node.generics.iter().any(|generic| mentions_ident(&value, &generic.ident)) {
|
||||
return None;
|
||||
}
|
||||
let name = name_input(node, &placeholder)? as u8;
|
||||
let input = input as u8;
|
||||
let level = attr.level;
|
||||
Some(quote!(#core_types::record::NamedRead::of::<#placeholder, #value>(#input, #name, #level)))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Rewrites `V::Assoc` into `<Row as Bound>::Assoc` once the row assigns `V`.
|
||||
/// A value type reached through an associated type needs the generic's own
|
||||
/// bound to name the projection, which only the signature carries.
|
||||
fn qualify_projection(node: &Node, ty: &Type, assignments: &[(Ident, Type)]) -> Type {
|
||||
let Type::Path(path) = ty else { return ty.clone() };
|
||||
if path.qself.is_some() || path.path.segments.len() < 2 {
|
||||
return ty.clone();
|
||||
}
|
||||
let base = &path.path.segments[0].ident;
|
||||
let Some(generic) = node.generics.iter().find(|generic| &generic.ident == base) else {
|
||||
return ty.clone();
|
||||
};
|
||||
let Some((_, row)) = assignments.iter().find(|(ident, _)| ident == base) else {
|
||||
return ty.clone();
|
||||
};
|
||||
let mut bounds = generic.bounds.iter().filter_map(|bound| match bound {
|
||||
TypeParamBound::Trait(bound) => Some(&bound.path),
|
||||
_ => None,
|
||||
});
|
||||
let (Some(bound), None) = (bounds.next(), bounds.next()) else {
|
||||
return ty.clone();
|
||||
};
|
||||
let rest = path.path.segments.iter().skip(1);
|
||||
syn::parse_quote!(<#row as #bound>::#(#rest)::*)
|
||||
}
|
||||
|
||||
/// Whether `ty` names `ident` anywhere, so a type written through a generic
|
||||
/// can be told from one already concrete.
|
||||
fn mentions_ident(ty: &Type, ident: &Ident) -> bool {
|
||||
struct Search<'a> {
|
||||
ident: &'a Ident,
|
||||
found: bool,
|
||||
}
|
||||
|
||||
impl syn::visit::Visit<'_> for Search<'_> {
|
||||
fn visit_ident(&mut self, found: &Ident) {
|
||||
self.found |= found == self.ident;
|
||||
}
|
||||
}
|
||||
|
||||
let mut search = Search { ident, found: false };
|
||||
syn::visit::Visit::visit_type(&mut search, ty);
|
||||
search.found
|
||||
}
|
||||
|
||||
/// The input position carrying `placeholder`'s name, which is the parameter
|
||||
/// declared at that placeholder.
|
||||
pub(crate) fn name_input(node: &Node, placeholder: &Type) -> Option<usize> {
|
||||
node.inputs.iter().position(|input| input.name_source.as_ref().is_some_and(|declared| declared == placeholder))
|
||||
}
|
||||
|
||||
fn level_delta(node: &Node) -> i8 {
|
||||
// A folded subject contributes no base layout, so the delta is relative to
|
||||
// the fresh (empty) base.
|
||||
@@ -380,13 +501,13 @@ pub(crate) enum LazyBinding {
|
||||
}
|
||||
|
||||
impl ValueBinding {
|
||||
/// Copies an element out of a record edge, so the frame is reclaimed after.
|
||||
/// Copies an element out of a record input, so the frame is reclaimed after.
|
||||
pub(crate) fn reads_out(&self) -> bool {
|
||||
matches!(self, ValueBinding::ReadingSecondary | ValueBinding::RecordElement | ValueBinding::Plain)
|
||||
}
|
||||
}
|
||||
|
||||
/// A record node's lazy inputs consumed as plain elements: their record edges
|
||||
/// A record node's lazy inputs consumed as plain elements: their record inputs
|
||||
/// need a layout slot at wiring, like the reading secondaries.
|
||||
pub(crate) fn element_lazy_indices(regular_fields: &[&ParsedField], node: &Node) -> Vec<usize> {
|
||||
if !matches!(node_kind(node), NodeKind::RecordIo) {
|
||||
@@ -446,7 +567,7 @@ fn has_attr_io(node: &Node) -> bool {
|
||||
pub(crate) fn materialized_levels(node: &Node, index: usize) -> u8 {
|
||||
let input = &node.inputs[index];
|
||||
// An eager input's declared `IList` nesting IS its materialization count,
|
||||
// independent of the rank delta; lazy edges never materialize.
|
||||
// independent of the rank delta; lazy inputs never materialize.
|
||||
match input.evaluation {
|
||||
Evaluation::Eager => input.shape.depth,
|
||||
Evaluation::Lazy => 0,
|
||||
@@ -488,7 +609,6 @@ pub(crate) fn lazy_binding(node: &Node, index: usize) -> LazyBinding {
|
||||
}
|
||||
|
||||
pub(crate) struct Node {
|
||||
pub(crate) kernel: Kernel,
|
||||
pub(crate) generics: Vec<Generic>,
|
||||
/// Correlated rows (zipped `#[implementations]`, not crossed); empty = erased.
|
||||
pub(crate) monomorphizations: Vec<ImplRow>,
|
||||
@@ -499,11 +619,6 @@ pub(crate) struct Node {
|
||||
pub(crate) derives: bool,
|
||||
}
|
||||
|
||||
/// The kernel fn the node wraps.
|
||||
pub(crate) struct Kernel {
|
||||
pub(crate) fn_name: Ident,
|
||||
}
|
||||
|
||||
pub(crate) struct Generic {
|
||||
pub(crate) ident: Ident,
|
||||
pub(crate) bounds: Vec<TypeParamBound>,
|
||||
@@ -522,6 +637,10 @@ pub(crate) struct Input {
|
||||
pub(crate) subject: bool,
|
||||
/// Written `&T`; the kernel borrows the evaluated element.
|
||||
pub(crate) lend: bool,
|
||||
/// The placeholder this input names, written `Named<X>`. Such an input
|
||||
/// carries constant text the compiler folds into a layout name, so it is
|
||||
/// never evaluated per lane.
|
||||
pub(crate) name_source: Option<Type>,
|
||||
}
|
||||
|
||||
/// `Lazy` = `impl Node<..>`, the kernel drives it.
|
||||
@@ -545,6 +664,8 @@ pub(crate) struct ItemShape {
|
||||
pub(crate) attrs: Vec<LevelAttr>,
|
||||
}
|
||||
|
||||
// Macro IR built once per node at expansion time, so the variant spread costs nothing at runtime.
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
pub(crate) enum Element {
|
||||
Concrete(Type),
|
||||
/// Indexes [`Node::generics`].
|
||||
@@ -557,6 +678,8 @@ pub(crate) enum Element {
|
||||
pub(crate) struct LevelAttr {
|
||||
pub(crate) marker: Type,
|
||||
pub(crate) level: u8,
|
||||
/// Writes only: the value crosses as an owned copy that parks at the lift.
|
||||
pub(crate) owned: bool,
|
||||
}
|
||||
|
||||
pub(crate) enum Effect {
|
||||
@@ -680,7 +803,7 @@ mod tests {
|
||||
Facts {
|
||||
sources: if skips_carrier(parsed) { vec![] } else { vec![0] },
|
||||
carried: token_carrier(parsed),
|
||||
writes: markers(write_markers.iter()),
|
||||
writes: markers(write_markers.iter().map(|write| &write.marker)),
|
||||
removes: markers(removes.iter()),
|
||||
delta: 0,
|
||||
}
|
||||
@@ -730,6 +853,127 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_named_write_takes_its_name_from_the_declared_input() {
|
||||
let mut parsed = crate::parsing::parse_node_fn(
|
||||
quote!(category("")),
|
||||
quote!(
|
||||
fn tag<'e, V: WireValue>(ctx: impl Ctx + ExtractArena<'e>, content: f64, name: Named<Name0>, value: V) -> (f64, Attr<'e, Named<Name0, V::Row>>) {
|
||||
(content, Attr(value))
|
||||
}
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
parsed.replace_impl_trait_in_input();
|
||||
let node = build(&parsed);
|
||||
let attrs = &node.output.shape.attrs;
|
||||
assert_eq!(attrs.len(), 1, "the write is recorded on the output");
|
||||
let (placeholder, _) = crate::parsing::named_marker(&attrs[0].marker).expect("the marker is name-generic");
|
||||
assert_eq!(name_input(&node, &placeholder), Some(1), "the name comes from the `Named<Name0>` parameter");
|
||||
|
||||
// The row resolves the value type written through the wired generic.
|
||||
let assignments = vec![(syn::parse_quote!(V), syn::parse_quote!(f64))];
|
||||
let emitted = named_field_writes(&node, "e!(gcore), &assignments);
|
||||
assert_eq!(emitted.len(), 1, "the row carries the named write, got {emitted:?}");
|
||||
assert!(emitted[0].to_string().contains("WireValue"), "the projection is qualified by the generic's bound, got {}", emitted[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_input_is_omitted_from_the_kernel_but_kept_on_the_wire() {
|
||||
let mut parsed = crate::parsing::parse_node_fn(
|
||||
quote!(category("")),
|
||||
quote!(
|
||||
fn tag<'e, V: WireValue>(ctx: impl Ctx + ExtractArena<'e>, content: f64, name: Named<Name0>, value: V) -> (f64, Attr<'e, Named<Name0, V::Row>>) {
|
||||
(content, Attr(value))
|
||||
}
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
parsed.replace_impl_trait_in_input();
|
||||
let node = build(&parsed);
|
||||
|
||||
// The name keeps its wired position, so a document's input order is
|
||||
// untouched, while the kernel neither declares nor is passed it.
|
||||
assert_eq!(node.inputs.len(), 3, "the wire keeps content, name and value");
|
||||
assert!(node.inputs[1].name_source.is_some(), "the name sits at its declared position");
|
||||
let named: Vec<usize> = node.inputs.iter().enumerate().filter(|(_, input)| input.name_source.is_some()).map(|(index, _)| index).collect();
|
||||
assert_eq!(named, vec![1], "exactly one input names a placeholder");
|
||||
|
||||
// A name input's wire type is plain text, which is what the fold reads.
|
||||
let ParsedFieldType::Regular(RegularParsedField { ty, name_source, .. }) = &parsed.fields[1].ty else {
|
||||
panic!("the name is a regular input");
|
||||
};
|
||||
assert!(name_source.is_some(), "the parameter declares a placeholder");
|
||||
assert_eq!(quote!(#ty).to_string(), "String", "the name crosses as constant text");
|
||||
|
||||
// The placeholder is a concrete token, so it adds no generic for the
|
||||
// struct to carry and none to go unconstrained.
|
||||
let generics: Vec<String> = node.generics.iter().map(|generic| generic.ident.to_string()).collect();
|
||||
assert_eq!(generics, vec!["V".to_string()], "only the value generic rides the node");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reading_input_whose_element_goes_nowhere_is_opaque() {
|
||||
let mut parsed = crate::parsing::parse_node_fn(
|
||||
quote!(category("")),
|
||||
quote!(
|
||||
fn peek<'e, T>(_: impl Ctx, (content, opacity): (T, Attr<'e, Opacity>)) -> f64 {
|
||||
let _ = content;
|
||||
*opacity
|
||||
}
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
parsed.replace_impl_trait_in_input();
|
||||
let token = crate::codegen::classify::opaque_reading_carrier(&parsed).expect("the element generic is opaque");
|
||||
assert_eq!(token.to_string(), "T");
|
||||
|
||||
// The node still reads, so it keeps the record-io tail, and the element
|
||||
// rides it as the byte-carried token: one row covers every element type.
|
||||
let node = build(&parsed);
|
||||
assert!(matches!(node_kind(&node), NodeKind::RecordIo), "an opaque reading input still reads attributes");
|
||||
assert!(
|
||||
matches!(crate::codegen::record_shape(&parsed), Some(shape) if matches!(shape.carrier, crate::codegen::RecordCarrier::Token)),
|
||||
"the element is carried as a token rather than read"
|
||||
);
|
||||
assert_eq!(node.inputs[0].shape.attrs.len(), 1, "the declared read survives the blessing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_element_generic_the_node_uses_is_not_opaque() {
|
||||
// Returned rather than dropped, so the element is carried, not opaque:
|
||||
// the usual passthrough rule still governs it.
|
||||
let mut carried = crate::parsing::parse_node_fn(
|
||||
quote!(category("")),
|
||||
quote!(
|
||||
fn keep<'e, T>(_: impl Ctx, (content, opacity): (T, Attr<'e, Opacity>)) -> (T, Attr<'e, Opacity>) {
|
||||
(content, opacity)
|
||||
}
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
carried.replace_impl_trait_in_input();
|
||||
assert!(crate::codegen::classify::opaque_reading_carrier(&carried).is_none(), "an element the output carries is not opaque");
|
||||
|
||||
// No reads at all, so the generic is an ordinary element and still owes
|
||||
// an implementations list.
|
||||
let mut plain = crate::parsing::parse_node_fn(
|
||||
quote!(category("")),
|
||||
quote!(
|
||||
fn plain<T>(_: impl Ctx, content: T) -> f64 {
|
||||
let _ = content;
|
||||
0.
|
||||
}
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
plain.replace_impl_trait_in_input();
|
||||
assert!(
|
||||
crate::codegen::classify::opaque_reading_carrier(&plain).is_none(),
|
||||
"a generic element without reads still needs implementations"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bridge_record_remove() {
|
||||
assert_bridge(
|
||||
@@ -780,6 +1024,19 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bridge_record_owned_write_async_source() {
|
||||
let node = assert_bridge(
|
||||
quote!(category("")),
|
||||
quote!(
|
||||
async fn tag_async(_: impl Ctx, _: (), val: f64) -> (f64, OwnedAttr<Label>) {
|
||||
(val, OwnedAttr::new(""))
|
||||
}
|
||||
),
|
||||
);
|
||||
assert!(node.output.shape.attrs.iter().all(|attr| attr.owned), "an `OwnedAttr` slot crosses the boundary owned");
|
||||
}
|
||||
|
||||
/// An async source's element is the value its slot stores, so a byte-carried
|
||||
/// generic token has no form here.
|
||||
#[test]
|
||||
@@ -840,9 +1097,7 @@ mod tests {
|
||||
let routing_source = |ty: &Type| generic.as_ref().is_some_and(|generic| crate::codegen::classify::routing_source_output(ty, generic));
|
||||
match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, lend, .. }) => {
|
||||
if record && !skips_carrier && index == 0 {
|
||||
"carrier"
|
||||
} else if carrier_flip && index == 0 {
|
||||
if index == 0 && ((record && !skips_carrier) || carrier_flip) {
|
||||
"carrier"
|
||||
} else if flip && lend.is_some() {
|
||||
"lend"
|
||||
|
||||
@@ -44,20 +44,27 @@ pub(crate) struct ParsedNodeFn {
|
||||
}
|
||||
|
||||
/// An `Attr<Marker>` slot in a parameter's read tuple: a declared attribute
|
||||
/// read on that input's wire, not a wired input of its own.
|
||||
/// read on that input, not a wired input of its own.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct AttributeRead {
|
||||
pub(crate) pat_ident: PatIdent,
|
||||
pub(crate) marker: Type,
|
||||
}
|
||||
|
||||
/// One attribute write slot: the marker, and whether it crosses as an owned
|
||||
/// copy (`OwnedAttr<M>`) instead of an evaluation-lifetime value (`Attr<M>`).
|
||||
pub(crate) struct AttrWrite {
|
||||
pub(crate) marker: Type,
|
||||
pub(crate) owned: bool,
|
||||
}
|
||||
|
||||
/// The write half of a record kernel's return: the element type in the first
|
||||
/// tuple slot, then the attribute markers written and the ones removed. `None`
|
||||
/// unless the value is a well-formed write tuple (a non-marker element first,
|
||||
/// then only `Attr` and `RemoveAttr` slots, at least one).
|
||||
/// then only `Attr`, `OwnedAttr` and `RemoveAttr` slots, at least one).
|
||||
pub(crate) struct RecordWrites {
|
||||
pub(crate) element: Type,
|
||||
pub(crate) markers: Vec<Type>,
|
||||
pub(crate) markers: Vec<AttrWrite>,
|
||||
pub(crate) removes: Vec<Type>,
|
||||
}
|
||||
|
||||
@@ -65,14 +72,16 @@ pub(crate) fn record_writes(value: &Type) -> Option<RecordWrites> {
|
||||
let Type::Tuple(tuple) = value else { return None };
|
||||
let mut slots = tuple.elems.iter();
|
||||
let element = slots.next()?;
|
||||
if attr_marker(element).is_some() || remove_attr_marker(element).is_some() {
|
||||
if attr_marker(element).is_some() || owned_attr_marker(element).is_some() || remove_attr_marker(element).is_some() {
|
||||
return None;
|
||||
}
|
||||
let mut markers = Vec::new();
|
||||
let mut removes = Vec::new();
|
||||
for slot in slots {
|
||||
if let Some(marker) = attr_marker(slot) {
|
||||
markers.push(marker);
|
||||
markers.push(AttrWrite { marker, owned: false });
|
||||
} else if let Some(marker) = owned_attr_marker(slot) {
|
||||
markers.push(AttrWrite { marker, owned: true });
|
||||
} else if let Some(marker) = remove_attr_marker(slot) {
|
||||
removes.push(marker);
|
||||
} else {
|
||||
@@ -91,11 +100,52 @@ pub(crate) fn attr_marker(ty: &Type) -> Option<Type> {
|
||||
marker_of(ty, "Attr")
|
||||
}
|
||||
|
||||
/// Returns the marker type of an `OwnedAttr<Marker>` type, if `ty` is one.
|
||||
pub(crate) fn owned_attr_marker(ty: &Type) -> Option<Type> {
|
||||
marker_of(ty, "OwnedAttr")
|
||||
}
|
||||
|
||||
/// Returns the marker type of a `RemoveAttr<Marker>` type, if `ty` is one.
|
||||
pub(crate) fn remove_attr_marker(ty: &Type) -> Option<Type> {
|
||||
marker_of(ty, "RemoveAttr")
|
||||
}
|
||||
|
||||
/// Splits a `Named<X, V>` marker into its placeholder and value type. A write
|
||||
/// of one takes its name from the input the placeholder is declared at rather
|
||||
/// than from the marker, so the name folds at graph compile time.
|
||||
pub(crate) fn named_marker(ty: &Type) -> Option<(Type, Type)> {
|
||||
let mut args = named_arguments(ty)?.into_iter();
|
||||
let (placeholder, value) = (args.next()?, args.next()?);
|
||||
args.next().is_none().then_some((placeholder, value))
|
||||
}
|
||||
|
||||
/// The placeholder a `Named<X>` parameter declares. Such a parameter is the
|
||||
/// name source for every `Attr<Named<X, _>>` the signature writes, and crosses
|
||||
/// the wire as constant text.
|
||||
pub(crate) fn named_source(ty: &Type) -> Option<Type> {
|
||||
let mut args = named_arguments(ty)?.into_iter();
|
||||
let placeholder = args.next()?;
|
||||
args.next().is_none().then_some(placeholder)
|
||||
}
|
||||
|
||||
fn named_arguments(ty: &Type) -> Option<Vec<Type>> {
|
||||
let Type::Path(path) = ty else { return None };
|
||||
let segment = path.path.segments.last()?;
|
||||
if segment.ident != "Named" {
|
||||
return None;
|
||||
}
|
||||
let PathArguments::AngleBracketed(args) = &segment.arguments else { return None };
|
||||
Some(
|
||||
args.args
|
||||
.iter()
|
||||
.filter_map(|argument| match argument {
|
||||
GenericArgument::Type(ty) => Some(ty.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
fn marker_of(ty: &Type, wrapper: &str) -> Option<Type> {
|
||||
let Type::Path(path) = ty else { return None };
|
||||
let segment = path.path.segments.last()?;
|
||||
@@ -138,7 +188,7 @@ pub(crate) struct NodeFnAttributes {
|
||||
pub(crate) batch: Option<Path>,
|
||||
/// Whether partial upstream values are mapped to `Pending` instead of flowing into this node
|
||||
pub(crate) no_partial: bool,
|
||||
/// Whether this node keeps the plain-wire lowering during the record transition
|
||||
/// Whether this node keeps the plain-input lowering during the record transition
|
||||
pub(crate) plain: bool,
|
||||
}
|
||||
|
||||
@@ -204,10 +254,13 @@ pub struct ParsedField {
|
||||
pub unit: Option<LitStr>,
|
||||
pub is_data_field: bool,
|
||||
/// The attribute reads destructured from this input's tuple, resolved
|
||||
/// against this input's wire.
|
||||
/// against this input.
|
||||
pub(crate) attribute_reads: Vec<AttributeRead>,
|
||||
}
|
||||
|
||||
// Both variants are large parsed-syntax payloads (888/672 bytes), so boxing one still leaves the other large while forcing a
|
||||
// deref on every pattern match across codegen; this is built once per node at compile time, never on a hot path
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum ParsedFieldType {
|
||||
Regular(RegularParsedField),
|
||||
@@ -319,6 +372,10 @@ impl Parse for NumberRange {
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct RegularParsedField {
|
||||
pub ty: Type,
|
||||
/// The placeholder this parameter names, written `Named<X>`. Its `ty` is
|
||||
/// rewritten to `String`, since the wire carries the name as constant text
|
||||
/// while the kernel takes only the placeholder.
|
||||
pub name_source: Option<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.
|
||||
@@ -605,10 +662,10 @@ impl Parse for NodeFnAttributes {
|
||||
let parsed_path: Path = meta.parse_args().map_err(|_| Error::new_spanned(meta, "Expected a valid path for 'batch', e.g., batch(my_batch)"))?;
|
||||
batch = Some(parsed_path);
|
||||
}
|
||||
// Instructs the generated eval to report `Pending` instead of passing partial upstream values into this node.
|
||||
// Keeps the plain-input lowering for this node during the record transition.
|
||||
//
|
||||
// Example usage:
|
||||
// #[node_macro::node(..., no_partial, ...)]
|
||||
// #[node_macro::node(..., plain, ...)]
|
||||
"plain" => {
|
||||
let path = meta.require_path_only()?;
|
||||
if plain {
|
||||
@@ -616,6 +673,10 @@ impl Parse for NodeFnAttributes {
|
||||
}
|
||||
plain = true;
|
||||
}
|
||||
// Instructs the generated eval to report `Pending` instead of passing partial upstream values into this node.
|
||||
//
|
||||
// Example usage:
|
||||
// #[node_macro::node(..., no_partial, ...)]
|
||||
"no_partial" => {
|
||||
let path = meta.require_path_only()?;
|
||||
if no_partial {
|
||||
@@ -815,7 +876,7 @@ fn is_frame_claim(ty: &Type) -> bool {
|
||||
}
|
||||
|
||||
/// Splits a lazy input's `Output = (T, Attr<..>..)` tuple into the element
|
||||
/// type (the wire type) and the declared reads on that edge. A tuple without
|
||||
/// type (the input type) and the declared reads on that input. A tuple without
|
||||
/// `Attr` slots is an ordinary tuple output and passes through untouched.
|
||||
fn split_lazy_reads(output_type: Type) -> syn::Result<(Type, Vec<AttributeRead>)> {
|
||||
let Type::Tuple(tuple) = &output_type else {
|
||||
@@ -851,7 +912,7 @@ fn split_lazy_reads(output_type: Type) -> syn::Result<(Type, Vec<AttributeRead>)
|
||||
|
||||
/// Parses a `(value, reads..): (T, Attr<..>..)` parameter: the value component
|
||||
/// is an ordinary field of the value type, each `Attr` component a read bound
|
||||
/// to this input's wire.
|
||||
/// to this input.
|
||||
fn parse_read_tuple(pat_tuple: &syn::PatTuple, ty: &Type, attrs: &[Attribute], index: usize) -> syn::Result<ParsedField> {
|
||||
let spelling = "an input with attribute reads destructures as `(value, Attr<..>)` over `(T, Attr<..>)`";
|
||||
let Type::Tuple(ty_tuple) = ty else {
|
||||
@@ -1017,7 +1078,7 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
|
||||
// Data fields act as internal state, using interior mutability to cache data between node evaluations.
|
||||
//
|
||||
// Normally, an input parameter is a construction argument to the node that is stored as a field on the node struct.
|
||||
// Specifically, its struct field stores the connected upstream node (an evaluatable lambda that returns data of the connection wire's type).
|
||||
// Specifically, its struct field stores the connected upstream node (an evaluatable lambda that returns data of the connection's type).
|
||||
// By comparison, a data field is also stored as a field on the node struct, allowing it to persist state between evaluations.
|
||||
// But it acts as internal state only, not exposed as a parameter in the UI or able to be wired to another node.
|
||||
//
|
||||
@@ -1152,7 +1213,7 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
|
||||
}
|
||||
|
||||
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
|
||||
// A subject named without an output is a whole-record input: 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) {
|
||||
@@ -1213,9 +1274,18 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
|
||||
}
|
||||
}
|
||||
|
||||
// A `Named<X>` parameter declares where `X`'s name is wired: the input
|
||||
// carries constant text, the kernel takes only the placeholder.
|
||||
let name_source = named_source(&ty);
|
||||
let ty = match name_source {
|
||||
Some(_) => parse_quote!(String),
|
||||
None => ty,
|
||||
};
|
||||
|
||||
Ok(ParsedField {
|
||||
pat_ident,
|
||||
ty: ParsedFieldType::Regular(RegularParsedField {
|
||||
name_source,
|
||||
exposed,
|
||||
number_soft_min,
|
||||
number_soft_max,
|
||||
@@ -1338,6 +1408,7 @@ impl ParsedNodeFn {
|
||||
widget_override: ParsedWidgetOverride::Hidden,
|
||||
ty: ParsedFieldType::Regular(RegularParsedField {
|
||||
ty,
|
||||
name_source: None,
|
||||
list_levels: 0,
|
||||
lend: None,
|
||||
exposed: false,
|
||||
@@ -1515,6 +1586,7 @@ mod tests {
|
||||
description: String::new(),
|
||||
widget_override: ParsedWidgetOverride::None,
|
||||
ty: ParsedFieldType::Regular(RegularParsedField {
|
||||
name_source: None,
|
||||
lend: None,
|
||||
list_levels: 0,
|
||||
ty: parse_quote!(f64),
|
||||
@@ -1613,6 +1685,7 @@ mod tests {
|
||||
description: String::new(),
|
||||
widget_override: ParsedWidgetOverride::None,
|
||||
ty: ParsedFieldType::Regular(RegularParsedField {
|
||||
name_source: None,
|
||||
lend: None,
|
||||
list_levels: 0,
|
||||
ty: parse_quote!(DVec2),
|
||||
@@ -1692,6 +1765,7 @@ mod tests {
|
||||
description: String::new(),
|
||||
widget_override: ParsedWidgetOverride::None,
|
||||
ty: ParsedFieldType::Regular(RegularParsedField {
|
||||
name_source: None,
|
||||
lend: None,
|
||||
list_levels: 0,
|
||||
ty: parse_quote!(f64),
|
||||
@@ -1769,6 +1843,7 @@ mod tests {
|
||||
description: String::new(),
|
||||
widget_override: ParsedWidgetOverride::None,
|
||||
ty: ParsedFieldType::Regular(RegularParsedField {
|
||||
name_source: None,
|
||||
lend: None,
|
||||
list_levels: 0,
|
||||
ty: parse_quote!(f64),
|
||||
@@ -1858,6 +1933,7 @@ mod tests {
|
||||
description: String::from("b"),
|
||||
widget_override: ParsedWidgetOverride::None,
|
||||
ty: ParsedFieldType::Regular(RegularParsedField {
|
||||
name_source: None,
|
||||
lend: None,
|
||||
list_levels: 0,
|
||||
ty: parse_quote!(f64),
|
||||
@@ -1950,6 +2026,7 @@ mod tests {
|
||||
description: String::new(),
|
||||
widget_override: ParsedWidgetOverride::None,
|
||||
ty: ParsedFieldType::Regular(RegularParsedField {
|
||||
name_source: None,
|
||||
lend: None,
|
||||
list_levels: 0,
|
||||
ty: parse_quote!(String),
|
||||
|
||||
@@ -232,6 +232,7 @@ impl PerPixelAdjustCodegen<'_> {
|
||||
widget_override: Default::default(),
|
||||
ty: ParsedFieldType::Regular(RegularParsedField {
|
||||
ty: parse_quote!(#wgpu_executor::WgpuExecutorHandle),
|
||||
name_source: None,
|
||||
list_levels: 0,
|
||||
lend: None,
|
||||
exposed: true,
|
||||
|
||||
@@ -54,7 +54,7 @@ fn validate_record_io(parsed: &ParsedNodeFn) {
|
||||
|
||||
for field in parsed.fields.iter().skip(1) {
|
||||
if let ParsedFieldType::Node(NodeParsedField { output_type, .. }) = &field.ty {
|
||||
// Lazy secondaries are consumed as plain elements through the wire.
|
||||
// Lazy secondaries are consumed as plain elements through the input.
|
||||
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");
|
||||
}
|
||||
@@ -127,12 +127,22 @@ fn validate_record_io(parsed: &ParsedNodeFn) {
|
||||
_ => 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");
|
||||
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) {
|
||||
// An opaque reading input never looks at its element, so it writes
|
||||
// a fresh one rather than carrying the input's through.
|
||||
let opaque_reading = crate::codegen::classify::opaque_reading_carrier(parsed).is_some();
|
||||
if opaque_reading {
|
||||
if crate::codegen::contains_open_generic(parsed, element) {
|
||||
emit_error!(parsed.output_type.span(), "an opaque reading input writes a concrete element, since `{}` is never read", token);
|
||||
}
|
||||
} else 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);
|
||||
}
|
||||
}
|
||||
@@ -162,8 +172,14 @@ fn validate_record_io(parsed: &ParsedNodeFn) {
|
||||
}
|
||||
if let Some(writes) = &writes {
|
||||
let mut seen_writes: Vec<String> = Vec::new();
|
||||
for marker in &writes.markers {
|
||||
let written = marker.to_token_stream().to_string();
|
||||
for write in &writes.markers {
|
||||
if write.owned && !async_source {
|
||||
emit_error!(
|
||||
parsed.output_type.span(),
|
||||
"an owned attribute crossing belongs to an async source; a synchronous write parks its value in the kernel"
|
||||
);
|
||||
}
|
||||
let written = write.marker.to_token_stream().to_string();
|
||||
if seen_writes.contains(&written) {
|
||||
emit_error!(parsed.output_type.span(), "attribute `{}` is written twice", written);
|
||||
}
|
||||
@@ -261,6 +277,14 @@ fn validate_async_source(parsed: &ParsedNodeFn) {
|
||||
"`async fn` source nodes cannot take `impl Node` inputs: the spawned future outlives any borrow of the graph, so it cannot evaluate other nodes; use the sync-prologue form (return `SourceFuture`) to evaluate lazy inputs before spawning"
|
||||
);
|
||||
}
|
||||
// One level snapshots to one owned legacy list; a deeper input has no
|
||||
// owned form to cross the future boundary with.
|
||||
if matches!(&field.ty, ParsedFieldType::Regular(RegularParsedField { list_levels, .. }) if *list_levels > 1) {
|
||||
emit_error!(
|
||||
field.pat_ident.span(),
|
||||
"`async fn` source nodes take a materialized input as an owned snapshot of one level, so nested `IList` is unsupported; flatten to a single `IList` or use the sync-prologue form (return `SourceFuture`)"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -413,13 +437,16 @@ fn validate_implementations_for_generics(parsed: &ParsedNodeFn) {
|
||||
(crate::codegen::ir::NodeKind::RecordIo, crate::codegen::ir::Element::Generic(ident)) => Some(ident.clone()),
|
||||
_ => None,
|
||||
};
|
||||
// An opaque reading carrier's element is never looked at, so it needs no
|
||||
// rows: the node registers one generic row and accepts any record wire.
|
||||
let opaque_reading = crate::codegen::classify::opaque_reading_carrier(parsed);
|
||||
let opaque_record_generic = |ty: &Type| {
|
||||
let (stripped, _) = crate::codegen::ir::strip_ilist(ty);
|
||||
let ident = match &stripped {
|
||||
Type::Path(path) => path.path.get_ident(),
|
||||
_ => None,
|
||||
};
|
||||
ident.is_some() && (ident == routing.as_ref().map(|routing| &routing.generic) || ident == record_token.as_ref())
|
||||
ident.is_some() && (ident == routing.as_ref().map(|routing| &routing.generic) || ident == record_token.as_ref() || ident == opaque_reading.as_ref())
|
||||
};
|
||||
|
||||
if !has_skip_impl && !parsed.fn_generics.is_empty() {
|
||||
|
||||
@@ -83,10 +83,7 @@ fn brush_stamp_generator(_: impl Ctx, #[unit(" px")] diameter: f64, color: Color
|
||||
|
||||
/// Used to efficiently paint brush strokes. Applies the same texture repeatedly at different positions with proper blending and boundary handling.
|
||||
#[node_macro::node(category(""), skip_impl)]
|
||||
fn blit<BlendFn>(_: impl Ctx, mut target: List<Raster<CPU>>, texture: Raster<CPU>, positions: Vec<DVec2>, blend_mode: BlendFn) -> List<Raster<CPU>>
|
||||
where
|
||||
BlendFn: Fn(Color, Color) -> Color,
|
||||
{
|
||||
fn blit<BlendFn: Fn(Color, Color) -> Color>(_: impl Ctx, mut target: List<Raster<CPU>>, texture: Raster<CPU>, positions: Vec<DVec2>, blend_mode: BlendFn) -> List<Raster<CPU>> {
|
||||
if positions.is_empty() {
|
||||
return target;
|
||||
}
|
||||
|
||||
Loaded 100 of 119 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user