mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
65
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 |
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
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
@@ -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>) {
|
||||
|
||||
@@ -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)))
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -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>) {
|
||||
@@ -502,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 });
|
||||
@@ -514,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);
|
||||
@@ -524,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;
|
||||
@@ -534,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);
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
|
||||
@@ -378,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 = {
|
||||
@@ -388,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| {
|
||||
@@ -395,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)
|
||||
@@ -412,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
|
||||
@@ -737,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>,
|
||||
@@ -764,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"),
|
||||
|
||||
@@ -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;
|
||||
@@ -177,9 +193,7 @@ impl DynamicExecutor {
|
||||
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, graphic_types::boundary::batch_to_legacy)
|
||||
.map(Arc::from);
|
||||
return self.introspect_with(node_path, graphic_types::boundary::batch_to_legacy).map(Arc::from);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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, SourceHandle, NodeIOTypes, RegistryEntry};
|
||||
use graphene_std::registry::{ConstructionError, NodeIOTypes, RegistryEntry, SourceHandle};
|
||||
#[cfg(feature = "gpu")]
|
||||
use graphene_std::runtime::RuntimeHandle;
|
||||
|
||||
@@ -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(SourceHandle::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>
|
||||
))
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
@@ -27,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 type's key, 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, TypeId)>>,
|
||||
/// 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 {
|
||||
@@ -53,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
|
||||
@@ -236,14 +240,23 @@ impl Arena {
|
||||
// Built before the write so an unencodable offset drops `value` here
|
||||
// rather than stranding it in the arena without drop glue.
|
||||
let weak = ArenaWeak::new(self.generation(), offset)?;
|
||||
// SAFETY: `reserve` returned `offset`, so it is within the backbone.
|
||||
let ptr = unsafe { self.base().add(offset) }.cast::<T>();
|
||||
// SAFETY: freshly reserved, aligned, in-bounds, unaliased.
|
||||
unsafe { ptr.write(value) };
|
||||
if std::mem::needs_drop::<T>() {
|
||||
/// # Safety
|
||||
/// `p` must address the live `T` this entry was registered for.
|
||||
unsafe fn glue<T>(p: *mut u8) {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { p.cast::<T>().drop_in_place() }
|
||||
}
|
||||
self.drops.lock().unwrap().push(DropEntry { offset, type_of, drop_fn: glue::<T>, retained });
|
||||
self.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.
|
||||
@@ -264,6 +277,12 @@ 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.
|
||||
@@ -290,8 +309,11 @@ impl Arena {
|
||||
(offset < self.buf.len()).then_some(())?;
|
||||
let type_of = TypeId::of::<T::Static>();
|
||||
let mut forwarded = self.forwarded.lock().unwrap();
|
||||
if let Some(&(moved, moved_type)) = forwarded.get(&offset) {
|
||||
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();
|
||||
@@ -305,7 +327,10 @@ impl Arena {
|
||||
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 {
|
||||
@@ -316,7 +341,7 @@ impl Arena {
|
||||
});
|
||||
dst.retained_heap.fetch_add(retained, Ordering::Relaxed);
|
||||
let _ = self.retained_heap.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| Some(current.saturating_sub(parked)));
|
||||
forwarded.insert(offset, (target as usize, type_of));
|
||||
forwarded.insert(offset, (target as usize, type_of, dst.generation()));
|
||||
Some(target.cast_const())
|
||||
}
|
||||
|
||||
@@ -335,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.
|
||||
@@ -344,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)
|
||||
}
|
||||
|
||||
@@ -362,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;
|
||||
@@ -550,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(());
|
||||
@@ -695,7 +777,10 @@ mod tests {
|
||||
|
||||
let (parked, _) = transient.alloc_sized_keyed(Owner(String::from("a keyed park")), 0).unwrap();
|
||||
let src = std::ptr::from_ref(parked).cast::<u8>();
|
||||
assert!(unsafe { transient.move_park::<Twin>(src, &persistent, 0) }.is_none(), "a park of another type of the same size is refused");
|
||||
assert!(
|
||||
unsafe { transient.move_park::<Twin>(src, &persistent, 0) }.is_none(),
|
||||
"a park of another type of the same size is refused"
|
||||
);
|
||||
unsafe { transient.move_park::<Owner>(src, &persistent, 0) }.unwrap();
|
||||
assert!(unsafe { transient.move_park::<Twin>(src, &persistent, 0) }.is_none(), "the forwarding refuses the same mistype");
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -135,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 {
|
||||
@@ -151,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
|
||||
@@ -167,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");
|
||||
@@ -251,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>;
|
||||
|
||||
@@ -290,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;
|
||||
$(
|
||||
@@ -325,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;
|
||||
$(
|
||||
@@ -481,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;
|
||||
|
||||
|
||||
@@ -342,7 +342,6 @@ impl AttributeDyn {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.0.len() == 0
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
impl Clone for AttributeDyn {
|
||||
@@ -375,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;
|
||||
}
|
||||
@@ -418,6 +418,7 @@ impl CacheHash for AttributeValueDyn {
|
||||
}
|
||||
}
|
||||
|
||||
// SAFETY: as for AttributeDyn.
|
||||
unsafe impl StaticType for AttributeValueDyn {
|
||||
type Static = Self;
|
||||
}
|
||||
@@ -501,6 +502,7 @@ impl CacheHash for ListDyn {
|
||||
}
|
||||
}
|
||||
|
||||
// SAFETY: as for AttributeDyn.
|
||||
unsafe impl StaticType for ListDyn {
|
||||
type Static = Self;
|
||||
}
|
||||
@@ -1190,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>;
|
||||
}
|
||||
|
||||
@@ -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,7 +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) }
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// One lane's record: its pointer paired with the batch's layout.
|
||||
|
||||
@@ -50,9 +50,10 @@ impl std::fmt::Debug for RecordValue<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
// SAFETY: `element_write` requires the element `Send + Sync` and attribute payloads
|
||||
// are `Copy` or arena-backed, so the record bytes behind the pointer are thread-safe;
|
||||
// `'e` ties the pointer's validity to the shared arena and record-stack discipline.
|
||||
// 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<'_> {}
|
||||
@@ -113,6 +114,29 @@ pub unsafe fn read_at<'e, A: attribute::Attribute>(rec: Rec<'_>, offset: Option<
|
||||
})
|
||||
}
|
||||
|
||||
/// [`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
|
||||
@@ -221,7 +245,9 @@ pub(in crate::record) unsafe fn lift_poll_into<'e, T: Send + Sync + dyn_any::Sta
|
||||
|
||||
/// # 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 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) };
|
||||
|
||||
@@ -111,6 +111,7 @@ impl<'e> Frames<'e> {
|
||||
inline: RecordValue::zeroed(),
|
||||
frame,
|
||||
free: self.reborrow(),
|
||||
filled_fields: false,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -90,7 +90,10 @@ where
|
||||
let Some(len) = range.end.checked_sub(range.start).and_then(|len| usize::try_from(len).ok()) else {
|
||||
return BatchStatus::InvalidRange;
|
||||
};
|
||||
let words = len * node.layout().lane_stride() / 8;
|
||||
// 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,
|
||||
@@ -211,6 +214,7 @@ impl<'a, 'e, N> RecordInput<'a, 'e, N> {
|
||||
/// `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) }
|
||||
}
|
||||
|
||||
@@ -513,6 +517,8 @@ impl<El: Clone + 'static, N> RecordExtract<El, N> {
|
||||
// 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)) })
|
||||
}
|
||||
}
|
||||
@@ -28,11 +28,17 @@ impl FieldWrite {
|
||||
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 {
|
||||
@@ -132,12 +138,18 @@ 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
|
||||
}
|
||||
@@ -155,6 +167,11 @@ impl Default for ElementWrite {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
@@ -198,8 +215,9 @@ impl Layout {
|
||||
|
||||
/// 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; the census keeps declared names to
|
||||
/// one type, so this only fires on wiring bugs.
|
||||
/// 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 {
|
||||
@@ -208,6 +226,10 @@ impl Layout {
|
||||
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);
|
||||
@@ -344,6 +366,76 @@ pub struct RecordLayout {
|
||||
/// 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
|
||||
@@ -365,6 +457,19 @@ pub struct LayoutMeta {
|
||||
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,
|
||||
@@ -401,6 +506,10 @@ impl LayoutMeta {
|
||||
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,
|
||||
@@ -445,13 +554,66 @@ impl LayoutMeta {
|
||||
// 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
|
||||
@@ -498,22 +660,32 @@ pub fn element_write<T: Clone + Send + Sync + dyn_any::StaticTypeSized>() -> Ele
|
||||
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.
|
||||
// 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));
|
||||
@@ -558,11 +730,17 @@ pub fn element_write_hashed<T: Clone + Send + Sync + graphene_hash::CacheHash +
|
||||
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 {
|
||||
@@ -619,6 +797,18 @@ mod tests {
|
||||
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() {
|
||||
|
||||
@@ -21,16 +21,16 @@ mod serve;
|
||||
mod test_support;
|
||||
mod testkit;
|
||||
|
||||
pub use access::{Rec, RecordValue, apply_plan, borrow_element, erase_static, read_at, read_element, token_only, write_element, write_element_sized, write_field};
|
||||
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, RecordLayout, copy_plan,
|
||||
element_dims, element_parked, element_write, element_write_hashed, empty_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, register_deep_element_clone, register_deep_field_value, replay_field_value};
|
||||
pub use owned::{OwnedRecord, deepen_field_value, has_deep_element_glue, register_deep_element_clone, register_deep_field_value, replay_field_value};
|
||||
pub use promote::{Promotion, assert_promoted, register_element_promote, register_field_promote, register_retained_heap};
|
||||
pub use route::{RecordSource, SourcePlan};
|
||||
pub use run::{Group, GroupItem, RunBuilder, RunColumn, RunView};
|
||||
pub use 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};
|
||||
@@ -32,6 +32,13 @@ pub(in crate::record) fn deep_element_glue(type_id: std::any::TypeId) -> Option<
|
||||
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:
|
||||
@@ -50,10 +57,7 @@ static DEEP_FIELD_VALUES: std::sync::LazyLock<std::sync::Mutex<std::collections:
|
||||
|
||||
/// 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,
|
||||
) {
|
||||
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 });
|
||||
}
|
||||
|
||||
@@ -87,7 +91,10 @@ pub fn replay_field_value(value: &dyn crate::list::AnyAttributeValue, arena: &cr
|
||||
pub struct OwnedRecord {
|
||||
pub(in crate::record) bytes: Box<[u8]>,
|
||||
pub(in crate::record) element: Option<Box<dyn std::any::Any + Send + Sync>>,
|
||||
fields: Vec<(usize, Box<dyn crate::list::AnyAttributeValue>)>,
|
||||
/// 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 {
|
||||
@@ -100,35 +107,61 @@ impl OwnedRecord {
|
||||
/// # Safety
|
||||
/// `rec` must be a live record of `layout`.
|
||||
pub unsafe fn copy_out(layout: &Layout, rec: Rec<'_>) -> OwnedRecord {
|
||||
let bytes: Box<[u8]> = unsafe { std::slice::from_raw_parts(rec.ptr(), layout.size) }.into();
|
||||
// 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())
|
||||
.map(|(index, field)| (index, deepen_field_value(unsafe { (field.read_erased)(rec.ptr().add(field.offset)) })))
|
||||
// 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`; the claim's layout is the one the copy was taken at,
|
||||
/// and `None` reports arena exhaustion.
|
||||
/// 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 {
|
||||
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(())
|
||||
@@ -142,6 +175,34 @@ mod tests {
|
||||
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)]);
|
||||
|
||||
@@ -99,6 +99,7 @@ pub(in crate::record) unsafe fn promote_record(layout: &Layout, dst: *mut u8, pr
|
||||
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) }?;
|
||||
}
|
||||
},
|
||||
@@ -243,6 +244,7 @@ impl MaterializedSpan {
|
||||
// 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) }?;
|
||||
|
||||
@@ -48,9 +48,11 @@ impl SourcePlan {
|
||||
|
||||
/// # Safety
|
||||
/// `src` must be a record of this plan's source layout and `dst` a
|
||||
/// buffer of the plan's union layout. The returned view borrows `dst`, so
|
||||
/// `'d` must not outlive it.
|
||||
/// 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 {
|
||||
|
||||
@@ -2,9 +2,53 @@
|
||||
|
||||
use super::access::write_element;
|
||||
use super::layout::{ElementWrite, FieldOffset, FieldWrite, Layout, element_write_hashed};
|
||||
use super::owned::deep_field_glue;
|
||||
use super::owned::{deep_field_glue, deepen_field_value, replay_field_value};
|
||||
use super::promote::{Promotion, promote_record};
|
||||
|
||||
/// A group's element is compared and hashed by content, so it needs glue: the
|
||||
/// byte fallback would read a padded element type's uninitialized padding.
|
||||
fn assert_element_glue(layout: &Layout) {
|
||||
assert!(
|
||||
layout.element.size == 0 || layout.element.content_hash.is_some(),
|
||||
"a run's element adopts only with content glue; declare it with `element_write_hashed`"
|
||||
);
|
||||
}
|
||||
|
||||
/// Whether a lane of `layout` names payloads a byte copy would leave parked in
|
||||
/// the source arena.
|
||||
fn holds_parked(layout: &Layout) -> bool {
|
||||
layout.element.parked || layout.fields.iter().any(|field| field.repark.is_some())
|
||||
}
|
||||
|
||||
/// Re-parks one copied lane's payloads into `arena`, so a lane copied across
|
||||
/// arenas owns what it names instead of pointing back at the source's parks.
|
||||
/// The counterpart of [`promote_record`] for a copy whose target is a serving
|
||||
/// arena rather than the persistent region, so every reference clones.
|
||||
/// `None` reports arena exhaustion.
|
||||
///
|
||||
/// # Safety
|
||||
/// `dst` must image a live record of `layout` whose parked references still
|
||||
/// resolve, which is the source lane's own image before this rewrites it.
|
||||
unsafe fn readopt_record(layout: &Layout, dst: *mut u8, arena: &crate::arena::Arena) -> Option<()> {
|
||||
if layout.element.parked {
|
||||
// SAFETY: the caller's contract; the clone owns all of its content.
|
||||
let owned = unsafe { (layout.element.clone_out)(dst.cast_const()) };
|
||||
// SAFETY: the clone is the element's own type, into its own slot.
|
||||
unsafe { (layout.element.repark)(&*owned, dst, arena) }?;
|
||||
}
|
||||
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) };
|
||||
// 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, arena)?;
|
||||
// SAFETY: the replay produced this field's own value type.
|
||||
unsafe { repark(resident.as_deref().unwrap_or(&*value), slot, arena) }?;
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Builds a resident run lane by lane: fresh frames in the arena at a layout
|
||||
/// derived from the element glue and field writes, elements pushed in order
|
||||
/// and attributes written onto pushed lanes. The finished item's frames are
|
||||
@@ -22,7 +66,7 @@ impl<'e> RunBuilder<'e> {
|
||||
/// `None` reports arena exhaustion.
|
||||
pub fn new(arena: &'e crate::arena::Arena, element: ElementWrite, fields: &[FieldWrite], len: usize) -> Option<Self> {
|
||||
let layout = Layout::default().with_writes(0, element, fields);
|
||||
assert!(!layout.element.parked || layout.element.content_hash.is_some(), "a parked element adopts only with content glue");
|
||||
assert_element_glue(&layout);
|
||||
for field in &layout.fields {
|
||||
assert!(field.repark.is_none() || field.content_hash.is_some(), "a parked field adopts only with content glue");
|
||||
}
|
||||
@@ -52,6 +96,8 @@ impl<'e> RunBuilder<'e> {
|
||||
// `lane` is below `len`; the element slot and each field's region are
|
||||
// disjoint parts of this lane.
|
||||
let base = unsafe { self.frames.add(lane * stride) };
|
||||
// SAFETY: the element slot is fresh, and the assert above matched `T` to
|
||||
// the layout's element type.
|
||||
unsafe { write_element(base, element, self.arena) }?;
|
||||
for field in &self.layout.fields {
|
||||
// SAFETY: as above; the field region is within the lane.
|
||||
@@ -89,13 +135,23 @@ impl<'e> RunBuilder<'e> {
|
||||
|
||||
/// Writes a legacy stored value on an already pushed lane through the
|
||||
/// census glue, parking droppable payloads. A marker outside the layout's
|
||||
/// fields is dropped; a wrong-typed stored value leaves the field's
|
||||
/// fields is dropped, as is one whose row and field agree on the name but
|
||||
/// not on the value type; a wrong-typed stored value leaves the field's
|
||||
/// default. `None` reports arena exhaustion.
|
||||
pub fn attr_stored(&mut self, lane: usize, info: &crate::attribute::AttributeInfo, value: &dyn crate::list::AnyAttributeValue) -> Option<()> {
|
||||
assert!(lane < self.pushed, "attributes write onto pushed lanes");
|
||||
let Some(offset) = self.layout.offset_of(info.name, 0) else { return Some(()) };
|
||||
// SAFETY: the offset comes from the builder's own layout, and the
|
||||
// census writer verifies the stored type before touching the field.
|
||||
let Some(field) = self.layout.fields.iter().find(|field| field.name == info.name && field.level == 0) else {
|
||||
return Some(());
|
||||
};
|
||||
let (offset, size, type_id) = (field.offset, field.size, field.type_id);
|
||||
// The row reaches the field by name alone, so the writer's own value type
|
||||
// is checked against the field before its glue writes there, as `push`
|
||||
// checks the default writer's.
|
||||
if info.size != size || info.value_type != type_id {
|
||||
return Some(());
|
||||
}
|
||||
// SAFETY: the offset comes from the builder's own layout, and the field
|
||||
// was just checked to hold the writer's own value type at its size.
|
||||
unsafe { (info.write_stored)(value, self.frames.add(lane * self.layout.lane_stride() + offset), self.arena) }
|
||||
}
|
||||
|
||||
@@ -160,10 +216,11 @@ impl<'e> GroupItem<'e> {
|
||||
/// Copies the batch's lanes into the arena and clones its layout.
|
||||
/// Returns `None` when the arena is exhausted. Parked regions must carry
|
||||
/// the content glue, so equality and hashing never fall back to pointer
|
||||
/// bytes.
|
||||
/// bytes. A copied lane's parked payloads re-park into `arena`, so the
|
||||
/// adopted run names nothing the source arena's reset frees.
|
||||
pub fn adopt(batch: crate::node::RecordBatch<'_>, arena: &'e crate::arena::Arena) -> Option<Self> {
|
||||
let layout = batch.layout().clone();
|
||||
assert!(!layout.element.parked || layout.element.content_hash.is_some(), "a parked element adopts only with content glue");
|
||||
assert_element_glue(&layout);
|
||||
for field in &layout.fields {
|
||||
assert!(field.repark.is_none() || field.content_hash.is_some(), "a parked field adopts only with content glue");
|
||||
}
|
||||
@@ -181,9 +238,16 @@ impl<'e> GroupItem<'e> {
|
||||
}
|
||||
let scratch = arena.alloc_scratch::<u64>((batch.len() * stride).div_ceil(8))?;
|
||||
let frames = scratch.as_mut_ptr().cast::<u8>();
|
||||
let parked = holds_parked(&layout);
|
||||
for lane in 0..batch.len() {
|
||||
// SAFETY: both sides hold `len` lanes at the shared layout's stride.
|
||||
unsafe { std::ptr::copy_nonoverlapping(batch.get(lane).rec().ptr(), frames.add(lane * stride), stride) };
|
||||
let dst = unsafe { frames.add(lane * stride) };
|
||||
// SAFETY: as above; the scratch was reserved for exactly these lanes.
|
||||
unsafe { std::ptr::copy_nonoverlapping(batch.get(lane).rec().ptr(), dst, stride) };
|
||||
if parked {
|
||||
// SAFETY: the copy images a live record of this layout.
|
||||
unsafe { readopt_record(&layout, dst, arena) }?;
|
||||
}
|
||||
}
|
||||
Some(Self {
|
||||
layout,
|
||||
@@ -239,11 +303,14 @@ impl<'e> GroupItem<'e> {
|
||||
/// A `GroupItem` over the batch's frames, without copying.
|
||||
///
|
||||
/// # Safety
|
||||
/// The frames must stay valid for the evaluation. Arena-resident batches
|
||||
/// qualify, caller stack scratch does not.
|
||||
/// The item borrows the batch's frames at `'e`, so the frames must stay
|
||||
/// valid for the whole of `'e` and nothing derived from the item may outlive
|
||||
/// it. Arena-resident batches span the evaluation; a caller's serve scratch
|
||||
/// spans only the window it lends the batch for, which is sound exactly when
|
||||
/// `'e` is bounded to that window.
|
||||
pub unsafe fn from_resident(batch: crate::node::RecordBatch<'e>) -> Self {
|
||||
let layout = batch.layout().clone();
|
||||
assert!(!layout.element.parked || layout.element.content_hash.is_some(), "a parked element adopts only with content glue");
|
||||
assert_element_glue(&layout);
|
||||
for field in &layout.fields {
|
||||
assert!(field.repark.is_none() || field.content_hash.is_some(), "a parked field adopts only with content glue");
|
||||
}
|
||||
@@ -279,11 +346,19 @@ impl<'e> GroupItem<'e> {
|
||||
let frames = self.frames();
|
||||
// SAFETY: the constructors store `len` lanes of `layout` at the
|
||||
// layout's stride, and the erased glue reads each lane's own region.
|
||||
let bytes: Box<[u8]> = unsafe { std::slice::from_raw_parts(frames, self.len * stride) }.into();
|
||||
// A lane's seam and stride tail are never written, so the copy stays
|
||||
// untyped: a `&[u8]` over the frames would read those bytes.
|
||||
let mut staged = Vec::<u8>::with_capacity(self.len * stride);
|
||||
let bytes = unsafe {
|
||||
std::ptr::copy_nonoverlapping(frames, staged.as_mut_ptr(), self.len * stride);
|
||||
staged.set_len(self.len * stride);
|
||||
staged.into_boxed_slice()
|
||||
};
|
||||
let elements = self
|
||||
.layout
|
||||
.element
|
||||
.parked
|
||||
// SAFETY: as above; a parked element sits at each lane's offset 0.
|
||||
.then(|| (0..self.len).map(|lane| unsafe { (self.layout.element.clone_out)(frames.add(lane * stride)) }).collect());
|
||||
let fields = self
|
||||
.layout
|
||||
@@ -292,6 +367,7 @@ impl<'e> GroupItem<'e> {
|
||||
.enumerate()
|
||||
.filter(|(_, field)| field.repark.is_some())
|
||||
.map(|(index, field)| {
|
||||
// SAFETY: as above; each lane reads this descriptor's own offset.
|
||||
let mut values: Vec<_> = (0..self.len).map(|lane| unsafe { (field.read_erased)(frames.add(lane * stride + field.offset)) }).collect();
|
||||
if let Some(glue) = values.first().and_then(|value| deep_field_glue(value.as_any().type_id())) {
|
||||
for value in &mut values {
|
||||
@@ -316,8 +392,9 @@ impl<'e> GroupItem<'e> {
|
||||
/// `arena`, sharing only where its lanes already live there.
|
||||
pub fn replay<'a>(&self, arena: &'a crate::arena::Arena) -> Option<GroupItem<'a>> {
|
||||
let ItemStorage::Owned(owned) = &self.storage else {
|
||||
// A resident item re-serves at the target arena's own lifetime,
|
||||
// so its lanes copy rather than relabeling the borrow.
|
||||
// A resident item re-serves at the target arena's own lifetime, so
|
||||
// its lanes copy and their parked payloads re-park there rather
|
||||
// than relabeling the borrow.
|
||||
return GroupItem::adopt(self.lanes(), arena);
|
||||
};
|
||||
let stride = self.layout.lane_stride();
|
||||
@@ -328,6 +405,7 @@ impl<'e> GroupItem<'e> {
|
||||
unsafe { std::ptr::copy_nonoverlapping(owned.bytes.as_ptr(), frames, owned.bytes.len()) };
|
||||
if let Some(elements) = &owned.elements {
|
||||
for (lane, element) in elements.iter().enumerate() {
|
||||
// SAFETY: as above; the clone is this element's own type, into its lane's slot.
|
||||
unsafe { (self.layout.element.repark)(&**element, frames.add(lane * stride), arena) }?;
|
||||
}
|
||||
}
|
||||
@@ -336,6 +414,8 @@ impl<'e> GroupItem<'e> {
|
||||
let repark = field.repark.expect("copied fields carry re-park glue");
|
||||
let glue = values.first().and_then(|value| deep_field_glue(value.as_any().type_id()));
|
||||
for (lane, value) in values.iter().enumerate() {
|
||||
// SAFETY: the copy took these values through this field's own glue,
|
||||
// so each writes its own type into its lane's region of the field.
|
||||
match glue {
|
||||
Some(glue) => match (glue.replay)(&**value, arena)? {
|
||||
Some(resident) => unsafe { repark(&*resident, frames.add(lane * stride + field.offset), arena) }?,
|
||||
@@ -400,6 +480,25 @@ impl<'e> GroupItem<'e> {
|
||||
}
|
||||
}
|
||||
|
||||
/// One typed run as an owned legacy list, elements cloned and every attribute
|
||||
/// copied through its erased read. The owned result outlives the evaluation the
|
||||
/// run was materialized in, so an async source can carry it across its await.
|
||||
pub fn run_to_owned_list<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(item: &GroupItem) -> Option<crate::list::List<T>> {
|
||||
let lanes = item.typed_lanes::<T>()?;
|
||||
let mut list = crate::list::List::new();
|
||||
for lane in 0..lanes.len() {
|
||||
list.push(crate::list::Item::new_from_element(lanes.element_ref(lane).clone()));
|
||||
}
|
||||
for field in &item.layout().fields {
|
||||
for lane in 0..lanes.len() {
|
||||
// SAFETY: the offset comes from the item's own layout.
|
||||
let value = unsafe { (field.read_erased)(item.lanes().get(lane).rec().ptr().add(field.offset)) };
|
||||
list.set_attribute_value_dyn(field.name, lane, crate::list::AttributeValueDyn(value));
|
||||
}
|
||||
}
|
||||
Some(list)
|
||||
}
|
||||
|
||||
/// A run read at its element type. Record fields hold each marker's value
|
||||
/// verbatim, so lane reads are plain typed reads at a hoisted offset.
|
||||
pub struct RunView<'a, T> {
|
||||
@@ -522,15 +621,26 @@ impl<'e> Group<'e> {
|
||||
}
|
||||
|
||||
/// Compares one record region of `layout` by content. Regions without glue
|
||||
/// compare as bytes, which is the content for unparked values.
|
||||
/// compare as bytes, which is the content for unparked values. Only written
|
||||
/// spans are read: the element's own bytes and each field's own bytes, never
|
||||
/// the element-to-field seam or the lane's stride tail, which no writer
|
||||
/// touches. The element always carries glue (`assert_element_glue`) and
|
||||
/// `FieldWrite::of` always installs field glue, so a padded value's own
|
||||
/// padding never reaches the byte fallback either.
|
||||
///
|
||||
/// # Safety
|
||||
/// `a` and `b` must both be live records of `layout`.
|
||||
unsafe fn record_content_eq(layout: &Layout, a: *const u8, b: *const u8) -> bool {
|
||||
// SAFETY: the caller's contract; each call reads a written span of the layout.
|
||||
let bytes_eq = |offset: usize, size: usize| unsafe { std::slice::from_raw_parts(a.add(offset), size) == std::slice::from_raw_parts(b.add(offset), size) };
|
||||
let element = match layout.element.content_eq {
|
||||
// SAFETY: the caller's contract; the glue is the element's own.
|
||||
Some(eq) => unsafe { eq(a, b) },
|
||||
None => bytes_eq(0, layout.element.size),
|
||||
};
|
||||
element
|
||||
&& layout.fields.iter().all(|field| match field.content_eq {
|
||||
// SAFETY: as above, at this descriptor's own offset.
|
||||
Some(eq) => unsafe { eq(a.add(field.offset), b.add(field.offset)) },
|
||||
None => bytes_eq(field.offset, field.size),
|
||||
})
|
||||
@@ -538,14 +648,21 @@ unsafe fn record_content_eq(layout: &Layout, a: *const u8, b: *const u8) -> bool
|
||||
|
||||
/// Hashes one record region of `layout` by content, with the byte fallback
|
||||
/// of [`record_content_eq`].
|
||||
///
|
||||
/// # Safety
|
||||
/// `ptr` must be a live record of `layout`.
|
||||
unsafe fn record_content_hash(layout: &Layout, ptr: *const u8, state: &mut dyn core::hash::Hasher) {
|
||||
match layout.element.content_hash {
|
||||
// SAFETY: the caller's contract; the glue is the element's own.
|
||||
Some(hash) => unsafe { hash(ptr, state) },
|
||||
// SAFETY: as above; the element's own bytes are written.
|
||||
None => state.write(unsafe { std::slice::from_raw_parts(ptr, layout.element.size) }),
|
||||
}
|
||||
for field in &layout.fields {
|
||||
match field.content_hash {
|
||||
// SAFETY: as above, at this descriptor's own offset.
|
||||
Some(hash) => unsafe { hash(ptr.add(field.offset), state) },
|
||||
// SAFETY: as above; the field's own bytes are written.
|
||||
None => state.write(unsafe { std::slice::from_raw_parts(ptr.add(field.offset), field.size) }),
|
||||
}
|
||||
}
|
||||
@@ -607,7 +724,6 @@ impl graphene_hash::CacheHash for Group<'_> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::record::access::{read_element, write_field};
|
||||
use crate::record::layout::element_write;
|
||||
use crate::record::test_support::f64_field;
|
||||
|
||||
#[test]
|
||||
@@ -618,7 +734,7 @@ mod tests {
|
||||
|
||||
let arena = crate::arena::Arena::new(4096).unwrap();
|
||||
let transform = DAffine2::from_translation((5., 6.).into());
|
||||
let mut builder = RunBuilder::new(&arena, element_write::<f64>(), &[FieldWrite::of::<Transform>(0), FieldWrite::of::<Opacity>(0)], 2).unwrap();
|
||||
let mut builder = RunBuilder::new(&arena, element_write_hashed::<f64>(), &[FieldWrite::of::<Transform>(0), FieldWrite::of::<Opacity>(0)], 2).unwrap();
|
||||
for lane in 0..2 {
|
||||
let lane = builder.push(lane as f64).unwrap();
|
||||
builder.attr::<Transform>(lane, transform);
|
||||
@@ -648,7 +764,7 @@ mod tests {
|
||||
use crate::lane::LaneSource;
|
||||
|
||||
let arena = crate::arena::Arena::new(1024).unwrap();
|
||||
let mut builder = RunBuilder::new(&arena, element_write::<f64>(), &[], 1).unwrap();
|
||||
let mut builder = RunBuilder::new(&arena, element_write_hashed::<f64>(), &[], 1).unwrap();
|
||||
builder.push(0f64).unwrap();
|
||||
let item = builder.finish();
|
||||
let run = RunView::<f64>::new(&item).expect("the run holds f64 elements");
|
||||
@@ -660,7 +776,7 @@ mod tests {
|
||||
fn an_interior_run_already_persistent_is_shared() {
|
||||
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 layout = Layout::default().with_writes(1, element_write_hashed::<f64>(), &[f64_field("opacity")]);
|
||||
let stride = layout.lane_stride();
|
||||
|
||||
let mut buffer = vec![0u64; (2 * stride).div_ceil(8)];
|
||||
@@ -682,7 +798,7 @@ mod tests {
|
||||
#[test]
|
||||
fn adopting_within_one_region_shares_the_run() {
|
||||
let arena = crate::arena::Arena::new(4096).unwrap();
|
||||
let layout = Layout::default().with_writes(1, element_write::<f64>(), &[f64_field("opacity")]);
|
||||
let layout = Layout::default().with_writes(1, element_write_hashed::<f64>(), &[f64_field("opacity")]);
|
||||
let stride = layout.lane_stride();
|
||||
|
||||
let mut buffer = vec![0u64; (2 * stride).div_ceil(8)];
|
||||
@@ -702,7 +818,7 @@ mod tests {
|
||||
#[test]
|
||||
fn adopted_lanes_round_trip_through_the_group_item() {
|
||||
let arena = crate::arena::Arena::new(1024).unwrap();
|
||||
let layout = Layout::default().with_writes(1, element_write::<f64>(), &[f64_field("opacity")]);
|
||||
let layout = Layout::default().with_writes(1, element_write_hashed::<f64>(), &[f64_field("opacity")]);
|
||||
let stride = layout.lane_stride();
|
||||
let offset = layout.offset_of("opacity", 0).unwrap();
|
||||
|
||||
@@ -730,6 +846,34 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cross_arena_adopt_re_parks_what_the_lanes_name() {
|
||||
use crate::lane::LaneSource;
|
||||
|
||||
let mut source = crate::arena::Arena::new(1 << 16).unwrap();
|
||||
let target = crate::arena::Arena::new(1 << 16).unwrap();
|
||||
|
||||
let adopted = {
|
||||
let mut builder = RunBuilder::new(&source, element_write_hashed::<String>(), &[FieldWrite::of::<crate::attribute::Name>(0)], 2).unwrap();
|
||||
for lane in 0..2 {
|
||||
let lane = builder.push(format!("element {lane}")).unwrap();
|
||||
let (name, _) = source.alloc(format!("field {lane}")).unwrap();
|
||||
builder.attr::<crate::attribute::Name>(lane, name.as_str());
|
||||
}
|
||||
let item = builder.finish();
|
||||
GroupItem::adopt(item.lanes(), &target).unwrap()
|
||||
};
|
||||
// The adopted run must own what it names: the source's flush frees every
|
||||
// payload the lanes were built over.
|
||||
source.reset();
|
||||
|
||||
let run = RunView::<String>::new(&adopted).expect("the run holds string elements");
|
||||
for lane in 0..2 {
|
||||
assert_eq!(run.element(lane).map(String::as_str), Some(format!("element {lane}").as_str()), "lane {lane}");
|
||||
assert_eq!(run.attr::<crate::attribute::Name>(lane), format!("field {lane}"), "lane {lane}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_content_equality_and_hashing_read_through_the_park() {
|
||||
use graphene_hash::CacheHash;
|
||||
@@ -768,20 +912,21 @@ mod tests {
|
||||
fn owned_items_replay_re_parked_payloads_after_the_source_dies() {
|
||||
let layout = Layout::default().with_writes(0, element_write_hashed::<String>(), &[FieldWrite::of::<crate::attribute::Name>(0)]);
|
||||
let stride = layout.lane_stride();
|
||||
let mut bytes = vec![0u8; stride * 2];
|
||||
// Word storage: the parked element and the `&str` field are 8-aligned.
|
||||
let mut bytes = vec![0u64; (stride * 2).div_ceil(8)];
|
||||
|
||||
let owned = {
|
||||
let arena = crate::arena::Arena::new(1024).unwrap();
|
||||
for lane in 0..2 {
|
||||
let base = unsafe { bytes.as_mut_ptr().add(lane * stride) };
|
||||
let base = unsafe { bytes.as_mut_ptr().cast::<u8>().add(lane * stride) };
|
||||
unsafe { write_element(base, format!("element {lane}"), &arena) }.unwrap();
|
||||
let (name, _) = arena.alloc(format!("field {lane}")).unwrap();
|
||||
unsafe { write_field::<&str>(base, layout.offset_of("name", 0).unwrap(), name.as_str()) };
|
||||
}
|
||||
let item = unsafe { GroupItem::from_resident(crate::node::RecordBatch::new(bytes.as_ptr(), 2, &layout)) };
|
||||
let item = unsafe { GroupItem::from_resident(crate::node::RecordBatch::new(bytes.as_ptr().cast(), 2, &layout)) };
|
||||
item.copy_out()
|
||||
};
|
||||
bytes.fill(u8::MAX);
|
||||
bytes.fill(u64::MAX);
|
||||
|
||||
let arena = crate::arena::Arena::new(1024).unwrap();
|
||||
let replayed = owned.replay(&arena).unwrap();
|
||||
@@ -843,6 +988,26 @@ mod tests {
|
||||
assert_eq!(run.attr::<crate::attribute::EditorLayerPath>(0), &[crate::uuid::NodeId(3)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_census_row_pointed_at_another_field_writes_nothing() {
|
||||
use crate::attribute::{Attribute, Opacity, Transform};
|
||||
use crate::lane::LaneSource;
|
||||
|
||||
let arena = crate::arena::Arena::new(1 << 16).unwrap();
|
||||
let mut builder = RunBuilder::new(&arena, element_write_hashed::<f64>(), &[FieldWrite::of::<Opacity>(0)], 1).unwrap();
|
||||
let lane = builder.push(0f64).unwrap();
|
||||
|
||||
// The transform writer renamed onto the 8-byte opacity field: a
|
||||
// 48-byte write past the lane if the name were the only check.
|
||||
let mut forged = crate::attribute::info(Transform::NAME).unwrap();
|
||||
forged.name = Opacity::NAME;
|
||||
builder.attr_stored(lane, &forged, &glam::DAffine2::from_translation((5., 6.).into())).unwrap();
|
||||
|
||||
let item = builder.finish();
|
||||
let run = RunView::<f64>::new(&item).expect("the run holds f64 elements");
|
||||
assert_eq!(run.attr::<Opacity>(0), 1., "the mistyped row leaves the census default");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wrong_typed_or_undeclared_column_leaves_the_default() {
|
||||
use crate::lane::LaneSource;
|
||||
@@ -862,10 +1027,11 @@ mod tests {
|
||||
#[should_panic(expected = "an owned item replays")]
|
||||
fn an_owned_item_refuses_reads() {
|
||||
let layout = Layout::default().with_writes(0, element_write_hashed::<String>(), &[]);
|
||||
let mut bytes = vec![0u8; layout.lane_stride()];
|
||||
// Word storage: the parked element slot holds an 8-aligned reference.
|
||||
let mut bytes = vec![0u64; layout.lane_stride().div_ceil(8)];
|
||||
let arena = crate::arena::Arena::new(1024).unwrap();
|
||||
unsafe { write_element(bytes.as_mut_ptr(), String::from("parked"), &arena) }.unwrap();
|
||||
let item = unsafe { GroupItem::from_resident(crate::node::RecordBatch::new(bytes.as_ptr(), 1, &layout)) };
|
||||
unsafe { write_element(bytes.as_mut_ptr().cast(), String::from("parked"), &arena) }.unwrap();
|
||||
let item = unsafe { GroupItem::from_resident(crate::node::RecordBatch::new(bytes.as_ptr().cast(), 1, &layout)) };
|
||||
item.copy_out().lanes();
|
||||
}
|
||||
}
|
||||
@@ -20,8 +20,13 @@ pub struct SlotRun<'a> {
|
||||
}
|
||||
|
||||
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>> {
|
||||
(scratch.len() * 8 >= len * layout.lane_stride()).then_some(SlotRun { scratch, layout, len, filled: 0 })
|
||||
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 {
|
||||
@@ -41,20 +46,24 @@ impl<'a> SlotRun<'a> {
|
||||
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.
|
||||
/// 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 capacity check `new` made, and the lane
|
||||
// takes the whole inline record.
|
||||
// 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 = self.filled.max(lane + 1);
|
||||
self.filled = lane + 1;
|
||||
}
|
||||
|
||||
/// The served lanes as the caller's exclusive batch.
|
||||
@@ -74,6 +83,9 @@ pub struct FrameClaim<'e, 'l> {
|
||||
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> {
|
||||
@@ -107,17 +119,27 @@ impl<'e, 'l> FrameClaim<'e, 'l> {
|
||||
///
|
||||
/// # 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.
|
||||
/// 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`.
|
||||
/// `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
|
||||
@@ -132,9 +154,17 @@ impl<'e, 'l> FrameClaim<'e, 'l> {
|
||||
/// 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.
|
||||
/// 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
|
||||
@@ -150,6 +180,7 @@ impl<'e, 'l> FrameClaim<'e, 'l> {
|
||||
/// 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
|
||||
@@ -196,10 +227,12 @@ impl<'e, 'l> FrameClaim<'e, 'l> {
|
||||
/// Translates a source record into the frame through a wiring-resolved plan.
|
||||
///
|
||||
/// # Safety
|
||||
/// `src` must be a live record of `plan`'s source layout, and `plan` must
|
||||
/// translate into this frame's layout.
|
||||
/// `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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -312,6 +345,35 @@ mod tests {
|
||||
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> {
|
||||
|
||||
@@ -127,12 +127,22 @@ impl<N: ?Sized> SharedSource<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);
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-derives on the way out of an exclusive re-borrow, so a mutation that
|
||||
/// panics cannot leave the cached pointer retired for a caller that catches.
|
||||
struct Rederive<'a, N: ?Sized>(&'a mut SharedSource<N>);
|
||||
|
||||
impl<N: ?Sized> Drop for Rederive<'_, N> {
|
||||
fn drop(&mut self) {
|
||||
self.0.rederive();
|
||||
}
|
||||
}
|
||||
|
||||
// SAFETY: `ptr` is derived from the owned Arc and never mutated through, so the source is exactly as
|
||||
// thread safe as the payload it shares.
|
||||
unsafe impl<N: ?Sized + Send + Sync> Send for SharedSource<N> {}
|
||||
@@ -207,6 +217,9 @@ unsafe impl Send for SourceHandle {}
|
||||
#[cfg(target_family = "wasm")]
|
||||
unsafe impl Sync for SourceHandle {}
|
||||
|
||||
#[cfg(all(target_family = "wasm", target_feature = "atomics"))]
|
||||
compile_error!("SourceHandle's wasm Send/Sync rest on a single-threaded build; a +atomics target needs the stored node bounded instead");
|
||||
|
||||
impl SourceHandle {
|
||||
pub fn new_record<T: 'static>(node: std::sync::Arc<ErasedRecordNode>) -> Self {
|
||||
Self::new_erased(node, record_source_type::<T>())
|
||||
@@ -224,9 +237,11 @@ impl SourceHandle {
|
||||
layout: |edge| Node::<ContextImpl>::layout(edge.downcast_ref::<SharedSource<N>>().expect("layout hook matches the stored edge type")),
|
||||
set_layout: |edge, layout| {
|
||||
let shared = edge.downcast_mut::<SharedSource<N>>().expect("set_layout hook matches the stored edge type");
|
||||
let node = std::sync::Arc::get_mut(&mut shared.own).expect("layout is installed before the node is shared");
|
||||
// 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,
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -50,6 +50,7 @@ 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() {
|
||||
@@ -72,6 +73,7 @@ unsafe fn deep_repark_artboard(value: &(dyn std::any::Any + Send + Sync), dst: *
|
||||
*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) }
|
||||
}
|
||||
|
||||
@@ -83,12 +85,14 @@ unsafe fn deep_repark_artboard(value: &(dyn std::any::Any + Send + Sync), dst: *
|
||||
/// `src` must point at a live parked `Artboard` element field, and `dst` at
|
||||
/// the element field the promoted reference is written to.
|
||||
unsafe fn promote_artboard(src: *const u8, dst: *mut u8, promotion: &core_types::record::Promotion<'_>) -> Option<()> {
|
||||
// SAFETY: the caller's contract on `src`.
|
||||
let artboard = unsafe { core_types::record::borrow_element::<Artboard>(core_types::record::Rec::new(src)) };
|
||||
if !crate::graphic::list_contains_groups(&artboard.0) {
|
||||
// SAFETY: a parked element slot holds one reference at offset 0, and
|
||||
// content no group is reachable from, elements and item attribute values
|
||||
// alike, owns all of itself.
|
||||
let header = unsafe { src.cast::<*const u8>().read() };
|
||||
// SAFETY: as above; the group-free check establishes the own-all-content half.
|
||||
if let Some(moved) = unsafe { promotion.move_park::<Artboard>(header, 0) } {
|
||||
// SAFETY: as above, into the promoted image's own element slot.
|
||||
unsafe { dst.cast::<*const Artboard>().write(moved) };
|
||||
@@ -101,6 +105,7 @@ unsafe fn promote_artboard(src: *const u8, dst: *mut u8, promotion: &core_types:
|
||||
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()) }
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! The record-crossing glue: group interiors carried between the owned, resident, and persistent regions.
|
||||
|
||||
use super::Graphic;
|
||||
use crate::appearance::Appearance;
|
||||
use core_types::Color;
|
||||
use core_types::list::{Item, List};
|
||||
use raster_types::{CPU, Raster};
|
||||
@@ -54,6 +55,7 @@ pub fn map_groups_to_resident<'a>(graphic: &Graphic<'a>, arena: &'a core_types::
|
||||
/// # Safety
|
||||
/// `ptr` must point at a live parked `Graphic` element field.
|
||||
unsafe fn deep_clone_graphic(ptr: *const u8) -> Box<dyn std::any::Any + Send + Sync> {
|
||||
// SAFETY: the caller's contract.
|
||||
let graphic = unsafe { core_types::record::borrow_element::<Graphic>(core_types::record::Rec::new(ptr)) };
|
||||
Box::new(map_groups_to_owned(graphic))
|
||||
}
|
||||
@@ -68,6 +70,7 @@ unsafe fn deep_repark_graphic(value: &(dyn std::any::Any + Send + Sync), dst: *m
|
||||
let graphic = value.downcast_ref::<Graphic>().expect("an element replays at its own type");
|
||||
let resident = map_groups_to_resident(graphic, arena)?;
|
||||
let retained = graphic_retained_heap(&resident);
|
||||
// SAFETY: the caller's contract; the resident form is a `Graphic` for `dst`.
|
||||
unsafe { core_types::record::write_element_sized(dst, resident, arena, retained) }
|
||||
}
|
||||
|
||||
@@ -106,12 +109,18 @@ fn attribute_keys(list: &List<Graphic>) -> Vec<String> {
|
||||
pub(crate) fn map_attribute_groups_to_owned(list: &mut List<Graphic<'_>>) {
|
||||
for key in attribute_keys(list) {
|
||||
// A column of a type that cannot hold groups is skipped whole.
|
||||
let Some(values) = list.iter_attribute_values_mut::<Option<List<Graphic>>>(&key) else { continue };
|
||||
for value in values.flatten() {
|
||||
for element in value.iter_element_values_mut() {
|
||||
*element = map_groups_to_owned(element);
|
||||
if let Some(values) = list.iter_attribute_values_mut::<Option<List<Graphic>>>(&key) {
|
||||
for value in values.flatten() {
|
||||
for element in value.iter_element_values_mut() {
|
||||
*element = map_groups_to_owned(element);
|
||||
}
|
||||
map_attribute_groups_to_owned(value);
|
||||
}
|
||||
map_attribute_groups_to_owned(value);
|
||||
continue;
|
||||
}
|
||||
let Some(appearances) = list.iter_attribute_values_mut::<Appearance>(&key) else { continue };
|
||||
for appearance in appearances {
|
||||
map_appearance_groups_to_owned(appearance);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -121,15 +130,21 @@ pub(crate) fn map_attribute_groups_to_owned(list: &mut List<Graphic<'_>>) {
|
||||
pub(crate) fn map_attribute_groups_to_resident(list: &mut List<Graphic<'_>>, arena: &core_types::arena::Arena) -> Option<()> {
|
||||
for key in attribute_keys(list) {
|
||||
// A column of a type that cannot hold groups is skipped whole.
|
||||
let Some(values) = list.iter_attribute_values_mut::<Option<List<Graphic>>>(&key) else { continue };
|
||||
for value in values.flatten() {
|
||||
for element in value.iter_element_values_mut() {
|
||||
let resident = map_groups_to_resident(element, arena)?;
|
||||
// SAFETY: the attribute store is erased, and the replay serves as
|
||||
// long as `arena`, which the store's reader outlives.
|
||||
*element = unsafe { core_types::record::erase_static(resident) };
|
||||
if let Some(values) = list.iter_attribute_values_mut::<Option<List<Graphic>>>(&key) {
|
||||
for value in values.flatten() {
|
||||
for element in value.iter_element_values_mut() {
|
||||
let resident = map_groups_to_resident(element, arena)?;
|
||||
// SAFETY: the attribute store is erased, and the replay serves as
|
||||
// long as `arena`, which the store's reader outlives.
|
||||
*element = unsafe { core_types::record::erase_static(resident) };
|
||||
}
|
||||
map_attribute_groups_to_resident(value, arena)?;
|
||||
}
|
||||
map_attribute_groups_to_resident(value, arena)?;
|
||||
continue;
|
||||
}
|
||||
let Some(appearances) = list.iter_attribute_values_mut::<Appearance>(&key) else { continue };
|
||||
for appearance in appearances {
|
||||
map_appearance_groups_to_resident(appearance, arena)?;
|
||||
}
|
||||
}
|
||||
Some(())
|
||||
@@ -141,15 +156,21 @@ pub(crate) fn map_attribute_groups_to_resident(list: &mut List<Graphic<'_>>, are
|
||||
pub(crate) fn map_attribute_groups_to_persistent(list: &mut List<Graphic<'_>>, promotion: &core_types::record::Promotion<'_>) -> Option<()> {
|
||||
for key in attribute_keys(list) {
|
||||
// A column of a type that cannot hold groups is skipped whole.
|
||||
let Some(values) = list.iter_attribute_values_mut::<Option<List<Graphic>>>(&key) else { continue };
|
||||
for value in values.flatten() {
|
||||
for element in value.iter_element_values_mut() {
|
||||
let promoted = map_groups_to_persistent(element, promotion)?;
|
||||
// SAFETY: the attribute store is erased, and persistent content
|
||||
// outlives the evaluation.
|
||||
*element = unsafe { core_types::record::erase_static(promoted) };
|
||||
if let Some(values) = list.iter_attribute_values_mut::<Option<List<Graphic>>>(&key) {
|
||||
for value in values.flatten() {
|
||||
for element in value.iter_element_values_mut() {
|
||||
let promoted = map_groups_to_persistent(element, promotion)?;
|
||||
// SAFETY: the attribute store is erased, and persistent content
|
||||
// outlives the evaluation.
|
||||
*element = unsafe { core_types::record::erase_static(promoted) };
|
||||
}
|
||||
map_attribute_groups_to_persistent(value, promotion)?;
|
||||
}
|
||||
map_attribute_groups_to_persistent(value, promotion)?;
|
||||
continue;
|
||||
}
|
||||
let Some(appearances) = list.iter_attribute_values_mut::<Appearance>(&key) else { continue };
|
||||
for appearance in appearances {
|
||||
map_appearance_groups_to_persistent(appearance, promotion)?;
|
||||
}
|
||||
}
|
||||
Some(())
|
||||
@@ -165,12 +186,14 @@ pub(crate) fn map_attribute_groups_to_persistent(list: &mut List<Graphic<'_>>, p
|
||||
/// `src` must point at a live parked `Graphic` element field, and `dst` at the
|
||||
/// element field the promoted reference is written to.
|
||||
unsafe fn promote_graphic(src: *const u8, dst: *mut u8, promotion: &core_types::record::Promotion<'_>) -> Option<()> {
|
||||
// SAFETY: the caller's contract on `src`.
|
||||
let graphic = unsafe { core_types::record::borrow_element::<Graphic>(core_types::record::Rec::new(src)) };
|
||||
if !graphic_contains_groups(graphic) {
|
||||
// SAFETY: a parked element slot holds one reference at offset 0, and a
|
||||
// graphic no group is reachable from, elements and item attribute values
|
||||
// alike, owns all of its content.
|
||||
let header = unsafe { src.cast::<*const u8>().read() };
|
||||
// SAFETY: as above; the group-free check establishes the own-all-content half.
|
||||
if let Some(moved) = unsafe { promotion.move_park::<Graphic<'static>>(header, graphic_retained_heap(graphic)) } {
|
||||
// SAFETY: as above, into the promoted image's own element slot.
|
||||
unsafe { dst.cast::<*const Graphic<'static>>().write(moved) };
|
||||
@@ -179,6 +202,7 @@ unsafe fn promote_graphic(src: *const u8, dst: *mut u8, promotion: &core_types::
|
||||
}
|
||||
let promoted = map_groups_to_persistent(graphic, promotion)?;
|
||||
let retained = graphic_retained_heap(&promoted);
|
||||
// SAFETY: the caller's contract on `dst`; the promoted form is a `Graphic`.
|
||||
unsafe { core_types::record::write_element_sized(dst, promoted, promotion.persistent(), retained) }
|
||||
}
|
||||
|
||||
@@ -225,13 +249,14 @@ pub(crate) fn list_contains_groups(list: &List<Graphic>) -> bool {
|
||||
|
||||
/// Whether any group hides in the list's item attribute values. Only the
|
||||
/// group-capable columns are scanned: those are the value types the deep field
|
||||
/// glue is registered for, today `Option<List<Graphic>>` alone. A list with no
|
||||
/// attribute columns costs nothing, and a column of any other type is decided
|
||||
/// by its one downcast rather than per value.
|
||||
/// glue is registered for, `Option<List<Graphic>>` and `Appearance`. A list
|
||||
/// with no attribute columns costs nothing, and a column of any other type is
|
||||
/// decided by its one downcast rather than per value.
|
||||
fn attribute_values_contain_groups(list: &List<Graphic>) -> bool {
|
||||
list.attribute_keys().any(|key| {
|
||||
list.iter_attribute_values::<Option<List<Graphic>>>(key)
|
||||
.is_some_and(|mut values| values.any(|value| value.as_ref().is_some_and(list_contains_groups)))
|
||||
|| list.iter_attribute_values::<Appearance>(key).is_some_and(|mut values| values.any(appearance_contains_groups))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -270,6 +295,8 @@ fn deep_repark_graphic_list(value: &dyn core_types::list::AnyAttributeValue, are
|
||||
*element = map_groups_to_resident(element, arena)?;
|
||||
}
|
||||
map_attribute_groups_to_resident(&mut list, arena)?;
|
||||
// SAFETY: every group the clone carried, in an element or an item attribute
|
||||
// value, now names `arena`, whose borrow the replayed field is read at.
|
||||
let list = unsafe { core_types::record::erase_static(list) };
|
||||
Some(Some(Box::new(Some(list))))
|
||||
}
|
||||
@@ -323,12 +350,143 @@ unsafe fn promote_graphic_list(src: *const u8, dst: *mut u8, promotion: &core_ty
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// The coverage list's attribute keys, owned so the columns can be walked mutably.
|
||||
fn appearance_attribute_keys(appearance: &Appearance) -> Vec<String> {
|
||||
appearance.0.attribute_keys().map(str::to_string).collect()
|
||||
}
|
||||
|
||||
/// Whether any group hides in an appearance. Groups can only arrive through the
|
||||
/// `Graphic`-typed columns of the coverage list, today the paint column alone;
|
||||
/// a coverage item's own attributes hold plain stroke parameters.
|
||||
fn appearance_contains_groups(appearance: &Appearance) -> bool {
|
||||
appearance
|
||||
.0
|
||||
.attribute_keys()
|
||||
.any(|key| appearance.0.iter_attribute_values::<Graphic>(key).is_some_and(|mut values| values.any(graphic_contains_groups)))
|
||||
}
|
||||
|
||||
/// The heap an appearance's paints own, group interiors excluded as
|
||||
/// [`graphic_retained_heap`] excludes them.
|
||||
fn appearance_retained_heap(appearance: &Appearance) -> usize {
|
||||
appearance
|
||||
.0
|
||||
.attribute_keys()
|
||||
.map(|key| appearance.0.iter_attribute_values::<Graphic>(key).map_or(0, |values| values.map(graphic_retained_heap).sum()))
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// Every group held in an appearance's paint columns, deep-copied to its owned form.
|
||||
fn map_appearance_groups_to_owned(appearance: &mut Appearance) {
|
||||
for key in appearance_attribute_keys(appearance) {
|
||||
// A column of a type that cannot hold groups is skipped whole.
|
||||
let Some(values) = appearance.0.iter_attribute_values_mut::<Graphic>(&key) else { continue };
|
||||
for value in values {
|
||||
*value = map_groups_to_owned(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every owned group held in an appearance's paint columns, re-parked into
|
||||
/// `arena`. `None` reports arena exhaustion.
|
||||
fn map_appearance_groups_to_resident(appearance: &mut Appearance, arena: &core_types::arena::Arena) -> Option<()> {
|
||||
for key in appearance_attribute_keys(appearance) {
|
||||
// A column of a type that cannot hold groups is skipped whole.
|
||||
let Some(values) = appearance.0.iter_attribute_values_mut::<Graphic>(&key) else { continue };
|
||||
for value in values {
|
||||
let resident = map_groups_to_resident(value, arena)?;
|
||||
// SAFETY: the attribute store is erased, and the replay serves as
|
||||
// long as `arena`, which the store's reader outlives.
|
||||
*value = unsafe { core_types::record::erase_static(resident) };
|
||||
}
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// The deep copy-out for appearance field values (the appearance marker's bare
|
||||
/// owned form): content groups leave any paint column in their owned form.
|
||||
/// Declines (`None`) for group-free content, which already owns everything.
|
||||
fn deep_clone_appearance(value: &dyn core_types::list::AnyAttributeValue) -> Option<Box<dyn core_types::list::AnyAttributeValue>> {
|
||||
let appearance = value.as_any().downcast_ref::<Appearance>().expect("an appearance field deep-copies at its own type");
|
||||
appearance_contains_groups(appearance).then_some(())?;
|
||||
let mut appearance = appearance.clone();
|
||||
map_appearance_groups_to_owned(&mut appearance);
|
||||
Some(Box::new(appearance))
|
||||
}
|
||||
|
||||
/// The deep replay for appearance field values: owned content groups replay
|
||||
/// into the serving arena before the field re-parks. `Some(None)` declines for
|
||||
/// group-free content; `None` reports arena exhaustion.
|
||||
fn deep_repark_appearance(value: &dyn core_types::list::AnyAttributeValue, arena: &core_types::arena::Arena) -> Option<Option<Box<dyn core_types::list::AnyAttributeValue>>> {
|
||||
let appearance = value.as_any().downcast_ref::<Appearance>().expect("an appearance field replays at its own type");
|
||||
if !appearance_contains_groups(appearance) {
|
||||
return Some(None);
|
||||
}
|
||||
let mut appearance = appearance.clone();
|
||||
map_appearance_groups_to_resident(&mut appearance, arena)?;
|
||||
Some(Some(Box::new(appearance)))
|
||||
}
|
||||
|
||||
/// Every group held in an appearance's paint columns, promoted into the
|
||||
/// persistent region on the same Cow dispatch the elements take. `None`
|
||||
/// reports arena exhaustion.
|
||||
fn map_appearance_groups_to_persistent(appearance: &mut Appearance, promotion: &core_types::record::Promotion<'_>) -> Option<()> {
|
||||
for key in appearance_attribute_keys(appearance) {
|
||||
// A column of a type that cannot hold groups is skipped whole.
|
||||
let Some(values) = appearance.0.iter_attribute_values_mut::<Graphic>(&key) else { continue };
|
||||
for value in values {
|
||||
let promoted = map_groups_to_persistent(value, promotion)?;
|
||||
// SAFETY: the attribute store is erased, and persistent content
|
||||
// outlives the evaluation.
|
||||
*value = unsafe { core_types::record::erase_static(promoted) };
|
||||
}
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// The promote for appearance fields, retargeting the paint list promote onto
|
||||
/// the coverage container: the header moves where no group is reachable from
|
||||
/// any paint column, and otherwise clones into a fresh persistent park, with
|
||||
/// content groups taking [`map_groups_to_persistent`]'s Cow dispatch one level
|
||||
/// inside, exactly as [`promote_graphic_list`] dispatches for the paint lists.
|
||||
///
|
||||
/// # Safety
|
||||
/// `src` must point at a live parked appearance field, and `dst` at the field
|
||||
/// slot the promoted reference is written to.
|
||||
unsafe fn promote_appearance(src: *const u8, dst: *mut u8, promotion: &core_types::record::Promotion<'_>) -> Option<()> {
|
||||
// SAFETY: the caller's contract; the slot holds one optional reference.
|
||||
let Some(appearance) = (unsafe { src.cast::<Option<&Appearance>>().read() }) else {
|
||||
// SAFETY: as above, into the promoted image's own field slot.
|
||||
unsafe { dst.cast::<Option<&Appearance>>().write(None) };
|
||||
return Some(());
|
||||
};
|
||||
let retained = appearance_retained_heap(appearance);
|
||||
if !appearance_contains_groups(appearance) {
|
||||
// SAFETY: an appearance no group is reachable from owns all of its
|
||||
// content, and the arena declines a reference that is not a park at the
|
||||
// appearance's own address and size.
|
||||
if let Some(moved) = unsafe { promotion.move_park::<Appearance>(std::ptr::from_ref(appearance).cast(), retained) } {
|
||||
// SAFETY: the move published a live appearance in the persistent region.
|
||||
unsafe { dst.cast::<Option<&Appearance>>().write(Some(&*moved)) };
|
||||
return Some(());
|
||||
}
|
||||
}
|
||||
let mut promoted = appearance.clone();
|
||||
map_appearance_groups_to_persistent(&mut promoted, promotion)?;
|
||||
let (parked, _) = promotion.persistent().alloc_sized(promoted, retained)?;
|
||||
// SAFETY: the slot holds one optional reference.
|
||||
unsafe { dst.cast::<Option<&Appearance>>().write(Some(parked)) };
|
||||
Some(())
|
||||
}
|
||||
|
||||
const _: () = {
|
||||
fn register_all() {
|
||||
core_types::record::register_deep_element_clone::<Graphic>(deep_clone_graphic, deep_repark_graphic);
|
||||
core_types::record::register_deep_field_value::<Option<List<Graphic>>>(deep_clone_graphic_list, deep_repark_graphic_list);
|
||||
core_types::record::register_field_promote::<Option<&'static List<Graphic<'static>>>>(promote_graphic_list);
|
||||
core_types::record::register_element_promote::<Graphic>(promote_graphic);
|
||||
core_types::record::register_deep_field_value::<Appearance>(deep_clone_appearance, deep_repark_appearance);
|
||||
core_types::record::register_field_promote::<Option<&'static Appearance>>(promote_appearance);
|
||||
core_types::record::register_retained_heap::<Appearance>(|value| value.downcast_ref::<Appearance>().map_or(0, appearance_retained_heap));
|
||||
core_types::record::register_retained_heap::<Graphic>(|value| value.downcast_ref::<Graphic>().map_or(0, graphic_retained_heap));
|
||||
core_types::record::register_retained_heap::<Vector>(|value| value.downcast_ref::<Vector>().map_or(0, vector_retained_heap));
|
||||
core_types::record::register_retained_heap::<Raster<CPU>>(|value| value.downcast_ref::<Raster<CPU>>().map_or(0, |raster| raster.data.len() * size_of::<Color>()));
|
||||
@@ -353,7 +511,7 @@ mod run_tests {
|
||||
use super::*;
|
||||
use crate::graphic::test_support::{native_group_paint, unit_square_at};
|
||||
use crate::graphic::{group_to_legacy_list, map_groups_to_legacy};
|
||||
use crate::markers::{Fill, Stroke};
|
||||
use crate::markers::EditorMergedLayers;
|
||||
use core_types::attribute::Attribute;
|
||||
use core_types::lane::LaneSource;
|
||||
use core_types::record::{FieldWrite, RunBuilder, RunView, element_write_hashed};
|
||||
@@ -365,9 +523,9 @@ mod run_tests {
|
||||
let vector = unit_square_at(DVec2::ZERO);
|
||||
|
||||
let source = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
let mut builder = RunBuilder::new(&source, element_write_hashed::<Vector>(), &[FieldWrite::of::<Fill>(0)], 1).unwrap();
|
||||
let mut builder = RunBuilder::new(&source, element_write_hashed::<Vector>(), &[FieldWrite::of::<EditorMergedLayers>(0)], 1).unwrap();
|
||||
let lane = builder.push(vector.clone()).unwrap();
|
||||
builder.attr::<Fill>(lane, Some(&paint));
|
||||
builder.attr::<EditorMergedLayers>(lane, Some(&paint));
|
||||
let group = core_types::record::Group { row: None, content: builder.finish() };
|
||||
let expected = group_to_legacy_list(&group);
|
||||
let owned = map_groups_to_owned(&Graphic::Group(group));
|
||||
@@ -409,9 +567,9 @@ mod run_tests {
|
||||
let paint = unsafe { core_types::record::erase_static(native_group_paint(&inner_vector, &source)) };
|
||||
|
||||
let vector = unit_square_at(DVec2::new(4., 4.));
|
||||
let mut builder = RunBuilder::new(&source, element_write_hashed::<Vector>(), &[FieldWrite::of::<Fill>(0)], 1).unwrap();
|
||||
let mut builder = RunBuilder::new(&source, element_write_hashed::<Vector>(), &[FieldWrite::of::<EditorMergedLayers>(0)], 1).unwrap();
|
||||
let lane = builder.push(vector.clone()).unwrap();
|
||||
builder.attr::<Fill>(lane, Some(&paint));
|
||||
builder.attr::<EditorMergedLayers>(lane, Some(&paint));
|
||||
let item = builder.finish();
|
||||
let owned = item.copy_out();
|
||||
let expected = map_groups_to_legacy(paint.element(0).unwrap());
|
||||
@@ -422,7 +580,7 @@ mod run_tests {
|
||||
let arena = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
let replayed = owned.replay(&arena).expect("the arena holds the replay");
|
||||
let run = RunView::<Vector>::new(&replayed).expect("the run holds vector elements");
|
||||
let served = run.attr::<Fill>(0).expect("the fill replays present");
|
||||
let served = run.attr::<EditorMergedLayers>(0).expect("the fill replays present");
|
||||
assert_eq!(map_groups_to_legacy(served.element(0).unwrap()), expected);
|
||||
}
|
||||
|
||||
@@ -435,12 +593,12 @@ mod run_tests {
|
||||
let paint = unsafe { core_types::record::erase_static(native_group_paint(&inner_vector, &source)) };
|
||||
|
||||
let vector = unit_square_at(DVec2::new(4., 4.));
|
||||
let mut builder = RunBuilder::new(&source, element_write_hashed::<Vector>(), &[FieldWrite::of::<Fill>(0)], 1).unwrap();
|
||||
let mut builder = RunBuilder::new(&source, element_write_hashed::<Vector>(), &[FieldWrite::of::<EditorMergedLayers>(0)], 1).unwrap();
|
||||
let lane = builder.push(vector.clone()).unwrap();
|
||||
builder.attr::<Fill>(lane, Some(&paint));
|
||||
builder.attr::<EditorMergedLayers>(lane, Some(&paint));
|
||||
let item = builder.finish();
|
||||
let layout = item.layout().clone();
|
||||
let offset = layout.offset_of(Fill::NAME, 0).unwrap();
|
||||
let offset = layout.offset_of(EditorMergedLayers::NAME, 0).unwrap();
|
||||
// SAFETY: the item's lane is a live record of `layout`.
|
||||
let owned = unsafe { core_types::record::OwnedRecord::copy_out(&layout, item.lanes().get(0).rec()) };
|
||||
let expected = map_groups_to_legacy(paint.element(0).unwrap());
|
||||
@@ -470,8 +628,8 @@ mod run_tests {
|
||||
) -> (core_types::record::Layout, core_types::record::MaterializedSpan, Vec<u64>) {
|
||||
use core_types::record::{Layout, MaterializedSpan, Promotion, element_write, write_field};
|
||||
|
||||
let layout = Layout::default().with_writes(0, element_write::<f64>(), &[FieldWrite::of::<Fill>(0)]);
|
||||
let offset = layout.offset_of(Fill::NAME, 0).unwrap();
|
||||
let layout = Layout::default().with_writes(0, element_write::<f64>(), &[FieldWrite::of::<EditorMergedLayers>(0)]);
|
||||
let offset = layout.offset_of(EditorMergedLayers::NAME, 0).unwrap();
|
||||
let stride = layout.lane_stride();
|
||||
let mut buffer = vec![0u64; (lanes * stride).div_ceil(8)];
|
||||
let base = buffer.as_mut_ptr().cast::<u8>();
|
||||
@@ -493,13 +651,8 @@ mod run_tests {
|
||||
}
|
||||
|
||||
/// The promoted paint of one lane, at the layout the promote published.
|
||||
fn promoted_paint<'p>(
|
||||
span: &core_types::record::MaterializedSpan,
|
||||
layout: &core_types::record::Layout,
|
||||
lane: usize,
|
||||
persistent: &'p core_types::arena::Arena,
|
||||
) -> &'p List<Graphic<'p>> {
|
||||
let offset = layout.offset_of(Fill::NAME, 0).unwrap();
|
||||
fn promoted_paint<'p>(span: &core_types::record::MaterializedSpan, layout: &core_types::record::Layout, lane: usize, persistent: &'p core_types::arena::Arena) -> &'p List<Graphic<'p>> {
|
||||
let offset = layout.offset_of(EditorMergedLayers::NAME, 0).unwrap();
|
||||
let batch = span.batch(persistent, layout).expect("the span resolves in its own region");
|
||||
// SAFETY: the promote wrote a record of `layout` into every lane.
|
||||
unsafe { batch.get(lane).rec().read::<Option<&List<Graphic>>>(offset) }.expect("the paint promotes present")
|
||||
@@ -515,7 +668,9 @@ mod run_tests {
|
||||
// list the evaluation parked.
|
||||
let published = native_group_paint(&inner_vector, &persistent);
|
||||
let interior = {
|
||||
let Some(Graphic::Group(group)) = published.element(0) else { panic!("the paint carries a native group") };
|
||||
let Some(Graphic::Group(group)) = published.element(0) else {
|
||||
panic!("the paint carries a native group")
|
||||
};
|
||||
group.content.lanes().get(0).rec().ptr()
|
||||
};
|
||||
// SAFETY: the list serves only while `persistent` is live, and the
|
||||
@@ -526,7 +681,9 @@ mod run_tests {
|
||||
let (layout, span, _frames) = promote_paint_field(Some(paint), 1, &transient, &persistent);
|
||||
let served = promoted_paint(&span, &layout, 0, &persistent);
|
||||
|
||||
let Some(Graphic::Group(group)) = served.element(0) else { panic!("the promote keeps the group form") };
|
||||
let Some(Graphic::Group(group)) = served.element(0) else {
|
||||
panic!("the promote keeps the group form")
|
||||
};
|
||||
assert_eq!(group.content.lanes().get(0).rec().ptr(), interior, "a persistent interior is shared pointer for pointer");
|
||||
assert!(
|
||||
persistent.occupancy() - occupied <= layout.frame_bytes() + size_of::<List<Graphic>>() + align_of::<List<Graphic>>(),
|
||||
@@ -548,8 +705,14 @@ mod run_tests {
|
||||
|
||||
let (layout, span, _frames) = promote_paint_field(Some(paint), 2, &transient, &persistent);
|
||||
let served = promoted_paint(&span, &layout, 0, &persistent);
|
||||
let Some(Graphic::Vector(vector)) = served.element(0) else { panic!("the promote keeps the vector") };
|
||||
assert_eq!(vector.point_domain.positions().as_ptr(), heap, "the promote moved the header, so the served paint names the pre-promote heap");
|
||||
let Some(Graphic::Vector(vector)) = served.element(0) else {
|
||||
panic!("the promote keeps the vector")
|
||||
};
|
||||
assert_eq!(
|
||||
vector.point_domain.positions().as_ptr(),
|
||||
heap,
|
||||
"the promote moved the header, so the served paint names the pre-promote heap"
|
||||
);
|
||||
assert!(std::ptr::eq(served, promoted_paint(&span, &layout, 1, &persistent)), "a paint two lanes share moves once");
|
||||
|
||||
transient.reset();
|
||||
@@ -569,7 +732,7 @@ mod run_tests {
|
||||
let mut paint = List::new_from_element(Graphic::Vector(unit_square_at(DVec2::new(4., 4.))));
|
||||
// SAFETY: the erased native list serves only while `transient` is live; the
|
||||
// promote under test replaces its borrows.
|
||||
paint.set_attribute::<Option<List<Graphic>>>(Stroke::NAME, 0, Some(unsafe { core_types::record::erase_static(native) }));
|
||||
paint.set_attribute::<Option<List<Graphic>>>("probe:paint", 0, Some(unsafe { core_types::record::erase_static(native) }));
|
||||
let (paint, _) = transient.alloc_sized_keyed(paint, 0).unwrap();
|
||||
|
||||
let (layout, span, _frames) = promote_paint_field(Some(paint), 1, &transient, &persistent);
|
||||
@@ -579,9 +742,13 @@ mod run_tests {
|
||||
|
||||
transient.reset();
|
||||
let served = promoted_paint(&span, &layout, 0, &persistent);
|
||||
let held = served.attribute::<Option<List<Graphic>>>(Stroke::NAME, 0).expect("the stroke attribute rides the promoted list");
|
||||
let held = served.attribute::<Option<List<Graphic>>>("probe:paint", 0).expect("the stroke attribute rides the promoted list");
|
||||
let held = held.as_ref().expect("the stroke is present");
|
||||
assert_eq!(map_groups_to_legacy(held.element(0).unwrap()), expected, "the attribute-held group serves from persistent storage after the reset");
|
||||
assert_eq!(
|
||||
map_groups_to_legacy(held.element(0).unwrap()),
|
||||
expected,
|
||||
"the attribute-held group serves from persistent storage after the reset"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -594,7 +761,7 @@ mod run_tests {
|
||||
// whose value holds none: neither denies the move.
|
||||
paint.set_attribute::<f64>("opacity", 0, 0.5);
|
||||
paint.set_attribute::<Color>("probe:color", 0, Color::BLACK);
|
||||
paint.set_attribute::<Option<List<Graphic>>>(Stroke::NAME, 0, Some(List::new_from_element(Graphic::Color(Color::WHITE))));
|
||||
paint.set_attribute::<Option<List<Graphic>>>("probe:paint", 0, Some(List::new_from_element(Graphic::Color(Color::WHITE))));
|
||||
let heap = {
|
||||
let Some(Graphic::Vector(vector)) = paint.element(0) else { panic!("the paint carries a vector") };
|
||||
vector.point_domain.positions().as_ptr()
|
||||
@@ -603,8 +770,14 @@ mod run_tests {
|
||||
|
||||
let (layout, span, _frames) = promote_paint_field(Some(paint), 1, &transient, &persistent);
|
||||
let served = promoted_paint(&span, &layout, 0, &persistent);
|
||||
let Some(Graphic::Vector(vector)) = served.element(0) else { panic!("the promote keeps the vector") };
|
||||
assert_eq!(vector.point_domain.positions().as_ptr(), heap, "the promote moved the header, so the served paint names the pre-promote heap");
|
||||
let Some(Graphic::Vector(vector)) = served.element(0) else {
|
||||
panic!("the promote keeps the vector")
|
||||
};
|
||||
assert_eq!(
|
||||
vector.point_domain.positions().as_ptr(),
|
||||
heap,
|
||||
"the promote moved the header, so the served paint names the pre-promote heap"
|
||||
);
|
||||
|
||||
transient.reset();
|
||||
let served = promoted_paint(&span, &layout, 0, &persistent);
|
||||
@@ -623,15 +796,15 @@ mod run_tests {
|
||||
let mut paint = List::new_from_element(Graphic::Vector(unit_square_at(DVec2::new(2., 2.))));
|
||||
// SAFETY: the erased native list serves only while `source` is live; the
|
||||
// deep glue under test replaces its borrows at the copy-out seam.
|
||||
paint.set_attribute::<Option<List<Graphic>>>(Stroke::NAME, 0, Some(unsafe { core_types::record::erase_static(native) }));
|
||||
paint.set_attribute::<Option<List<Graphic>>>("probe:paint", 0, Some(unsafe { core_types::record::erase_static(native) }));
|
||||
|
||||
let vector = unit_square_at(DVec2::new(4., 4.));
|
||||
let mut builder = RunBuilder::new(&source, element_write_hashed::<Vector>(), &[FieldWrite::of::<Fill>(0)], 1).unwrap();
|
||||
let mut builder = RunBuilder::new(&source, element_write_hashed::<Vector>(), &[FieldWrite::of::<EditorMergedLayers>(0)], 1).unwrap();
|
||||
let lane = builder.push(vector.clone()).unwrap();
|
||||
builder.attr::<Fill>(lane, Some(&paint));
|
||||
builder.attr::<EditorMergedLayers>(lane, Some(&paint));
|
||||
let item = builder.finish();
|
||||
let layout = item.layout().clone();
|
||||
let offset = layout.offset_of(Fill::NAME, 0).unwrap();
|
||||
let offset = layout.offset_of(EditorMergedLayers::NAME, 0).unwrap();
|
||||
// SAFETY: the item's lane is a live record of `layout`.
|
||||
let owned = unsafe { core_types::record::OwnedRecord::copy_out(&layout, item.lanes().get(0).rec()) };
|
||||
drop(item);
|
||||
@@ -646,8 +819,244 @@ mod run_tests {
|
||||
let value = unsafe { slot.finish() };
|
||||
// SAFETY: the replay wrote a record of `layout`.
|
||||
let served = unsafe { layout.rec(&value).read::<Option<&List<Graphic>>>(offset) }.expect("the fill replays present");
|
||||
let held = served.attribute::<Option<List<Graphic>>>(Stroke::NAME, 0).expect("the stroke attribute rides the replayed list");
|
||||
let held = served.attribute::<Option<List<Graphic>>>("probe:paint", 0).expect("the stroke attribute rides the replayed list");
|
||||
let held = held.as_ref().expect("the stroke is present");
|
||||
assert_eq!(map_groups_to_legacy(held.element(0).unwrap()), expected, "the attribute-held group replayed into the serving arena");
|
||||
}
|
||||
|
||||
use crate::appearance::{Cover, CoverPlacement, Coverage};
|
||||
use crate::markers::Appearance as AppearanceMarker;
|
||||
|
||||
/// A `lanes`-long frame promoted out of `transient` into `persistent`, with
|
||||
/// `appearance` written into the appearance field of every lane. The frame
|
||||
/// buffer comes back so it outlives the promote's reads.
|
||||
fn promote_appearance_field(
|
||||
appearance: Option<&Appearance>,
|
||||
lanes: usize,
|
||||
transient: &core_types::arena::Arena,
|
||||
persistent: &core_types::arena::Arena,
|
||||
) -> (core_types::record::Layout, core_types::record::MaterializedSpan, Vec<u64>) {
|
||||
use core_types::record::{Layout, MaterializedSpan, Promotion, element_write, write_field};
|
||||
|
||||
let layout = Layout::default().with_writes(0, element_write::<f64>(), &[FieldWrite::of::<AppearanceMarker>(0)]);
|
||||
let offset = layout.offset_of(AppearanceMarker::NAME, 0).unwrap();
|
||||
let stride = layout.lane_stride();
|
||||
let mut buffer = vec![0u64; (lanes * stride).div_ceil(8)];
|
||||
let base = buffer.as_mut_ptr().cast::<u8>();
|
||||
let bounds = (base as usize, buffer.len() * 8);
|
||||
for lane in 0..lanes {
|
||||
// SAFETY: the frame is this layout's, written at the element slot and
|
||||
// at the appearance field's own offset.
|
||||
unsafe {
|
||||
base.add(lane * stride).cast::<f64>().write(lane as f64);
|
||||
write_field::<Option<&Appearance>>(base.add(lane * stride), offset, appearance);
|
||||
}
|
||||
}
|
||||
// SAFETY: the frames hold `lanes` live records of `layout`.
|
||||
let batch = unsafe { core_types::node::RecordBatch::new(base.cast_const(), lanes, &layout) };
|
||||
let promotion = Promotion::new(transient, bounds, persistent);
|
||||
// SAFETY: as above.
|
||||
let span = unsafe { MaterializedSpan::to_persistent(&batch, &promotion) }.expect("the region holds the promote");
|
||||
(layout, span, buffer)
|
||||
}
|
||||
|
||||
/// The promoted appearance of one lane, at the layout the promote published.
|
||||
fn promoted_appearance<'p>(span: &core_types::record::MaterializedSpan, layout: &core_types::record::Layout, lane: usize, persistent: &'p core_types::arena::Arena) -> &'p Appearance {
|
||||
let offset = layout.offset_of(AppearanceMarker::NAME, 0).unwrap();
|
||||
let batch = span.batch(persistent, layout).expect("the span resolves in its own region");
|
||||
// SAFETY: the promote wrote a record of `layout` into every lane.
|
||||
unsafe { batch.get(lane).rec().read::<Option<&Appearance>>(offset) }.expect("the appearance promotes present")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_promoted_appearance_shares_persistent_interiors() {
|
||||
let inner_vector = unit_square_at(DVec2::ZERO);
|
||||
let transient = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
let persistent = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
|
||||
// The interior an upstream promote already published, named by a paint
|
||||
// the evaluation parked in a coverage's paint column.
|
||||
let published = native_group_paint(&inner_vector, &persistent);
|
||||
let Some(Graphic::Group(group)) = published.element(0) else {
|
||||
panic!("the paint carries a native group")
|
||||
};
|
||||
let interior = group.content.lanes().get(0).rec().ptr();
|
||||
// SAFETY: the group serves only while `persistent` is live, and the
|
||||
// promote under test replaces every borrow it carries.
|
||||
let paint = unsafe { core_types::record::erase_static(Graphic::Group(group.clone())) };
|
||||
let appearance = Appearance::new_single(Coverage::new_fill(), paint);
|
||||
let (appearance, _) = transient.alloc_sized_keyed(appearance, 0).unwrap();
|
||||
|
||||
let (layout, span, _frames) = promote_appearance_field(Some(appearance), 1, &transient, &persistent);
|
||||
let served = promoted_appearance(&span, &layout, 0, &persistent);
|
||||
|
||||
let Some(Graphic::Group(group)) = served.paint_at(0) else {
|
||||
panic!("the promote keeps the group form")
|
||||
};
|
||||
assert_eq!(group.content.lanes().get(0).rec().ptr(), interior, "a persistent interior is shared pointer for pointer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_free_appearance_moves_its_parked_header() {
|
||||
let mut transient = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
let persistent = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
|
||||
let appearance = Appearance::new_single(Coverage::new_fill(), Graphic::Vector(unit_square_at(DVec2::ZERO)));
|
||||
let heap = {
|
||||
let Some(Graphic::Vector(vector)) = appearance.paint_at(0) else {
|
||||
panic!("the paint carries a vector")
|
||||
};
|
||||
vector.point_domain.positions().as_ptr()
|
||||
};
|
||||
let (appearance, _) = transient.alloc_sized_keyed(appearance, 0).unwrap();
|
||||
|
||||
let (layout, span, _frames) = promote_appearance_field(Some(appearance), 2, &transient, &persistent);
|
||||
let served = promoted_appearance(&span, &layout, 0, &persistent);
|
||||
let Some(Graphic::Vector(vector)) = served.paint_at(0) else {
|
||||
panic!("the promote keeps the vector")
|
||||
};
|
||||
assert_eq!(
|
||||
vector.point_domain.positions().as_ptr(),
|
||||
heap,
|
||||
"the promote moved the header, so the served paint names the pre-promote heap"
|
||||
);
|
||||
assert!(std::ptr::eq(served, promoted_appearance(&span, &layout, 1, &persistent)), "an appearance two lanes share moves once");
|
||||
|
||||
transient.reset();
|
||||
let served = promoted_appearance(&span, &layout, 0, &persistent);
|
||||
assert!(matches!(served.paint_at(0), Some(Graphic::Vector(_))), "the moved appearance survives the transient reset");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_appearance_whose_paint_holds_groups_never_moves() {
|
||||
let inner_vector = unit_square_at(DVec2::ZERO);
|
||||
let mut transient = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
let persistent = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
|
||||
let native = native_group_paint(&inner_vector, &transient);
|
||||
let Some(native_group) = native.element(0) else { panic!("the paint carries a group") };
|
||||
let expected = map_groups_to_legacy(native_group);
|
||||
// SAFETY: the erased native group serves only while `transient` is live;
|
||||
// the promote under test replaces its borrows.
|
||||
let paint = unsafe { core_types::record::erase_static(native_group.clone()) };
|
||||
let appearance = Appearance::new_single(Coverage::new_fill(), paint);
|
||||
let (appearance, _) = transient.alloc_sized_keyed(appearance, 0).unwrap();
|
||||
|
||||
let (layout, span, _frames) = promote_appearance_field(Some(appearance), 1, &transient, &persistent);
|
||||
let served = promoted_appearance(&span, &layout, 0, &persistent);
|
||||
let moved = std::ptr::eq(std::ptr::from_ref(served).cast::<u8>(), std::ptr::from_ref(appearance).cast::<u8>());
|
||||
assert!(!moved, "a paint-held group denies the move, so the promote parks a header of its own");
|
||||
|
||||
transient.reset();
|
||||
let served = promoted_appearance(&span, &layout, 0, &persistent);
|
||||
let held = served.paint_at(0).expect("the paint rides the promoted appearance");
|
||||
assert_eq!(map_groups_to_legacy(held), expected, "the paint-held group serves from persistent storage after the reset");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_free_appearance_moves_past_its_stroke_columns() {
|
||||
let mut transient = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
let persistent = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
|
||||
// Stroke parameters on the coverage and a group-free paint: neither denies the move.
|
||||
let mut appearance = Appearance::new_single(Coverage::new_stroke(&vector_types::vector::style::Stroke::new(2.)), Graphic::Vector(unit_square_at(DVec2::ZERO)));
|
||||
appearance.replace_or_insert(Coverage::new_fill(), Graphic::Color(Color::WHITE), CoverPlacement::Below);
|
||||
let heap = {
|
||||
let Some(Graphic::Vector(vector)) = appearance.paint_at(1) else {
|
||||
panic!("the stroke paint carries a vector")
|
||||
};
|
||||
vector.point_domain.positions().as_ptr()
|
||||
};
|
||||
let (appearance, _) = transient.alloc_sized_keyed(appearance, 0).unwrap();
|
||||
|
||||
let (layout, span, _frames) = promote_appearance_field(Some(appearance), 1, &transient, &persistent);
|
||||
let served = promoted_appearance(&span, &layout, 0, &persistent);
|
||||
let Some(Graphic::Vector(vector)) = served.paint_at(1) else {
|
||||
panic!("the promote keeps the vector")
|
||||
};
|
||||
assert_eq!(
|
||||
vector.point_domain.positions().as_ptr(),
|
||||
heap,
|
||||
"the promote moved the header, so the served paint names the pre-promote heap"
|
||||
);
|
||||
|
||||
transient.reset();
|
||||
let served = promoted_appearance(&span, &layout, 0, &persistent);
|
||||
assert_eq!(
|
||||
served.first_coverage_of(Cover::Stroke).map(|coverage| coverage.stroke_params().weight),
|
||||
Some(2.),
|
||||
"the stroke parameters survive the move"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_paint_field_whose_appearance_column_holds_groups_never_moves() {
|
||||
let inner_vector = unit_square_at(DVec2::ZERO);
|
||||
let mut transient = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
let persistent = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
|
||||
// Group-free elements, with the resident group hidden in an item's appearance paint cell.
|
||||
let native = native_group_paint(&inner_vector, &transient);
|
||||
let Some(native_group) = native.element(0) else { panic!("the paint carries a group") };
|
||||
let expected = map_groups_to_legacy(native_group);
|
||||
// SAFETY: the erased native group serves only while `transient` is live;
|
||||
// the promote under test replaces its borrows.
|
||||
let paint_cell = unsafe { core_types::record::erase_static(native_group.clone()) };
|
||||
let mut paint = List::new_from_element(Graphic::Vector(unit_square_at(DVec2::new(4., 4.))));
|
||||
paint.set_attribute(crate::markers::ATTR_APPEARANCE, 0, Appearance::new_single(Coverage::new_fill(), paint_cell));
|
||||
let (paint, _) = transient.alloc_sized_keyed(paint, 0).unwrap();
|
||||
|
||||
let (layout, span, _frames) = promote_paint_field(Some(paint), 1, &transient, &persistent);
|
||||
let served = promoted_paint(&span, &layout, 0, &persistent);
|
||||
let moved = std::ptr::eq(std::ptr::from_ref(served).cast::<u8>(), std::ptr::from_ref(paint).cast::<u8>());
|
||||
assert!(!moved, "an appearance-held group denies the move, so the promote parks a header of its own");
|
||||
|
||||
transient.reset();
|
||||
let served = promoted_paint(&span, &layout, 0, &persistent);
|
||||
let held = served.attribute::<Appearance>(crate::markers::ATTR_APPEARANCE, 0).expect("the appearance rides the promoted list");
|
||||
let held = held.paint_at(0).expect("the fill coverage keeps its paint");
|
||||
assert_eq!(map_groups_to_legacy(held), expected, "the appearance-held group serves from persistent storage after the reset");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_owned_record_deep_copies_appearance_column_groups() {
|
||||
let inner_vector = unit_square_at(DVec2::ZERO);
|
||||
let source = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
let native = native_group_paint(&inner_vector, &source);
|
||||
let Some(native_group) = native.element(0) else { panic!("the paint carries a group") };
|
||||
let expected = map_groups_to_legacy(native_group);
|
||||
|
||||
// The field's elements are group-free; the group rides an item's appearance
|
||||
// paint cell, which the shallow read alone would leave borrowing `source`.
|
||||
// SAFETY: the erased native group serves only while `source` is live; the
|
||||
// deep glue under test replaces its borrows at the copy-out seam.
|
||||
let paint_cell = unsafe { core_types::record::erase_static(native_group.clone()) };
|
||||
let mut paint = List::new_from_element(Graphic::Vector(unit_square_at(DVec2::new(2., 2.))));
|
||||
paint.set_attribute(crate::markers::ATTR_APPEARANCE, 0, Appearance::new_single(Coverage::new_fill(), paint_cell));
|
||||
|
||||
let vector = unit_square_at(DVec2::new(4., 4.));
|
||||
let mut builder = RunBuilder::new(&source, element_write_hashed::<Vector>(), &[FieldWrite::of::<EditorMergedLayers>(0)], 1).unwrap();
|
||||
let lane = builder.push(vector.clone()).unwrap();
|
||||
builder.attr::<EditorMergedLayers>(lane, Some(&paint));
|
||||
let item = builder.finish();
|
||||
let layout = item.layout().clone();
|
||||
let offset = layout.offset_of(EditorMergedLayers::NAME, 0).unwrap();
|
||||
// SAFETY: the item's lane is a live record of `layout`.
|
||||
let owned = unsafe { core_types::record::OwnedRecord::copy_out(&layout, item.lanes().get(0).rec()) };
|
||||
drop(item);
|
||||
drop(paint);
|
||||
drop(source);
|
||||
|
||||
let arena = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
let frames = core_types::record::test_frames(layout.frame_bytes());
|
||||
let mut slot = frames.claim(&layout);
|
||||
owned.replay_into(&mut slot, &arena).expect("the arena holds the replay");
|
||||
// SAFETY: the replay completes the record in the claimed frame.
|
||||
let value = unsafe { slot.finish() };
|
||||
// SAFETY: the replay wrote a record of `layout`.
|
||||
let served = unsafe { layout.rec(&value).read::<Option<&List<Graphic>>>(offset) }.expect("the field replays present");
|
||||
let held = served.attribute::<Appearance>(crate::markers::ATTR_APPEARANCE, 0).expect("the appearance rides the replayed list");
|
||||
let held = held.paint_at(0).expect("the fill coverage keeps its paint");
|
||||
assert_eq!(map_groups_to_legacy(held), expected, "the appearance-held group replayed into the serving arena");
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
//! The legacy bridge: record-backed groups rebuilt as owned legacy lists.
|
||||
|
||||
use super::walk::push_lane_paint_into_interiors;
|
||||
use super::{Graphic, detable_items};
|
||||
use crate::markers::{ATTR_FILL, ATTR_STROKE};
|
||||
use crate::appearance::Appearance;
|
||||
use crate::markers::{ATTR_APPEARANCE, ATTR_EDITOR_MERGED_LAYERS, ATTR_PAINT};
|
||||
use core_types::Color;
|
||||
use core_types::list::{AttributeValueDyn, Item, List};
|
||||
use core_types::list::{Item, List};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
use vector_types::{GradientStops, Vector};
|
||||
|
||||
@@ -12,26 +12,22 @@ use vector_types::{GradientStops, Vector};
|
||||
/// through its erased read. Content keeps its native form; the legacy
|
||||
/// conversions layer their mapping on top.
|
||||
pub fn run_to_list<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(item: &core_types::record::GroupItem) -> Option<List<T>> {
|
||||
let lanes = item.typed_lanes::<T>()?;
|
||||
let mut list = List::new();
|
||||
for lane in 0..lanes.len() {
|
||||
list.push(Item::new_from_element(lanes.element_ref(lane).clone()));
|
||||
}
|
||||
for field in &item.layout().fields {
|
||||
for lane in 0..lanes.len() {
|
||||
// SAFETY: the offset comes from the item's own layout.
|
||||
let value = unsafe { (field.read_erased)(item.lanes().get(lane).rec().ptr().add(field.offset)) };
|
||||
list.set_attribute_value_dyn(field.name, lane, AttributeValueDyn(value));
|
||||
}
|
||||
}
|
||||
Some(list)
|
||||
core_types::record::run_to_owned_list(item)
|
||||
}
|
||||
|
||||
/// Converts the group content of the list's paint attribute values to legacy
|
||||
/// form, so a legacy product owns everything its attributes reach.
|
||||
/// 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>) {
|
||||
for key in [ATTR_FILL, ATTR_STROKE, crate::markers::ATTR_EDITOR_MERGED_LAYERS] {
|
||||
let Some(values) = list.iter_attribute_values_mut::<Option<List<Graphic>>>(key) else { continue };
|
||||
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);
|
||||
@@ -98,7 +94,6 @@ pub fn group_to_legacy_list(group: &core_types::record::Group) -> List<Graphic<'
|
||||
for element in list.iter_element_values_mut() {
|
||||
*element = map_groups_to_legacy(element);
|
||||
}
|
||||
push_lane_paint_into_interiors(&mut list);
|
||||
return list;
|
||||
}
|
||||
None.or_else(|| run_to_legacy_list::<Vector>(item).map(|list| detable_items(list, Graphic::Vector)))
|
||||
@@ -113,24 +108,25 @@ pub fn group_to_legacy_list(group: &core_types::record::Group) -> List<Graphic<'
|
||||
#[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::Fill;
|
||||
use core_types::attribute::Attribute;
|
||||
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_paint_attr_content() {
|
||||
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::<Fill>(0)], 1).unwrap();
|
||||
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::<Fill>(lane, Some(&paint));
|
||||
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());
|
||||
@@ -138,9 +134,10 @@ mod run_tests {
|
||||
drop(paint);
|
||||
drop(source);
|
||||
|
||||
let served = legacy.attribute::<Option<List<Graphic>>>(Fill::NAME, 0).expect("the fill attribute rides the list");
|
||||
let served = served.as_ref().expect("the fill is present");
|
||||
assert_eq!(served.element(0).unwrap(), &expected);
|
||||
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]
|
||||
|
||||
@@ -7,13 +7,12 @@ pub(crate) use glue::{list_contains_groups, map_attribute_groups_to_owned, map_a
|
||||
pub use glue::{map_groups_to_owned, map_groups_to_persistent, map_groups_to_resident};
|
||||
pub(crate) use legacy::run_to_legacy_list;
|
||||
pub use legacy::{group_to_legacy_graphic, group_to_legacy_list, map_groups_to_legacy, map_paint_attrs_to_legacy, run_to_list};
|
||||
pub use paint::{
|
||||
LanePaint, PaintColumns, PaintOverlay, PaintOverlayColumn, PaintReach, bake_paint_transforms, has_paint, is_paint_present, paint_graphics, set_paint_attribute, set_paint_attribute_at,
|
||||
vector_can_reduce_to_clip_path,
|
||||
};
|
||||
pub use 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};
|
||||
@@ -176,6 +175,7 @@ fn flatten_graphic_list<T>(content: List<Graphic>, extract_variant: fn(Graphic)
|
||||
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 {
|
||||
@@ -197,6 +197,14 @@ fn flatten_graphic_list<T>(content: List<Graphic>, extract_variant: fn(Graphic)
|
||||
*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());
|
||||
}
|
||||
@@ -388,9 +396,9 @@ impl<'e> Graphic<'e> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn can_reduce_to_clip_path(&self) -> bool {
|
||||
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)),
|
||||
Graphic::Vector(vector) => vector_can_reduce_to_clip_path(&core_types::lane::Single(vector), inherited_appearance),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -411,9 +419,8 @@ impl<'e> Graphic<'e> {
|
||||
pub fn is_fully_transparent(&self) -> bool {
|
||||
match self {
|
||||
Graphic::Graphic(list) => list.iter_element_values().all(Graphic::is_fully_transparent),
|
||||
// A bare leaf carries no paint attribute, so only an unstroked
|
||||
// vector is invisible on its own.
|
||||
Graphic::Vector(vector) => vector.stroke.as_ref().is_none_or(|stroke| !stroke.has_renderable_stroke()),
|
||||
// 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,
|
||||
@@ -599,6 +606,33 @@ mod tests {
|
||||
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)]
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
//! The paint column level: fill and stroke read as lane columns and threaded down to the elements they reach.
|
||||
//! The appearance cascade level: the declared appearance read as a lane column and threaded down to the elements it reaches.
|
||||
|
||||
use super::{Graphic, IntoGraphicList};
|
||||
use crate::markers::{ATTR_FILL, ATTR_STROKE, Fill, Stroke};
|
||||
use super::Graphic;
|
||||
use crate::appearance::Appearance;
|
||||
use crate::markers::Appearance as AppearanceMarker;
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
use core_types::attribute::{Attribute, Opacity};
|
||||
use core_types::attribute::Opacity;
|
||||
use core_types::lane::{LaneColumn, LaneSource};
|
||||
use core_types::list::{ItemAttributeValues, List};
|
||||
use glam::DAffine2;
|
||||
@@ -15,213 +16,84 @@ pub fn is_paint_present(graphic_list: &List<Graphic>) -> bool {
|
||||
graphic_list.element(0).is_some_and(|graphic| !graphic.is_empty())
|
||||
}
|
||||
|
||||
/// Look up the paint graphics stored under the marker `A`, in the canonical `List<Graphic>` form.
|
||||
pub fn paint_graphics<'a, A, S>(source: &'a S, index: usize) -> Option<&'a List<Graphic<'static>>>
|
||||
where
|
||||
S: LaneSource,
|
||||
A: Attribute<Value<'a> = Option<&'a List<Graphic<'static>>>>,
|
||||
{
|
||||
source
|
||||
.attr::<A>(index)
|
||||
// Treat a blank paint attribute as absent so an empty attribute doesn't count as painted
|
||||
.filter(|graphic_list| is_paint_present(graphic_list))
|
||||
}
|
||||
|
||||
/// Whether the item carries a non-blank canonical `List<Graphic>` paint under the marker `A`,
|
||||
/// checked by borrowing without cloning the renderable list.
|
||||
pub fn has_paint<'a, A, S>(source: &'a S, index: usize) -> bool
|
||||
where
|
||||
S: LaneSource,
|
||||
A: Attribute<Value<'a> = Option<&'a List<Graphic<'static>>>>,
|
||||
{
|
||||
paint_graphics::<A, S>(source, index).is_some()
|
||||
}
|
||||
|
||||
/// Whether every lane of a vector source draws as a plain clip path: fully
|
||||
/// opaque, fill absent or opaque, stroke invisible or fully transparent.
|
||||
pub fn vector_can_reduce_to_clip_path<S: LaneSource<Element = Vector>>(source: &S) -> bool {
|
||||
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| {
|
||||
let Some(element) = source.element(index) else { return false };
|
||||
if source.element(index).is_none() {
|
||||
return false;
|
||||
}
|
||||
let opacity: f64 = source.attr::<Opacity>(index);
|
||||
|
||||
let fill_opaque_or_absent = paint_graphics::<Fill, _>(source, index).is_none_or(|graphic_list| graphic_list.element(0).is_none_or(|graphic| graphic.is_opaque()));
|
||||
let appearance = Appearance::cascade(source.attr::<AppearanceMarker>(index), inherited_appearance);
|
||||
let resolved = appearance.map(Appearance::fill_and_stroke).unwrap_or_default();
|
||||
|
||||
let stroke_invisible_or_transparent = element.stroke.as_ref().is_none_or(|stroke| !stroke.has_renderable_stroke())
|
||||
|| paint_graphics::<Stroke, _>(source, index).is_none_or(|graphic_list| graphic_list.element(0).is_none_or(|graphic| graphic.is_fully_transparent()));
|
||||
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
|
||||
})
|
||||
}
|
||||
|
||||
/// The paint a lane carries for its interiors, in the reference form
|
||||
/// [`PaintOverlay`] threads down.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
pub struct LanePaint<'a> {
|
||||
pub fill: Option<&'a List<Graphic<'static>>>,
|
||||
pub stroke: Option<&'a List<Graphic<'static>>>,
|
||||
}
|
||||
|
||||
impl<'a> LanePaint<'a> {
|
||||
pub const NONE: Self = Self { fill: None, stroke: None };
|
||||
|
||||
pub fn is_present(&self) -> bool {
|
||||
self.fill.is_some() || self.stroke.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
/// A source's fill and stroke columns, resolved once for per-lane reads.
|
||||
/// A source's declared appearance column, resolved once for per-lane reads.
|
||||
pub struct PaintColumns<'a, S: LaneSource + 'a> {
|
||||
fill: S::Column<'a, Fill>,
|
||||
stroke: S::Column<'a, Stroke>,
|
||||
appearance: S::Column<'a, AppearanceMarker>,
|
||||
}
|
||||
|
||||
impl<'a, S: LaneSource> PaintColumns<'a, S> {
|
||||
pub fn new(source: &'a S) -> Self {
|
||||
Self {
|
||||
fill: source.column::<Fill>(),
|
||||
stroke: source.column::<Stroke>(),
|
||||
appearance: source.column::<AppearanceMarker>(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The lane's present, non-blank paint.
|
||||
pub fn read(&self, lane: usize) -> LanePaint<'a> {
|
||||
let present = |value: Option<Option<&'a List<Graphic<'static>>>>| value.flatten().filter(|list| is_paint_present(list));
|
||||
LanePaint {
|
||||
fill: present(self.fill.try_get(lane)),
|
||||
stroke: present(self.stroke.try_get(lane)),
|
||||
}
|
||||
/// 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)
|
||||
}
|
||||
}
|
||||
|
||||
/// How far a lane's paint reaches into the element beneath it, mirroring the
|
||||
/// legacy conversion's paint push: vector interiors directly and vector
|
||||
/// children of a nested graphic list, one level deep.
|
||||
/// 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> {
|
||||
pub paint: LanePaint<'a>,
|
||||
hops: u8,
|
||||
/// 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 { paint: LanePaint::NONE, hops: 0 };
|
||||
pub const NONE: Self = Self { appearance: None };
|
||||
|
||||
/// The lane's effective reach: an inherited paint stays authoritative
|
||||
/// (lane paint below a push's origin is inert in the legacy model), an
|
||||
/// absent one reads the lane's own paint.
|
||||
/// 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 {
|
||||
match self.paint.is_present() {
|
||||
true => self,
|
||||
false => Self { paint: columns.read(index), hops: 2 },
|
||||
}
|
||||
}
|
||||
|
||||
pub fn applies(&self) -> bool {
|
||||
self.hops > 0 && self.paint.is_present()
|
||||
}
|
||||
|
||||
/// The reach one graphic nesting level further down.
|
||||
pub fn nested(self) -> Self {
|
||||
Self {
|
||||
paint: self.paint,
|
||||
hops: self.hops.saturating_sub(1),
|
||||
}
|
||||
}
|
||||
|
||||
/// The reach entering a group's own graphic run: a spent or absent reach
|
||||
/// resets so the group's own lane paint applies at its own boundary.
|
||||
pub fn into_group_graphics(self) -> Self {
|
||||
match self.applies() {
|
||||
true => self.nested(),
|
||||
false => Self::NONE,
|
||||
appearance: Appearance::cascade(columns.read_appearance(index), self.appearance),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A source with a lane's paint forced over its fill and stroke columns,
|
||||
/// reaching the interiors the legacy conversion's paint push reached.
|
||||
pub struct PaintOverlay<'a, S> {
|
||||
inner: &'a S,
|
||||
paint: LanePaint<'a>,
|
||||
}
|
||||
|
||||
impl<'a, S> PaintOverlay<'a, S> {
|
||||
pub fn new(inner: &'a S, paint: LanePaint<'a>) -> Self {
|
||||
Self { inner, paint }
|
||||
}
|
||||
}
|
||||
|
||||
pub struct PaintOverlayColumn<'a, S: LaneSource + 'a, A: Attribute> {
|
||||
inner: S::Column<'a, A>,
|
||||
forced: Option<A::Value<'a>>,
|
||||
}
|
||||
|
||||
impl<'a, S: LaneSource, A: Attribute> LaneColumn<'a, A> for PaintOverlayColumn<'a, S, A> {
|
||||
fn try_get(&self, lane: usize) -> Option<A::Value<'a>> {
|
||||
match self.forced {
|
||||
Some(forced) => Some(forced),
|
||||
None => self.inner.try_get(lane),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The forced value for the marker `A`: the lane paint where `A` is this
|
||||
/// crate's fill or stroke marker, absent otherwise.
|
||||
fn forced_paint<'a, A: Attribute>(paint: LanePaint<'a>) -> Option<A::Value<'a>> {
|
||||
let slot = match A::NAME {
|
||||
name if name == Fill::NAME => paint.fill,
|
||||
name if name == Stroke::NAME => paint.stroke,
|
||||
/// 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,
|
||||
}?;
|
||||
assert_eq!(
|
||||
std::any::TypeId::of::<A::Value<'static>>(),
|
||||
std::any::TypeId::of::<Option<&'static List<Graphic<'static>>>>(),
|
||||
"attribute `{}` is declared at another value type than this crate's paint form",
|
||||
A::NAME
|
||||
);
|
||||
assert_eq!(
|
||||
size_of::<A::Value<'a>>(),
|
||||
size_of::<Option<&'a List<Graphic<'a>>>>(),
|
||||
"the paint value form must span the marker's value"
|
||||
);
|
||||
// SAFETY: the census admits one value type per attribute name, so a `fill` or `stroke` marker carries this crate's `Option<&List<Graphic>>` at the asserted size.
|
||||
Some(unsafe { std::mem::transmute_copy::<Option<&'a List<Graphic>>, A::Value<'a>>(&Some(slot)) })
|
||||
}
|
||||
|
||||
impl<'a, S: LaneSource> LaneSource for PaintOverlay<'a, S> {
|
||||
type Element = S::Element;
|
||||
type Column<'b, A: Attribute>
|
||||
= PaintOverlayColumn<'b, S, A>
|
||||
where
|
||||
Self: 'b;
|
||||
|
||||
fn lane_count(&self) -> usize {
|
||||
self.inner.lane_count()
|
||||
}
|
||||
|
||||
fn element(&self, lane: usize) -> Option<&S::Element> {
|
||||
self.inner.element(lane)
|
||||
}
|
||||
|
||||
fn column<A: Attribute>(&self) -> PaintOverlayColumn<'_, S, A> {
|
||||
PaintOverlayColumn {
|
||||
inner: self.inner.column::<A>(),
|
||||
forced: forced_paint::<A>(self.paint),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Stores a paint attribute in the paint marker's owned form, the only representation paint readers accept.
|
||||
pub fn set_paint_attribute(attributes: &mut ItemAttributeValues, key: &str, paint: impl IntoGraphicList) {
|
||||
attributes.insert(key, Some(paint.into_graphic_list()));
|
||||
}
|
||||
|
||||
/// Stores a paint attribute at a list index in the paint marker's owned form, the only representation paint readers accept.
|
||||
pub fn set_paint_attribute_at<T>(list: &mut List<T>, index: usize, key: &str, paint: impl IntoGraphicList) {
|
||||
list.set_attribute(key, index, Some(paint.into_graphic_list()));
|
||||
}
|
||||
|
||||
/// Bake the provided transform into the per-item transforms of the paint graphics stored under the
|
||||
/// canonical `List<Graphic>` fill and stroke attributes.
|
||||
/// 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) {
|
||||
@@ -234,9 +106,13 @@ pub fn bake_paint_transforms(attributes: &mut ItemAttributeValues, transform: DA
|
||||
}
|
||||
}
|
||||
|
||||
for paint_key in [ATTR_FILL, ATTR_STROKE] {
|
||||
if let Some(Some(graphics)) = attributes.get_mut::<Option<List<Graphic>>>(paint_key) {
|
||||
bake_graphic_paint_transform(graphics, transform);
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -251,22 +127,44 @@ mod run_tests {
|
||||
use glam::DVec2;
|
||||
|
||||
#[test]
|
||||
fn a_run_serves_the_parked_paint_reference() {
|
||||
let paint = List::new_from_element(Graphic::Color(Color::BLACK));
|
||||
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::<Fill>(0)], 1).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::<Fill>(lane, Some(&paint));
|
||||
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::<Fill>(0), Some(&paint));
|
||||
assert_eq!(paint_graphics::<Fill, _>(&run, 0), Some(&paint));
|
||||
assert_eq!(paint_graphics::<Stroke, _>(&run, 0), None);
|
||||
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!(paint_graphics::<Fill, _>(&legacy, 0), paint_graphics::<Fill, _>(&run, 0));
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
//! The native-content walk: vector rows reached through a graphic's own storage, with no legacy conversion.
|
||||
|
||||
use super::Graphic;
|
||||
use super::paint::{LanePaint, PaintColumns, PaintReach, is_paint_present, paint_graphics, set_paint_attribute_at};
|
||||
use crate::markers::{ATTR_FILL, ATTR_STROKE, Fill};
|
||||
use 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;
|
||||
@@ -251,7 +252,7 @@ pub struct VectorRow<'w> {
|
||||
source: RowSourceRef<'w>,
|
||||
scale: FlattenScale,
|
||||
layer_path: Option<&'w [NodeId]>,
|
||||
paint: LanePaint<'w>,
|
||||
appearance: Option<&'w Appearance>,
|
||||
}
|
||||
|
||||
enum RowSourceRef<'w> {
|
||||
@@ -270,16 +271,14 @@ impl VectorRow<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the built row will carry fill paint: the reaching lane paint,
|
||||
/// else the row's own.
|
||||
/// Whether the built row will carry fill paint: a painted fill coverage on
|
||||
/// the row's resolved appearance.
|
||||
pub fn has_fill(&self) -> bool {
|
||||
if self.paint.fill.is_some() {
|
||||
return true;
|
||||
}
|
||||
match &self.source {
|
||||
RowSourceRef::Lane(level, index) => paint_graphics::<Fill, _>(level, *index).is_some(),
|
||||
RowSourceRef::Run(run, _, index) => paint_graphics::<Fill, _>(*run, *index).is_some(),
|
||||
}
|
||||
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
|
||||
@@ -296,11 +295,6 @@ impl VectorRow<'_> {
|
||||
out.push(Item::from_parts(vector, run_lane_attributes(item, *lane)));
|
||||
}
|
||||
}
|
||||
for (key, slot) in [(ATTR_FILL, self.paint.fill), (ATTR_STROKE, self.paint.stroke)] {
|
||||
if let Some(paint) = slot {
|
||||
set_paint_attribute_at(out, index, key, paint.clone());
|
||||
}
|
||||
}
|
||||
if self.scale.has_transform || out.attribute::<DAffine2>(ATTR_TRANSFORM, index).is_some() {
|
||||
let row_transform: DAffine2 = out.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
out.set_attribute(ATTR_TRANSFORM, index, self.scale.transform * row_transform);
|
||||
@@ -316,10 +310,22 @@ impl VectorRow<'_> {
|
||||
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]>, paint: LanePaint<'_>, visit: &mut dyn FnMut(VectorRow<'_>) -> RowStep) -> RowStep {
|
||||
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;
|
||||
};
|
||||
@@ -328,7 +334,7 @@ fn walk_rows_of_run(item: &core_types::record::GroupItem, scale: FlattenScale, l
|
||||
source: RowSourceRef::Run(&run, item, lane),
|
||||
scale,
|
||||
layer_path,
|
||||
paint,
|
||||
appearance,
|
||||
}) {
|
||||
return RowStep::Stop;
|
||||
}
|
||||
@@ -337,9 +343,9 @@ fn walk_rows_of_run(item: &core_types::record::GroupItem, scale: FlattenScale, l
|
||||
}
|
||||
|
||||
/// Walks a graphic level into its flattened vector rows, matching the legacy
|
||||
/// push-then-flatten lowering: lane paint threads with [`PaintReach`],
|
||||
/// ancestor transform, opacity and fill opacity compose down, the containing
|
||||
/// level's parent layer path overwrites its rows, and non-vector content is
|
||||
/// 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);
|
||||
@@ -355,47 +361,27 @@ fn walk_vector_rows_impl<'a>(
|
||||
if let GraphicLevel::Run(item) = level {
|
||||
// A vector-typed run is already its rows.
|
||||
if item.typed_lanes::<Vector>().is_some() {
|
||||
let paint = match inherited.applies() {
|
||||
true => inherited.paint,
|
||||
false => LanePaint::NONE,
|
||||
};
|
||||
return walk_rows_of_run(item, scale, parent_layer_path, paint, visit);
|
||||
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 row_paint = match reach.applies() {
|
||||
true => reach.paint,
|
||||
false => LanePaint::NONE,
|
||||
};
|
||||
let step = match element {
|
||||
Graphic::Vector(_) => visit(VectorRow {
|
||||
source: RowSourceRef::Lane(level, index),
|
||||
scale,
|
||||
layer_path: parent_layer_path,
|
||||
paint: row_paint,
|
||||
appearance: reach.appearance,
|
||||
}),
|
||||
Graphic::Graphic(children) => walk_vector_rows_impl(
|
||||
GraphicLevel::Legacy(children),
|
||||
scale.composed(&level, index),
|
||||
level.try_attr::<EditorLayerPath>(index),
|
||||
reach.nested(),
|
||||
visit,
|
||||
),
|
||||
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), row_paint, visit)
|
||||
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.into_group_graphics(),
|
||||
visit,
|
||||
)
|
||||
walk_vector_rows_impl(GraphicLevel::Run(item), scale.composed(&level, index), level.try_attr::<EditorLayerPath>(index), reach, visit)
|
||||
} else {
|
||||
RowStep::Continue
|
||||
}
|
||||
@@ -420,26 +406,6 @@ pub fn flatten_vector_rows(level: GraphicLevel<'_>) -> List<Vector> {
|
||||
out
|
||||
}
|
||||
|
||||
/// The transitional paint placement: a lane-level fill or stroke paint
|
||||
/// attribute moves onto the vector interiors the legacy paint readers
|
||||
/// inspect, reaching as far as the pre-flip broadcast did.
|
||||
pub(in crate::graphic) fn push_lane_paint_into_interiors(list: &mut List<Graphic>) {
|
||||
for index in 0..list.len() {
|
||||
for key in [ATTR_FILL, ATTR_STROKE] {
|
||||
let stored = list.attribute::<Option<List<Graphic>>>(key, index).and_then(|optional| optional.as_ref());
|
||||
let Some(paint) = stored.filter(|paint| is_paint_present(paint)).cloned() else {
|
||||
continue;
|
||||
};
|
||||
let Some(Graphic::Graphic(children)) = list.element_mut(index) else { continue };
|
||||
for child in 0..children.len() {
|
||||
if matches!(children.element(child), Some(Graphic::Vector(_))) {
|
||||
set_paint_attribute_at(children, child, key, paint.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The count [`map_groups_to_legacy`] would expose through [`Graphic::as_vector`],
|
||||
/// read from the run's lanes instead of materializing the legacy list. Mirrors
|
||||
/// [`group_to_legacy_graphic`]'s typed-run path, where `Vector` is tried first.
|
||||
@@ -479,6 +445,10 @@ mod run_tests {
|
||||
|
||||
#[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();
|
||||
@@ -490,7 +460,7 @@ mod run_tests {
|
||||
painted.push(Item::new_from_element(Graphic::Vector(unit_square_at(DVec2::ONE))));
|
||||
painted.set_attribute(core_types::ATTR_TRANSFORM, 0, DAffine2::from_translation(DVec2::new(1., 0.)));
|
||||
painted.set_attribute(core_types::ATTR_TRANSFORM, 1, DAffine2::from_translation(DVec2::new(0., 1.)));
|
||||
set_paint_attribute_at(&mut painted, 1, ATTR_FILL, List::new_from_element(Graphic::Color(Color::WHITE)));
|
||||
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.)));
|
||||
@@ -503,12 +473,12 @@ mod run_tests {
|
||||
top.push(Item::new_from_element(Graphic::Vector(unit_square_at(DVec2::new(6., 0.)))));
|
||||
top.set_attribute(core_types::ATTR_TRANSFORM, 0, DAffine2::from_translation(DVec2::new(5., 5.)));
|
||||
top.set_attribute(core_types::ATTR_EDITOR_LAYER_PATH, 0, vec![core_types::uuid::NodeId(7)]);
|
||||
set_paint_attribute_at(&mut top, 0, ATTR_FILL, List::new_from_element(Graphic::Color(Color::BLACK)));
|
||||
top.set_attribute(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)]);
|
||||
set_paint_attribute_at(&mut top, 4, ATTR_FILL, List::new_from_element(Graphic::Color(Color::WHITE)));
|
||||
top.set_attribute(ATTR_APPEARANCE, 4, single(Color::WHITE));
|
||||
|
||||
let legacy = {
|
||||
let mut list = List::new();
|
||||
@@ -516,7 +486,6 @@ mod run_tests {
|
||||
let (element, attributes) = item.into_parts();
|
||||
list.push(Item::from_parts(map_groups_to_legacy(&element), attributes));
|
||||
}
|
||||
push_lane_paint_into_interiors(&mut list);
|
||||
list.into_flattened_list::<Vector>()
|
||||
};
|
||||
let native = flatten_vector_rows(GraphicLevel::Legacy(&top));
|
||||
@@ -538,9 +507,9 @@ mod run_tests {
|
||||
"layer path, row {row}"
|
||||
);
|
||||
assert_eq!(
|
||||
native.attribute::<Option<List<Graphic>>>(ATTR_FILL, row),
|
||||
legacy.attribute::<Option<List<Graphic>>>(ATTR_FILL, row),
|
||||
"fill, row {row}"
|
||||
native.attribute::<Appearance>(ATTR_APPEARANCE, row),
|
||||
legacy.attribute::<Appearance>(ATTR_APPEARANCE, row),
|
||||
"appearance, row {row}"
|
||||
);
|
||||
}
|
||||
assert_eq!(native, legacy);
|
||||
@@ -569,4 +538,33 @@ mod run_tests {
|
||||
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 {
|
||||
@@ -2878,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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3033,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 {
|
||||
@@ -3044,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);
|
||||
@@ -3056,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 };
|
||||
@@ -3075,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 };
|
||||
|
||||
@@ -3094,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 };
|
||||
|
||||
@@ -3111,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]
|
||||
@@ -3119,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 };
|
||||
@@ -3138,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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -240,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)
|
||||
@@ -796,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();
|
||||
@@ -980,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 {
|
||||
@@ -1088,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 => {
|
||||
@@ -1239,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,6 +1292,9 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
};
|
||||
// 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();
|
||||
};
|
||||
@@ -1514,7 +1544,7 @@ 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 input; the kernel borrows the
|
||||
@@ -1714,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)))
|
||||
@@ -1754,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! {
|
||||
@@ -1807,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`.
|
||||
@@ -1850,6 +1902,37 @@ 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 input at every merge point, into the
|
||||
// carried frame when the node has a carrier.
|
||||
@@ -1956,7 +2039,7 @@ 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 input; the kernel borrows the
|
||||
@@ -1966,16 +2049,6 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
}
|
||||
});
|
||||
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.
|
||||
@@ -2097,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();
|
||||
@@ -2225,7 +2307,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,
|
||||
);
|
||||
// The rebind path with nothing hoisted: every non-carrier input binds
|
||||
// fresh per lane, so an index-dependent input reaches its own lane.
|
||||
@@ -2242,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.
|
||||
@@ -2464,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
|
||||
@@ -2512,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! {
|
||||
@@ -2528,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
|
||||
@@ -2566,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
|
||||
@@ -2593,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(),
|
||||
@@ -2611,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}");
|
||||
@@ -2657,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)*
|
||||
@@ -2694,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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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());
|
||||
@@ -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;
|
||||
|
||||
@@ -6,13 +6,25 @@ 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 input is a record input,
|
||||
@@ -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),
|
||||
@@ -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))
|
||||
})
|
||||
@@ -378,7 +397,7 @@ 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))
|
||||
};
|
||||
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
@@ -261,7 +265,10 @@ 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
|
||||
@@ -274,6 +281,8 @@ pub(crate) fn layout_meta_tokens(node: &Node, element_spec: TokenStream2, core_t
|
||||
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;
|
||||
@@ -290,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,
|
||||
@@ -354,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;
|
||||
@@ -362,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.
|
||||
@@ -527,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.
|
||||
@@ -739,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(
|
||||
|
||||
@@ -110,6 +110,42 @@ 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()?;
|
||||
@@ -222,6 +258,9 @@ pub struct ParsedField {
|
||||
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),
|
||||
@@ -333,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.
|
||||
@@ -1231,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,
|
||||
@@ -1356,6 +1408,7 @@ impl ParsedNodeFn {
|
||||
widget_override: ParsedWidgetOverride::Hidden,
|
||||
ty: ParsedFieldType::Regular(RegularParsedField {
|
||||
ty,
|
||||
name_source: None,
|
||||
list_levels: 0,
|
||||
lend: None,
|
||||
exposed: false,
|
||||
@@ -1533,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),
|
||||
@@ -1631,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),
|
||||
@@ -1710,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),
|
||||
@@ -1787,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),
|
||||
@@ -1876,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),
|
||||
@@ -1968,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,
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -164,7 +174,10 @@ fn validate_record_io(parsed: &ParsedNodeFn) {
|
||||
let mut seen_writes: Vec<String> = Vec::new();
|
||||
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");
|
||||
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) {
|
||||
@@ -264,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`)"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -416,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() {
|
||||
|
||||
@@ -262,7 +262,7 @@ mod tests {
|
||||
use core_types::context::{ContextImpl, EvalScope};
|
||||
use core_types::node::Node;
|
||||
use core_types::record::LiftedSource;
|
||||
use core_types::registry::{SourceHandle, ErasedRecordNode};
|
||||
use core_types::registry::{ErasedRecordNode, SourceHandle};
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
|
||||
fn lifted<T: Clone + Send + Sync + core_types::StaticTypeSized>(value: T) -> LiftedSource<T, impl for<'c> Fn(&ContextImpl<'c>) -> GPoll<T>>
|
||||
|
||||
@@ -360,6 +360,15 @@ fn offset(_: impl Ctx, element: f64, by: &f64) -> f64 {
|
||||
element + *by
|
||||
}
|
||||
|
||||
/// Test-only flip node holding a borrow of its lent carrier across a lazy
|
||||
/// input's evaluation: the borrow points into the carrier's frame, so the lazy
|
||||
/// input's claim has to start beyond it.
|
||||
#[node_macro::node(category("Test"))]
|
||||
fn lend_across_lazy(ctx: impl Ctx, element: &f64, addend: impl Node<Context<'_>, Output = f64>) -> Result<f64, Interrupt> {
|
||||
let added = addend.eval(ctx)?;
|
||||
Ok(*element + added)
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Test"))]
|
||||
async fn double_async(_: impl Ctx, element: f64) -> f64 {
|
||||
element * 2.
|
||||
@@ -653,6 +662,9 @@ mod tests {
|
||||
// The fixtures wire constants into every eager input, which the compiler
|
||||
// pass records as lane-invariant.
|
||||
let resolved = core_types::record::RecordLayout {
|
||||
named_writes: Vec::new(),
|
||||
named_reads: Vec::new(),
|
||||
named_read_defaults: Vec::new(),
|
||||
lane_invariant: u32::MAX,
|
||||
..meta.resolve(inputs)
|
||||
};
|
||||
@@ -662,6 +674,9 @@ mod tests {
|
||||
|
||||
fn install_flip<N: Node<ContextImpl<'static>>>(mut node: N, layout: &Layout) -> N {
|
||||
let bundle = core_types::record::RecordLayout {
|
||||
named_writes: Vec::new(),
|
||||
named_reads: Vec::new(),
|
||||
named_read_defaults: Vec::new(),
|
||||
frame_bytes: layout.frame_bytes(),
|
||||
plan: Vec::new(),
|
||||
layout: layout.clone(),
|
||||
@@ -755,6 +770,10 @@ mod tests {
|
||||
let frames = frames_for(&[&base, &count_layout]);
|
||||
|
||||
let meta = core_types::record::LayoutMeta {
|
||||
named_writes: Vec::new(),
|
||||
folded_names: Vec::new(),
|
||||
named_reads: Vec::new(),
|
||||
folded_read_names: Vec::new(),
|
||||
sources: vec![0],
|
||||
reads: vec![],
|
||||
element: core_types::record::ElementSpec::Carried,
|
||||
@@ -791,6 +810,10 @@ mod tests {
|
||||
let frames = frames_for(&[&base, &count_layout]);
|
||||
|
||||
let meta = core_types::record::LayoutMeta {
|
||||
named_writes: Vec::new(),
|
||||
folded_names: Vec::new(),
|
||||
named_reads: Vec::new(),
|
||||
folded_read_names: Vec::new(),
|
||||
sources: vec![0],
|
||||
reads: vec![],
|
||||
element: core_types::record::ElementSpec::Carried,
|
||||
@@ -835,6 +858,10 @@ mod tests {
|
||||
let frames = frames_for(&[&base, &count_layout, &reverse_layout]);
|
||||
|
||||
let meta = core_types::record::LayoutMeta {
|
||||
named_writes: Vec::new(),
|
||||
folded_names: Vec::new(),
|
||||
named_reads: Vec::new(),
|
||||
folded_read_names: Vec::new(),
|
||||
sources: vec![0],
|
||||
reads: vec![],
|
||||
element: core_types::record::ElementSpec::Carried,
|
||||
@@ -885,6 +912,10 @@ mod tests {
|
||||
&[Some(&base)],
|
||||
);
|
||||
let meta = core_types::record::LayoutMeta {
|
||||
named_writes: Vec::new(),
|
||||
folded_names: Vec::new(),
|
||||
named_reads: Vec::new(),
|
||||
folded_read_names: Vec::new(),
|
||||
sources: vec![0],
|
||||
reads: vec![],
|
||||
element: core_types::record::ElementSpec::Carried,
|
||||
@@ -983,6 +1014,10 @@ mod tests {
|
||||
field: Some((Length::NAME, 7.)),
|
||||
};
|
||||
let meta = core_types::record::LayoutMeta {
|
||||
named_writes: Vec::new(),
|
||||
folded_names: Vec::new(),
|
||||
named_reads: Vec::new(),
|
||||
folded_read_names: Vec::new(),
|
||||
sources: vec![0, 1],
|
||||
reads: vec![],
|
||||
element: core_types::record::ElementSpec::Carried,
|
||||
@@ -1051,6 +1086,10 @@ mod tests {
|
||||
field: Some((Opacity::NAME, 0.25)),
|
||||
};
|
||||
let meta = || core_types::record::LayoutMeta {
|
||||
named_writes: Vec::new(),
|
||||
folded_names: Vec::new(),
|
||||
named_reads: Vec::new(),
|
||||
folded_read_names: Vec::new(),
|
||||
sources: vec![0, 1],
|
||||
reads: vec![],
|
||||
element: core_types::record::ElementSpec::Carried,
|
||||
@@ -1125,6 +1164,10 @@ mod tests {
|
||||
field: Some((Length::NAME, 7.)),
|
||||
};
|
||||
let meta = core_types::record::LayoutMeta {
|
||||
named_writes: Vec::new(),
|
||||
folded_names: Vec::new(),
|
||||
named_reads: Vec::new(),
|
||||
folded_read_names: Vec::new(),
|
||||
sources: vec![0, 1],
|
||||
reads: vec![],
|
||||
element: core_types::record::ElementSpec::Carried,
|
||||
@@ -1169,6 +1212,10 @@ mod tests {
|
||||
|
||||
let content_layout = leveled_f64_layout(&[]);
|
||||
let meta = || core_types::record::LayoutMeta {
|
||||
named_writes: Vec::new(),
|
||||
folded_names: Vec::new(),
|
||||
named_reads: Vec::new(),
|
||||
folded_read_names: Vec::new(),
|
||||
sources: vec![0],
|
||||
reads: vec![],
|
||||
element: core_types::record::ElementSpec::Carried,
|
||||
@@ -1178,6 +1225,10 @@ mod tests {
|
||||
folded: None,
|
||||
};
|
||||
let extend_meta = || core_types::record::LayoutMeta {
|
||||
named_writes: Vec::new(),
|
||||
folded_names: Vec::new(),
|
||||
named_reads: Vec::new(),
|
||||
folded_read_names: Vec::new(),
|
||||
sources: vec![0, 1],
|
||||
reads: vec![],
|
||||
element: core_types::record::ElementSpec::Carried,
|
||||
@@ -1253,6 +1304,10 @@ mod tests {
|
||||
let layout = leveled_f64_layout(&[]);
|
||||
let frames = frames_for(&[&layout]);
|
||||
let meta = || core_types::record::LayoutMeta {
|
||||
named_writes: Vec::new(),
|
||||
folded_names: Vec::new(),
|
||||
named_reads: Vec::new(),
|
||||
folded_read_names: Vec::new(),
|
||||
sources: vec![0],
|
||||
reads: vec![],
|
||||
element: core_types::record::ElementSpec::Carried,
|
||||
@@ -1306,6 +1361,10 @@ mod tests {
|
||||
};
|
||||
let (index_edge, index_layout) = lifted_value(index);
|
||||
let meta = core_types::record::LayoutMeta {
|
||||
named_writes: Vec::new(),
|
||||
folded_names: Vec::new(),
|
||||
named_reads: Vec::new(),
|
||||
folded_read_names: Vec::new(),
|
||||
sources: vec![0],
|
||||
reads: vec![],
|
||||
element: core_types::record::ElementSpec::Carried,
|
||||
@@ -1522,6 +1581,9 @@ mod tests {
|
||||
let evals = std::cell::Cell::new(0u32);
|
||||
let mut node = MirrorNode::new(RecordSource::new(content, &layout, &layout), counting_value(true, &evals));
|
||||
let resolved = core_types::record::RecordLayout {
|
||||
named_writes: Vec::new(),
|
||||
named_reads: Vec::new(),
|
||||
named_read_defaults: Vec::new(),
|
||||
lane_invariant: 0,
|
||||
..mirror_layout_meta().resolve(&[Some(&layout)])
|
||||
};
|
||||
@@ -1600,6 +1662,10 @@ mod tests {
|
||||
&[Some(&base)],
|
||||
);
|
||||
let meta = core_types::record::LayoutMeta {
|
||||
named_writes: Vec::new(),
|
||||
folded_names: Vec::new(),
|
||||
named_reads: Vec::new(),
|
||||
folded_read_names: Vec::new(),
|
||||
sources: vec![0],
|
||||
reads: vec![],
|
||||
element: core_types::record::ElementSpec::Carried,
|
||||
@@ -1653,6 +1719,10 @@ mod tests {
|
||||
&[Some(&base)],
|
||||
);
|
||||
let meta = core_types::record::LayoutMeta {
|
||||
named_writes: Vec::new(),
|
||||
folded_names: Vec::new(),
|
||||
named_reads: Vec::new(),
|
||||
folded_read_names: Vec::new(),
|
||||
sources: vec![0],
|
||||
reads: vec![],
|
||||
element: core_types::record::ElementSpec::Carried,
|
||||
@@ -1763,6 +1833,10 @@ mod tests {
|
||||
let (count_edge, count_layout) = lifted_value(2u32);
|
||||
let (reverse_edge, reverse_layout) = lifted_value(false);
|
||||
let meta = core_types::record::LayoutMeta {
|
||||
named_writes: Vec::new(),
|
||||
folded_names: Vec::new(),
|
||||
named_reads: Vec::new(),
|
||||
folded_read_names: Vec::new(),
|
||||
sources: vec![0],
|
||||
reads: vec![],
|
||||
element: core_types::record::ElementSpec::Carried,
|
||||
@@ -1889,6 +1963,10 @@ mod tests {
|
||||
let frames = frames_for(&[&base, &count_layout, &out]);
|
||||
|
||||
let meta = core_types::record::LayoutMeta {
|
||||
named_writes: Vec::new(),
|
||||
folded_names: Vec::new(),
|
||||
named_reads: Vec::new(),
|
||||
folded_read_names: Vec::new(),
|
||||
sources: vec![0],
|
||||
reads: vec![],
|
||||
element: core_types::record::ElementSpec::Carried,
|
||||
@@ -2342,6 +2420,35 @@ mod tests {
|
||||
assert_eq!(served.attr::<Opacity>(), 0.25);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lent_carrier_borrow_survives_a_lazy_inputs_claim() {
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let carrier_layout = f64_layout(&["opacity"]);
|
||||
let addend_layout = f64_layout(&["opacity"]);
|
||||
assert!(carrier_layout.frame_bytes() != 0, "the lend must borrow into a spilled frame for the claims to overlap");
|
||||
let frames = frames_for(&[&carrier_layout, &addend_layout]);
|
||||
|
||||
let node = install(
|
||||
LendAcrossLazyNode::new(
|
||||
f64_record_source(&carrier_layout, 2., vec![("opacity", 0.25)]),
|
||||
f64_record_source(&addend_layout, 40., vec![("opacity", 0.5)]),
|
||||
&carrier_layout,
|
||||
&addend_layout,
|
||||
),
|
||||
lend_across_lazy_layout_meta(),
|
||||
&[Some(&carrier_layout), None],
|
||||
);
|
||||
let GPoll::Final(served) = core_types::record::capture(&node, &ctx, &frames) else {
|
||||
panic!("expected a final record");
|
||||
};
|
||||
assert_eq!(served.element::<f64>(), 42., "the lazy input claims beyond the carrier's frame, so the borrow keeps its element");
|
||||
assert_eq!(served.attr::<Opacity>(), 0.25);
|
||||
}
|
||||
|
||||
struct InlineRuntime;
|
||||
|
||||
impl core_types::runtime::Runtime for InlineRuntime {
|
||||
@@ -2405,13 +2512,7 @@ mod tests {
|
||||
let frames = frames_for(&[&source_layout]);
|
||||
|
||||
let node = install(
|
||||
FadeAsyncNode::new(
|
||||
f64_record_source(&source_layout, 3., vec![("length", 9.)]),
|
||||
ValueSource::new(0.5),
|
||||
runtime,
|
||||
source_id,
|
||||
&source_layout,
|
||||
),
|
||||
FadeAsyncNode::new(f64_record_source(&source_layout, 3., vec![("length", 9.)]), ValueSource::new(0.5), runtime, source_id, &source_layout),
|
||||
fade_async_layout_meta(),
|
||||
&[Some(&source_layout)],
|
||||
);
|
||||
@@ -2444,11 +2545,7 @@ mod tests {
|
||||
let layout = measure_async_layout();
|
||||
let frames = frames_for(&[&layout]);
|
||||
|
||||
let node = install(
|
||||
MeasureAsyncNode::new(ValueSource::new(()), ValueSource::new(-4.), runtime, source_id),
|
||||
measure_async_layout_meta(),
|
||||
&[],
|
||||
);
|
||||
let node = install(MeasureAsyncNode::new(ValueSource::new(()), ValueSource::new(-4.), runtime, source_id), measure_async_layout_meta(), &[]);
|
||||
assert_eq!(Node::<ContextImpl>::layout(&node), &layout);
|
||||
|
||||
let GPoll::Final(served) = core_types::record::capture(&node, &ctx, &frames) else {
|
||||
@@ -2859,8 +2956,14 @@ mod tests {
|
||||
let frames = frames_for(&[&layout]);
|
||||
let base = {
|
||||
let probe = frames.scope();
|
||||
// SAFETY: nothing reads the probe's record; only its address is taken.
|
||||
let value = unsafe { probe.claim(&layout).finish() };
|
||||
let mut claim = probe.claim(&layout);
|
||||
claim.element(0f64, &arena).expect("the arena holds the element");
|
||||
for name in ["opacity", "length"] {
|
||||
// SAFETY: the offset is this claim's own layout's, at the f64 the field was declared with.
|
||||
unsafe { claim.attr_at(layout.offset_of(name, 0).expect("the fixture declares the field"), 0f64) };
|
||||
}
|
||||
// SAFETY: the element and both fields complete the record.
|
||||
let value = unsafe { claim.finish() };
|
||||
layout.rec(&value).ptr()
|
||||
};
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use core_types::attribute::{Attr, EditorLayerPath, Transform as TransformAttr};
|
||||
use core_types::attribute::{Attr, EditorLayerPath, Name0, Named, Transform as TransformAttr, WireValue};
|
||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::extent::{ExtentIn, LevelIn, ListIn, ValueIn};
|
||||
use core_types::gpoll::{Extent, GPoll, GraphError, Interrupt, Level};
|
||||
@@ -11,6 +11,7 @@ use graphic_types::graphic::{Graphic, IntoGraphicList};
|
||||
use graphic_types::{ATTR_EDITOR_MERGED_LAYERS, Artboard, Vector};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
|
||||
use vector_types::gradient::{GradientSpreadMethod, GradientType as GradientTypeValue};
|
||||
use vector_types::{GradientStop, GradientStops, ReferencePoint};
|
||||
|
||||
/// Resolves a signed index over `total` lanes: negatives count from the end,
|
||||
@@ -180,8 +181,7 @@ fn mirror_lane<'e, T: Clone + Default + Send + Sync + 'static>(
|
||||
(
|
||||
T,
|
||||
Attr<'e, TransformAttr>,
|
||||
Attr<'e, graphic_types::markers::Fill>,
|
||||
Attr<'e, graphic_types::markers::Stroke>,
|
||||
Attr<'e, graphic_types::markers::Appearance>,
|
||||
Attr<'e, core_types::attribute::BlendMode>,
|
||||
Attr<'e, core_types::attribute::Opacity>,
|
||||
Attr<'e, core_types::attribute::OpacityFill>,
|
||||
@@ -212,28 +212,22 @@ where
|
||||
trace: Vec::new(),
|
||||
})
|
||||
};
|
||||
let park_paint = |paint: Option<List<Graphic<'static>>>| -> Result<Option<&'e List<Graphic<'static>>>, Interrupt> {
|
||||
match paint {
|
||||
Some(paint) => Ok(Some(arena.alloc_sized_keyed(paint, 0).ok_or_else(exhausted)?.0)),
|
||||
None => Ok(None),
|
||||
}
|
||||
};
|
||||
|
||||
let element = legacy.element(source).cloned().unwrap_or_default();
|
||||
let mut transform: DAffine2 = legacy.attribute_cloned_or_default(ATTR_TRANSFORM, source);
|
||||
if mirrored {
|
||||
transform = reflected_transform.expect("a mirrored lane exists only under a reflection") * transform;
|
||||
}
|
||||
let fill = park_paint(legacy.attribute::<Option<List<Graphic>>>(graphic_types::ATTR_FILL, source).cloned().flatten())?;
|
||||
let stroke = park_paint(legacy.attribute::<Option<List<Graphic>>>(graphic_types::ATTR_STROKE, source).cloned().flatten())?;
|
||||
let appearance = match legacy.attribute::<graphic_types::Appearance>(graphic_types::ATTR_APPEARANCE, source).cloned() {
|
||||
Some(appearance) => Some(&*arena.alloc_sized_keyed(appearance, 0).ok_or_else(exhausted)?.0),
|
||||
None => None,
|
||||
};
|
||||
let layer_path: Vec<NodeId> = legacy.attribute::<Vec<NodeId>>(ATTR_EDITOR_LAYER_PATH, source).cloned().unwrap_or_default();
|
||||
let layer_path = arena.alloc(layer_path).ok_or_else(exhausted)?.0;
|
||||
|
||||
Ok((
|
||||
element,
|
||||
Attr(transform),
|
||||
Attr(fill),
|
||||
Attr(stroke),
|
||||
Attr(appearance),
|
||||
Attr(legacy.attribute_cloned_or_default(core_types::ATTR_BLEND_MODE, source)),
|
||||
Attr(legacy.attribute_cloned_or(core_types::ATTR_OPACITY, source, 1.)),
|
||||
Attr(legacy.attribute_cloned_or(core_types::ATTR_OPACITY_FILL, source, 1.)),
|
||||
@@ -265,8 +259,7 @@ fn mirror<'e>(
|
||||
IList<(
|
||||
Graphic<'static>,
|
||||
Attr<'e, TransformAttr>,
|
||||
Attr<'e, graphic_types::markers::Fill>,
|
||||
Attr<'e, graphic_types::markers::Stroke>,
|
||||
Attr<'e, graphic_types::markers::Appearance>,
|
||||
Attr<'e, core_types::attribute::BlendMode>,
|
||||
Attr<'e, core_types::attribute::Opacity>,
|
||||
Attr<'e, core_types::attribute::OpacityFill>,
|
||||
@@ -315,8 +308,7 @@ fn mirror_vector<'e>(
|
||||
IList<(
|
||||
Vector,
|
||||
Attr<'e, TransformAttr>,
|
||||
Attr<'e, graphic_types::markers::Fill>,
|
||||
Attr<'e, graphic_types::markers::Stroke>,
|
||||
Attr<'e, graphic_types::markers::Appearance>,
|
||||
Attr<'e, core_types::attribute::BlendMode>,
|
||||
Attr<'e, core_types::attribute::Opacity>,
|
||||
Attr<'e, core_types::attribute::OpacityFill>,
|
||||
@@ -368,6 +360,73 @@ pub fn stamp_layer_path<'e, T>(ctx: impl Ctx + ExtractArena<'e>, element: T, pat
|
||||
Ok((element, Attr(parked.as_slice())))
|
||||
}
|
||||
|
||||
/// Writes `value` onto each lane under the attribute `name` names. The name is
|
||||
/// constant text the compiler folds into the layout when the graph compiles, so
|
||||
/// the write costs exactly what a marker node's does; a name that is not
|
||||
/// constant is refused there rather than resolved here.
|
||||
#[node_macro::node(category("Attributes: Write"))]
|
||||
pub fn write_attribute<'e, T, V: WireValue>(
|
||||
ctx: impl Ctx + ExtractArena<'e>,
|
||||
content: T,
|
||||
/// The attribute name, folded into the layout when the graph compiles.
|
||||
name: Named<Name0>,
|
||||
#[implementations(f64, u32, u64, bool, DVec2, DAffine2, Color, Vec<NodeId>, String)] value: V,
|
||||
) -> Result<(T, Attr<'e, Named<Name0, V::Row>>), Interrupt> {
|
||||
let parked = value.park(ctx.arena()).ok_or(GraphError {
|
||||
kind: core_types::gpoll::ErrorKind::ArenaExhausted,
|
||||
trace: Vec::new(),
|
||||
})?;
|
||||
Ok((content, Attr(parked)))
|
||||
}
|
||||
|
||||
// The attribute reads: one node per value type, since a name means one type
|
||||
// and there is no coercion between them. Each takes any record wire, never
|
||||
// looks at its element, and serves the name's own default where the attribute
|
||||
// is absent, so the value always carries the declared type.
|
||||
//
|
||||
// The name is constant text the compiler folds into an offset when the graph
|
||||
// compiles; a name written at another value type is a graph error rather than
|
||||
// a conversion.
|
||||
macro_rules! attribute_reads {
|
||||
($($(#[$meta:meta])* $node:ident: $row:ty => $value:ty;)*) => {
|
||||
$(
|
||||
$(#[$meta])*
|
||||
#[node_macro::node(category("Attributes: Read"))]
|
||||
pub fn $node<T>(
|
||||
_: impl Ctx,
|
||||
/// The content whose lanes carry the attribute; its element is never read.
|
||||
(content, value): (T, Attr<Named<Name0, $row>>),
|
||||
/// The attribute name, folded into an offset when the graph compiles.
|
||||
name: Named<Name0>,
|
||||
) -> $value {
|
||||
let _ = content;
|
||||
*value
|
||||
}
|
||||
)*
|
||||
};
|
||||
}
|
||||
|
||||
attribute_reads! {
|
||||
/// Reads a named `f64` attribute, such as `opacity` or `font_size`.
|
||||
read_number_attribute: f64 => f64;
|
||||
/// Reads a named `u64` attribute, such as a regex match's `start` or `end`.
|
||||
read_integer_attribute: u64 => u64;
|
||||
/// Reads a named `bool` attribute, such as `clipping_mask` or `clip`.
|
||||
read_bool_attribute: bool => bool;
|
||||
/// Reads a named `DVec2` attribute, such as an artboard's `location` or `dimensions`.
|
||||
read_coordinate_attribute: DVec2 => DVec2;
|
||||
/// Reads a named `DAffine2` attribute, such as `transform`.
|
||||
read_transform_attribute: DAffine2 => DAffine2;
|
||||
/// Reads a named `Color` attribute, such as an artboard's `background`.
|
||||
read_color_attribute: Color => Color;
|
||||
/// Reads a named `BlendMode` attribute, such as `blend_mode`.
|
||||
read_blend_mode_attribute: core_types::blending::BlendMode => core_types::blending::BlendMode;
|
||||
/// Reads a named gradient-shape attribute, such as `gradient_type`.
|
||||
read_gradient_type_attribute: GradientTypeValue => GradientTypeValue;
|
||||
/// Reads a named gradient-spread attribute, such as `spread_method`.
|
||||
read_spread_method_attribute: GradientSpreadMethod => GradientSpreadMethod;
|
||||
}
|
||||
|
||||
/// Joins two levels of the same type, the base's lanes followed by the new's.
|
||||
#[node_macro::node(category("General"), extent(extend_extent))]
|
||||
pub fn extend<T>(
|
||||
|
||||
@@ -285,6 +285,9 @@ mod tests {
|
||||
// The fixtures wire constants into every eager input, which the compiler
|
||||
// pass records as lane-invariant.
|
||||
let resolved = record::RecordLayout {
|
||||
named_writes: Vec::new(),
|
||||
named_reads: Vec::new(),
|
||||
named_read_defaults: Vec::new(),
|
||||
lane_invariant: u32::MAX,
|
||||
..meta.resolve(inputs)
|
||||
};
|
||||
@@ -294,6 +297,9 @@ mod tests {
|
||||
|
||||
fn install_flip<N: Node<ContextImpl<'static>>>(mut node: N, layout: &Layout) -> N {
|
||||
let bundle = record::RecordLayout {
|
||||
named_writes: Vec::new(),
|
||||
named_reads: Vec::new(),
|
||||
named_read_defaults: Vec::new(),
|
||||
frame_bytes: layout.frame_bytes(),
|
||||
plan: Vec::new(),
|
||||
layout: layout.clone(),
|
||||
@@ -420,6 +426,10 @@ mod tests {
|
||||
|
||||
fn routing_meta(source: u8, level_delta: i8) -> record::LayoutMeta {
|
||||
record::LayoutMeta {
|
||||
named_writes: Vec::new(),
|
||||
folded_names: Vec::new(),
|
||||
named_reads: Vec::new(),
|
||||
folded_read_names: Vec::new(),
|
||||
sources: vec![source],
|
||||
reads: vec![],
|
||||
element: record::ElementSpec::Carried,
|
||||
@@ -750,10 +760,11 @@ mod tests {
|
||||
let copy = unsafe { (out.element.clone_out)(out.rec(&value).ptr()) };
|
||||
|
||||
let replay_arena = Arena::new(1 << 16).unwrap();
|
||||
let mut slot = [0u8; 8];
|
||||
unsafe { (out.element.repark)(&*copy, slot.as_mut_ptr(), &replay_arena) }.expect("the arena holds the replay");
|
||||
// Word storage: a parked element slot holds an 8-aligned reference.
|
||||
let mut slot = [0u64; 1];
|
||||
unsafe { (out.element.repark)(&*copy, slot.as_mut_ptr().cast(), &replay_arena) }.expect("the arena holds the replay");
|
||||
// SAFETY: the re-park wrote a parked `Graphic` element into `slot`.
|
||||
let Graphic::Group(group) = (unsafe { record::borrow_element::<Graphic>(record::Rec::new(slot.as_ptr())) }) else {
|
||||
let Graphic::Group(group) = (unsafe { record::borrow_element::<Graphic>(record::Rec::new(slot.as_ptr().cast())) }) else {
|
||||
panic!("the replay restores the group element");
|
||||
};
|
||||
let item = &group.content;
|
||||
@@ -880,7 +891,11 @@ mod tests {
|
||||
let head = ctx.index_head();
|
||||
let group = {
|
||||
// SAFETY: the element is cloned out inside the scope, so no borrow
|
||||
// into the frame escapes it.
|
||||
// into the frame escapes it. The clone is shallow, so the `'static`
|
||||
// the `GraphicSource` rows infer launders a borrow of `arena`: it is
|
||||
// contained because `arena` outlives every use below and this test
|
||||
// never resets it, so the interior stays resident for the whole
|
||||
// generation the group is read in.
|
||||
let scope = frames.scope();
|
||||
let GPoll::Final(value) = record::serve_input(&wrapped, &ctx.promoted(&head, 0), &scope) else {
|
||||
panic!("expected a final record");
|
||||
|
||||
@@ -12,7 +12,7 @@ pub use graphene_application_io as application_io;
|
||||
pub use graphene_core;
|
||||
pub use graphene_core::debug;
|
||||
pub use graphic_nodes;
|
||||
pub use graphic_types::{Artboard, Graphic, Vector};
|
||||
pub use graphic_types::{Appearance, Artboard, Cover, Coverage, Graphic, Vector};
|
||||
pub use math_nodes;
|
||||
pub use path_bool_nodes;
|
||||
pub use raster_nodes;
|
||||
|
||||
@@ -9,13 +9,13 @@ use core_types::gpoll::GPoll;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use core_types::list::List;
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use core_types::math::bbox::Bbox;
|
||||
use core_types::runtime::SourceFuture;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use core_types::transform::Footprint;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use core_types::{ATTR_TRANSFORM, WasmNotSend};
|
||||
use core_types::{Color, Ctx};
|
||||
pub use graph_craft::application_io::resource::{Resource, ResourceHash};
|
||||
pub use graph_craft::application_io::*;
|
||||
@@ -204,17 +204,17 @@ fn create_canvas(_: impl Ctx) -> CanvasHandle {
|
||||
/// Renders a view of the input graphic within an area defined by the *Footprint*.
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[node_macro::node(category(""))]
|
||||
async fn rasterize<T: WasmNotSend + Clone>(
|
||||
async fn rasterize<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(
|
||||
_: impl Ctx,
|
||||
_: (),
|
||||
#[implementations(
|
||||
List<Vector>,
|
||||
List<Raster<CPU>>,
|
||||
List<Graphic>,
|
||||
List<Color>,
|
||||
List<GradientStops>,
|
||||
Vector,
|
||||
Raster<CPU>,
|
||||
Graphic,
|
||||
Color,
|
||||
GradientStops,
|
||||
)]
|
||||
mut data: List<T>,
|
||||
mut data: IList<T>,
|
||||
footprint: Footprint,
|
||||
mut canvas: CanvasHandle,
|
||||
) -> (Raster<CPU>, Attr<Transform>, OwnedAttr<EditorMergedLayers>)
|
||||
|
||||
@@ -43,7 +43,7 @@ pub struct CacheKey {
|
||||
pub for_mask: bool,
|
||||
pub thumbnail: bool,
|
||||
pub aligned_strokes: bool,
|
||||
pub override_paint_order: bool,
|
||||
pub stroke_below: bool,
|
||||
pub animation_time_ms: i64,
|
||||
pub real_time_ms: i64,
|
||||
pub pointer: [u8; 16],
|
||||
@@ -60,7 +60,7 @@ impl CacheKey {
|
||||
for_mask: bool,
|
||||
thumbnail: bool,
|
||||
aligned_strokes: bool,
|
||||
override_paint_order: bool,
|
||||
stroke_below: bool,
|
||||
animation_time: f64,
|
||||
real_time: f64,
|
||||
pointer: Option<DVec2>,
|
||||
@@ -85,7 +85,7 @@ impl CacheKey {
|
||||
for_mask,
|
||||
thumbnail,
|
||||
aligned_strokes,
|
||||
override_paint_order,
|
||||
stroke_below,
|
||||
animation_time_ms: (animation_time * 1000.).round() as i64,
|
||||
real_time_ms: (real_time * 1000.).round() as i64,
|
||||
pointer: pointer_bytes,
|
||||
@@ -360,7 +360,7 @@ pub fn render_output_cache(
|
||||
render_params.for_mask,
|
||||
render_params.thumbnail,
|
||||
render_params.aligned_strokes,
|
||||
render_params.override_paint_order,
|
||||
render_params.stroke_below,
|
||||
ctx.try_animation_time().unwrap_or(0.),
|
||||
ctx.try_real_time().unwrap_or(0.),
|
||||
ctx.try_pointer_position(),
|
||||
|
||||
@@ -272,6 +272,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(),
|
||||
},
|
||||
);
|
||||
let GPoll::Final(result) = core_types::record::serve_input(&graph, &ctx, &frames) else {
|
||||
|
||||
@@ -1053,6 +1053,9 @@ mod graphene_test {
|
||||
|
||||
fn installed<N: Node<ContextImpl<'static>>>(mut node: N, layout: &Layout) -> N {
|
||||
node.set_layout(core_types::record::RecordLayout {
|
||||
named_writes: Vec::new(),
|
||||
named_reads: Vec::new(),
|
||||
named_read_defaults: Vec::new(),
|
||||
frame_bytes: layout.frame_bytes(),
|
||||
plan: Vec::new(),
|
||||
layout: layout.clone(),
|
||||
@@ -1114,6 +1117,9 @@ mod graphene_test {
|
||||
let mut wired = construct(&entries[0], vec![record_value_source(true), record_value_source(false)]).unwrap();
|
||||
let layout = out_layout::<bool>();
|
||||
wired.set_layout(core_types::record::RecordLayout {
|
||||
named_writes: Vec::new(),
|
||||
named_reads: Vec::new(),
|
||||
named_read_defaults: Vec::new(),
|
||||
frame_bytes: layout.frame_bytes(),
|
||||
plan: Vec::new(),
|
||||
layout: layout.clone(),
|
||||
@@ -1160,6 +1166,9 @@ mod graphene_test {
|
||||
let mut wired = construct(&entries[0], vec![record_value_source(1.5f64), record_value_source(2.5f64)]).unwrap();
|
||||
let layout = out_layout::<f64>();
|
||||
wired.set_layout(core_types::record::RecordLayout {
|
||||
named_writes: Vec::new(),
|
||||
named_reads: Vec::new(),
|
||||
named_read_defaults: Vec::new(),
|
||||
frame_bytes: layout.frame_bytes(),
|
||||
plan: Vec::new(),
|
||||
layout: layout.clone(),
|
||||
|
||||
@@ -3,8 +3,9 @@ use core_types::list::{Item, List};
|
||||
use core_types::uuid::NodeId;
|
||||
use core_types::{ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, BlendMode, Color, Ctx};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::graphic::{GraphicLevel, PaintColumns, PaintReach, bake_paint_transforms, is_paint_present, set_paint_attribute, set_paint_attribute_at};
|
||||
use graphic_types::markers::{EditorMergedLayers, Fill, Stroke};
|
||||
use graphic_types::appearance::{Appearance, Coverage};
|
||||
use graphic_types::graphic::{GraphicLevel, PaintColumns, PaintReach, bake_paint_transforms};
|
||||
use graphic_types::markers::{Appearance as AppearanceMarker, EditorMergedLayers};
|
||||
use graphic_types::raster_types::{CPU, GPU, Raster};
|
||||
use graphic_types::vector_types::GradientStops;
|
||||
use graphic_types::vector_types::gradient::{GradientSpreadMethod, GradientType};
|
||||
@@ -12,7 +13,7 @@ use graphic_types::vector_types::subpath::{ManipulatorGroup, Subpath};
|
||||
use graphic_types::vector_types::vector::PointId;
|
||||
use graphic_types::vector_types::vector::algorithms::merge_by_distance::MergeByDistanceExt;
|
||||
use graphic_types::vector_types::{ATTR_GRADIENT_TYPE, ATTR_SPREAD_METHOD};
|
||||
use graphic_types::{ATTR_FILL, ATTR_STROKE, Graphic, IntoGraphicList, Vector};
|
||||
use graphic_types::{Graphic, IntoGraphicList, Vector};
|
||||
use linesweeper::topology::Topology;
|
||||
use linesweeper::{BinaryOp, FillRule, binary_op};
|
||||
use smallvec::SmallVec;
|
||||
@@ -33,8 +34,7 @@ fn boolean_core<'e>(
|
||||
(
|
||||
Vector,
|
||||
Attr<'e, TransformAttr>,
|
||||
Attr<'e, Fill>,
|
||||
Attr<'e, Stroke>,
|
||||
Attr<'e, AppearanceMarker>,
|
||||
Attr<'e, BlendModeAttr>,
|
||||
Attr<'e, Opacity>,
|
||||
Attr<'e, OpacityFill>,
|
||||
@@ -54,7 +54,6 @@ fn boolean_core<'e>(
|
||||
|
||||
let result_vector = result_vector_list.element_mut(0).unwrap();
|
||||
Vector::transform(result_vector, transform);
|
||||
result_vector.set_stroke_transform(DAffine2::IDENTITY);
|
||||
|
||||
// Clean up the boolean operation result by merging duplicated points
|
||||
let merge_transform: DAffine2 = result_vector_list.attribute_cloned_or_default(ATTR_TRANSFORM, 0);
|
||||
@@ -67,17 +66,12 @@ fn boolean_core<'e>(
|
||||
trace: Vec::new(),
|
||||
})
|
||||
};
|
||||
let park_paint = |paint: Option<List<Graphic<'static>>>| -> Result<Option<&'e List<Graphic>>, core_types::gpoll::Interrupt> {
|
||||
match paint {
|
||||
Some(list) => Ok(Some(arena.alloc_sized_keyed(list, 0).ok_or_else(exhausted)?.0)),
|
||||
None => Ok(None),
|
||||
}
|
||||
};
|
||||
|
||||
let element = result_vector_list.element(0).cloned().unwrap_or_default();
|
||||
use core_types::lane::LaneSource;
|
||||
let fill = park_paint(result_vector_list.attr::<Fill>(0).filter(|paint| is_paint_present(paint)).cloned())?;
|
||||
let stroke = park_paint(result_vector_list.attr::<Stroke>(0).filter(|paint| is_paint_present(paint)).cloned())?;
|
||||
let appearance = match result_vector_list.attr::<AppearanceMarker>(0).cloned() {
|
||||
Some(appearance) => Some(&*arena.alloc_sized_keyed(appearance, 0).ok_or_else(exhausted)?.0),
|
||||
None => None,
|
||||
};
|
||||
let layer_path: Vec<NodeId> = result_vector_list.attribute::<Vec<NodeId>>(ATTR_EDITOR_LAYER_PATH, 0).cloned().unwrap_or_default();
|
||||
let layer_path = arena.alloc(layer_path).ok_or_else(exhausted)?.0;
|
||||
// Snapshot the input layers so the renderer can recurse into them for
|
||||
@@ -87,8 +81,7 @@ fn boolean_core<'e>(
|
||||
Ok((
|
||||
element,
|
||||
Attr(result_vector_list.attribute_cloned_or_default(ATTR_TRANSFORM, 0)),
|
||||
Attr(fill),
|
||||
Attr(stroke),
|
||||
Attr(appearance),
|
||||
Attr(result_vector_list.attribute_cloned_or_default(ATTR_BLEND_MODE, 0)),
|
||||
Attr(result_vector_list.attribute_cloned_or(ATTR_OPACITY, 0, 1.)),
|
||||
Attr(result_vector_list.attribute_cloned_or(ATTR_OPACITY_FILL, 0, 1.)),
|
||||
@@ -115,8 +108,7 @@ fn boolean_operation<'e>(
|
||||
(
|
||||
Vector,
|
||||
Attr<'e, TransformAttr>,
|
||||
Attr<'e, Fill>,
|
||||
Attr<'e, Stroke>,
|
||||
Attr<'e, AppearanceMarker>,
|
||||
Attr<'e, BlendModeAttr>,
|
||||
Attr<'e, Opacity>,
|
||||
Attr<'e, OpacityFill>,
|
||||
@@ -142,8 +134,7 @@ fn boolean_operation_vector<'e>(
|
||||
(
|
||||
Vector,
|
||||
Attr<'e, TransformAttr>,
|
||||
Attr<'e, Fill>,
|
||||
Attr<'e, Stroke>,
|
||||
Attr<'e, AppearanceMarker>,
|
||||
Attr<'e, BlendModeAttr>,
|
||||
Attr<'e, Opacity>,
|
||||
Attr<'e, OpacityFill>,
|
||||
@@ -244,12 +235,7 @@ fn boolean_operation_on_vector_list(vector: &List<Vector>, boolean_operation: Bo
|
||||
|
||||
bake_paint_transforms(&mut attributes, copy_from_transform);
|
||||
|
||||
let copy_from = vector.element(index).unwrap();
|
||||
let element = Vector {
|
||||
stroke: copy_from.stroke.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
Item::from_parts(element, attributes)
|
||||
Item::from_parts(Vector::default(), attributes)
|
||||
} else {
|
||||
Item::<Vector>::default()
|
||||
};
|
||||
@@ -300,21 +286,23 @@ fn raster_stand_in_rows<S: core_types::lane::LaneSource>(image: &S, parent_trans
|
||||
.with_attribute(ATTR_OPACITY_FILL, fill)
|
||||
.with_attribute(ATTR_CLIPPING_MASK, clip)
|
||||
.with_attribute(ATTR_EDITOR_LAYER_PATH, layer);
|
||||
set_paint_attribute(item.attributes_mut(), ATTR_FILL, List::new_from_element(Color::BLACK));
|
||||
item.set_attribute(graphic_types::ATTR_APPEARANCE, fill_appearance(List::new_from_element(Graphic::Color(Color::BLACK))));
|
||||
item
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The single-fill appearance a built row paints with.
|
||||
fn fill_appearance(paint: List<Graphic<'static>>) -> Appearance {
|
||||
Appearance::new_single(Coverage::new_fill(), Graphic::Graphic(paint))
|
||||
}
|
||||
|
||||
/// A color row: an empty vector carrying the color as its fill paint over the
|
||||
/// lane's attributes.
|
||||
fn color_paint_row(color: Color, mut attributes: core_types::list::ItemAttributeValues) -> Item<Vector> {
|
||||
set_paint_attribute(&mut attributes, ATTR_FILL, List::new_from_element(color));
|
||||
attributes.insert(graphic_types::ATTR_APPEARANCE, fill_appearance(List::new_from_element(Graphic::Color(color))));
|
||||
|
||||
let mut element = Vector::default();
|
||||
element.set_stroke_transform(DAffine2::IDENTITY);
|
||||
|
||||
Item::from_parts(element, attributes)
|
||||
Item::from_parts(Vector::default(), attributes)
|
||||
}
|
||||
|
||||
/// A gradient row: an empty vector carrying the stops as its fill paint, the
|
||||
@@ -330,12 +318,9 @@ fn gradient_paint_row(stops: GradientStops, mut attributes: core_types::list::It
|
||||
if let Some(spread_method) = attributes.remove::<GradientSpreadMethod>(ATTR_SPREAD_METHOD) {
|
||||
gradient_paint.set_attribute(ATTR_SPREAD_METHOD, 0, spread_method);
|
||||
}
|
||||
attributes.insert(ATTR_FILL, Some(gradient_paint));
|
||||
attributes.insert(graphic_types::ATTR_APPEARANCE, fill_appearance(gradient_paint));
|
||||
|
||||
let mut element = Vector::default();
|
||||
element.set_stroke_transform(DAffine2::IDENTITY);
|
||||
|
||||
Item::from_parts(element, attributes)
|
||||
Item::from_parts(Vector::default(), attributes)
|
||||
}
|
||||
|
||||
/// A text lane's rows: the shaped glyph vectors under the composed transform.
|
||||
@@ -361,13 +346,7 @@ fn push_rows(out: &mut List<Vector>, rows: Vec<Item<Vector>>) {
|
||||
fn push_leaf_vector_row(out: &mut List<Vector>, level: GraphicLevel<'_>, index: usize, vector: &Vector, ancestors: DAffine2, reach: PaintReach<'_>) {
|
||||
let out_index = out.len();
|
||||
out.push(Item::from_parts(vector.clone(), graphic_types::graphic::lane_attributes(level, index)));
|
||||
if reach.applies() {
|
||||
for (key, slot) in [(ATTR_FILL, reach.paint.fill), (ATTR_STROKE, reach.paint.stroke)] {
|
||||
if let Some(paint) = slot {
|
||||
set_paint_attribute_at(out, out_index, key, paint.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
stamp_inherited_appearance(out, out_index, reach.appearance);
|
||||
let current: DAffine2 = out.attribute_cloned_or_default(ATTR_TRANSFORM, out_index);
|
||||
out.set_attribute(ATTR_TRANSFORM, out_index, ancestors * current);
|
||||
}
|
||||
@@ -377,18 +356,21 @@ fn push_vector_rows(out: &mut List<Vector>, rows: &List<Vector>, composed: DAffi
|
||||
let Some(item) = rows.clone_item(row) else { continue };
|
||||
let index = out.len();
|
||||
out.push(item);
|
||||
if reach.applies() {
|
||||
for (key, slot) in [(ATTR_FILL, reach.paint.fill), (ATTR_STROKE, reach.paint.stroke)] {
|
||||
if let Some(paint) = slot {
|
||||
set_paint_attribute_at(out, index, key, paint.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
stamp_inherited_appearance(out, index, reach.appearance);
|
||||
let current: DAffine2 = out.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
out.set_attribute(ATTR_TRANSFORM, index, composed * current);
|
||||
}
|
||||
}
|
||||
|
||||
/// The cascade's resolved appearance lands on a row whose own is undeclared, since a declared row wins wholesale.
|
||||
fn stamp_inherited_appearance(out: &mut List<Vector>, index: usize, inherited: Option<&Appearance>) {
|
||||
if let Some(appearance) = inherited
|
||||
&& out.attribute::<Appearance>(graphic_types::ATTR_APPEARANCE, index).and_then(Appearance::declared).is_none()
|
||||
{
|
||||
out.set_attribute(graphic_types::ATTR_APPEARANCE, index, appearance.clone());
|
||||
}
|
||||
}
|
||||
|
||||
fn push_union(out: &mut List<Vector>, flattened: List<Vector>) {
|
||||
for row in boolean_operation_on_vector_list(&flattened, BooleanOperation::Union).into_iter() {
|
||||
out.push(row);
|
||||
@@ -413,7 +395,7 @@ fn flatten_vector_run_into<'a>(out: &mut List<Vector>, level: GraphicLevel<'a>,
|
||||
let composed = transform * level.attr::<TransformAttr>(index);
|
||||
match element {
|
||||
Graphic::Vector(vector) => push_leaf_vector_row(out, level, index, vector, transform, reach),
|
||||
Graphic::Graphic(children) => push_union(out, flatten_vector_run(GraphicLevel::Legacy(children), composed, reach.nested())),
|
||||
Graphic::Graphic(children) => push_union(out, flatten_vector_run(GraphicLevel::Legacy(children), composed, reach)),
|
||||
Graphic::Group(group) => flatten_group(out, group, composed, reach),
|
||||
Graphic::RasterCPU(raster) => push_rows(out, raster_stand_in_rows(&LeafLane::new(&level, index, raster), transform)),
|
||||
Graphic::RasterGPU(raster) => push_rows(out, raster_stand_in_rows(&LeafLane::new(&level, index, raster), transform)),
|
||||
@@ -435,7 +417,7 @@ fn flatten_group(out: &mut List<Vector>, group: &core_types::record::Group, comp
|
||||
if let Some(rows) = graphic_types::graphic::run_to_list::<Vector>(item) {
|
||||
push_vector_rows(out, &rows, composed, reach);
|
||||
} else if core_types::record::RunView::<Graphic>::new(item).is_some() {
|
||||
push_union(out, flatten_vector_run(GraphicLevel::Run(item), composed, reach.into_group_graphics()));
|
||||
push_union(out, flatten_vector_run(GraphicLevel::Run(item), composed, reach));
|
||||
} else if let Some(image) = graphic_types::graphic::run_to_list::<Raster<CPU>>(item) {
|
||||
push_rows(out, raster_stand_in_rows(&image, composed));
|
||||
} else if let Some(image) = graphic_types::graphic::run_to_list::<Raster<GPU>>(item) {
|
||||
@@ -570,22 +552,28 @@ mod tests {
|
||||
top.push(Item::new_from_element(Graphic::Color(Color::BLACK)));
|
||||
top.push(Item::new_from_element(Graphic::Group(Group { row: None, content: inner_item })));
|
||||
top.set_attribute(ATTR_TRANSFORM, 0, DAffine2::from_translation(DVec2::new(5., 5.)));
|
||||
set_paint_attribute_at(&mut top, 0, ATTR_FILL, black_paint());
|
||||
top.set_attribute(graphic_types::ATTR_APPEARANCE, 0, fill_appearance(black_paint()));
|
||||
top.set_attribute(ATTR_OPACITY, 1, 0.5);
|
||||
top.set_attribute(ATTR_TRANSFORM, 2, DAffine2::from_scale(DVec2::splat(3.)));
|
||||
|
||||
let rows = flatten_vector_run(GraphicLevel::Legacy(&top), DAffine2::IDENTITY, PaintReach::NONE);
|
||||
assert_eq!(rows.len(), 3);
|
||||
|
||||
let fill_of = |index: usize| {
|
||||
rows.attribute::<Appearance>(graphic_types::ATTR_APPEARANCE, index)
|
||||
.and_then(|appearance| appearance.first_paint_of(graphic_types::appearance::Cover::Fill))
|
||||
.and_then(graphic_types::graphic::paint_cell_rows)
|
||||
};
|
||||
|
||||
// Lane 0: the leaf row keeps its lane attributes, with the lane fill
|
||||
// present and the ancestor composition the identity.
|
||||
assert_eq!(rows.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM, 0), DAffine2::from_translation(DVec2::new(5., 5.)));
|
||||
assert!(graphic_types::graphic::paint_graphics::<Fill, _>(&rows, 0).is_some());
|
||||
assert!(fill_of(0).is_some());
|
||||
|
||||
// Lane 1: the color stand-in carries the lane opacity and the color as
|
||||
// its fill.
|
||||
assert_eq!(rows.attribute_cloned_or::<f64>(ATTR_OPACITY, 1, 1.), 0.5);
|
||||
let fill = graphic_types::graphic::paint_graphics::<Fill, _>(&rows, 1).expect("the color row carries its fill");
|
||||
let fill = fill_of(1).expect("the color row carries its fill");
|
||||
assert!(matches!(fill.element(0), Some(Graphic::Color(color)) if *color == Color::BLACK));
|
||||
|
||||
// Lane 2: the group's vector run serves its row under the lane
|
||||
|
||||
@@ -950,6 +950,8 @@ fn selective_color<T: Adjust<Color> + Clone + Send + Sync + no_std_types::contex
|
||||
(SelectiveColorChoice::Blacks, (k_c, k_m, k_y, k_k)),
|
||||
];
|
||||
let mut sum = Vec3::ZERO;
|
||||
// Indexed rather than iterated because this compiles to SPIR-V, whose backend rejects the arbitrary pointer offset an array iterator produces
|
||||
#[allow(clippy::needless_range_loop)]
|
||||
for i in 0..array.len() {
|
||||
let (color_parameter_group, (c, m, y, k)) = array[i];
|
||||
|
||||
|
||||
@@ -63,6 +63,8 @@ impl CubicSplines {
|
||||
assert!(augmented_matrix[row][row].abs() > f32::EPSILON);
|
||||
|
||||
let scale_factor = augmented_matrix[row_below_current][row] / augmented_matrix[row][row];
|
||||
// `col` indexes two distinct rows at once, one of them mutably, so an iterator would need a split borrow
|
||||
#[allow(clippy::needless_range_loop)]
|
||||
for col in row..5 {
|
||||
augmented_matrix[row_below_current][col] -= augmented_matrix[row][col] * scale_factor
|
||||
}
|
||||
|
||||
@@ -17,10 +17,11 @@ use core_types::transform::Transform;
|
||||
use core_types::uuid::NodeId;
|
||||
use core_types::{ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, CacheHash, Color, Ctx, DeriveCtx, ExtractIndex, InjectIndex};
|
||||
use glam::{DAffine2, DMat2, DVec2};
|
||||
use graphic_types::graphic::{bake_paint_transforms, has_paint, is_paint_present, set_paint_attribute_at};
|
||||
use graphic_types::markers::{EditorMergedLayers, Fill, Stroke as StrokeAttr};
|
||||
use graphic_types::appearance::{Appearance, Cover, CoverPlacement, Coverage};
|
||||
use graphic_types::graphic::{bake_paint_transforms, is_paint_present};
|
||||
use graphic_types::markers::{Appearance as AppearanceMarker, EditorMergedLayers};
|
||||
use graphic_types::raster_types::{CPU, GPU, Raster};
|
||||
use graphic_types::{ATTR_EDITOR_MERGED_LAYERS, ATTR_FILL, ATTR_STROKE, Graphic, IntoGraphicList};
|
||||
use graphic_types::{ATTR_EDITOR_MERGED_LAYERS, Graphic, IntoGraphicList};
|
||||
use graphic_types::{Artboard, Vector};
|
||||
use kurbo::simplify::{SimplifyOptions, simplify_bezpath};
|
||||
use kurbo::{Affine, BezPath, DEFAULT_ACCURACY, Line, ParamCurve, ParamCurveArclen, PathEl, PathSeg, Shape};
|
||||
@@ -37,7 +38,7 @@ use vector_types::vector::misc::{
|
||||
CentroidType, ExtrudeJoiningAlgorithm, HandleId, InterpolationDistribution, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns, bezpath_from_manipulator_groups,
|
||||
bezpath_to_manipulator_groups, handles_to_segment, is_linear, point_to_dvec2, segment_to_handles,
|
||||
};
|
||||
use vector_types::vector::style::{GradientStops, PaintOrder, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use vector_types::vector::style::{GradientStops, HasTransform, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use vector_types::vector::{FillId, PointId, RegionId, SegmentDomain, SegmentId, StrokeId, VectorExt};
|
||||
use vector_types::{ATTR_GRADIENT_TYPE, ATTR_SPREAD_METHOD};
|
||||
use vector_types::{GradientSpreadMethod, GradientType};
|
||||
@@ -100,20 +101,19 @@ fn assign_colors<'e>(
|
||||
/// The number of elements to span across the gradient before repeating. A 0 value will span the entire gradient once.
|
||||
#[widget(ParsedWidgetOverride::Custom = "assign_colors_repeat_every")]
|
||||
repeat_every: u32,
|
||||
) -> Result<IList<(Vector, Attr<'e, TransformAttr>, Attr<'e, Fill>, Attr<'e, StrokeAttr>, Attr<'e, EditorLayerPath>)>, Interrupt> {
|
||||
) -> Result<IList<(Vector, Attr<'e, TransformAttr>, Attr<'e, AppearanceMarker>, Attr<'e, EditorLayerPath>)>, Interrupt> {
|
||||
let lane = ctx.index() as usize;
|
||||
if lane >= content.len() {
|
||||
return Err(GraphError::past_end().into());
|
||||
}
|
||||
let element = content.element_ref(lane).clone();
|
||||
let park_existing = |paint: Option<&List<Graphic<'static>>>| -> Result<Option<&'e List<Graphic>>, Interrupt> { paint.map(|paint| park_paint(ctx.arena(), paint.clone())).transpose() };
|
||||
let existing_fill = park_existing(content.lane(lane).attr::<Fill>())?;
|
||||
let existing_stroke = park_existing(content.lane(lane).attr::<StrokeAttr>())?;
|
||||
let carried = carried_lane_attrs(ctx.arena(), *content.lane(lane))?;
|
||||
let (transform, layer_path) = carried;
|
||||
let existing_appearance = content.lane(lane).attr::<AppearanceMarker>().cloned();
|
||||
let park_appearance_attr = |appearance: Option<Appearance>| -> Result<Option<&'e Appearance>, Interrupt> { appearance.map(|appearance| park_appearance(ctx.arena(), appearance)).transpose() };
|
||||
let (transform, layer_path) = carried_lane_attrs(ctx.arena(), *content.lane(lane))?;
|
||||
|
||||
if gradient.is_empty() {
|
||||
return Ok((element, transform, Attr(existing_fill), Attr(existing_stroke), layer_path));
|
||||
let parked_appearance = park_appearance_attr(existing_appearance)?;
|
||||
return Ok((element, transform, Attr(parked_appearance), layer_path));
|
||||
}
|
||||
let gradient_element = gradient.element_ref(0);
|
||||
let reversed;
|
||||
@@ -127,17 +127,20 @@ fn assign_colors<'e>(
|
||||
|
||||
let color = assign_color_at(gradient_element, lane, content.len(), randomize, seed, repeat_every);
|
||||
let paint = List::new_from_element(color).into_graphic_list();
|
||||
let parked = park_paint(ctx.arena(), paint)?;
|
||||
|
||||
let fill_attr = match fill {
|
||||
true => Some(parked),
|
||||
false => existing_fill,
|
||||
};
|
||||
let stroke_attr = match stroke && element.stroke.is_some() {
|
||||
true => Some(parked),
|
||||
false => existing_stroke,
|
||||
};
|
||||
Ok((element, transform, Attr(fill_attr), Attr(stroke_attr), layer_path))
|
||||
// The recolor lands on the appearance's coverage paints
|
||||
let mut appearance = existing_appearance.unwrap_or_default();
|
||||
let paint_cell = Graphic::Graphic(paint);
|
||||
if fill && !appearance.set_paint_of(Cover::Fill, paint_cell.clone()) {
|
||||
appearance.replace_or_insert(Coverage::new_fill(), paint_cell.clone(), CoverPlacement::Below);
|
||||
}
|
||||
// The stroke recolor is gated on an existing stroke coverage, since restyling never adds a stroke
|
||||
if stroke {
|
||||
appearance.set_paint_of(Cover::Stroke, paint_cell);
|
||||
}
|
||||
let parked_appearance = park_appearance_attr(Some(appearance))?;
|
||||
|
||||
Ok((element, transform, Attr(parked_appearance), layer_path))
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
@@ -228,15 +231,20 @@ fn assign_colors_graphic<'e>(
|
||||
let element = match rows {
|
||||
Some(mut rows) => {
|
||||
for row in 0..rows.len() {
|
||||
let has_stroke = rows.element(row).is_some_and(|vector| vector.stroke.is_some());
|
||||
let color = assign_color_at(gradient_element, position + row, length, randomize, seed, repeat_every);
|
||||
let paint = List::new_from_element(color).into_graphic_list();
|
||||
if fill {
|
||||
set_paint_attribute_at(&mut rows, row, ATTR_FILL, paint.clone());
|
||||
|
||||
// The recolor lands on the row's appearance coverage paints
|
||||
let mut appearance = rows.attribute_cloned_or_default::<Appearance>(graphic_types::ATTR_APPEARANCE, row);
|
||||
let paint_cell = Graphic::Graphic(paint);
|
||||
if fill && !appearance.set_paint_of(Cover::Fill, paint_cell.clone()) {
|
||||
appearance.replace_or_insert(Coverage::new_fill(), paint_cell.clone(), CoverPlacement::Below);
|
||||
}
|
||||
if stroke && has_stroke {
|
||||
set_paint_attribute_at(&mut rows, row, ATTR_STROKE, paint.clone());
|
||||
// The stroke recolor is gated on an existing stroke coverage, since restyling never adds a stroke
|
||||
if stroke {
|
||||
appearance.set_paint_of(Cover::Stroke, paint_cell);
|
||||
}
|
||||
rows.set_attribute(graphic_types::ATTR_APPEARANCE, row, appearance);
|
||||
}
|
||||
let content = core_types::record::GroupItem::from_list(rows, ctx.arena()).ok_or_else(|| Interrupt::from(GraphError::new("the arena is exhausted")))?;
|
||||
Graphic::Group(core_types::record::Group { row: None, content })
|
||||
@@ -276,16 +284,26 @@ fn assign_colors_graphic_extent(
|
||||
|
||||
pub use _assign_colors_graphic_mod::assign_colors_graphic_entries;
|
||||
|
||||
/// Keyed, so a group-free paint's promote moves this header rather than
|
||||
/// Keyed, so a group-free appearance's promote moves this header rather than
|
||||
/// cloning the content it owns.
|
||||
fn park_paint<'e>(arena: &'e core_types::arena::Arena, paint: List<Graphic<'static>>) -> Result<&'e List<Graphic<'static>>, Interrupt> {
|
||||
let (parked, _) = arena.alloc_sized_keyed(paint, 0).ok_or(GraphError {
|
||||
fn park_appearance<'e>(arena: &'e core_types::arena::Arena, appearance: Appearance) -> Result<&'e Appearance, Interrupt> {
|
||||
let (parked, _) = arena.alloc_sized_keyed(appearance, 0).ok_or(GraphError {
|
||||
kind: core_types::gpoll::ErrorKind::ArenaExhausted,
|
||||
trace: Vec::new(),
|
||||
})?;
|
||||
Ok(parked)
|
||||
}
|
||||
|
||||
/// Appends one coverage to the content's appearance following the painter's algorithm:
|
||||
/// the most downstream paint node in the chain paints on top unless it asks for the
|
||||
/// below placement. The coverage's paint is the canonical paint list carried as one
|
||||
/// graphic cell, the input lane's own envelope dropped.
|
||||
fn stamped_appearance(content_appearance: Option<&Appearance>, coverage: Coverage, paint: &List<Graphic<'static>>, placement: CoverPlacement) -> Appearance {
|
||||
let mut appearance = content_appearance.cloned().unwrap_or_default();
|
||||
appearance.replace_or_insert(coverage, Graphic::Graphic(paint.clone()), placement);
|
||||
appearance
|
||||
}
|
||||
|
||||
/// The gradient defaulting the legacy fill performed, applied to the nested
|
||||
/// stops list the paint table wraps.
|
||||
fn default_gradient_paint(paint: &mut List<Graphic>, bounds: Option<[DVec2; 2]>, gradient_type: GradientType, spread_method: GradientSpreadMethod, transform: Option<DAffine2>) {
|
||||
@@ -331,7 +349,7 @@ fn paint_table(paint: core_types::node::List<'_, Graphic<'_>>) -> List<Graphic<'
|
||||
fn fill<'e>(
|
||||
ctx: impl Ctx + ExtractArena<'e> + ExtractIndex + InjectIndex + Copy,
|
||||
/// The content with vector paths to apply the fill style to.
|
||||
(element, _content_fill): (Vector, Attr<Fill>),
|
||||
(element, content_appearance): (Vector, Attr<AppearanceMarker>),
|
||||
/// The fill to paint the path with.
|
||||
#[default(Color::BLACK)]
|
||||
fill: IList<Graphic<'static>>,
|
||||
@@ -339,36 +357,39 @@ fn fill<'e>(
|
||||
_backup_gradient: IList<GradientStops>,
|
||||
_gradient_type: GradientType,
|
||||
_spread_method: GradientSpreadMethod,
|
||||
_transform: Option<DAffine2>,
|
||||
) -> Result<(Vector, Attr<'e, Fill>), Interrupt> {
|
||||
_has_transform: HasTransform,
|
||||
_transform: DAffine2,
|
||||
) -> Result<(Vector, Attr<'e, AppearanceMarker>), Interrupt> {
|
||||
let mut paint = paint_table(fill);
|
||||
default_gradient_paint(&mut paint, element.bounding_box(), _gradient_type, _spread_method, _transform);
|
||||
let parked = park_paint(ctx.arena(), paint)?;
|
||||
Ok((element, Attr(Some(parked))))
|
||||
default_gradient_paint(&mut paint, element.bounding_box(), _gradient_type, _spread_method, _has_transform.0.then_some(_transform));
|
||||
let appearance = stamped_appearance(*content_appearance, Coverage::new_fill(), &paint, CoverPlacement::Above);
|
||||
let parked_appearance = park_appearance(ctx.arena(), appearance)?;
|
||||
Ok((element, Attr(Some(parked_appearance))))
|
||||
}
|
||||
|
||||
/// The fill over graphic lanes: the marker parks on the lane and the render
|
||||
/// boundary moves it onto the interior vector lists the legacy paint readers
|
||||
/// inspect. Registered under the fill's identifier.
|
||||
/// The fill over graphic lanes: the appearance parks on the lane and cascades
|
||||
/// to the vectors beneath it. Registered under the fill's identifier.
|
||||
#[node_macro::node(category(""))]
|
||||
fn fill_graphic_leveled<'e>(
|
||||
ctx: impl Ctx + ExtractArena<'e> + ExtractIndex + InjectIndex + Copy,
|
||||
(element, _content_fill): (Graphic<'static>, Attr<Fill>),
|
||||
(element, content_appearance): (Graphic<'static>, Attr<AppearanceMarker>),
|
||||
#[default(Color::BLACK)] fill: IList<Graphic<'static>>,
|
||||
_backup_color: IList<Color>,
|
||||
_backup_gradient: IList<GradientStops>,
|
||||
_gradient_type: GradientType,
|
||||
_spread_method: GradientSpreadMethod,
|
||||
_transform: Option<DAffine2>,
|
||||
) -> Result<(Graphic<'static>, Attr<'e, Fill>), Interrupt> {
|
||||
_has_transform: HasTransform,
|
||||
_transform: DAffine2,
|
||||
) -> Result<(Graphic<'static>, Attr<'e, AppearanceMarker>), Interrupt> {
|
||||
let bounds = match BoundingBox::bounding_box(&element, DAffine2::IDENTITY, false) {
|
||||
RenderBoundingBox::Rectangle(bounds) => Some(bounds),
|
||||
_ => None,
|
||||
};
|
||||
let mut paint = paint_table(fill);
|
||||
default_gradient_paint(&mut paint, bounds, _gradient_type, _spread_method, _transform);
|
||||
let parked = park_paint(ctx.arena(), paint)?;
|
||||
Ok((element, Attr(Some(parked))))
|
||||
default_gradient_paint(&mut paint, bounds, _gradient_type, _spread_method, _has_transform.0.then_some(_transform));
|
||||
let appearance = stamped_appearance(*content_appearance, Coverage::new_fill(), &paint, CoverPlacement::Above);
|
||||
let parked_appearance = park_appearance(ctx.arena(), appearance)?;
|
||||
Ok((element, Attr(Some(parked_appearance))))
|
||||
}
|
||||
|
||||
/// Applies a stroke style to the vector content, giving an appearance to the area within the outline of the geometry.
|
||||
@@ -376,7 +397,7 @@ fn fill_graphic_leveled<'e>(
|
||||
fn stroke<'e>(
|
||||
ctx: impl Ctx + ExtractArena<'e> + ExtractIndex + InjectIndex + Copy,
|
||||
/// The content with vector paths to apply the stroke style to.
|
||||
(element, content_transform): (Vector, Attr<TransformAttr>),
|
||||
(element, content_transform, content_appearance): (Vector, Attr<TransformAttr>, Attr<AppearanceMarker>),
|
||||
/// The stroke paint.
|
||||
#[default(Color::BLACK)]
|
||||
paint: IList<Graphic<'static>>,
|
||||
@@ -393,73 +414,13 @@ fn stroke<'e>(
|
||||
/// The threshold for when a miter-joined stroke is converted to a bevel-joined stroke when a sharp angle becomes pointier than this ratio.
|
||||
#[default(4.)]
|
||||
miter_limit: f64,
|
||||
/// The order to paint the stroke on top of the fill, or the fill on top of the stroke.
|
||||
paint_order: PaintOrder,
|
||||
/// The stroke dash lengths. Each length forms a distance in a pattern where the first length is a dash, the second is a gap, and so on. If the list is an odd length, the pattern repeats with solid-gap roles reversed.
|
||||
dash_lengths: IList<f64>,
|
||||
/// The phase offset distance from the starting point of the dash pattern.
|
||||
#[unit(" px")]
|
||||
dash_offset: f64,
|
||||
) -> Result<(Vector, Attr<TransformAttr>, Attr<'e, StrokeAttr>), Interrupt> {
|
||||
let dash_lengths = (0..dash_lengths.len()).map(|index| dash_lengths.get(index).max(0.)).collect();
|
||||
let mut stroke = Stroke {
|
||||
weight,
|
||||
dash_lengths,
|
||||
dash_offset,
|
||||
cap,
|
||||
join,
|
||||
join_miter_limit: miter_limit,
|
||||
align,
|
||||
transform: DAffine2::IDENTITY,
|
||||
paint_order,
|
||||
};
|
||||
stroke.transform *= *content_transform;
|
||||
|
||||
let mut element = element;
|
||||
element.stroke = Some(stroke);
|
||||
|
||||
let paint = paint_table(paint);
|
||||
let parked = park_paint(ctx.arena(), paint)?;
|
||||
Ok((element, Attr(*content_transform), Attr(Some(parked))))
|
||||
}
|
||||
|
||||
/// The vector items of a graphic lane's interior, one wrap level deep, the
|
||||
/// reach of the pre-flip broadcast over a legacy list.
|
||||
fn for_each_interior_vector_mut(element: &mut Graphic, mut f: impl FnMut(&mut Vector, DAffine2)) {
|
||||
match element {
|
||||
Graphic::Vector(vector) => f(vector, DAffine2::IDENTITY),
|
||||
Graphic::Graphic(children) => {
|
||||
for index in 0..children.len() {
|
||||
let transform: DAffine2 = children.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
if let Some(Graphic::Vector(vector)) = children.element_mut(index) {
|
||||
f(vector, transform);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The stroke over graphic lanes: the style applies to the interior vectors,
|
||||
/// the paint marker parks on the lane for the render boundary to place.
|
||||
/// Registered under the stroke's identifier.
|
||||
#[node_macro::node(category(""))]
|
||||
fn stroke_graphic_leveled<'e>(
|
||||
ctx: impl Ctx + ExtractArena<'e> + ExtractIndex + InjectIndex + Copy,
|
||||
(element, content_transform): (Graphic<'static>, Attr<TransformAttr>),
|
||||
#[default(Color::BLACK)] paint: IList<Graphic<'static>>,
|
||||
#[unit(" px")]
|
||||
#[default(2.)]
|
||||
weight: f64,
|
||||
align: StrokeAlign,
|
||||
cap: StrokeCap,
|
||||
join: StrokeJoin,
|
||||
#[default(4.)] miter_limit: f64,
|
||||
paint_order: PaintOrder,
|
||||
dash_lengths: IList<f64>,
|
||||
#[unit(" px")] dash_offset: f64,
|
||||
) -> Result<(Graphic<'static>, Attr<TransformAttr>, Attr<'e, StrokeAttr>), Interrupt> {
|
||||
let dash_lengths = (0..dash_lengths.len()).map(|index| dash_lengths.get(index).max(0.)).collect();
|
||||
) -> Result<(Vector, Attr<TransformAttr>, Attr<'e, AppearanceMarker>), Interrupt> {
|
||||
let dash_lengths: Vec<f64> = (0..dash_lengths.len()).map(|index| dash_lengths.get(index).max(0.)).collect();
|
||||
let stroke = Stroke {
|
||||
weight,
|
||||
dash_lengths,
|
||||
@@ -469,19 +430,57 @@ fn stroke_graphic_leveled<'e>(
|
||||
join_miter_limit: miter_limit,
|
||||
align,
|
||||
transform: DAffine2::IDENTITY,
|
||||
paint_order,
|
||||
};
|
||||
|
||||
let mut element = element;
|
||||
for_each_interior_vector_mut(&mut element, |vector, transform| {
|
||||
let mut stroke = stroke.clone();
|
||||
stroke.transform *= transform;
|
||||
vector.stroke = Some(stroke);
|
||||
});
|
||||
// The coverage records the stroke's authoring space: the item transform, translation included
|
||||
let mut coverage_stroke = stroke;
|
||||
coverage_stroke.transform *= *content_transform;
|
||||
|
||||
let paint = paint_table(paint);
|
||||
let parked = park_paint(ctx.arena(), paint)?;
|
||||
Ok((element, Attr(*content_transform), Attr(Some(parked))))
|
||||
// A below stroke is the chain running the stroke node before the fill, so the coverage appends above
|
||||
let appearance = stamped_appearance(*content_appearance, Coverage::new_stroke(&coverage_stroke), &paint, CoverPlacement::Above);
|
||||
let parked_appearance = park_appearance(ctx.arena(), appearance)?;
|
||||
Ok((element, Attr(*content_transform), Attr(Some(parked_appearance))))
|
||||
}
|
||||
|
||||
/// The stroke over graphic lanes: the appearance parks on the lane and cascades
|
||||
/// to the vectors beneath it. Registered under the stroke's identifier.
|
||||
#[node_macro::node(category(""))]
|
||||
fn stroke_graphic_leveled<'e>(
|
||||
ctx: impl Ctx + ExtractArena<'e> + ExtractIndex + InjectIndex + Copy,
|
||||
(element, content_transform, content_appearance): (Graphic<'static>, Attr<TransformAttr>, Attr<AppearanceMarker>),
|
||||
#[default(Color::BLACK)] paint: IList<Graphic<'static>>,
|
||||
#[unit(" px")]
|
||||
#[default(2.)]
|
||||
weight: f64,
|
||||
align: StrokeAlign,
|
||||
cap: StrokeCap,
|
||||
join: StrokeJoin,
|
||||
#[default(4.)] miter_limit: f64,
|
||||
dash_lengths: IList<f64>,
|
||||
#[unit(" px")] dash_offset: f64,
|
||||
) -> Result<(Graphic<'static>, Attr<TransformAttr>, Attr<'e, AppearanceMarker>), Interrupt> {
|
||||
let dash_lengths: Vec<f64> = (0..dash_lengths.len()).map(|index| dash_lengths.get(index).max(0.)).collect();
|
||||
let stroke = Stroke {
|
||||
weight,
|
||||
dash_lengths,
|
||||
dash_offset,
|
||||
cap,
|
||||
join,
|
||||
join_miter_limit: miter_limit,
|
||||
align,
|
||||
transform: DAffine2::IDENTITY,
|
||||
};
|
||||
|
||||
// The coverage records the stroke's authoring space: the lane transform, translation included
|
||||
let mut coverage_stroke = stroke;
|
||||
coverage_stroke.transform *= *content_transform;
|
||||
|
||||
let paint = paint_table(paint);
|
||||
// A below stroke is the chain running the stroke node before the fill, so the coverage appends above
|
||||
let appearance = stamped_appearance(*content_appearance, Coverage::new_stroke(&coverage_stroke), &paint, CoverPlacement::Above);
|
||||
let parked_appearance = park_appearance(ctx.arena(), appearance)?;
|
||||
Ok((element, Attr(*content_transform), Attr(Some(parked_appearance))))
|
||||
}
|
||||
|
||||
pub use _fill_graphic_leveled_mod::fill_graphic_leveled_entries;
|
||||
@@ -622,10 +621,7 @@ fn round_corners(
|
||||
// Convert 0-100 to 0-0.5
|
||||
let edge_length_limit = edge_length_limit * 0.005;
|
||||
|
||||
let mut result = Vector {
|
||||
stroke: source.stroke.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
let mut result = Vector::default();
|
||||
|
||||
// Grab the initial point ID as a stable starting point
|
||||
let mut initial_point_id = source.point_domain.ids().first().copied().unwrap_or(PointId::generate());
|
||||
@@ -984,8 +980,6 @@ fn box_warp(_: impl Ctx, (vector, transform): (Vector, Attr<TransformAttr>), #[e
|
||||
});
|
||||
}
|
||||
|
||||
result.set_stroke_transform(DAffine2::IDENTITY);
|
||||
|
||||
// Reset the transform since we've applied it directly to the points
|
||||
(result, Attr(DAffine2::IDENTITY))
|
||||
}
|
||||
@@ -1131,10 +1125,7 @@ fn auto_tangents(
|
||||
) -> (Vector, Attr<TransformAttr>) {
|
||||
let transform: DAffine2 = *lane_transform;
|
||||
|
||||
let mut result = Vector {
|
||||
stroke: source.stroke.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
let mut result = Vector::default();
|
||||
|
||||
for mut subpath in source.stroke_bezier_paths() {
|
||||
subpath.apply_transform(transform);
|
||||
@@ -1266,19 +1257,14 @@ fn auto_tangents(
|
||||
|
||||
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
|
||||
fn bounding_box(_: impl Ctx, vector: Vector) -> Vector {
|
||||
let mut result = vector
|
||||
vector
|
||||
.bounding_box_rect()
|
||||
.map(|bbox| {
|
||||
let mut vector = Vector::default();
|
||||
vector.append_bezpath(bbox.to_path(DEFAULT_ACCURACY));
|
||||
vector
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
result.stroke = vector.stroke.clone();
|
||||
result.set_stroke_transform(DAffine2::IDENTITY);
|
||||
|
||||
result
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Vector: Measure"), path(core_types::vector))]
|
||||
@@ -1329,11 +1315,7 @@ fn offset_path(_: impl Ctx, (vector, lane_transform): (Vector, Attr<TransformAtt
|
||||
let transform = Affine::new(transform_attribute.to_cols_array());
|
||||
|
||||
let bezpaths = vector.stroke_bezpath_iter();
|
||||
let mut result = Vector {
|
||||
stroke: vector.stroke.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
result.set_stroke_transform(DAffine2::IDENTITY);
|
||||
let mut result = Vector::default();
|
||||
|
||||
// Perform operation on all subpaths in this shape.
|
||||
for mut bezpath in bezpaths {
|
||||
@@ -1363,16 +1345,23 @@ fn offset_path(_: impl Ctx, (vector, lane_transform): (Vector, Attr<TransformAtt
|
||||
fn solidify_rows(flattened: List<Vector>) -> List<Vector> {
|
||||
// TODO: Make this node support stroke align, which it currently ignores
|
||||
|
||||
// A fill exists when the canonical attribute carries paint
|
||||
let has_fills: Vec<bool> = (0..flattened.len()).map(|index| has_paint::<Fill, _>(&flattened, index)).collect();
|
||||
// A fill exists when the row's appearance carries a painted fill coverage
|
||||
let has_fills: Vec<bool> = (0..flattened.len())
|
||||
.map(|index| {
|
||||
flattened
|
||||
.attribute::<Appearance>(graphic_types::ATTR_APPEARANCE, index)
|
||||
.is_some_and(|appearance| appearance.has_painted_cover(Cover::Fill))
|
||||
})
|
||||
.collect();
|
||||
|
||||
let output: List<Vector> = flattened
|
||||
.into_iter()
|
||||
.zip(has_fills)
|
||||
.flat_map(|(row, has_fill)| {
|
||||
let (mut vector, attributes) = row.into_parts();
|
||||
let (vector, attributes) = row.into_parts();
|
||||
|
||||
let stroke = vector.stroke.clone().unwrap_or_default();
|
||||
let appearance = attributes.get::<Appearance>(graphic_types::ATTR_APPEARANCE).cloned().unwrap_or_default();
|
||||
let stroke = appearance.first_coverage_of(Cover::Stroke).map(Coverage::stroke_params).unwrap_or_default();
|
||||
let bezpaths = vector.stroke_bezpath_iter();
|
||||
let mut solidified_stroke = Vector::default();
|
||||
|
||||
@@ -1390,7 +1379,11 @@ fn solidify_rows(flattened: List<Vector>) -> List<Vector> {
|
||||
let dash_offset = stroke.dash_offset;
|
||||
let dash_pattern = stroke.dash_lengths;
|
||||
let miter_limit = stroke.join_miter_limit;
|
||||
let paint_order = stroke.paint_order;
|
||||
// The paint order rides the row's coverage order
|
||||
let stroke_below = attributes
|
||||
.get::<Appearance>(graphic_types::ATTR_APPEARANCE)
|
||||
.map(Appearance::fill_and_stroke)
|
||||
.is_some_and(|resolved| resolved.stroke_below);
|
||||
|
||||
let stroke_style = kurbo::Stroke::new(stroke.weight)
|
||||
.with_caps(cap)
|
||||
@@ -1419,26 +1412,32 @@ fn solidify_rows(flattened: List<Vector>) -> List<Vector> {
|
||||
solidified_stroke.append_bezpath(solidified);
|
||||
}
|
||||
|
||||
// If the original vector has a fill, preserve it as a separate item with the stroke cleared.
|
||||
// If the original vector has a fill, preserve it as a separate item with the stroke coverages dropped.
|
||||
let fill_row = has_fill.then(|| {
|
||||
vector.stroke = None;
|
||||
let mut fill_attributes = attributes.clone();
|
||||
// No stroke remains on the fill row
|
||||
fill_attributes.remove::<Option<List<Graphic>>>(ATTR_STROKE);
|
||||
if let Some(appearance) = fill_attributes.get_mut::<Appearance>(graphic_types::ATTR_APPEARANCE) {
|
||||
appearance.retain_cover(Cover::Fill);
|
||||
}
|
||||
Item::from_parts(vector, fill_attributes)
|
||||
});
|
||||
|
||||
let mut stroke_attributes = attributes;
|
||||
// Drop the original fill and use the stroke paint to fill the outlined stroke
|
||||
stroke_attributes.remove::<Option<List<Graphic>>>(ATTR_FILL);
|
||||
stroke_attributes.rename(ATTR_STROKE, ATTR_FILL);
|
||||
if let Some(appearance) = stroke_attributes.get_mut::<Appearance>(graphic_types::ATTR_APPEARANCE) {
|
||||
// The outlined stroke is filled with the stroke coverage's paint
|
||||
let stroke_paint = appearance.first_paint_of(Cover::Stroke).cloned();
|
||||
*appearance = Appearance::default();
|
||||
if let Some(paint) = stroke_paint {
|
||||
appearance.replace_or_insert(Coverage::new_fill(), paint, CoverPlacement::Above);
|
||||
}
|
||||
}
|
||||
|
||||
let stroke_row = Item::from_parts(solidified_stroke, stroke_attributes);
|
||||
|
||||
// Ordering based on the paint order. The first item in the `List` is rendered below the second.
|
||||
match paint_order {
|
||||
PaintOrder::StrokeAbove => fill_row.into_iter().chain(std::iter::once(stroke_row)).collect::<Vec<_>>(),
|
||||
PaintOrder::StrokeBelow => std::iter::once(stroke_row).chain(fill_row).collect::<Vec<_>>(),
|
||||
// Ordering based on the coverage order. The first item in the `List` is rendered below the second.
|
||||
match stroke_below {
|
||||
false => fill_row.into_iter().chain(std::iter::once(stroke_row)).collect::<Vec<_>>(),
|
||||
true => std::iter::once(stroke_row).chain(fill_row).collect::<Vec<_>>(),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
@@ -1459,8 +1458,7 @@ fn solidify_native_lane<'e>(
|
||||
(
|
||||
Vector,
|
||||
Attr<'e, TransformAttr>,
|
||||
Attr<'e, Fill>,
|
||||
Attr<'e, StrokeAttr>,
|
||||
Attr<'e, AppearanceMarker>,
|
||||
Attr<'e, BlendModeAttr>,
|
||||
Attr<'e, Opacity>,
|
||||
Attr<'e, OpacityFill>,
|
||||
@@ -1519,8 +1517,7 @@ fn emit_legacy_lane<'e>(
|
||||
(
|
||||
Vector,
|
||||
Attr<'e, TransformAttr>,
|
||||
Attr<'e, Fill>,
|
||||
Attr<'e, StrokeAttr>,
|
||||
Attr<'e, AppearanceMarker>,
|
||||
Attr<'e, BlendModeAttr>,
|
||||
Attr<'e, Opacity>,
|
||||
Attr<'e, OpacityFill>,
|
||||
@@ -1541,15 +1538,10 @@ fn emit_legacy_lane<'e>(
|
||||
};
|
||||
|
||||
let element = output.element(lane).cloned().unwrap_or_default();
|
||||
let fill = output
|
||||
.attribute::<Option<List<Graphic>>>(ATTR_FILL, lane)
|
||||
.and_then(|paint| paint.as_ref())
|
||||
.map(|paint| park_paint(arena, paint.clone()))
|
||||
.transpose()?;
|
||||
let stroke = output
|
||||
.attribute::<Option<List<Graphic>>>(ATTR_STROKE, lane)
|
||||
.and_then(|paint| paint.as_ref())
|
||||
.map(|paint| park_paint(arena, paint.clone()))
|
||||
let appearance = output
|
||||
.attribute::<Appearance>(graphic_types::ATTR_APPEARANCE, lane)
|
||||
.cloned()
|
||||
.map(|appearance| park_appearance(arena, appearance))
|
||||
.transpose()?;
|
||||
let layer_path: Vec<NodeId> = output.attribute::<Vec<NodeId>>(ATTR_EDITOR_LAYER_PATH, lane).cloned().unwrap_or_default();
|
||||
let layer_path = arena.alloc(layer_path).ok_or_else(exhausted)?.0;
|
||||
@@ -1562,8 +1554,7 @@ fn emit_legacy_lane<'e>(
|
||||
Ok((
|
||||
element,
|
||||
Attr(output.attribute_cloned_or_default(ATTR_TRANSFORM, lane)),
|
||||
Attr(fill),
|
||||
Attr(stroke),
|
||||
Attr(appearance),
|
||||
Attr(output.attribute_cloned_or_default(ATTR_BLEND_MODE, lane)),
|
||||
Attr(output.attribute_cloned_or(ATTR_OPACITY, lane, 1.)),
|
||||
Attr(output.attribute_cloned_or(ATTR_OPACITY_FILL, lane, 1.)),
|
||||
@@ -1609,8 +1600,7 @@ fn solidify_stroke<'e>(
|
||||
IList<(
|
||||
Vector,
|
||||
Attr<'e, TransformAttr>,
|
||||
Attr<'e, Fill>,
|
||||
Attr<'e, StrokeAttr>,
|
||||
Attr<'e, AppearanceMarker>,
|
||||
Attr<'e, BlendModeAttr>,
|
||||
Attr<'e, Opacity>,
|
||||
Attr<'e, OpacityFill>,
|
||||
@@ -1649,8 +1639,7 @@ fn solidify_stroke_vector<'e>(
|
||||
IList<(
|
||||
Vector,
|
||||
Attr<'e, TransformAttr>,
|
||||
Attr<'e, Fill>,
|
||||
Attr<'e, StrokeAttr>,
|
||||
Attr<'e, AppearanceMarker>,
|
||||
Attr<'e, BlendModeAttr>,
|
||||
Attr<'e, Opacity>,
|
||||
Attr<'e, OpacityFill>,
|
||||
@@ -1695,7 +1684,6 @@ fn separate_subpaths_core(content: List<Vector>) -> List<Vector> {
|
||||
return vec![row];
|
||||
}
|
||||
|
||||
let stroke = row.element().stroke.clone();
|
||||
let (_, attributes) = row.into_parts();
|
||||
|
||||
bezpaths
|
||||
@@ -1703,7 +1691,6 @@ fn separate_subpaths_core(content: List<Vector>) -> List<Vector> {
|
||||
.map(|bezpath| {
|
||||
let mut vector = Vector::default();
|
||||
vector.append_bezpath(bezpath);
|
||||
vector.stroke = stroke.clone();
|
||||
|
||||
Item::from_parts(vector, attributes.clone())
|
||||
})
|
||||
@@ -1721,8 +1708,7 @@ fn separate_subpaths<'e>(
|
||||
IList<(
|
||||
Vector,
|
||||
Attr<'e, TransformAttr>,
|
||||
Attr<'e, Fill>,
|
||||
Attr<'e, StrokeAttr>,
|
||||
Attr<'e, AppearanceMarker>,
|
||||
Attr<'e, BlendModeAttr>,
|
||||
Attr<'e, Opacity>,
|
||||
Attr<'e, OpacityFill>,
|
||||
@@ -1777,8 +1763,7 @@ fn map_points<'e>(
|
||||
IList<(
|
||||
Vector,
|
||||
Attr<'e, TransformAttr>,
|
||||
Attr<'e, Fill>,
|
||||
Attr<'e, StrokeAttr>,
|
||||
Attr<'e, AppearanceMarker>,
|
||||
Attr<'e, BlendModeAttr>,
|
||||
Attr<'e, Opacity>,
|
||||
Attr<'e, OpacityFill>,
|
||||
@@ -1814,17 +1799,7 @@ fn flatten_path_core<'e>(
|
||||
arena: &'e core_types::arena::Arena,
|
||||
flattened: List<Vector>,
|
||||
snapshot: List<Graphic<'static>>,
|
||||
) -> Result<
|
||||
(
|
||||
Vector,
|
||||
Attr<'e, TransformAttr>,
|
||||
Attr<'e, Fill>,
|
||||
Attr<'e, StrokeAttr>,
|
||||
Attr<'e, EditorLayerPath>,
|
||||
Attr<'e, EditorMergedLayers>,
|
||||
),
|
||||
Interrupt,
|
||||
> {
|
||||
) -> Result<(Vector, Attr<'e, TransformAttr>, Attr<'e, AppearanceMarker>, Attr<'e, EditorLayerPath>, Attr<'e, EditorMergedLayers>), Interrupt> {
|
||||
let mut output = Vector::default();
|
||||
let mut primary_source = None;
|
||||
|
||||
@@ -1841,35 +1816,19 @@ fn flatten_path_core<'e>(
|
||||
let source_transform = flattened.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
output.concat(element, source_transform, collision_hash_seed);
|
||||
|
||||
// TODO: Make this instead use the first encountered stroke
|
||||
// Use the last encountered stroke as the output stroke
|
||||
output.stroke = element.stroke.clone();
|
||||
|
||||
primary_source = Some((index, source_transform));
|
||||
}
|
||||
|
||||
let mut fill = None;
|
||||
let mut stroke = None;
|
||||
// The primary row's appearance carries over whole, its paint transforms baked
|
||||
let mut appearance = None;
|
||||
let mut layer_path = Vec::new();
|
||||
if let Some((primary, source_transform)) = primary_source {
|
||||
let source_attributes = flattened.clone_item_attributes(primary);
|
||||
let mut attributes = ItemAttributeValues::new();
|
||||
|
||||
attributes.insert_cloned_from(&source_attributes, ATTR_FILL);
|
||||
attributes.insert_cloned_from(&source_attributes, ATTR_STROKE);
|
||||
attributes.insert_cloned_from(&source_attributes, graphic_types::ATTR_APPEARANCE);
|
||||
bake_paint_transforms(&mut attributes, source_transform);
|
||||
|
||||
let carrier = List::new_from_item(Item::from_parts(Vector::default(), attributes));
|
||||
fill = carrier
|
||||
.attribute::<Option<List<Graphic>>>(ATTR_FILL, 0)
|
||||
.and_then(|paint| paint.as_ref())
|
||||
.map(|paint| park_paint(arena, paint.clone()))
|
||||
.transpose()?;
|
||||
stroke = carrier
|
||||
.attribute::<Option<List<Graphic>>>(ATTR_STROKE, 0)
|
||||
.and_then(|paint| paint.as_ref())
|
||||
.map(|paint| park_paint(arena, paint.clone()))
|
||||
.transpose()?;
|
||||
appearance = attributes.remove::<Appearance>(graphic_types::ATTR_APPEARANCE).and_then(|appearance| appearance.declared().cloned());
|
||||
|
||||
// Adopt the last input item's layer so the editor can also bucket clicks under a contributing child layer
|
||||
layer_path = flattened.attribute_cloned_or_default::<Vec<NodeId>>(ATTR_EDITOR_LAYER_PATH, primary);
|
||||
@@ -1885,7 +1844,9 @@ fn flatten_path_core<'e>(
|
||||
// editor click-target preservation, as the boolean operation does.
|
||||
let merged_layers = arena.alloc_sized_keyed(snapshot, 0).ok_or_else(exhausted)?.0;
|
||||
|
||||
Ok((output, Attr(DAffine2::IDENTITY), Attr(fill), Attr(stroke), Attr(layer_path.as_slice()), Attr(Some(merged_layers))))
|
||||
let appearance = appearance.map(|appearance| park_appearance(arena, appearance)).transpose()?;
|
||||
|
||||
Ok((output, Attr(DAffine2::IDENTITY), Attr(appearance), Attr(layer_path.as_slice()), Attr(Some(merged_layers))))
|
||||
}
|
||||
|
||||
// TODO: Rename to "Combine Paths" and make this happen per-element instead of flattening every element into a single path. The migration for this should then become a Flatten Vector -> Combine Paths pair of nodes.
|
||||
@@ -1893,17 +1854,7 @@ fn flatten_path_core<'e>(
|
||||
pub fn flatten_path<'e>(
|
||||
ctx: impl Ctx + ExtractArena<'e> + ExtractIndex + InjectIndex + Copy,
|
||||
content: IList<Graphic<'static>>,
|
||||
) -> Result<
|
||||
(
|
||||
Vector,
|
||||
Attr<'e, TransformAttr>,
|
||||
Attr<'e, Fill>,
|
||||
Attr<'e, StrokeAttr>,
|
||||
Attr<'e, EditorLayerPath>,
|
||||
Attr<'e, EditorMergedLayers>,
|
||||
),
|
||||
Interrupt,
|
||||
> {
|
||||
) -> Result<(Vector, Attr<'e, TransformAttr>, Attr<'e, AppearanceMarker>, Attr<'e, EditorLayerPath>, Attr<'e, EditorMergedLayers>), Interrupt> {
|
||||
let item = content.as_group_item();
|
||||
let flattened = graphic_types::graphic::flatten_vector_rows(graphic_types::graphic::GraphicLevel::Run(&item));
|
||||
let snapshot = graphic_types::graphic::run_to_list::<Graphic>(&item).expect("the run holds the row's element type");
|
||||
@@ -1916,17 +1867,7 @@ pub fn flatten_path<'e>(
|
||||
pub fn flatten_path_vector<'e>(
|
||||
ctx: impl Ctx + ExtractArena<'e> + ExtractIndex + InjectIndex + Copy,
|
||||
content: IList<Vector>,
|
||||
) -> Result<
|
||||
(
|
||||
Vector,
|
||||
Attr<'e, TransformAttr>,
|
||||
Attr<'e, Fill>,
|
||||
Attr<'e, StrokeAttr>,
|
||||
Attr<'e, EditorLayerPath>,
|
||||
Attr<'e, EditorMergedLayers>,
|
||||
),
|
||||
Interrupt,
|
||||
> {
|
||||
) -> Result<(Vector, Attr<'e, TransformAttr>, Attr<'e, AppearanceMarker>, Attr<'e, EditorLayerPath>, Attr<'e, EditorMergedLayers>), Interrupt> {
|
||||
let wrapper = wrap_vector_level(content);
|
||||
let flattened = graphic_types::graphic::flatten_vector_rows(graphic_types::graphic::GraphicLevel::Legacy(&wrapper));
|
||||
let snapshot = legacy_graphic_list_of(content);
|
||||
@@ -1964,16 +1905,7 @@ fn sample_polyline(
|
||||
}
|
||||
};
|
||||
|
||||
let mut element = element;
|
||||
let mut result = Vector {
|
||||
point_domain: Default::default(),
|
||||
segment_domain: Default::default(),
|
||||
region_domain: Default::default(),
|
||||
colinear_manipulators: Default::default(),
|
||||
stroke: std::mem::take(&mut element.stroke),
|
||||
};
|
||||
// Transfer the stroke transform from the input vector content to the result.
|
||||
result.set_stroke_transform(*transform);
|
||||
let mut result = Vector::default();
|
||||
|
||||
for local_bezpath in element.stroke_bezpath_iter() {
|
||||
// Apply the transform to compute sample locations in world space (for correct distance-based spacing)
|
||||
@@ -2036,10 +1968,7 @@ fn simplify(
|
||||
let transform = Affine::new(transform_attribute.to_cols_array());
|
||||
let inverse_transform = transform.inverse();
|
||||
|
||||
let mut result = Vector {
|
||||
stroke: content.stroke.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
let mut result = Vector::default();
|
||||
|
||||
for mut bezpath in content.stroke_bezpath_iter() {
|
||||
bezpath.apply_affine(transform);
|
||||
@@ -2126,10 +2055,7 @@ fn decimate(
|
||||
let transform = Affine::new(transform_attribute.to_cols_array());
|
||||
let inverse_transform = transform.inverse();
|
||||
|
||||
let mut result = Vector {
|
||||
stroke: content.stroke.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
let mut result = Vector::default();
|
||||
|
||||
for mut bezpath in content.stroke_bezpath_iter() {
|
||||
bezpath.apply_affine(transform);
|
||||
@@ -2203,10 +2129,7 @@ fn cut_path_core(mut content: List<Vector>, progression: f64, reverse: bool, par
|
||||
let index = if t_value >= bezpath_count { (bezpath_count - 1.) as usize } else { t_value as usize };
|
||||
|
||||
if let Some((row_index, bezpath)) = bezpaths.get(index).cloned() {
|
||||
let mut result_vector = Vector {
|
||||
stroke: content.element(row_index).unwrap().stroke.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
let mut result_vector = Vector::default();
|
||||
|
||||
for (_, (_, bezpath)) in bezpaths.iter().enumerate().filter(|(i, (ri, _))| *i != index && *ri == row_index) {
|
||||
result_vector.append_bezpath(bezpath.clone());
|
||||
@@ -2245,8 +2168,7 @@ fn cut_path<'e>(
|
||||
IList<(
|
||||
Vector,
|
||||
Attr<'e, TransformAttr>,
|
||||
Attr<'e, Fill>,
|
||||
Attr<'e, StrokeAttr>,
|
||||
Attr<'e, AppearanceMarker>,
|
||||
Attr<'e, BlendModeAttr>,
|
||||
Attr<'e, Opacity>,
|
||||
Attr<'e, OpacityFill>,
|
||||
@@ -2448,8 +2370,6 @@ fn scatter_points(
|
||||
}
|
||||
|
||||
// Transfer the style from the input vector content to the result.
|
||||
result.stroke = element.stroke.clone();
|
||||
result.set_stroke_transform(DAffine2::IDENTITY);
|
||||
|
||||
result
|
||||
}
|
||||
@@ -2625,7 +2545,6 @@ fn offset_points(
|
||||
///
|
||||
/// *Progression* morphs through all objects. Interpolation is linear unless *Path* geometry is provided to control the trajectory between key objects. The **Origins to Polyline** node may be used to create a path with anchor points corresponding to each object. Other nodes can modify its path segments.
|
||||
fn morph_core(flattened: List<Vector>, snapshot: List<Graphic<'static>>, progression: f64, reverse: bool, distribution: InterpolationDistribution, path: List<Vector>) -> List<Vector> {
|
||||
use core_types::lane::LaneSource;
|
||||
/// Promotes a segment's handle pair to cubic-equivalent Bézier control points.
|
||||
/// For linear segments (both None), handles are placed at their respective anchors (zero-length)
|
||||
/// so that interpolation against another zero-length cubic doesn't introduce unwanted curvature.
|
||||
@@ -2786,6 +2705,51 @@ fn morph_core(flattened: List<Vector>, snapshot: List<Graphic<'static>>, progres
|
||||
}
|
||||
}
|
||||
|
||||
/// Lerps two appearances pairing coverages by cover, so a fill and a stroke never interpolate into each other.
|
||||
/// Stroke parameter pairs interpolate; other coverage pairings and the paint order step at the midpoint.
|
||||
fn lerp_appearance(a: Option<&Appearance>, b: Option<&Appearance>, time: f64) -> Option<Appearance> {
|
||||
if a.is_none() && b.is_none() {
|
||||
return None;
|
||||
}
|
||||
let empty = Appearance::default();
|
||||
let (a, b) = (a.unwrap_or(&empty), b.unwrap_or(&empty));
|
||||
|
||||
// The side holding the paint order at this time leads, so covers only the other side has follow behind it
|
||||
let (leading, trailing) = if time < 0.5 { (a, b) } else { (b, a) };
|
||||
let mut covers: Vec<Cover> = Vec::new();
|
||||
for cover in leading.covers().chain(trailing.covers()).map(Coverage::cover) {
|
||||
if !covers.contains(&cover) {
|
||||
covers.push(cover);
|
||||
}
|
||||
}
|
||||
|
||||
let mut result = Appearance::default();
|
||||
for cover in covers {
|
||||
let (source_index, target_index) = (a.first_index_of(cover), b.first_index_of(cover));
|
||||
|
||||
// An unmatched stroke steps out at the midpoint, matching the stroke geometry, while an unmatched fill persists and fades
|
||||
let coverage = match (source_index.and_then(|index| a.cover_at(index)), target_index.and_then(|index| b.cover_at(index))) {
|
||||
(Some(source), Some(target)) if cover == Cover::Stroke => Coverage::new_stroke(&source.stroke_params().lerp(&target.stroke_params(), time)),
|
||||
(Some(source), Some(target)) => (if time < 0.5 { source } else { target }).clone(),
|
||||
(Some(_), None) if cover == Cover::Stroke && time >= 0.5 => continue,
|
||||
(None, Some(_)) if cover == Cover::Stroke && time < 0.5 => continue,
|
||||
(Some(source), None) => source.clone(),
|
||||
(None, Some(target)) => target.clone(),
|
||||
(None, None) => continue,
|
||||
};
|
||||
|
||||
// An unmatched side falls to `None` here, which `lerp_graphic` fades against transparent.
|
||||
// The paint cell carries its graphic list as one wrapped cell, so the lerp works on the unwrapped rows.
|
||||
let source_paint = source_index.and_then(|index| a.paint_at(index)).and_then(graphic_types::graphic::paint_cell_rows);
|
||||
let target_paint = target_index.and_then(|index| b.paint_at(index)).and_then(graphic_types::graphic::paint_cell_rows);
|
||||
let paint = lerp_graphic(source_paint, target_paint, time).map(Graphic::Graphic).unwrap_or_default();
|
||||
|
||||
result.replace_or_insert(coverage, paint, CoverPlacement::Above);
|
||||
}
|
||||
|
||||
Some(result)
|
||||
}
|
||||
|
||||
// Preserve the original legacy snapshot as upstream data so this group layer's nested layers can be edited by the tools.
|
||||
let mut graphic_list_content = snapshot;
|
||||
|
||||
@@ -3043,35 +3007,12 @@ fn morph_core(flattened: List<Vector>, snapshot: List<Graphic<'static>>, progres
|
||||
return List::new_from_item(Item::from_parts(endpoint_element.clone(), attributes));
|
||||
}
|
||||
|
||||
let stroke = match (source_element.stroke.as_ref(), target_element.stroke.as_ref()) {
|
||||
(Some(a), Some(b)) => Some(a.lerp(b, time)),
|
||||
(Some(a), None) => {
|
||||
if time < 0.5 {
|
||||
Some(a.clone())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
(None, Some(b)) => {
|
||||
if time < 0.5 {
|
||||
None
|
||||
} else {
|
||||
Some(b.clone())
|
||||
}
|
||||
}
|
||||
(None, None) => None,
|
||||
};
|
||||
let mut vector = Vector { stroke, ..Default::default() };
|
||||
let mut vector = Vector::default();
|
||||
|
||||
let fill_paint = {
|
||||
let source = content.attr::<Fill>(source_index).filter(|paint| is_paint_present(paint));
|
||||
let target = content.attr::<Fill>(target_index).filter(|paint| is_paint_present(paint));
|
||||
lerp_graphic(source, target, time)
|
||||
};
|
||||
let stroke_paint = {
|
||||
let source = content.attr::<StrokeAttr>(source_index).filter(|paint| is_paint_present(paint));
|
||||
let target = content.attr::<StrokeAttr>(target_index).filter(|paint| is_paint_present(paint));
|
||||
lerp_graphic(source, target, time)
|
||||
let appearance = {
|
||||
let source = content.attribute::<Appearance>(graphic_types::ATTR_APPEARANCE, source_index);
|
||||
let target = content.attribute::<Appearance>(graphic_types::ATTR_APPEARANCE, target_index);
|
||||
lerp_appearance(source, target, time)
|
||||
};
|
||||
|
||||
// Work directly with manipulator groups, bypassing the BezPath intermediate representation.
|
||||
@@ -3231,11 +3172,8 @@ fn morph_core(flattened: List<Vector>, snapshot: List<Graphic<'static>>, progres
|
||||
.with_attribute(ATTR_EDITOR_LAYER_PATH, layer_path)
|
||||
.with_attribute(ATTR_EDITOR_MERGED_LAYERS, Some(graphic_list_content));
|
||||
|
||||
if let Some(fill) = fill_paint {
|
||||
item.set_attribute(ATTR_FILL, Some(fill));
|
||||
}
|
||||
if let Some(stroke) = stroke_paint {
|
||||
item.set_attribute(ATTR_STROKE, Some(stroke));
|
||||
if let Some(appearance) = appearance {
|
||||
item.set_attribute(graphic_types::ATTR_APPEARANCE, appearance);
|
||||
}
|
||||
|
||||
List::new_from_item(item)
|
||||
@@ -3256,8 +3194,7 @@ fn morph_lane<'e>(
|
||||
(
|
||||
Vector,
|
||||
Attr<'e, TransformAttr>,
|
||||
Attr<'e, Fill>,
|
||||
Attr<'e, StrokeAttr>,
|
||||
Attr<'e, AppearanceMarker>,
|
||||
Attr<'e, BlendModeAttr>,
|
||||
Attr<'e, Opacity>,
|
||||
Attr<'e, OpacityFill>,
|
||||
@@ -3296,8 +3233,7 @@ fn morph<'e>(
|
||||
(
|
||||
Vector,
|
||||
Attr<'e, TransformAttr>,
|
||||
Attr<'e, Fill>,
|
||||
Attr<'e, StrokeAttr>,
|
||||
Attr<'e, AppearanceMarker>,
|
||||
Attr<'e, BlendModeAttr>,
|
||||
Attr<'e, Opacity>,
|
||||
Attr<'e, OpacityFill>,
|
||||
@@ -3328,8 +3264,7 @@ fn morph_vector<'e>(
|
||||
(
|
||||
Vector,
|
||||
Attr<'e, TransformAttr>,
|
||||
Attr<'e, Fill>,
|
||||
Attr<'e, StrokeAttr>,
|
||||
Attr<'e, AppearanceMarker>,
|
||||
Attr<'e, BlendModeAttr>,
|
||||
Attr<'e, Opacity>,
|
||||
Attr<'e, OpacityFill>,
|
||||
@@ -3775,7 +3710,6 @@ fn centroid(_: impl Ctx, vector: IList<Vector>, centroid_type: CentroidType) ->
|
||||
mod test {
|
||||
use super::*;
|
||||
use core_types::transform::Footprint;
|
||||
use graphic_types::graphic::paint_graphics;
|
||||
use kurbo::{CubicBez, Ellipse, Point, Rect};
|
||||
use vector_types::vector::algorithms::bezpath_algorithms::{TValue, trim_pathseg};
|
||||
use vector_types::vector::misc::pathseg_abs_diff_eq;
|
||||
@@ -3931,12 +3865,13 @@ mod test {
|
||||
v
|
||||
};
|
||||
|
||||
let fill_appearance = |color: Color| Appearance::new_single(Coverage::new_fill(), Graphic::Graphic(List::new_from_element(color).into_graphic_list()));
|
||||
let item_a = Item::new_from_element(rect())
|
||||
.with_attribute(ATTR_TRANSFORM, DAffine2::IDENTITY)
|
||||
.with_attribute(ATTR_FILL, Some(List::new_from_element(Color::RED).into_graphic_list()));
|
||||
.with_attribute(graphic_types::ATTR_APPEARANCE, fill_appearance(Color::RED));
|
||||
let item_b = Item::new_from_element(rect())
|
||||
.with_attribute(ATTR_TRANSFORM, DAffine2::from_translation((-100., -100.).into()))
|
||||
.with_attribute(ATTR_FILL, Some(List::new_from_element(Color::BLUE).into_graphic_list()));
|
||||
.with_attribute(graphic_types::ATTR_APPEARANCE, fill_appearance(Color::BLUE));
|
||||
|
||||
let mut content = List::new_from_item(item_a);
|
||||
content.push(item_b);
|
||||
@@ -3944,7 +3879,13 @@ mod test {
|
||||
let snapshot = content.into_graphic_list();
|
||||
let morphed = super::morph_core(snapshot.clone().into_flattened_list(), snapshot, 0.5, false, InterpolationDistribution::default(), List::default());
|
||||
|
||||
let fill = paint_graphics::<Fill, _>(&morphed, 0).expect("Morph should keep the fill paint at the midpoint");
|
||||
let appearance = morphed
|
||||
.attribute::<Appearance>(graphic_types::ATTR_APPEARANCE, 0)
|
||||
.expect("Morph should keep the appearance at the midpoint");
|
||||
let fill = appearance
|
||||
.first_paint_of(Cover::Fill)
|
||||
.and_then(graphic_types::graphic::paint_cell_rows)
|
||||
.expect("Morph should keep the fill paint at the midpoint");
|
||||
|
||||
// Interpolated color between red and blue should have >0 value on both R and B
|
||||
let Some(Graphic::Color(color)) = fill.element(0) else {
|
||||
|
||||
@@ -29,76 +29,76 @@ pub fn message_handler_data_attr_impl(attr: TokenStream, input_item: TokenStream
|
||||
if segment.ident != "MessageHandler" {
|
||||
return Err(syn::Error::new(segment.ident.span(), "Expected MessageHandler trait"));
|
||||
}
|
||||
if let syn::PathArguments::AngleBracketed(args) = &segment.arguments {
|
||||
if args.args.len() >= 2 {
|
||||
// Extract the message type (M) and context struct type (C) from the trait params
|
||||
let message_type = &args.args[0];
|
||||
let data_type = &args.args[1];
|
||||
if let syn::PathArguments::AngleBracketed(args) = &segment.arguments
|
||||
&& args.args.len() >= 2
|
||||
{
|
||||
// Extract the message type (M) and context struct type (C) from the trait params
|
||||
let message_type = &args.args[0];
|
||||
let data_type = &args.args[1];
|
||||
|
||||
let impl_item = match data_type {
|
||||
syn::GenericArgument::Type(t) => {
|
||||
match t {
|
||||
syn::Type::Path(type_path) if !type_path.path.segments.is_empty() => {
|
||||
// Get just the base identifier (ToolMessageData) without generics
|
||||
let type_name = &type_path.path.segments.first().unwrap().ident;
|
||||
let impl_item = match data_type {
|
||||
syn::GenericArgument::Type(t) => {
|
||||
match t {
|
||||
syn::Type::Path(type_path) if !type_path.path.segments.is_empty() => {
|
||||
// Get just the base identifier (ToolMessageData) without generics
|
||||
let type_name = &type_path.path.segments.first().unwrap().ident;
|
||||
|
||||
let handler_data_line_number = type_name.span().start().line;
|
||||
let handler_data_line_number = type_name.span().start().line;
|
||||
|
||||
quote! {
|
||||
#input_item
|
||||
impl #message_type {
|
||||
pub fn message_handler_data_str() -> MessageData {
|
||||
MessageData::new(format!("{}", stringify!(#type_name)), #type_name::field_types(), #type_name::path(), #type_name::line_number())
|
||||
}
|
||||
pub fn message_handler_str() -> MessageData {
|
||||
MessageData::new(format!("{}", stringify!(#input_type)), #input_type::field_types(), #input_type::path(), #input_type::line_number())
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
syn::Type::Tuple(_) => quote! {
|
||||
quote! {
|
||||
#input_item
|
||||
impl #message_type {
|
||||
pub fn message_handler_str() -> MessageData {
|
||||
MessageData::new(format!("{}", stringify!(#input_type)), #input_type::field_types(), #input_type::path(), #input_type::line_number())
|
||||
}
|
||||
pub fn message_handler_data_str() -> MessageData {
|
||||
MessageData::new(format!("{}", stringify!(#type_name)), #type_name::field_types(), #type_name::path(), #type_name::line_number())
|
||||
}
|
||||
},
|
||||
syn::Type::Reference(type_reference) => {
|
||||
let message_type = call_site_ident(format!("{input_type}Message"));
|
||||
let type_ident = match &*type_reference.elem {
|
||||
syn::Type::Path(type_path) => &type_path.path.segments.first().unwrap().ident,
|
||||
_ => return Err(syn::Error::new(type_reference.elem.span(), "Expected type path")),
|
||||
};
|
||||
pub fn message_handler_str() -> MessageData {
|
||||
MessageData::new(format!("{}", stringify!(#input_type)), #input_type::field_types(), #input_type::path(), #input_type::line_number())
|
||||
|
||||
let type_line_number = type_ident.span().start().line;
|
||||
|
||||
let tr = clean_rust_type_syntax(type_reference.to_token_stream().to_string());
|
||||
quote! {
|
||||
#input_item
|
||||
impl #message_type {
|
||||
pub fn message_handler_data_str() -> MessageData {
|
||||
MessageData::new(format!("{}", #tr), #type_ident::field_types(), #type_ident::path(), #type_ident::line_number())
|
||||
}
|
||||
|
||||
pub fn message_handler_str() -> MessageData {
|
||||
MessageData::new(format!("{}", stringify!(#input_type)), #input_type::field_types(), #input_type::path(), #input_type::line_number())
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => return Err(syn::Error::new(t.span(), "Unsupported type format")),
|
||||
}
|
||||
}
|
||||
syn::Type::Tuple(_) => quote! {
|
||||
#input_item
|
||||
impl #message_type {
|
||||
pub fn message_handler_str() -> MessageData {
|
||||
MessageData::new(format!("{}", stringify!(#input_type)), #input_type::field_types(), #input_type::path(), #input_type::line_number())
|
||||
}
|
||||
}
|
||||
},
|
||||
syn::Type::Reference(type_reference) => {
|
||||
let message_type = call_site_ident(format!("{input_type}Message"));
|
||||
let type_ident = match &*type_reference.elem {
|
||||
syn::Type::Path(type_path) => &type_path.path.segments.first().unwrap().ident,
|
||||
_ => return Err(syn::Error::new(type_reference.elem.span(), "Expected type path")),
|
||||
};
|
||||
|
||||
_ => quote! {
|
||||
#input_item
|
||||
},
|
||||
};
|
||||
return Ok(impl_item);
|
||||
}
|
||||
let type_line_number = type_ident.span().start().line;
|
||||
|
||||
let tr = clean_rust_type_syntax(type_reference.to_token_stream().to_string());
|
||||
quote! {
|
||||
#input_item
|
||||
impl #message_type {
|
||||
pub fn message_handler_data_str() -> MessageData {
|
||||
MessageData::new(format!("{}", #tr), #type_ident::field_types(), #type_ident::path(), #type_ident::line_number())
|
||||
}
|
||||
|
||||
pub fn message_handler_str() -> MessageData {
|
||||
MessageData::new(format!("{}", stringify!(#input_type)), #input_type::field_types(), #input_type::path(), #input_type::line_number())
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => return Err(syn::Error::new(t.span(), "Unsupported type format")),
|
||||
}
|
||||
}
|
||||
|
||||
_ => quote! {
|
||||
#input_item
|
||||
},
|
||||
};
|
||||
return Ok(impl_item);
|
||||
}
|
||||
}
|
||||
Ok(input_item)
|
||||
|
||||
@@ -249,6 +249,9 @@ fn dot_to_svg(dot: &str) -> Result<String> {
|
||||
String::from_utf8(output.stdout).with_context(|| "SVG output was not valid UTF-8")
|
||||
}
|
||||
|
||||
/// A subgraph cluster's id, label, fill color, and the predicate picking its crates.
|
||||
type Cluster<'a> = (&'a str, &'a str, &'a str, Box<dyn Fn(&CrateInfo) -> bool>);
|
||||
|
||||
fn generate_dot(crates: &[CrateInfo]) -> String {
|
||||
let mut out = String::new();
|
||||
out.push_str("digraph CrateHierarchy {\n");
|
||||
@@ -257,7 +260,7 @@ fn generate_dot(crates: &[CrateInfo]) -> String {
|
||||
out.push_str(" edge [color=gray];\n\n");
|
||||
|
||||
// Define subgraph clusters
|
||||
let clusters: &[(&str, &str, &str, Box<dyn Fn(&CrateInfo) -> bool>)] = &[
|
||||
let clusters: &[Cluster] = &[
|
||||
(
|
||||
"cluster_core",
|
||||
"Core Components",
|
||||
|
||||
Reference in new issue
Block a user