Compare commits

...
Author SHA1 Message Date
Dennis Kobert b0a75ab97e Let migrations choose a target per anchor, ask the compiler, and run on whole states 2026-11-02 14:17:49 +00:00
Dennis Kobert 2055a74502 Run headless editor tests on a vulkan software GPU (#4880)
* Run headless editor tests on a software GPU

* Update comment
2026-11-02 10:46:25 +00:00
Keavon Chambers f5313bd7d1 Replace 'Copy to Points' and 'Assign Colors' with a family of 'Vary' nodes (#4906)
* Replace 'Copy to Points' and 'Assign Colors' with a family of 'Vary' nodes

* Resolve the type of Copy to Points content wired from a secondary output
2026-11-01 21:46:54 -08:00
Keavon Chambers cd9e58d313 Add mipmaps to images so they average their pixels when zoomed out (#4908) 2026-11-01 21:06:43 -08:00
Keavon Chambers b156d23e13 Make the migration and regression corpus checks warn rather than fail 2026-11-01 20:50:34 -08:00
64 changed files with 2809 additions and 399 deletions

No files matched your search

+2 -2
View File
@@ -1,2 +1,2 @@
https://github.com/Keavon/graphite-branded-assets/archive/2b13ba7ab77cc98cde645583e42e61ce4293def2.tar.gz
77abd4423cda8cba9f097a64d5337f48ad23f31bd537bb553aa654a128b2a51d
https://github.com/Keavon/graphite-branded-assets/archive/4e42efe8dbf2ae2d82e12123aa9c103d5740a465.tar.gz
6b7883a26952c77aad56758a11207761c2fcd1b61bf6dd5996c3cf9d4eb1cb5e
+17 -1
View File
@@ -163,6 +163,10 @@ jobs:
with:
version: ${{ env.SCCACHE_VERSION }}
# GitHub's runners have no GPU, so the editor's tests render on Mesa's software Vulkan driver
- name: 🎮 Install a software Vulkan driver
run: sudo apt-get update && sudo apt-get install --yes mesa-vulkan-drivers
- name: 🦀 Fetch Rust dependencies
run: cargo fetch --locked
@@ -233,10 +237,16 @@ jobs:
run: sudo apt-get update && sudo apt-get install --yes mesa-vulkan-drivers
- name: 🖼️ Check the corpus renders against its references
id: corpus
continue-on-error: true
run: cargo run --package regression -- --corpus target/regression-corpus check --output target/regression
- name: ⚠️ Warn about mismatched renders
if: ${{ steps.corpus.outcome == 'failure' }}
run: echo "::warning title=Regression corpus::Some corpus documents render differently from their references. Their renders and diffs are in the regression-mismatches artifact."
- name: 📤 Upload the renders and diffs of mismatches
if: ${{ failure() }}
if: ${{ steps.corpus.outcome == 'failure' }}
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
with:
name: regression-mismatches
@@ -269,8 +279,14 @@ jobs:
run: git fetch --depth=1 origin "$BASE_SHA"
- name: 🔬 Check migrations against the base commit
id: migrations
continue-on-error: true
run: cargo run --locked --package migration-snapshot -- check --baseline "$BASE_SHA"
- name: ⚠️ Warn about missing migrations
if: ${{ steps.migrations.outcome == 'failure' }}
run: echo "::warning title=Migrations::Some node changes lack a version bump or a migration. The log of the check above lists them."
# Rust format check on GitHub runner
rust-fmt:
needs: skip-check
+6 -1
View File
@@ -47,12 +47,17 @@ let
# Plotting tools
pkgs.graphviz
];
libs = [
pkgs.vulkan-loader
];
env = {
VK_ADD_DRIVER_FILES = "${pkgs.mesa}/share/vulkan/icd.d/lvp_icd.${pkgs.stdenv.hostPlatform.uname.processor}.json";
};
}
(lib.optionalAttrs desktop (
{
libs = [
pkgs.wayland
pkgs.vulkan-loader
pkgs.libGL
pkgs.libxkbcommon
self.packages.${system}.graphite-cef
Generated
+18 -3
View File
@@ -2708,6 +2708,7 @@ dependencies = [
"image",
"interpreted-executor",
"log",
"migration-compiled",
"migration-formats",
"migration-nodes",
"preprocessor",
@@ -2989,6 +2990,7 @@ dependencies = [
"kurbo",
"log",
"math-parser",
"migration-compiled",
"migration-formats",
"migration-nodes",
"node-macro",
@@ -4367,6 +4369,19 @@ dependencies = [
"autocfg",
]
[[package]]
name = "migration-compiled"
version = "0.0.0"
dependencies = [
"document-graph-storage",
"graph-craft",
"graphene-std",
"migration-core",
"migration-runner",
"preprocessor",
"serde",
]
[[package]]
name = "migration-core"
version = "0.0.0"
@@ -8024,7 +8039,7 @@ dependencies = [
[[package]]
name = "vello_common"
version = "0.3.0"
source = "git+https://github.com/Keavon/vello.git?rev=f20a8dde35de04c44d05e88b33864f27ad7d6f70#f20a8dde35de04c44d05e88b33864f27ad7d6f70"
source = "git+https://github.com/Keavon/vello.git?rev=4df331db2a02cb0f1cef4a0190dbbb2a00f4b075#4df331db2a02cb0f1cef4a0190dbbb2a00f4b075"
dependencies = [
"bytemuck",
"fearless_simd",
@@ -8039,7 +8054,7 @@ dependencies = [
[[package]]
name = "vello_gpu"
version = "0.3.0"
source = "git+https://github.com/Keavon/vello.git?rev=f20a8dde35de04c44d05e88b33864f27ad7d6f70#f20a8dde35de04c44d05e88b33864f27ad7d6f70"
source = "git+https://github.com/Keavon/vello.git?rev=4df331db2a02cb0f1cef4a0190dbbb2a00f4b075#4df331db2a02cb0f1cef4a0190dbbb2a00f4b075"
dependencies = [
"bytemuck",
"hashbrown 0.17.1",
@@ -8053,7 +8068,7 @@ dependencies = [
[[package]]
name = "vello_gpu_shaders"
version = "0.3.0"
source = "git+https://github.com/Keavon/vello.git?rev=f20a8dde35de04c44d05e88b33864f27ad7d6f70#f20a8dde35de04c44d05e88b33864f27ad7d6f70"
source = "git+https://github.com/Keavon/vello.git?rev=4df331db2a02cb0f1cef4a0190dbbb2a00f4b075#4df331db2a02cb0f1cef4a0190dbbb2a00f4b075"
dependencies = [
"naga",
"wesl",
+5 -3
View File
@@ -17,6 +17,7 @@ members = [
"document/migrations/formats",
"document/migrations/snapshot",
"document/migrations/nodes",
"document/migrations/compiled",
"document/peer-transport",
"editor",
"frontend/wrapper",
@@ -113,6 +114,7 @@ migration-core = { path = "document/migrations/core", default-features = false }
migration-macros = { path = "document/migrations/macros" }
migration-runner = { path = "document/migrations/runner" }
migration-formats = { path = "document/migrations/formats" }
migration-compiled = { path = "document/migrations/compiled" }
migration-nodes = { path = "document/migrations/nodes" }
peer-transport = { path = "document/peer-transport" }
raster-nodes = { path = "node-graph/nodes/raster" }
@@ -303,6 +305,6 @@ debug = true
[patch.crates-io]
rfd = { git = "https://github.com/timon-schelling/rfd.git", branch = "graphite" } # TODO: Remove this once https://github.com/PolyMeilex/rfd/pull/317 is merged and released
# TODO: Remove these once the fork's fixes are upstreamed and released
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "f20a8dde35de04c44d05e88b33864f27ad7d6f70" }
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "f20a8dde35de04c44d05e88b33864f27ad7d6f70" }
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "f20a8dde35de04c44d05e88b33864f27ad7d6f70" }
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "4df331db2a02cb0f1cef4a0190dbbb2a00f4b075" }
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "4df331db2a02cb0f1cef4a0190dbbb2a00f4b075" }
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "4df331db2a02cb0f1cef4a0190dbbb2a00f4b075" }
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false}],[4,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":3,"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":{"Number":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false}],[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":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{Line 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":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Definition":3927671882444294739},"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":{"Number":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false}],[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":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[9.4105020317595,0.0,0.0,9.4105020317595,-5.928761491996683,27.64206180233515]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[1924303400883620400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[12399235852192450000,16255990754021933000,15620668684239604000,5432878891027338000],"remove":[5992115648840007000],"delta":[[5432878891027338000,[-0.8525377229081244,-6.779663923182397]],[12399235852192450000,[3.4492455418381667,-6.252914951989055]],[15620668684239604000,[-7.105427357601002e-15,61.89300411522633]],[16255990754021933000,[3.423868312757215,60.83950617283953]]]},"segments":{"add":[1366074222973177300,9911415907547690000,3820594103877681000,5933636287523951000],"remove":[16939395239973712000],"start_point":[[1366074222973177300,12399235852192450000],[3820594103877681000,15620668684239604000],[5933636287523951000,5432878891027338000],[9911415907547690000,16255990754021933000]],"end_point":[[1366074222973177300,16255990754021933000],[3820594103877681000,5432878891027338000],[5933636287523951000,12399235852192450000],[9911415907547690000,15620668684239604000]],"handle_primary":[[1366074222973177300,[-12.729766803840905,34.6776406035666]],[3820594103877681000,[-1.2746024488136916,-0.5300005080526233]],[5933636287523951000,[0.0,0.0Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":13907401402762847509,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[31.55635094002563,-2.7755575615628914e-17,2.7755575615628914e-17,31.55635094002563,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":13907401402762847509,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[31.55635094002563,-2.7755575615628914e-17,2.7755575615628914e-17,31.55635094002563,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Definition":2345381328536166816},"visible":true,"skip_deduplication":false}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":[[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]]]},"add_g1_continuous":[],"remove_g1_continuous":[],"path_breaks":[1]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Definition":17990361595748109803},"visible":true,"skip_deduplication":false}],[665049002420596400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34],"remove":[],"delta":[[1,[-103.55555555555554,126.66666666666664]],[2,[-67.55555555555554,158.22222222222217]],[3,[45.77777777777777,145.33333333333331]],[4,[18.66666666666663,157.77777777777771]],[5,[66.22222222222223,152.88888888888886]],[6,[123.99999999999994,148.4444444444444]],[7,[229.33333333333331,152.4444444444444]],[8,[252.4444444444444,124.88888888888886]],[9,[156.4444444444444,97.33333333333331]],[10,[216.4444444444444,72.4444444444444]],[11,[136.88888888888886,39.111111111111086]],[12,[199.5555555555555,10.666666666666629]],[13,[153.77777777777777,-1.3333333333333712]],[14,[183.11111111111103,-19.111111111111143]],[15,[111.11111111111114,-60.888888888888914]],[16,[159.5555555555555,-75.55555555555557]],[17,[123.99999999999994,-84.00000000000003]],[18,[145.77777777777777,-97.7777777777778]],[19,[90.66666666666664,-129.33333333333334]],[20,[128.4444444444444,-142.22222222222223]],[21,[76.0,-202.22222222222223]],[22,[71.11111111111109,-201.7777777777778]],[23,[19.555555555555543,-139.55555555555557]],[24,[57.77777777777777,-129.33333333333334]],[25,[0.8888888888888573,-94.66666666666669]],[26,[22.66666666666663,-81.33333333333337]],[27,[-11.111111111111144,-72.00000000000003]],[28,[39.111111111111086,-58.22222222222226]],[29,[-32.888888888888914,-14.666666666666686]],[30,[-9.333333333333371,0.0]],[31,[-53.33333333333337,13.777777777777771]],[32,[9.333333333333314,38.66666666666663]],[33,[-78.22222222222223,75.55555555555554]],[34,[-5.333333333333371,99.11111111111109]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34],"remove":[],"sLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]]},"add_g1_continuous":[],"remove_g1_continuous":[],"path_breaks":[1]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Definition":11972573546269881380},"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":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Definition":16663118882744990321},"visible":true,"skip_deduplication":false}],[421715625023770179,{"inputs":[{"Node":{"node_id":3670529450440935325,"output_index":0}},{"Node":{"node_id":18214377096178867498,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Definition":376741554282583191},"visible":true,"skip_deduplication":false}],[431994205232245356,{"inputs":[{"Node":{"node_id":12387541320114693418,"output_index":0}},{"Node":{"node_id":14894569344576297448,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Definition":4973965320410448070},"visible":true,"skip_deduplication":false}],[454416440369338250,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2],"remove":[],"delta":[[1,[696.0,593.3333333333333]],[2,[733.7777777777778,518.6666666666666]]]},"segments":{"add":[1],"remove":[],"start_point":[[1,1]],"end_point":[[1,2]],"handle_primary":[[1,[0.0,0.0]]],"handle_end":[[1,[-18.666666666666515,26.66666666666663]]]},"add_g1_continuous":[],"remove_g1_continuous":[],"path_breaks":[1]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Definition":2691771812247834901},"visible":true,"skip_deduplication":false}],[501401493219507773,{"inputs":[{"Node":{"node_id":9425359632144678256,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.5271152,"green":0.02121901,"blue":0.015996292,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.5271152,"green":0.02121901,"blue":0.015996292,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[15.687661979265044,0.0,0.0,15.687661979265044,606.9205403814434,96.19238853662318]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedConLine truncated
+38 -1
View File
@@ -123,6 +123,17 @@ pub(crate) struct PendingPersist {
pub(crate) snapshot: bool,
}
/// What [`Gdd::open_in_with`] passes on to node migrations.
#[derive(Default)]
struct MigrationInputs<'a> {
#[cfg(feature = "migrations")]
byte_store: Option<&'a dyn graphene_resource::LoadResource>,
#[cfg(feature = "migrations")]
host: Option<&'a dyn migration_core::MigrationHost>,
#[cfg(not(feature = "migrations"))]
_lifetime: std::marker::PhantomData<&'a ()>,
}
impl<L: Layout + Clone> Clone for Gdd<L> {
fn clone(&self) -> Self {
Self {
@@ -195,12 +206,38 @@ impl<L: Layout> Gdd<L> {
Self::open_in(working, layout).await
}
/// [`open_from_archive`](Self::open_from_archive), offering migrations what [`open_in_with`](Self::open_in_with) describes.
#[cfg(all(feature = "migrations", any(feature = "zip", feature = "xz")))]
pub async fn open_from_archive_with(
bytes: &[u8],
mut working: AnyContainer,
layout: L,
byte_store: Option<&dyn graphene_resource::LoadResource>,
host: Option<&dyn migration_core::MigrationHost>,
) -> Result<Self, Error> {
document_container::archive::open_auto(bytes, &mut working)?;
Self::open_in_with(working, layout, byte_store, host).await
}
/// Backend-agnostic open. Splits out so tests can supply a [`document_container::backends::memory::MemoryBackend`].
///
/// # Errors
/// [`Error::MissingManifest`] if the container holds no manifest, [`Error::WrongFormat`] / [`Error::UnsupportedVersion`]
/// if it fails validation, plus the usual [`Error::Read`] / [`Error::Codec`] / [`Error::Crdt`] if a payload is malformed.
pub async fn open_in(working: AnyContainer, layout: L) -> Result<Self, Error> {
Self::open_stored(working, layout, MigrationInputs::default()).await
}
/// [`open_in`](Self::open_in), offering migrations what only the caller has. `host` gives them the compiler, and without one, those asking for it
/// settle on their fallback for good. `byte_store` holds declarations the container doesn't, such as the editor's global cache.
#[cfg(feature = "migrations")]
pub async fn open_in_with(working: AnyContainer, layout: L, byte_store: Option<&dyn graphene_resource::LoadResource>, host: Option<&dyn migration_core::MigrationHost>) -> Result<Self, Error> {
Self::open_stored(working, layout, MigrationInputs { byte_store, host }).await
}
#[cfg_attr(not(feature = "migrations"), expect(unused_variables, reason = "only node migrations use what the caller offers"))]
async fn open_stored(working: AnyContainer, layout: L, inputs: MigrationInputs<'_>) -> Result<Self, Error> {
persist::finish_staged_rewrite(&working, &layout).await?;
let manifest: Manifest = match io::read_single(&working, layout.manifest_basename(), MANIFEST_CODEC).await {
@@ -291,7 +328,7 @@ impl<L: Layout> Gdd<L> {
#[cfg(feature = "migrations")]
{
let migrated_nodes = gdd.migrate_nodes().await?;
let migrated_nodes = gdd.migrate_nodes(inputs.byte_store, inputs.host).await?;
gdd.migrated = format_outcome.is_some() || migrated_nodes;
if gdd.migrated {
gdd.manifest.format_version = gdd.manifest.format_version.max(manifest::SUPPORTED_FORMAT_VERSION);
+76 -14
View File
@@ -4,8 +4,9 @@
use std::collections::{BTreeSet, HashMap};
use document_container::AsyncContainer;
use document_graph_storage::{Delta, EncodedDeclaration, HistoryMetadata, PeerId, Registry, ResourceEntry, ResourceId, Rev, Session, Subject, TimeStamp};
use migration_core::{Declaration, DeclarationResolver, NodeMigration, Payload, PayloadCodec};
use document_graph_storage::{Declarations, Delta, EncodedDeclaration, HistoryMetadata, PeerId, Registry, ResourceEntry, ResourceId, Rev, Session, Subject, TimeStamp};
use graphene_resource::LoadResource;
use migration_core::{Declaration, DeclarationResolver, MigrationHost, NodeMigration, Payload, PayloadCodec};
use migration_runner::{DocumentPayloads, HistoryOutcome, RunnerError, holds, migrate_history, migrate_registry, references, registry_at, run_format_migrations};
use crate::error::Error;
@@ -61,32 +62,37 @@ fn payload_codec(codec: Codec) -> PayloadCodec {
}
impl<L: Layout> Gdd<L> {
/// Rewrite history through every registered node migration whose source declaration it references. Returns whether any ran.
pub(crate) async fn migrate_nodes(&mut self) -> Result<bool, Error> {
/// Rewrite history through every registered node migration whose source declaration it references, in dependency order. Returns whether any ran.
pub(crate) async fn migrate_nodes(&mut self, byte_store: Option<&dyn LoadResource>, host: Option<&dyn MigrationHost>) -> Result<bool, Error> {
let migrations = migration_core::registered_migrations();
if migrations.is_empty() {
return Ok(false);
}
let resolver = DocumentDeclarations::new(&migrations, self.session.peer());
let mut resolver = DocumentDeclarations::new(&migrations, self.session.peer());
let hot_ops = self.session.hot_log().iter().map(|hot_op| &hot_op.op);
let kinds: Vec<_> = self.session.history().map(|delta| &delta.kind).chain(hot_ops).collect();
let registry = self.session.registry();
let pending: Vec<Declaration> = migrations
let pending: Vec<&'static dyn NodeMigration> = migrations
.iter()
.map(|migration| migration.source())
.filter(|source| holds(registry, *source, &resolver) || kinds.iter().any(|kind| references(kind, *source, &resolver)))
.copied()
.filter(|migration| holds(registry, migration.source(), &resolver) || kinds.iter().any(|kind| references(kind, migration.source(), &resolver)))
.collect();
if pending.is_empty() {
return Ok(false);
}
// Only a document with a pending migration asking the compiler pays for loading its declarations
if host.is_some() && pending.iter().any(|migration| migration.asks_compiler()) {
resolver.stored = self.load_stored_declarations(byte_store).await;
}
// Hot ops join history first, so they migrate with it
self.session.retire_all()?;
let migrated = migrate_registry(&migrations, self.session.retired_registry(), &resolver)?;
(self.session, self.metadata) = match self.session_with_rewritten_history(&migrations, &migrated, &resolver) {
let migrated = migrate_registry(&migrations, self.session.retired_registry(), &resolver, host)?;
(self.session, self.metadata) = match self.session_with_rewritten_history(&migrations, &migrated, &resolver, host) {
Ok(rewritten) => rewritten,
Err(error) => {
log::warn!("Migrating this document's history failed, so undo can't reach before this point: {error}");
@@ -103,15 +109,57 @@ impl<L: Layout> Gdd<L> {
}
}
let names: Vec<String> = pending.iter().map(ToString::to_string).collect();
let names: Vec<String> = pending.iter().map(|migration| migration.source().to_string()).collect();
log::info!("Migrated nodes from {}", names.join(", "));
Ok(true)
}
/// Every declaration this document's nodes and history reference, from `byte_store` where it has them and otherwise from the container.
async fn load_stored_declarations(&self, byte_store: Option<&dyn LoadResource>) -> Declarations {
let mut declarations = Declarations::new();
for (id, hash) in self.session.all_declaration_resources() {
let Some(hash) = hash else { continue };
let cached = match byte_store {
Some(byte_store) => byte_store.load(hash).await,
None => None,
};
let stored = match cached {
Some(_) => None,
None => self.working.read(&self.layout.resource_path(&hash)).await.ok(),
};
let decoded = match (&cached, &stored) {
(Some(cached), _) => document_graph_storage::decode_declaration(cached.as_ref()),
(None, Some(stored)) => document_graph_storage::decode_declaration(stored.as_ref()),
(None, None) => {
log::warn!("Declaration bytes for {id} (hash {hash}) are missing, so what reads through it won't compile");
continue;
}
};
match decoded {
Ok(proto) => {
declarations.insert(id, proto);
}
Err(error) => log::warn!("Declaration {id} failed to decode: {error}"),
}
}
declarations
}
/// A session over the rewritten history, as long as replaying that history reaches `migrated`, which a history missing its beginning wouldn't.
fn session_with_rewritten_history(&self, migrations: &[&'static dyn NodeMigration], migrated: &Registry, resolver: &DocumentDeclarations) -> Result<(Session, HistoryMetadata), RunnerError> {
fn session_with_rewritten_history(
&self,
migrations: &[&'static dyn NodeMigration],
migrated: &Registry,
resolver: &DocumentDeclarations,
host: Option<&dyn MigrationHost>,
) -> Result<(Session, HistoryMetadata), RunnerError> {
let history: Vec<Delta> = self.session.history().cloned().collect();
let rewritten = migrate_history(migrations, history, resolver)?;
let cursors = self.session.head_rev().into_iter().chain(self.session.redo_stack().iter().copied());
let rewritten = migrate_history(migrations, history, resolver, host, cursors)?;
let remap = |rev: Rev| rewritten.revs.get(&rev).copied().flatten();
let head = self.session.head_rev().and_then(remap);
@@ -151,6 +199,8 @@ impl<L: Layout> Gdd<L> {
struct DocumentDeclarations {
known: HashMap<ResourceId, Declaration>,
encoded: HashMap<Declaration, EncodedDeclaration>,
/// The document's own declarations, loaded only for a migration asking the compiler.
stored: Declarations,
peer: PeerId,
}
@@ -173,7 +223,12 @@ impl DocumentDeclarations {
}
}
Self { known, encoded, peer }
Self {
known,
encoded,
stored: Declarations::new(),
peer,
}
}
}
@@ -196,4 +251,11 @@ impl DeclarationResolver for DocumentDeclarations {
let encoded = self.encoded.get(&declaration)?;
Some(ResourceEntry::embedded(encoded.hash, self.peer, TimeStamp::ORIGIN))
}
fn proto(&self, resource: ResourceId) -> Option<document_graph_storage::ProtoNode> {
if let Some(proto) = self.stored.get(&resource) {
return Some(proto.clone());
}
Some(self.encoded.get(self.known.get(&resource)?)?.proto.clone())
}
}
+185
View File
@@ -0,0 +1,185 @@
// Migrations asking the compiler run as part of opening, in order, and cost nothing to documents they don't apply to
#![cfg(feature = "migrations")]
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout};
use document_graph_storage::{EncodedDeclaration, Implementation, NoMetadata, PeerId, Registry};
use futures::executor::block_on;
use graph_craft::application_io::resource::HashMapResourceStorage;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeNetwork};
use graph_craft::{ProtoNodeIdentifier, concrete};
use graphene_resource::{LoadResource, ResourceFuture, ResourceHash, ResourceRegistry, ResourceStorage};
use migration_core::{Compiler, DeclarationResolver, MigrationHost, Node, Target, ValueType, decl, migration};
use migration_formats as _;
use std::sync::atomic::{AtomicUsize, Ordering};
struct IsVector;
impl ValueType for IsVector {
fn element_name(&self) -> Option<&str> {
Some(std::any::type_name::<IsVector>())
}
}
struct FakeCompiler;
impl Compiler for FakeCompiler {
fn input_type(&self, _node: &Node, _slot: usize) -> Option<Box<dyn ValueType>> {
Some(Box::new(IsVector))
}
}
/// Picks by what the compiler says about the state.
#[migration("test_nodes::CopyNode"@1 => "test_nodes::FallbackNode"@2)]
pub fn by_compiler(node: &Node, compiler: Option<&dyn Compiler>, target: &mut Target) {
if compiler.and_then(|compiler| compiler.input_type(node, 0)).is_some_and(|value_type| value_type.element_is::<IsVector>()) {
target.set(decl!("test_nodes::VectorNode"@1));
}
}
/// Records that it was asked, and what the resolver knew when it was.
#[derive(Default)]
struct Host {
asked: AtomicUsize,
missing_declarations: AtomicUsize,
}
impl MigrationHost for Host {
fn compiler(&self, state: &Registry, resolver: &dyn DeclarationResolver) -> Option<Box<dyn Compiler + '_>> {
self.asked.fetch_add(1, Ordering::Relaxed);
for node in state.node_instances.values() {
if let Implementation::ProtoNode(resource) = node.implementation()
&& resolver.proto(*resource).is_none()
{
self.missing_declarations.fetch_add(1, Ordering::Relaxed);
}
}
Some(Box::new(FakeCompiler))
}
}
/// A byte store that has nothing, like a device's cache that has never seen this document, and counts what it's asked for.
#[derive(Default)]
struct EmptyStore {
loads: AtomicUsize,
}
impl LoadResource for EmptyStore {
fn load(&self, _hash: ResourceHash) -> ResourceFuture<'_> {
self.loads.fetch_add(1, Ordering::Relaxed);
Box::pin(async { None })
}
}
fn network_of(nodes: &[(u64, &'static str)]) -> NodeNetwork {
let node = |identifier: &'static str| DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new(identifier)),
call_argument: concrete!(()),
..Default::default()
};
NodeNetwork {
nodes: nodes.iter().map(|(id, identifier)| (NodeId(*id), node(identifier))).collect(),
..Default::default()
}
}
fn stored(nodes: &[(u64, &'static str)]) -> AnyContainer {
stored_with_bytes_in(nodes, &HashMapResourceStorage::new())
}
/// A document whose declaration bytes went to `store`, as the editor sends them to its global cache.
fn stored_with_bytes_in(nodes: &[(u64, &'static str)], store: &HashMapResourceStorage) -> AnyContainer {
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(7), 1, "editor".into(), "std".into()).unwrap();
gdd.commit_from_runtime(&network_of(nodes), &NoMetadata, &ResourceRegistry::new(), store).unwrap();
gdd.into_storage().0
}
fn implementation_of(identifier: &str, version: u32) -> Implementation {
Implementation::ProtoNode(EncodedDeclaration::new(identifier.to_string(), version).unwrap().id)
}
#[test]
fn a_document_without_the_node_pays_nothing() {
block_on(async {
let (host, store) = (Host::default(), EmptyStore::default());
let working = stored(&[(1, "test_nodes::OtherNode")]);
let gdd = GddV1::open_in_with(working, GddV1Layout, Some(&store), Some(&host)).await.unwrap();
assert!(!gdd.migrated());
assert_eq!(host.asked.load(Ordering::Relaxed), 0, "the compiler is never built");
assert_eq!(store.loads.load(Ordering::Relaxed), 0, "no declaration is loaded");
});
}
#[test]
fn opening_runs_it_in_one_pass_and_the_result_persists() {
block_on(async {
let host = Host::default();
let working = stored(&[(1, "test_nodes::CopyNode")]);
let gdd = GddV1::open_in_with(working, GddV1Layout, None, Some(&host)).await.unwrap();
let anchor = *gdd.registry().node_instances.keys().next().unwrap();
assert_eq!(*gdd.registry().node_instances[&anchor].implementation(), implementation_of("test_nodes::VectorNode", 1));
assert!(gdd.migrated());
let target = EncodedDeclaration::new("test_nodes::VectorNode".to_string(), 1).unwrap();
assert_eq!(gdd.declarations(&gdd).await[&target.id], target.proto, "the chosen declaration's bytes are stored");
let registry = gdd.registry().clone();
let (working, layout) = gdd.into_storage();
let reopened = GddV1::open_in(working, layout).await.unwrap();
assert!(reopened.registry().value_equal(&registry));
assert!(!reopened.migrated());
});
}
#[test]
fn declarations_come_from_the_container_when_the_cache_lacks_them() {
block_on(async {
let (host, store) = (Host::default(), EmptyStore::default());
let nodes = [(1, "test_nodes::CopyNode"), (2, "test_nodes::OtherNode")];
// An archive carries its declarations in the container, which a device's cache hasn't seen yet
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(7), 1, "editor".into(), "std".into()).unwrap();
gdd.commit_from_runtime(&network_of(&nodes), &NoMetadata, &ResourceRegistry::new(), &HashMapResourceStorage::new())
.unwrap();
for (_, identifier) in nodes {
gdd.store(&EncodedDeclaration::new(identifier.to_string(), 1).unwrap().bytes);
}
let working = gdd.into_storage().0;
GddV1::open_in_with(working, GddV1Layout, Some(&store), Some(&host)).await.unwrap();
assert!(store.loads.load(Ordering::Relaxed) > 0, "the cache is asked first");
assert!(host.asked.load(Ordering::Relaxed) > 0);
assert_eq!(host.missing_declarations.load(Ordering::Relaxed), 0, "the container fills in what the cache lacks");
});
}
#[test]
fn declarations_come_from_the_cache_when_the_container_lacks_them() {
block_on(async {
let (host, store) = (Host::default(), HashMapResourceStorage::new());
let working = stored_with_bytes_in(&[(1, "test_nodes::CopyNode"), (2, "test_nodes::OtherNode")], &store);
GddV1::open_in_with(working, GddV1Layout, Some(&store), Some(&host)).await.unwrap();
assert!(host.asked.load(Ordering::Relaxed) > 0);
assert_eq!(host.missing_declarations.load(Ordering::Relaxed), 0);
});
}
#[test]
fn opening_without_a_host_takes_the_fallback() {
block_on(async {
let working = stored(&[(1, "test_nodes::CopyNode")]);
let gdd = GddV1::open_in(working, GddV1Layout).await.unwrap();
let node = gdd.registry().node_instances.values().next().unwrap();
assert_eq!(*node.implementation(), implementation_of("test_nodes::FallbackNode", 2));
});
}
+7 -1
View File
@@ -935,7 +935,13 @@ impl Session {
pub fn bootstrap_from_registry(peer: PeerId, user: UserId, registry: Registry) -> Result<Self, CrdtError> {
let ops = crate::delta::compute_deltas(&Registry::default(), &registry);
let mut session = Self::with_identity(peer, user);
session.commit_ops(ops, false)?;
let revs = session.commit_ops(ops, false)?;
// All of it is one step that undo can land on, with the first edit after it undoable as its own
if let Some(last) = revs.last() {
session.mark_interaction_end(*last);
}
// No hot ops on this path, so the working registry must mirror the freshly-built snapshot.
session.document.working_registry = session.document.retired_snapshot.clone();
Ok(session)
+19
View File
@@ -0,0 +1,19 @@
[package]
name = "migration-compiled"
description = "Node migrations of Graphite documents that ask the compiler, and the capability giving them access to it"
edition.workspace = true
version.workspace = true
license.workspace = true
authors.workspace = true
publish.workspace = true
[dependencies]
document-graph-storage = { workspace = true, features = ["conversion"] }
graph-craft = { workspace = true }
graphene-std = { workspace = true }
migration-core = { workspace = true, features = ["typed"] }
preprocessor = { workspace = true }
[dev-dependencies]
migration-runner = { workspace = true, features = ["testing"] }
serde = { workspace = true }
@@ -0,0 +1,72 @@
use document_graph_storage::{Declarations, Implementation, NodeId, Registry, ResourceId};
use graph_craft::Type;
use graph_craft::document::{NodeId as RuntimeNodeId, NodeNetwork};
use graphene_std::platform_application_io::ResourceHash;
use migration_core::{Compiler, DeclarationResolver, MigrationHost, Node, ValueType};
use preprocessor::Preprocessor;
use std::collections::HashMap;
use std::sync::OnceLock;
/// A value type from the live node registry.
struct LiveType(Type);
impl ValueType for LiveType {
fn element_name(&self) -> Option<&str> {
let element = match &self.0 {
Type::Item(element) | Type::List(element) => &**element,
other => other,
};
match element {
Type::Concrete(descriptor) => Some(&descriptor.name),
_ => None,
}
}
}
/// One state of a document, as the compiler sees it.
struct StateCompiler<'a> {
inlined: NodeNetwork,
local_ids: HashMap<NodeId, RuntimeNodeId>,
resource_hashes: HashMap<ResourceId, ResourceHash>,
preprocessor: &'a Preprocessor,
}
impl Compiler for StateCompiler<'_> {
fn input_type(&self, node: &Node, slot: usize) -> Option<Box<dyn ValueType>> {
let local_id = *self.local_ids.get(&node.id())?;
let resource_hash = |resource| self.resource_hashes.get(&resource).copied();
let value_type = self.preprocessor.input_type(&self.inlined, local_id, slot, &resource_hash)?;
Some(Box::new(LiveType(value_type)))
}
}
/// Offers migrations the compiler. Building it costs nothing, and only a document with a migration asking for it pays for what comes after.
#[derive(Default)]
pub struct CompilerHost {
preprocessor: OnceLock<Preprocessor>,
}
impl MigrationHost for CompilerHost {
fn compiler(&self, state: &Registry, resolver: &dyn DeclarationResolver) -> Option<Box<dyn Compiler + '_>> {
let mut declarations = Declarations::new();
for node in state.node_instances.values() {
if let Implementation::ProtoNode(resource) = node.implementation()
&& let Some(proto) = resolver.proto(*resource)
{
declarations.insert(*resource, proto);
}
}
// A state that doesn't convert answers nothing, so each migration asking takes its fallback
let (mut inlined, nodes, _) = state.to_runtime_with_full_metadata(&declarations).ok()?;
inlined.inline_definitions().ok()?;
Some(Box::new(StateCompiler {
inlined,
local_ids: nodes.into_iter().map(|node| (node.storage_id, node.local_id)).collect(),
resource_hashes: state.resources.iter().filter_map(|(id, entry)| Some((*id, entry.hash?))).collect(),
preprocessor: self.preprocessor.get_or_init(Preprocessor::new),
}))
}
}
+6
View File
@@ -0,0 +1,6 @@
//! Node migrations that ask the compiler about a document, and [`CompilerHost`], which the editor and CLI offer it through.
//! Unlike `migration-nodes`, these link the node crates and depend on the build they run in, so a document's peers can't all reach the same result.
mod compiler;
pub use compiler::CompilerHost;
@@ -0,0 +1,84 @@
//! The compiler host, on the real node registry.
use document_graph_storage::{NodeId, NodeInput};
use graphene_std::vector::Vector;
use migration_compiled::CompilerHost;
use migration_core::{Compiler, Declaration, Node, NodeMigration, Target, decl, literal, migration};
use migration_runner::testing::{Fixture, SourceContract, check_commutation_with};
use serde::Serialize;
const STAR: Declaration = decl!("vector_nodes::generator_nodes::StarNode"@1);
/// Frozen mirror of the `TaggedValue` variants these tests store.
#[derive(Serialize)]
enum Tagged {
None,
Integer(i64),
Number(f64),
}
/// Picks by the element type of its first input, with a fallback for what doesn't compile.
#[migration("test_nodes::anchor"@1 => "test_nodes::fallback"@2)]
pub fn by_compiler(node: &Node, compiler: Option<&dyn Compiler>, target: &mut Target) {
if compiler.and_then(|compiler| compiler.input_type(node, 0)).is_some_and(|value_type| value_type.element_is::<Vector>()) {
target.set(decl!("test_nodes::vector"@1));
}
}
fn star_inputs() -> Vec<NodeInput> {
vec![literal(Tagged::None), literal(Tagged::Integer(5)), literal(Tagged::Number(50.)), literal(Tagged::Number(25.))]
}
fn wire(id: NodeId) -> NodeInput {
NodeInput::Node { id, index: 0 }
}
#[test]
fn a_wire_from_a_real_node_gives_its_type() {
let mut fixture = Fixture::new(&ByCompiler);
let star = fixture.add(STAR, star_inputs());
let anchor = fixture.add(ByCompiler.source(), vec![wire(star)]);
let migrated = fixture.migrate_with(&ByCompiler, Some(&CompilerHost::default())).unwrap();
assert_eq!(fixture.declaration_of(&migrated, anchor), Some(decl!("test_nodes::vector"@1)));
}
#[test]
fn no_host_takes_the_fallback() {
let mut fixture = Fixture::new(&ByCompiler);
let star = fixture.add(STAR, star_inputs());
let anchor = fixture.add(ByCompiler.source(), vec![wire(star)]);
let migrated = fixture.migrate(&ByCompiler).unwrap();
assert_eq!(fixture.declaration_of(&migrated, anchor), Some(decl!("test_nodes::fallback"@2)));
}
#[test]
fn what_does_not_compile_takes_the_fallback() {
let mut fixture = Fixture::new(&ByCompiler);
let missing = fixture.add(decl!("test_nodes::not_a_node"@1), vec![]);
let anchor = fixture.add(ByCompiler.source(), vec![wire(missing)]);
let migrated = fixture.migrate_with(&ByCompiler, Some(&CompilerHost::default())).unwrap();
assert_eq!(fixture.declaration_of(&migrated, anchor), Some(decl!("test_nodes::fallback"@2)));
}
#[test]
fn a_literal_takes_the_fallback() {
let mut fixture = Fixture::new(&ByCompiler);
let anchor = fixture.add(ByCompiler.source(), vec![literal(Tagged::Number(1.))]);
let migrated = fixture.migrate_with(&ByCompiler, Some(&CompilerHost::default())).unwrap();
assert_eq!(fixture.declaration_of(&migrated, anchor), Some(decl!("test_nodes::fallback"@2)));
}
#[test]
fn asking_the_compiler_commutes() {
let host = CompilerHost::default();
let contract = SourceContract::new(1, |_, _| literal(Tagged::Number(0.)));
check_commutation_with(&ByCompiler, &contract, Some(&host));
}
+28
View File
@@ -0,0 +1,28 @@
use crate::{DeclarationResolver, Node};
use document_graph_storage::Registry;
/// A value type as the compiler reports it. Only ever compared within one run, so nothing about it is stored.
pub trait ValueType {
/// The `type_name` of the element an `Item` or `List` holds, or of the type itself when it's neither. `None` for what isn't concrete.
fn element_name(&self) -> Option<&str>;
}
impl dyn ValueType {
/// Whether the elements of this value type are `T`.
pub fn element_is<T: 'static>(&self) -> bool {
// The compiler's types carry no `TypeId`, and compare by this same name
self.element_name() == Some(std::any::type_name::<T>())
}
}
/// Answers what flows through one state of a document. A migration asks for it with an `Option<&dyn Compiler>` parameter, and handles `None`.
pub trait Compiler {
/// The value type slot `slot` of `node` carries, or `None` where what feeds it doesn't compile.
fn input_type(&self, node: &Node, slot: usize) -> Option<Box<dyn ValueType>>;
}
/// What the caller opening a document offers migrations beyond the stored data.
pub trait MigrationHost: Sync {
/// A compiler describing `state`, whose declarations `resolver` names. `None` runs the migrations asking for one on their fallback.
fn compiler(&self, state: &Registry, resolver: &dyn DeclarationResolver) -> Option<Box<dyn Compiler + '_>>;
}
+5 -1
View File
@@ -1,4 +1,4 @@
use document_graph_storage::{ResourceEntry, ResourceId};
use document_graph_storage::{ProtoNode, ResourceEntry, ResourceId};
use serde::Serialize;
/// A proto-node declaration at one version, written `identifier@version`.
@@ -38,4 +38,8 @@ pub trait DeclarationResolver {
fn resource_entry(&self, _declaration: Declaration) -> Option<ResourceEntry> {
None
}
/// What a resource this resolver knows decodes to, for converting a state to a runtime network.
fn proto(&self, _resource: ResourceId) -> Option<ProtoNode> {
None
}
}
+5 -1
View File
@@ -5,6 +5,8 @@
//! successor on the typed `Registry`. The `migration-runner` crate applies both. Design rationale
//! lives in `node-graph/rfcs/document-format-migrations.md`.
#[cfg(feature = "typed")]
mod compiler;
#[cfg(feature = "typed")]
mod connector;
#[cfg(feature = "typed")]
@@ -20,6 +22,8 @@ mod value;
#[cfg(feature = "typed")]
mod view;
#[cfg(feature = "typed")]
pub use compiler::{Compiler, MigrationHost, ValueType};
#[cfg(feature = "typed")]
pub use connector::{InputConnector, NewNode, OutputConnector};
#[cfg(feature = "typed")]
@@ -40,7 +44,7 @@ pub use registry::{register_migration, registered_migrations};
#[cfg(feature = "typed")]
pub use value::{encode, literal, literal_of};
#[cfg(feature = "typed")]
pub use view::{AddedNode, AnchorContext, Downstream, Edits, Graph, Inputs, InputsEdit, Node, Region, Upstream, View};
pub use view::{AddedNode, AnchorContext, Downstream, Edits, Graph, Inputs, InputsEdit, Node, Region, Target, Upstream, View};
// For the registration `#[migration]`, `rename!`, and `format_migration!` generate
#[doc(hidden)]
+5 -1
View File
@@ -4,12 +4,16 @@ use crate::{AnchorContext, Declaration, Edits, MigrationError, Region};
pub trait NodeMigration: Send + Sync {
/// The declaration whose nodes are anchors.
fn source(&self) -> Declaration;
/// The declaration the runner switches anchors to.
/// The declaration the runner switches anchors to, unless a run chooses one of its [`pins`](Self::pins) through [`Target`](crate::Target).
fn target(&self) -> Declaration;
/// Declarations the body names, which order it after the migration producing each and before the one consuming it.
fn pins(&self) -> &'static [Declaration] {
&[]
}
/// Whether the body takes an `Option<&dyn Compiler>`, which orders it as late as its dependencies allow.
fn asks_compiler(&self) -> bool {
false
}
/// The union of the regions the migration's parameters read and edit.
fn footprint(&self) -> Region;
/// Run on one anchor, returning what its views recorded.
+50 -1
View File
@@ -1,4 +1,4 @@
use crate::{Declaration, DeclarationResolver, InputConnector, MigrationError, NewNode, OutputConnector};
use crate::{Compiler, Declaration, DeclarationResolver, InputConnector, MigrationError, NewNode, OutputConnector};
use document_graph_storage::{InputSlot, NetworkId, NodeId, NodeInput, Registry, TimeStamp};
use std::ops::Deref;
@@ -19,6 +19,11 @@ impl Region {
Self(self.0 | other.0)
}
/// Whether a footprint reads the graph around its anchor, which needs a whole state rather than one in the middle of an interaction.
pub const fn reads_network(self) -> bool {
self.overlaps(Self::NETWORK)
}
const fn overlaps(self, other: Self) -> bool {
self.0 & other.0 != 0
}
@@ -69,6 +74,7 @@ pub struct AnchorContext<'a> {
source: Declaration,
target: Declaration,
resolver: &'a dyn DeclarationResolver,
compiler: Option<&'a dyn Compiler>,
}
impl<'a> AnchorContext<'a> {
@@ -82,9 +88,21 @@ impl<'a> AnchorContext<'a> {
source,
target,
resolver,
compiler: None,
})
}
/// Offer the run a `compiler` describing the state this context reads.
pub fn with_compiler(mut self, compiler: Option<&'a dyn Compiler>) -> Self {
self.compiler = compiler;
self
}
/// What a migration's `Option<&dyn Compiler>` parameter receives.
pub fn compiler(&self) -> Option<&'a dyn Compiler> {
self.compiler
}
pub fn source_node(&self) -> &Node<'a> {
&self.anchor
}
@@ -195,6 +213,8 @@ pub struct Edits {
pub added_nodes: Vec<AddedNode>,
pub removed_nodes: Vec<NodeId>,
pub connections: Vec<(OutputConnector, InputConnector)>,
/// The declaration this anchor switches to, when not the migration's target.
pub target: Option<Declaration>,
}
impl Edits {
@@ -205,6 +225,35 @@ impl Edits {
self.added_nodes.extend(other.added_nodes);
self.removed_nodes.extend(other.removed_nodes);
self.connections.extend(other.connections);
self.target = other.target.or(self.target);
}
}
/// Which declaration the anchor becomes, when that isn't the same for every anchor.
#[derive(Default)]
pub struct Target {
chosen: Option<Declaration>,
}
impl Target {
/// Switch this anchor to `declaration`, named with `decl!` in the migration's body, instead of the migration's target.
pub fn set(&mut self, declaration: Declaration) {
self.chosen = Some(declaration);
}
}
impl<'a> View<'a> for Target {
const REGION: Region = Region::ANCHOR;
fn extract(_context: &AnchorContext<'a>) -> Self {
Self::default()
}
fn into_edits(self) -> Result<Edits, MigrationError> {
Ok(Edits {
target: self.chosen,
..Default::default()
})
}
}
+21 -4
View File
@@ -14,8 +14,8 @@ use syn::{Error, FnArg, Ident, ItemFn, ReturnType, Type, parse_macro_input};
/// Turns a function into a node migration, named by its source and target declarations:
/// `#[migration("module::node"@1 => @2)]` for a version step, `#[migration("module::old"@1 => "module::new"@2)]` for a replacement.
///
/// Parameters state what the migration reads and writes: `&Node` and `&Graph` read the source state, and each `&mut` parameter is a
/// view (`Inputs`, `Upstream`, `Downstream`) recording edits to its region. The function may return `()` or `Result<(), MigrationError>`.
/// Parameters state what the migration reads and writes: `&Node` and `&Graph` read the source state, `Option<&dyn Compiler>` asks what only the
/// compiler can tell about it, and each `&mut` parameter is a view (`Inputs`, `Upstream`, `Downstream`, `Target`) recording edits to its region. The function may return `()` or `Result<(), MigrationError>`.
///
/// Generates a unit struct named after the function in Pascal case implementing `NodeMigration`, and registers it.
#[proc_macro_attribute]
@@ -57,6 +57,7 @@ pub fn format_migration(input: TokenStream) -> TokenStream {
enum Argument {
Node,
Graph,
Compiler,
View(Box<Type>),
}
@@ -80,6 +81,7 @@ fn expand_migration(step: Step, function: ItemFn) -> syn::Result<TokenStream2> {
})
.collect();
let reads_graph = arguments.iter().any(|argument| matches!(argument, Argument::Graph));
let asks_compiler = arguments.iter().any(|argument| matches!(argument, Argument::Compiler));
// Call the function with the source state and one extracted view per `&mut` parameter
let view_bindings: Vec<Ident> = (0..views.len()).map(|index| format_ident!("__view_{index}")).collect();
@@ -87,6 +89,7 @@ fn expand_migration(step: Step, function: ItemFn) -> syn::Result<TokenStream2> {
let call_arguments = arguments.iter().map(|argument| match argument {
Argument::Node => quote!(context.source_node()),
Argument::Graph => quote!(&__graph),
Argument::Compiler => quote!(context.compiler()),
Argument::View(_) => {
let binding = &view_bindings[view_index];
view_index += 1;
@@ -118,7 +121,14 @@ fn expand_migration(step: Step, function: ItemFn) -> syn::Result<TokenStream2> {
}
};
let network_region = reads_graph.then(|| quote!(.union(#core::Region::NETWORK)));
let network_region = (reads_graph || asks_compiler).then(|| quote!(.union(#core::Region::NETWORK)));
let asks_compiler = asks_compiler.then(|| {
quote! {
fn asks_compiler(&self) -> bool {
true
}
}
});
let footprint = quote! {
fn footprint(&self) -> #core::Region {
#core::Region::ANCHOR #(.union(<#views as #core::View>::REGION))* #network_region
@@ -166,6 +176,7 @@ fn expand_migration(step: Step, function: ItemFn) -> syn::Result<TokenStream2> {
#target
}
#pins
#asks_compiler
#footprint
#run
}
@@ -182,8 +193,14 @@ fn classify(argument: &FnArg) -> syn::Result<Argument> {
let FnArg::Typed(typed) = argument else {
return Err(Error::new(argument.span(), "migrations are free functions"));
};
if let Type::Path(path) = &*typed.ty
&& path.path.segments.last().is_some_and(|segment| segment.ident == "Option")
{
return Ok(Argument::Compiler);
}
let Type::Reference(reference) = &*typed.ty else {
return Err(Error::new(typed.ty.span(), "migration parameters are `&Node`, `&Graph`, or `&mut` views"));
return Err(Error::new(typed.ty.span(), "migration parameters are `&Node`, `&Graph`, `Option<&dyn Compiler>`, or `&mut` views"));
};
if reference.mutability.is_some() {
+2
View File
@@ -27,6 +27,8 @@ pub enum RunnerError {
Format { from: u32, error: MigrationError },
#[error("migration from {migration} failed on node {anchor:?}: {error}")]
Migration { migration: Declaration, anchor: NodeId, error: MigrationError },
#[error("node {anchor:?} chose {target}, which the migration from {migration} doesn't name")]
UnnamedTarget { migration: Declaration, anchor: NodeId, target: Declaration },
#[error("node {anchor:?} adds two nodes of {declaration} under the key {key:?}")]
DuplicateAddedNode { anchor: NodeId, declaration: Declaration, key: String },
#[error("added node {0:?} already exists")]
+129 -18
View File
@@ -2,8 +2,8 @@
use crate::RunnerError;
use document_graph_storage::delta::compute_deltas;
use document_graph_storage::{Delta, Implementation, Node, NodeId, Registry, RegistryDelta, ResourceHash, ResourceId, Rev, apply_retired_op};
use migration_core::{AnchorContext, Declaration, DeclarationResolver, Edits, InputConnector, InputsEdit, NodeMigration, OutputConnector};
use document_graph_storage::{Delta, Implementation, NetworkId, Node, NodeId, NodeInput, ProtoNode, Registry, RegistryDelta, ResourceHash, ResourceId, Rev, apply_retired_op};
use migration_core::{AnchorContext, Compiler, Declaration, DeclarationResolver, Edits, InputConnector, InputsEdit, MigrationHost, NodeMigration, OutputConnector};
use std::collections::{HashMap, HashSet};
/// A [`DeclarationResolver`] over a fixed set of declarations for tests, whose resource IDs derive from `identifier@version` rather than the encoded declarations documents store.
@@ -49,17 +49,99 @@ impl DeclarationResolver for DeclarationTable {
fn resource(&self, declaration: Declaration) -> ResourceId {
Self::resource_id(declaration)
}
fn proto(&self, resource: ResourceId) -> Option<ProtoNode> {
let declaration = self.declaration(resource)?;
Some(ProtoNode {
identifier: declaration.identifier.to_string(),
version: declaration.version,
attributes: Default::default(),
})
}
}
/// `M`: run `migration` on every anchor in `source` and apply the edits. Every run reads `source`, so no run observes another's edits.
pub(crate) fn apply_migration(migration: &dyn NodeMigration, source: &Registry, resolver: &dyn DeclarationResolver) -> Result<Registry, RunnerError> {
/// A migration asking the compiler runs upstream anchors first instead, in rounds, since the compiler can't describe what's still in the old shape.
pub(crate) fn apply_migration(migration: &dyn NodeMigration, source: &Registry, resolver: &dyn DeclarationResolver, host: Option<&dyn MigrationHost>) -> Result<Registry, RunnerError> {
let anchors = anchors(migration.source(), source, resolver);
if anchors.is_empty() {
return Ok(source.clone());
}
let Some(host) = host.filter(|_| migration.asks_compiler()) else {
return apply_runs(migration, source, &anchors, resolver, None);
};
let mut state = source.clone();
let mut remaining = anchors;
while !remaining.is_empty() {
let ready = upstream_most(&state, &remaining);
let compiler = host.compiler(&state, resolver);
state = apply_runs(migration, &state, &ready, resolver, compiler.as_deref())?;
remaining.retain(|anchor| !ready.contains(anchor));
}
Ok(state)
}
/// The `anchors` with no other of them upstream, or all of them if they form a cycle. O(registry) per anchor.
fn upstream_most(registry: &Registry, anchors: &[NodeId]) -> Vec<NodeId> {
let mut callers: HashMap<NetworkId, Vec<&Node>> = HashMap::new();
for node in registry.node_instances.values() {
if let Implementation::Network(network) = node.implementation() {
callers.entry(*network).or_default().push(node);
}
}
let others: HashSet<NodeId> = anchors.iter().copied().collect();
let reads_another = |anchor: NodeId| {
let mut visited = HashSet::from([anchor]);
let mut pending = vec![anchor];
while let Some(id) = pending.pop() {
let Some(node) = registry.node_instances.get(&id) else { continue };
let mut read = |input: &NodeInput| {
if let NodeInput::Node { id, .. } = input
&& visited.insert(*id)
{
pending.push(*id);
}
};
for slot in node.inputs() {
read(&slot.input);
if let NodeInput::Import { index } = slot.input {
for caller in callers.get(&node.network()).into_iter().flatten() {
if let Some(slot) = caller.inputs().get(index as usize) {
read(&slot.input);
}
}
}
}
if let Implementation::Network(network) = node.implementation()
&& let Some(network) = registry.networks.get(network)
{
for target in network.exports.iter().filter_map(|export| export.target.as_ref()) {
read(target);
}
}
}
visited.iter().any(|id| *id != anchor && others.contains(id))
};
let ready: Vec<NodeId> = anchors.iter().copied().filter(|anchor| !reads_another(*anchor)).collect();
if ready.is_empty() { anchors.to_vec() } else { ready }
}
/// Run `migration` on `anchors` and apply the edits, with every run reading `source`.
fn apply_runs(migration: &dyn NodeMigration, source: &Registry, anchors: &[NodeId], resolver: &dyn DeclarationResolver, compiler: Option<&dyn Compiler>) -> Result<Registry, RunnerError> {
let mut target = source.clone();
let mut runs = Vec::new();
for anchor in anchors(migration.source(), source, resolver) {
for anchor in anchors.iter().copied() {
let Some(context) = AnchorContext::new(source, anchor, migration.source(), migration.target(), resolver) else {
continue;
};
let context = context.with_compiler(compiler);
let edits = migration.run(&context).map_err(|error| RunnerError::Migration {
migration: migration.source(),
anchor,
@@ -91,15 +173,24 @@ pub(crate) fn apply_migration(migration: &dyn NodeMigration, source: &Registry,
}
}
let target_implementation = Implementation::ProtoNode(resolver.resource(migration.target()));
for (anchor, _) in &runs {
if let Some(node) = target.node_instances.get_mut(anchor) {
*node.implementation_mut() = target_implementation.clone();
let mut used_declarations = vec![migration.target()];
for (anchor, edits) in &runs {
let chosen = edits.target.unwrap_or(migration.target());
if chosen != migration.target() && !migration.pins().contains(&chosen) {
return Err(RunnerError::UnnamedTarget {
migration: migration.source(),
anchor: *anchor,
target: chosen,
});
}
}
let added_declarations = runs.iter().flat_map(|(_, edits)| edits.added_nodes.iter().map(|added| added.node.declaration));
for declaration in std::iter::once(migration.target()).chain(added_declarations) {
if let Some(node) = target.node_instances.get_mut(anchor) {
*node.implementation_mut() = Implementation::ProtoNode(resolver.resource(chosen));
}
used_declarations.push(chosen);
used_declarations.extend(edits.added_nodes.iter().map(|added| added.node.declaration));
}
for declaration in used_declarations {
if let Some(entry) = resolver.resource_entry(declaration) {
target.resources.entry(resolver.resource(declaration)).or_insert(entry);
}
@@ -197,14 +288,34 @@ struct Branch {
/// Undoing and then editing leaves an abandoned branch, which rewrites like any other since each delta only depends on its ancestors.
/// Fails on a delta that merges branches, or whose parent isn't in `history`.
///
/// A migration reading the graph or asking the compiler needs whole states, so it only runs at the boundaries undo can land on, the end of an interaction,
/// and rewrites everything since the last one as a single chain. Each delta inside maps to the boundary before it, and `kept` names further states to keep.
///
/// Each delta costs one full evaluation of `M` and one full diff, so this is O(history × registry), until the RFC's footprint-scoped
/// evaluation lands. A state is only copied where history branches.
pub(crate) fn rewrite_history(migration: &dyn NodeMigration, history: &[Delta], resolver: &dyn DeclarationResolver) -> Result<RewrittenHistory, RunnerError> {
pub(crate) fn rewrite_history(
migration: &dyn NodeMigration,
history: &[Delta],
resolver: &dyn DeclarationResolver,
host: Option<&dyn MigrationHost>,
kept: &HashSet<Rev>,
) -> Result<RewrittenHistory, RunnerError> {
let mut children: HashMap<Option<Rev>, usize> = HashMap::new();
let mut child_authors: HashMap<Rev, HashSet<_>> = HashMap::new();
for delta in history {
*children.entry(delta.parent).or_default() += 1;
if let Some(parent) = delta.parent {
child_authors.entry(parent).or_default().insert(delta.author);
}
}
let child_counts = children.clone();
let whole_states_only = migration.footprint().reads_network();
let is_boundary = |delta: &Delta| {
let continues_alone = child_counts.get(&Some(delta.id)) == Some(&1) && child_authors.get(&delta.id).is_some_and(|authors| authors.contains(&delta.author));
delta.is_interaction_end() || !continues_alone || kept.contains(&delta.id)
};
let mut branches = HashMap::from([(
None,
Branch {
@@ -234,12 +345,12 @@ pub(crate) fn rewrite_history(migration: &dyn NodeMigration, history: &[Delta],
apply_retired_op(&mut branch.original, delta.kind.clone(), delta.timestamp)?;
let chain = if passes_through(&delta.kind) {
vec![delta.kind.clone()]
} else {
let migrated = apply_migration(migration, &branch.original, resolver)?;
compute_deltas(&branch.rewritten, &migrated)
};
let passes = passes_through(&delta.kind);
let mut chain = if passes { vec![delta.kind.clone()] } else { Vec::new() };
if if whole_states_only { is_boundary(delta) } else { !passes } {
let migrated = apply_migration(migration, &branch.original, resolver, host)?;
chain.extend(compute_deltas(&branch.rewritten, &migrated));
}
check_single_writes(&chain)?;
// Every op of the chain shares the original's timestamp, which orders it after everything the original saw
+19 -8
View File
@@ -3,12 +3,12 @@
use crate::node::{apply_migration, rewrite_history};
use crate::{RewrittenHistory, RunnerError};
use document_graph_storage::{Delta, Implementation, Node, Registry, RegistryDelta, Rev};
use migration_core::{Declaration, DeclarationResolver, NodeMigration};
use std::collections::{BTreeSet, HashMap};
use migration_core::{Declaration, DeclarationResolver, MigrationHost, NodeMigration};
use std::collections::{BTreeSet, HashMap, HashSet};
/// Order `migrations` so each runs after the one producing its source and before the one consuming its target, and pinned
/// declarations exist in exactly the version the body names. Unrelated migrations order by source declaration, so the result
/// doesn't depend on registration order. Kahn's algorithm, O(n²) in the number of migrations to find edges.
/// doesn't depend on registration order, except that those asking the compiler go last, so what they ask about is in its current shape. Kahn's algorithm, O(n²) in the number of migrations to find edges.
pub fn order_migrations(migrations: &[&'static dyn NodeMigration]) -> Result<Vec<&'static dyn NodeMigration>, RunnerError> {
let mut migrations = migrations.to_vec();
migrations.sort_by_key(|migration| (migration.source(), migration.target()));
@@ -25,6 +25,8 @@ pub fn order_migrations(migrations: &[&'static dyn NodeMigration]) -> Result<Vec
});
}
migrations.sort_by_key(|migration| (migration.asks_compiler(), migration.source(), migration.target()));
let consumer = |declaration: Declaration| migrations.iter().position(|migration| migration.source() == declaration);
// `successors[a]` holds every migration that must run after `a`
@@ -73,8 +75,16 @@ pub fn order_migrations(migrations: &[&'static dyn NodeMigration]) -> Result<Vec
}
/// Rewrite `history` through every migration whose source declaration it references, in dependency order. A migration is pending
/// even when no live node uses its source, since a removed node keeps its old shape in history and undo can bring it back.
pub fn migrate_history(migrations: &[&'static dyn NodeMigration], history: Vec<Delta>, resolver: &dyn DeclarationResolver) -> Result<RewrittenHistory, RunnerError> {
/// even when no live node uses its source, since a removed node keeps its old shape in history and undo can bring it back. `kept` names the
/// states a cursor rests on, which even a migration only running at interaction boundaries has to keep.
pub fn migrate_history(
migrations: &[&'static dyn NodeMigration],
history: Vec<Delta>,
resolver: &dyn DeclarationResolver,
host: Option<&dyn MigrationHost>,
kept: impl IntoIterator<Item = Rev>,
) -> Result<RewrittenHistory, RunnerError> {
let mut kept: HashSet<Rev> = kept.into_iter().collect();
let mut revs: HashMap<Rev, Option<Rev>> = history.iter().map(|delta| (delta.id, Some(delta.id))).collect();
let mut deltas = history;
@@ -83,7 +93,8 @@ pub fn migrate_history(migrations: &[&'static dyn NodeMigration], history: Vec<D
continue;
}
let step = rewrite_history(migration, &deltas, resolver)?;
let step = rewrite_history(migration, &deltas, resolver, host, &kept)?;
kept = kept.iter().filter_map(|rev| step.revs.get(rev).copied().flatten()).collect();
for rev in revs.values_mut() {
*rev = rev.and_then(|rev| step.revs.get(&rev).copied().flatten());
}
@@ -94,10 +105,10 @@ pub fn migrate_history(migrations: &[&'static dyn NodeMigration], history: Vec<D
}
/// `M` of every migration on one state, for a document whose history can't be rewritten. Undo can't cross the result.
pub fn migrate_registry(migrations: &[&'static dyn NodeMigration], registry: &Registry, resolver: &dyn DeclarationResolver) -> Result<Registry, RunnerError> {
pub fn migrate_registry(migrations: &[&'static dyn NodeMigration], registry: &Registry, resolver: &dyn DeclarationResolver, host: Option<&dyn MigrationHost>) -> Result<Registry, RunnerError> {
let mut migrated = registry.clone();
for migration in order_migrations(migrations)? {
migrated = apply_migration(migration, &migrated, resolver)?;
migrated = apply_migration(migration, &migrated, resolver, host)?;
}
Ok(migrated)
}
+22 -7
View File
@@ -4,7 +4,8 @@
use crate::node::{apply_migration, rewrite_history};
use crate::{DeclarationTable, RunnerError, references, registry_at};
use document_graph_storage::{Delta, ExportSlot, Implementation, Network, Node, NodeId, NodeInput, PeerId, ROOT_NETWORK, Registry, RegistryDelta, Session, UserId, apply_retired_op};
use migration_core::{Declaration, DeclarationResolver, NodeMigration, decl, literal, registered_migrations};
use migration_core::{Declaration, DeclarationResolver, MigrationHost, NodeMigration, decl, literal, registered_migrations};
use std::collections::HashSet;
/// A root network built node by node, for running one migration on.
pub struct Fixture {
@@ -47,7 +48,11 @@ impl Fixture {
}
pub fn migrate(&self, migration: &dyn NodeMigration) -> Result<Registry, RunnerError> {
apply_migration(migration, &self.registry, &self.table)
self.migrate_with(migration, None)
}
pub fn migrate_with(&self, migration: &dyn NodeMigration, host: Option<&dyn MigrationHost>) -> Result<Registry, RunnerError> {
apply_migration(migration, &self.registry, &self.table, host)
}
pub fn declaration_of(&self, registry: &Registry, node: NodeId) -> Option<Declaration> {
@@ -262,15 +267,20 @@ pub fn replay(deltas: &[Delta]) -> Registry {
/// `replay(rewrite(H)) == M(replay(H))` at every delta of generated histories, abandoned branches included, which also proves the rewrite
/// leaves none of the old shape behind.
pub fn check_commutation(migration: &dyn NodeMigration, contract: &SourceContract) {
check_commutation_with(migration, contract, None);
}
/// [`check_commutation`] for a migration asking `host`'s compiler.
pub fn check_commutation_with(migration: &dyn NodeMigration, contract: &SourceContract, host: Option<&dyn MigrationHost>) {
for seed in 1..50 {
let (session, table) = generate(migration, contract, seed, 40);
let history: Vec<Delta> = session.history().cloned().collect();
let rewritten = rewrite_history(migration, &history, &table).unwrap_or_else(|error| panic!("seed {seed}: rewrite failed: {error}"));
let rewritten = rewrite_history(migration, &history, &table, host, &HashSet::new()).unwrap_or_else(|error| panic!("seed {seed}: rewrite failed: {error}"));
for delta in &history {
let original = registry_at(&history, Some(delta.id)).unwrap_or_else(|error| panic!("seed {seed}: {error}"));
let expected = apply_migration(migration, &original, &table).unwrap_or_else(|error| panic!("seed {seed}: M failed: {error}"));
let expected = apply_migration(migration, &original, &table, host).unwrap_or_else(|error| panic!("seed {seed}: M failed: {error}"));
let replayed = registry_at(&rewritten.deltas, rewritten.revs[&delta.id]).unwrap_or_else(|error| panic!("seed {seed}: {error}"));
assert!(
replayed.value_equal(&expected),
@@ -292,10 +302,15 @@ pub fn check_commutation(migration: &dyn NodeMigration, contract: &SourceContrac
/// Undo walks the rewritten deltas' reverse priors, so undoing in rewritten history must land on `M` of the undone original.
pub fn check_undo(migration: &dyn NodeMigration, contract: &SourceContract) {
check_undo_with(migration, contract, None);
}
/// [`check_undo`] for a migration asking `host`'s compiler.
pub fn check_undo_with(migration: &dyn NodeMigration, contract: &SourceContract, host: Option<&dyn MigrationHost>) {
for seed in 1..20 {
let (session, table) = generate(migration, contract, seed, 30);
let history: Vec<Delta> = session.history().cloned().collect();
let rewritten = rewrite_history(migration, &history, &table).unwrap_or_else(|error| panic!("seed {seed}: rewrite failed: {error}"));
let rewritten = rewrite_history(migration, &history, &table, host, &HashSet::new()).unwrap_or_else(|error| panic!("seed {seed}: rewrite failed: {error}"));
let head = session.head_rev();
let migrated_head = head.and_then(|head| rewritten.revs[&head]);
@@ -305,13 +320,13 @@ pub fn check_undo(migration: &dyn NodeMigration, contract: &SourceContract) {
let mut original = Session::load(PeerId(1), UserId(1), original_registry, history, head, Vec::new(), 0);
let mut migrated = Session::load(PeerId(1), UserId(1), migrated_registry, rewritten.deltas, migrated_head, Vec::new(), 0);
let mut previous = apply_migration(migration, original.registry(), &table).unwrap_or_else(|error| panic!("seed {seed}: M failed: {error}"));
let mut previous = apply_migration(migration, original.registry(), &table, host).unwrap_or_else(|error| panic!("seed {seed}: M failed: {error}"));
for undo in 0..5 {
// An interaction that only touched what `M` drops left no delta in the rewrite, so undo there passes over it
let mut expected = previous.clone();
while expected.value_equal(&previous) && original.can_undo() {
original.undo().expect("can_undo said so");
expected = apply_migration(migration, original.registry(), &table).unwrap_or_else(|error| panic!("seed {seed}, undo {undo}: M failed: {error}"));
expected = apply_migration(migration, original.registry(), &table, host).unwrap_or_else(|error| panic!("seed {seed}, undo {undo}: M failed: {error}"));
}
if expected.value_equal(&previous) {
break;
@@ -0,0 +1,269 @@
//! Migrations choosing a target per anchor, and asking the compiler, which only run on whole states.
use document_graph_storage::{Implementation, Node, NodeId, NodeInput, PeerId, ROOT_NETWORK, Registry, RegistryDelta, Session, UserId};
use migration_core::{Compiler, DeclarationResolver, Graph, MigrationError, MigrationHost, NodeMigration, Target, ValueType, decl, literal, literal_of, migration};
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_commutation_with, check_undo, check_undo_with};
use migration_runner::{DeclarationTable, RunnerError, migrate_history, order_migrations};
use std::any::type_name;
use std::sync::atomic::{AtomicUsize, Ordering};
/// Chooses by a literal toggle, at the version each target already has, rather than stepping them all.
#[migration("choice::toggle"@1 => "choice::on"@2)]
pub fn choice_by_toggle(node: &migration_core::Node, target: &mut Target) {
if literal_of::<bool>(&node.inputs()[0].input) == Some(false) {
target.set(decl!("choice::off"@5));
}
}
/// Names a target only at runtime, which the runner can't order against anything.
#[migration("choice::unnamed"@1 => "choice::named"@2)]
pub fn choice_unnamed(target: &mut Target) {
target.set(migration_core::Declaration::new("choice::elsewhere", 1));
}
/// A fake value type, whose element stands for how many nodes are alive in the state the compiler describes.
struct Crowded(bool);
struct Many;
struct Few;
impl ValueType for Crowded {
fn element_name(&self) -> Option<&str> {
Some(if self.0 { type_name::<Many>() } else { type_name::<Few>() })
}
}
struct FakeCompiler(usize);
impl Compiler for FakeCompiler {
fn input_type(&self, _node: &migration_core::Node, _slot: usize) -> Option<Box<dyn ValueType>> {
Some(Box::new(Crowded(self.0 > 3)))
}
}
/// Chooses by what the compiler says, and only sees whole states.
#[migration("compiler::anchor"@1 => "compiler::few"@2)]
pub fn by_compiler(node: &migration_core::Node, compiler: Option<&dyn Compiler>, target: &mut Target) {
if compiler.and_then(|compiler| compiler.input_type(node, 0)).is_some_and(|value_type| value_type.element_is::<Many>()) {
target.set(decl!("compiler::many"@1));
}
}
/// Asks the compiler, and sorts before `order::static_late` by source, so only the runner's rule can put it after.
#[migration("order::asking"@1 => "order::asked"@2)]
pub fn order_asking(_compiler: Option<&dyn Compiler>) {}
#[migration("order::static_late"@1 => @2)]
pub fn order_static_late() {}
/// Asks the compiler, but `order::inspector` inspects what it produces, so it has to run first after all.
#[migration("order::pinned_asking"@1 => "order::produced"@2)]
pub fn order_pinned_asking(_compiler: Option<&dyn Compiler>) {}
#[migration("order::inspector"@1 => @2)]
pub fn order_inspector() {
let _ = decl!("order::produced"@2);
}
/// Reads the graph, which doesn't ask the host but still only sees whole states.
#[migration("compiler::graph_reader"@1 => @2)]
pub fn graph_reader(_graph: &Graph) -> Result<(), MigrationError> {
GRAPH_READS.fetch_add(1, Ordering::Relaxed);
Ok(())
}
static GRAPH_READS: AtomicUsize = AtomicUsize::new(0);
#[derive(Default)]
pub struct AnswerHost {
asked: AtomicUsize,
}
impl MigrationHost for AnswerHost {
fn compiler(&self, state: &Registry, _resolver: &dyn DeclarationResolver) -> Option<Box<dyn Compiler + '_>> {
self.asked.fetch_add(1, Ordering::Relaxed);
Some(Box::new(FakeCompiler(state.node_instances.len())))
}
}
fn wire(id: NodeId) -> NodeInput {
NodeInput::Node { id, index: 0 }
}
/// A history of one interaction per entry in `interactions`, each adding that many nodes implementing the `source` of `migration`.
fn history_of(migration: &dyn NodeMigration, table: &mut DeclarationTable, interactions: &[usize]) -> Session {
table.register_migration(migration);
let resource = table.register(migration.source());
let mut session = Session::with_identity(PeerId(1), UserId(1));
session
.stage_computed_ops(vec![RegistryDelta::AddNetwork {
id: ROOT_NETWORK,
network: Default::default(),
}])
.unwrap();
session.retire_all().unwrap();
for nodes in interactions {
let mut last = None;
for _ in 0..*nodes {
let id = session.next_node_id();
let node = Node::new(ROOT_NETWORK, Implementation::ProtoNode(resource), 0);
session.stage_computed_ops(vec![RegistryDelta::AddNode { id, node }]).unwrap();
last = session.retire_all().unwrap().last().copied();
}
session.mark_interaction_end(last.expect("an interaction adds nodes"));
}
session
}
#[test]
fn each_anchor_chooses_its_target() {
let mut fixture = Fixture::new(&ChoiceByToggle);
let on = fixture.add(ChoiceByToggle.source(), vec![literal(true)]);
let off = fixture.add(ChoiceByToggle.source(), vec![literal(false)]);
let migrated = fixture.migrate(&ChoiceByToggle).unwrap();
assert_eq!(fixture.declaration_of(&migrated, on), Some(decl!("choice::on"@2)));
assert_eq!(fixture.declaration_of(&migrated, off), Some(decl!("choice::off"@5)));
}
#[test]
fn a_choice_changing_across_history_commutes() {
let contract = SourceContract::new(1, |random, _| literal(random.below(2) == 0));
check_commutation(&ChoiceByToggle, &contract);
check_undo(&ChoiceByToggle, &contract);
}
#[test]
fn a_target_the_body_does_not_name_fails() {
let mut fixture = Fixture::new(&ChoiceUnnamed);
fixture.add(ChoiceUnnamed.source(), vec![]);
assert!(matches!(fixture.migrate(&ChoiceUnnamed), Err(RunnerError::UnnamedTarget { .. })));
}
#[test]
fn the_compiler_decides_per_state() {
let host = AnswerHost::default();
let mut few = Fixture::new(&ByCompiler);
let anchor = few.add(ByCompiler.source(), vec![]);
let migrated = few.migrate_with(&ByCompiler, Some(&host)).unwrap();
assert_eq!(few.declaration_of(&migrated, anchor), Some(decl!("compiler::few"@2)));
let mut many = Fixture::new(&ByCompiler);
let anchor = many.add(ByCompiler.source(), vec![]);
for _ in 0..3 {
many.add(decl!("compiler::other"@1), vec![]);
}
let migrated = many.migrate_with(&ByCompiler, Some(&host)).unwrap();
assert_eq!(many.declaration_of(&migrated, anchor), Some(decl!("compiler::many"@1)));
}
#[test]
fn without_a_host_it_takes_the_fallback() {
let mut fixture = Fixture::new(&ByCompiler);
let anchor = fixture.add(ByCompiler.source(), vec![]);
for _ in 0..3 {
fixture.add(decl!("compiler::other"@1), vec![]);
}
let migrated = fixture.migrate(&ByCompiler).unwrap();
assert_eq!(fixture.declaration_of(&migrated, anchor), Some(decl!("compiler::few"@2)));
}
#[test]
fn asking_the_compiler_goes_last_unless_a_dependency_says_otherwise() {
let position = |ordered: &[&'static dyn NodeMigration], source: migration_core::Declaration| ordered.iter().position(|migration| migration.source() == source).unwrap();
let ordered = order_migrations(&[&OrderAsking, &OrderStaticLate]).unwrap();
assert!(position(&ordered, OrderStaticLate.source()) < position(&ordered, OrderAsking.source()));
let ordered = order_migrations(&[&OrderPinnedAsking, &OrderInspector]).unwrap();
assert!(position(&ordered, OrderPinnedAsking.source()) < position(&ordered, OrderInspector.source()));
}
#[test]
fn upstream_anchors_run_before_those_reading_them() {
let host = AnswerHost::default();
let mut fixture = Fixture::new(&ByCompiler);
let first = fixture.add(ByCompiler.source(), vec![]);
let second = fixture.add(ByCompiler.source(), vec![wire(first)]);
fixture.add(ByCompiler.source(), vec![wire(second)]);
fixture.migrate_with(&ByCompiler, Some(&host)).unwrap();
assert_eq!(host.asked.load(Ordering::Relaxed), 3, "one round per level of nesting");
}
#[test]
fn unrelated_anchors_share_one_round() {
let host = AnswerHost::default();
let mut fixture = Fixture::new(&ByCompiler);
for _ in 0..3 {
fixture.add(ByCompiler.source(), vec![]);
}
fixture.migrate_with(&ByCompiler, Some(&host)).unwrap();
assert_eq!(host.asked.load(Ordering::Relaxed), 1);
}
#[test]
fn the_compiler_is_only_asked_at_interaction_boundaries() {
let mut table = DeclarationTable::default();
let session = history_of(&ByCompiler, &mut table, &[4, 3]);
let history: Vec<_> = session.history().cloned().collect();
let host = AnswerHost::default();
let rewritten = migrate_history(&[&ByCompiler], history.clone(), &table, Some(&host), session.head_rev()).unwrap();
// The root network's interaction has no anchors yet, so it never asks, and each of the other two asks once for its one round of unrelated anchors
assert_eq!(host.asked.load(Ordering::Relaxed), 2);
// A delta inside an interaction has no state of its own, and an interaction end does
let ends: Vec<_> = history.iter().filter(|delta| delta.is_interaction_end()).collect();
assert_eq!(ends.len(), 2);
for end in ends {
assert!(rewritten.revs[&end.id].is_some());
let rev = rewritten.revs[&end.id].unwrap();
assert!(rewritten.deltas.iter().any(|delta| delta.id == rev && delta.is_interaction_end()));
}
}
#[test]
fn a_cursor_inside_an_interaction_keeps_its_state() {
let mut table = DeclarationTable::default();
let session = history_of(&ByCompiler, &mut table, &[4]);
let history: Vec<_> = session.history().cloned().collect();
let inside = history[history.len() - 2].id;
let host = AnswerHost::default();
let rewritten = migrate_history(&[&ByCompiler], history, &table, Some(&host), [inside]).unwrap();
assert_eq!(host.asked.load(Ordering::Relaxed), 2, "the cursor and the interaction's end");
assert!(rewritten.revs[&inside].is_some());
}
#[test]
fn reading_the_graph_also_only_sees_whole_states() {
let mut table = DeclarationTable::default();
let session = history_of(&GraphReader, &mut table, &[5]);
let history: Vec<_> = session.history().cloned().collect();
let before = GRAPH_READS.load(Ordering::Relaxed);
migrate_history(&[&GraphReader], history, &table, None, session.head_rev()).unwrap();
// All five anchors exist at the one boundary, and the anchorless root network's boundary reads nothing
assert_eq!(GRAPH_READS.load(Ordering::Relaxed) - before, 5);
}
#[test]
fn asking_the_compiler_commutes() {
let host = AnswerHost::default();
let contract = SourceContract::new(1, |_, _| literal(0.));
check_commutation_with(&ByCompiler, &contract, Some(&host));
check_undo_with(&ByCompiler, &contract, Some(&host));
}
@@ -1,3 +1,4 @@
mod compiler;
mod examples;
mod registration;
mod rewrite;
@@ -1,5 +1,6 @@
//! What `#[migration]` and `rename!` generate and register, and how the runner orders and chains the registry.
use crate::compiler;
use crate::examples::{ExtractXyToSplit, OpacityToggles, ROTATION, Tagged, TransformDegrees};
use document_graph_storage::{Delta, Implementation, Network, Node, NodeId, NodeInput, PeerId, ROOT_NETWORK, RegistryDelta, Session, UserId};
use migration_core::{AnchorContext, Declaration, DeclarationResolver, Edits, MigrationError, NodeMigration, Region, decl, literal, registered_migrations};
@@ -13,8 +14,16 @@ fn every_migration_registers_once() {
let mut expected = vec![
decl!("blending_nodes::opacity"@1),
decl!("compiler::anchor"@1),
decl!("compiler::graph_reader"@1),
decl!("choice::toggle"@1),
decl!("choice::unnamed"@1),
decl!("graphene_core::ops::AddNode"@1),
decl!("math_nodes::multiply"@1),
decl!("order::asking"@1),
decl!("order::inspector"@1),
decl!("order::pinned_asking"@1),
decl!("order::static_late"@1),
decl!("transform_nodes::transform"@1),
decl!("vector_nodes::angle_between"@1),
decl!("vector_nodes::extract_xy"@1),
@@ -198,7 +207,7 @@ fn migrate_history_chains_every_pending_migration() {
});
let history: Vec<Delta> = session.history().cloned().collect();
let migrated = migrate_history(&registered_migrations(), history.clone(), &table).unwrap();
let migrated = migrate_history(&registered_migrations(), history.clone(), &table, Some(&compiler::AnswerHost::default()), None).unwrap();
let registry = replay(&migrated.deltas);
let declaration_of = |id: NodeId| match registry.node_instances[&id].implementation() {
+3 -3
View File
@@ -1,8 +1,8 @@
//! Compares every node's API against a baseline commit, to find changes that need a version bump or a migration.
use crate::lineage::{MigrationStep, find_migrations};
use crate::lineage::{MigrationStep, find_all_migrations};
use crate::nodes::{NodeSource, find_nodes};
use crate::scaffold::{MIGRATIONS, NODE_CRATES};
use crate::scaffold::{MIGRATION_CRATES, NODE_CRATES};
use std::collections::HashMap;
use std::path::Path;
use std::process::{Command, Stdio};
@@ -10,7 +10,7 @@ use std::process::{Command, Stdio};
/// Fail if the nodes at the git ref `baseline` differ from the working tree's in a way documents would notice.
pub(crate) fn check_against(workspace: &Path, baseline: &str) -> Result<(), String> {
let current = find_nodes(&workspace.join(NODE_CRATES))?;
let migrations = find_migrations(&workspace.join(MIGRATIONS))?;
let migrations = find_all_migrations(workspace, &MIGRATION_CRATES)?;
let directory = std::env::temp_dir().join(format!("migration-api-baseline-{}", std::process::id()));
let baseline_nodes = extract_baseline(workspace, baseline, &directory).and_then(|()| find_nodes(&directory.join(NODE_CRATES)));
@@ -39,6 +39,18 @@ pub(crate) fn find_migrations(directory: &Path) -> Result<Vec<MigrationStep>, St
Ok(steps)
}
/// Every migration step of the crates at `directories` under `workspace`, leaving out those that don't exist.
pub(crate) fn find_all_migrations(workspace: &Path, directories: &[&str]) -> Result<Vec<MigrationStep>, String> {
let mut steps = Vec::new();
for directory in directories {
let directory = workspace.join(directory);
if directory.exists() {
steps.extend(find_migrations(&directory)?);
}
}
Ok(steps)
}
/// `file` is a module whose `mod child;` declarations live in `children`.
fn read_module(file: &Path, children: &Path, steps: &mut Vec<MigrationStep>) -> Result<(), String> {
let source = std::fs::read_to_string(file).map_err(|error| format!("{}: {error}", file.display()))?;
+1 -1
View File
@@ -119,7 +119,7 @@ fn check(workspace: &Path) -> Result<(), String> {
.into_iter()
.map(|node| (node.identifier, node.version))
.collect();
let migrations = lineage::find_migrations(&workspace.join(scaffold::MIGRATIONS))?;
let migrations = lineage::find_all_migrations(workspace, &scaffold::MIGRATION_CRATES)?;
let problems = lineage::lineage_problems(&nodes, &migrations);
if !problems.is_empty() {
return Err(problems.join("\n"));
@@ -7,6 +7,8 @@ use std::path::{Path, PathBuf};
pub(crate) const NODE_CRATES: &str = "node-graph";
pub(crate) const MIGRATIONS: &str = "document/migrations/nodes/src";
/// Every crate holding migrations, including those asking for a capability, which `new` doesn't scaffold.
pub(crate) const MIGRATION_CRATES: [&str; 2] = [MIGRATIONS, "document/migrations/compiled/src"];
/// `new` scaffolds every step missing between a node's newest migration and its version, `new <identifier>` does so for one node,
/// `new <old>@<version> <identifier>` replaces a node by another, and `rename <old>@<version> <identifier>` registers a finished rename.
+1
View File
@@ -24,6 +24,7 @@ graphite-proc-macros = { workspace = true }
graph-craft = { workspace = true }
document-format = { workspace = true, features = ["migrations"] }
migration-formats = { workspace = true }
migration-compiled = { workspace = true }
migration-nodes = { workspace = true }
document-graph-storage = { workspace = true, features = ["conversion"] }
document-container = { workspace = true }
+1
View File
@@ -25,5 +25,6 @@ pub mod utility_types;
pub use document_container::store as document_store;
// Referenced so the linker keeps their self-registering migrations, which run as documents open
use migration_compiled as _;
use migration_formats as _;
use migration_nodes as _;
@@ -1234,33 +1234,50 @@ fn static_input_inspector() -> InputInspector {
}),
);
map.insert(
"assign_colors_gradient".to_string(),
"vary_fill_colors_gradient".to_string(),
Box::new(|node_id, index, context| {
let gradient_row = node_inspector::color_widget(ParameterWidgetsInfo::at_index(node_id, index, true, context), ColorInput::default().allow_none(false));
Ok(vec![gradient_row])
}),
);
map.insert(
"assign_colors_seed".to_string(),
"vary_fill_colors_seed".to_string(),
Box::new(|node_id, index, context| node_inspector::vary_seed_widget(node_id, index, context, vector::vary_fill_colors::RandomizeInput)),
);
map.insert(
"vary_fill_colors_repeat_every".to_string(),
Box::new(|node_id, index, context| node_inspector::vary_repeat_every_widget(node_id, index, context, vector::vary_fill_colors::RandomizeInput)),
);
map.insert(
"vary_stroke_colors_gradient".to_string(),
Box::new(|node_id, index, context| {
let randomize_enabled = node_inspector::query_assign_colors_randomize(node_id, context)?;
let seed_row = node_inspector::number_widget(
ParameterWidgetsInfo::at_index(node_id, index, true, context),
NumberInput::default().min(0.).int().disabled(!randomize_enabled),
);
Ok(vec![seed_row.into()])
let gradient_row = node_inspector::color_widget(ParameterWidgetsInfo::at_index(node_id, index, true, context), ColorInput::default().allow_none(false));
Ok(vec![gradient_row])
}),
);
map.insert(
"assign_colors_repeat_every".to_string(),
Box::new(|node_id, index, context| {
let randomize_enabled = node_inspector::query_assign_colors_randomize(node_id, context)?;
let repeat_every_row = node_inspector::number_widget(
ParameterWidgetsInfo::at_index(node_id, index, true, context),
NumberInput::default().min(0.).int().disabled(randomize_enabled),
);
Ok(vec![repeat_every_row.into()])
}),
"vary_stroke_colors_seed".to_string(),
Box::new(|node_id, index, context| node_inspector::vary_seed_widget(node_id, index, context, vector::vary_stroke_colors::RandomizeInput)),
);
map.insert(
"vary_stroke_colors_repeat_every".to_string(),
Box::new(|node_id, index, context| node_inspector::vary_repeat_every_widget(node_id, index, context, vector::vary_stroke_colors::RandomizeInput)),
);
map.insert(
"vary_rotations_seed".to_string(),
Box::new(|node_id, index, context| node_inspector::vary_seed_widget(node_id, index, context, transform_nodes::vary_rotations::RandomizeInput)),
);
map.insert(
"vary_rotations_repeat_every".to_string(),
Box::new(|node_id, index, context| node_inspector::vary_repeat_every_widget(node_id, index, context, transform_nodes::vary_rotations::RandomizeInput)),
);
map.insert(
"vary_scales_seed".to_string(),
Box::new(|node_id, index, context| node_inspector::vary_seed_widget(node_id, index, context, transform_nodes::vary_scales::RandomizeInput)),
);
map.insert(
"vary_scales_repeat_every".to_string(),
Box::new(|node_id, index, context| node_inspector::vary_repeat_every_widget(node_id, index, context, transform_nodes::vary_scales::RandomizeInput)),
);
map.insert(
"transform_rotation".to_string(),
@@ -1637,17 +1637,35 @@ pub fn query_noise_pattern_state(node_id: NodeId, context: &NodeInspectorContext
))
}
pub fn query_assign_colors_randomize(node_id: NodeId, context: &NodeInspectorContext) -> Result<bool, String> {
use graphene_std::vector::assign_colors::*;
fn query_vary_randomize(node_id: NodeId, context: &NodeInspectorContext, randomize: impl NodeParameter) -> Result<bool, String> {
let document_node = get_document_node(node_id, context)?;
// This is safe since the node is a proto node and the implementation cannot be changed.
Ok(match document_node.input(RandomizeInput).and_then(|input| input.as_value()) {
Ok(match document_node.input(randomize).and_then(|input| input.as_value()) {
Some(TaggedValue::Bool(randomize_enabled)) => *randomize_enabled,
_ => false,
})
}
/// The seed of a vary node (like Vary Fill Colors), which applies only while its given Randomize parameter is enabled.
pub fn vary_seed_widget(node_id: NodeId, index: usize, context: &mut NodeInspectorContext, randomize: impl NodeParameter) -> Result<Vec<LayoutGroup>, String> {
let randomize_enabled = query_vary_randomize(node_id, context, randomize)?;
let seed_row = number_widget(
ParameterWidgetsInfo::at_index(node_id, index, true, context),
NumberInput::default().min(0.).int().disabled(!randomize_enabled),
);
Ok(vec![seed_row.into()])
}
/// The repeat count of a vary node (like Vary Fill Colors), which applies only while its given Randomize parameter is disabled.
pub fn vary_repeat_every_widget(node_id: NodeId, index: usize, context: &mut NodeInspectorContext, randomize: impl NodeParameter) -> Result<Vec<LayoutGroup>, String> {
let randomize_enabled = query_vary_randomize(node_id, context, randomize)?;
let repeat_every_row = number_widget(
ParameterWidgetsInfo::at_index(node_id, index, true, context),
NumberInput::default().min(0.).int().disabled(randomize_enabled),
);
Ok(vec![repeat_every_row.into()])
}
/// 2-stop black-to-white gradient track for sliders that map a value to a grayscale axis.
fn bw_track() -> Gradient {
Gradient::from(vec![Color::BLACK, Color::WHITE])
@@ -4,16 +4,21 @@
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, NodeTemplateImplementation, OutputConnector};
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, NodeTemplate, NodeTemplateImplementation, OutputConnector};
use crate::messages::prelude::DocumentMessageHandler;
use crate::node_graph_executor::redirect_export_chain;
use glam::{DVec2, IVec2};
use graph_craft::application_io::PlatformEditorApi;
use graph_craft::application_io::resource::{DataSource, Resource, ResourceHash, ResourceId};
use graph_craft::document::DocumentNode;
use graph_craft::document::{DocumentNodeImplementation, NodeInput, value::TaggedValue};
use graph_craft::document::{DocumentNodeImplementation, NodeInput, NodeNetwork, value::TaggedValue};
use graph_craft::graphene_compiler::Compiler;
use graph_craft::proto::TypingContext;
use graph_craft::{Type, concrete, item, list};
use graphene_std::Color;
use graphene_std::ParameterRef;
use graphene_std::ProtoNodeIdentifier;
use graphene_std::RuntimeHandle;
use graphene_std::extract_xy::XY;
use graphene_std::raster::RedGreenBlueAlpha;
use graphene_std::text::{TextAlign, TypesettingConfig};
@@ -21,9 +26,11 @@ use graphene_std::transform::ScaleType;
use graphene_std::uuid::NodeId;
use graphene_std::vector::graphic_types;
use graphene_std::vector::style::{GradientRamp, GradientSpread, PaintOrder, StrokeAlign};
use interpreted_executor::node_registry::NODE_REGISTRY;
use std::collections::{HashMap, HashSet};
use std::f64::consts::PI;
use std::ops::Range;
use std::sync::Arc;
const TEXT_REPLACEMENTS: &[(&str, &str)] = &[
("graphene_core::vector::vector_nodes::SamplePointsNode", "graphene_core::vector::SamplePolylineNode"),
@@ -786,10 +793,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
node: graphene_std::vector::area::IDENTIFIER,
aliases: &["graphene_core::vector::AreaNode"],
},
NodeReplacement {
node: graphene_std::vector::assign_colors::IDENTIFIER,
aliases: &["graphene_core::vector::AssignColorsNode"],
},
NodeReplacement {
node: graphene_std::vector::smooth_anchors::IDENTIFIER,
aliases: &[
@@ -919,10 +922,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
node: graphene_std::repeat::repeat_on_points::IDENTIFIER,
aliases: &["graphene_core::vector::InstanceOnPointsNode", "core_types::vector::InstanceOnPointsNode"],
},
NodeReplacement {
node: graphene_std::vector::copy_to_points::IDENTIFIER,
aliases: &["graphene_core::vector::CopyToPointsNode", "core_types::vector::CopyToPointsNode"],
},
NodeReplacement {
node: graphene_std::vector::jitter_points::IDENTIFIER,
aliases: &["graphene_core::vector::JitterPointsNode"],
@@ -1861,6 +1860,11 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
.set_input(&InputConnector::node_at_index(node_id, index), NodeInput::value(TaggedValue::Integer(integer), exposed), &network_path);
}
migrate_assign_colors_nodes(document);
// Last, so the rest of the graph is upgraded enough to compile when each Copy to Points node's content type is resolved
migrate_copy_to_points_nodes(document);
// Bringing an old document up to date is not a set of edits on it, it is how the document arrives.
// The upgrades run through the ordinary mutators, so the store records them; dropping what they
// recorded leaves the opened document as the baseline rather than as a pile of changes to itself.
@@ -3843,6 +3847,382 @@ fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, ne
Some(())
}
/// Splits each removed Assign Colors node into the Vary Fill Colors and Vary Stroke Colors nodes its Fill and Stroke toggles call for.
fn migrate_assign_colors_nodes(document: &mut DocumentMessageHandler) {
let assign_colors_nodes: Vec<(NodeId, Vec<NodeId>)> = document
.network_interface
.document_network()
.recursive_nodes()
.filter(|(_, node, _)| node.inputs.len() == 8 && matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if identifier.as_str().ends_with("::AssignColorsNode")))
.map(|(node_id, _, path)| (*node_id, path))
.collect();
for (node_id, network_path) in assign_colors_nodes {
migrate_assign_colors(&node_id, &network_path, document);
}
}
/// Rebuilds a removed Assign Colors node as Vary Fill Colors, Vary Stroke Colors, or both in a row ending at the original node to keep its downstream wires.
/// A wired toggle counts as enabled, and a node with both toggles disabled is hidden so it still passes its content through unchanged.
fn migrate_assign_colors(node_id: &NodeId, network_path: &[NodeId], document: &mut DocumentMessageHandler) -> Option<()> {
use graphene_std::vector::{vary_fill_colors, vary_stroke_colors};
let enabled = |input: &NodeInput| !matches!(input.as_value(), Some(TaggedValue::Bool(false)));
let old_node = document.network_interface.document_node(node_id, network_path)?;
let (fill, stroke) = (enabled(&old_node.inputs[1]), enabled(&old_node.inputs[2]));
let identifier = if stroke { vary_stroke_colors::IDENTIFIER } else { vary_fill_colors::IDENTIFIER };
let mut node_template = resolve_proto_node_type(identifier)?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
reset_default_display_name(document, node_id, network_path, "Assign Colors");
// The content and color parameters carry over in the same order, without the toggles
let [content, _, _, gradient, reverse, randomize, seed, repeat_every] = <[NodeInput; 8]>::try_from(old_inputs).ok()?;
let carried_inputs = [content, gradient, reverse, randomize, seed, repeat_every];
for (index, input) in carried_inputs.iter().enumerate() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input.clone(), network_path);
}
// Styling both gets a Vary Fill Colors node with the same parameters inserted before the Vary Stroke Colors one
if fill && stroke {
let fill_id = NodeId::new();
document
.network_interface
.insert_node(fill_id, resolve_proto_node_type(vary_fill_colors::IDENTIFIER)?.default_node_template(), network_path);
for (index, input) in carried_inputs.iter().enumerate().skip(1) {
document.network_interface.set_input(&InputConnector::node_at_index(fill_id, index), input.clone(), network_path);
}
document.network_interface.insert_node_before_input(&fill_id, &InputConnector::node_at_index(*node_id, 0), network_path);
}
if !fill && !stroke {
document.network_interface.set_visibility(node_id, network_path, false);
}
Some(())
}
/// Rebuilds each removed Copy to Points node, with any feeding another's content rebuilt first so that content compiles when its type is resolved.
fn migrate_copy_to_points_nodes(document: &mut DocumentMessageHandler) {
let copy_to_points_nodes: Vec<(NodeId, Vec<NodeId>)> = document
.network_interface
.document_network()
.recursive_nodes()
.filter(|(_, node, _)| node.inputs.len() == 8 && matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if identifier.as_str().ends_with("::CopyToPointsNode")))
.map(|(node_id, _, path)| (*node_id, path))
.collect();
if copy_to_points_nodes.is_empty() {
return;
}
// A node feeding another's content has fewer of these nodes upstream of its own content, so sorting by that count puts it first
let mut ordered = copy_to_points_nodes.clone();
ordered.sort_by_cached_key(|(node_id, network_path)| {
let Some(NodeInput::Node { node_id: content_source, .. }) = document.network_interface.document_node(node_id, network_path).and_then(|node| node.inputs.get(1)) else {
return 0;
};
document
.network_interface
.upstream_flow_back_from_nodes(vec![*content_source], network_path, FlowType::UpstreamFlow)
.filter(|upstream| copy_to_points_nodes.iter().any(|(other, other_path)| other == upstream && other_path == network_path))
.count()
});
let preprocessor = preprocessor::Preprocessor::new();
let mut content_types: HashMap<(Vec<NodeId>, NodeId, usize), Option<Type>> = HashMap::new();
for (node_id, network_path) in ordered {
let Some(node) = document.network_interface.document_node(&node_id, &network_path).cloned() else {
continue;
};
let content_type = match &node.inputs[1] {
NodeInput::Node { node_id: source, output_index, .. } => content_types
.entry((network_path.clone(), *source, *output_index))
.or_insert_with(|| resolved_output_type(document, &preprocessor, &node.inputs[1], &network_path))
.clone(),
_ => None,
};
migrate_copy_to_points(&node_id, &node, &network_path, content_type, document);
}
}
/// The compile-time type of the node output an input is wired to, resolved on a copy of the graph pruned to that output's upstream.
/// It is `None` where that copy doesn't compile, such as for content reading a scope only the runtime provides.
fn resolved_output_type(document: &DocumentMessageHandler, preprocessor: &preprocessor::Preprocessor, input: &NodeInput, network_path: &[NodeId]) -> Option<Type> {
let NodeInput::Node { node_id, output_index, .. } = input else { return None };
// A hidden node passes its primary input through rather than giving the output its type describes
if !document.network_interface.is_visible(node_id, network_path) {
return None;
}
// Subnetworks stored as shared definitions are inlined so the export chain can be redirected down through them
let mut network = document.network_interface.document_network().clone();
network.inline_definitions().ok()?;
let output_path: Vec<NodeId> = network_path.iter().copied().chain([*node_id]).collect();
if !redirect_export_chain(&mut network, &output_path, *output_index) {
return None;
}
network.exports.truncate(1);
network.remove_dead_nodes(0);
// Wrap it in the scopes the runtime injects, given only as types since nothing is evaluated
let scope_stand_in = |ty: Type| DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER),
inputs: vec![NodeInput::value(TaggedValue::TypeDefault(ty), false)],
..Default::default()
};
let content_network = DocumentNode {
implementation: DocumentNodeImplementation::Network(network),
..Default::default()
};
let mut scoped_network = NodeNetwork {
exports: vec![NodeInput::node(NodeId(0), 0)],
nodes: [
(NodeId(0), content_network),
(NodeId(1), scope_stand_in(item!(Arc<PlatformEditorApi>))),
(NodeId(2), scope_stand_in(item!(RuntimeHandle))),
]
.into_iter()
.collect(),
scope_injections: [
("editor-api".to_string(), (NodeId(1), item!(Arc<PlatformEditorApi>))),
("runtime".to_string(), (NodeId(2), item!(RuntimeHandle))),
]
.into_iter()
.collect(),
definitions: Default::default(),
generated: true,
};
let resources = &document.resources.registry;
preprocessor.preprocess(&mut scoped_network, &|resource_id| resources.hash(&resource_id)).ok()?;
// The compiler asserts every scope input resolves, so content reading any other scope is left unresolved
if !scope_inputs_resolve(&scoped_network, &HashSet::new()) {
return None;
}
let proto_network = Compiler {}.compile_single(scoped_network).ok()?.network;
let mut typing_context = TypingContext::new(&NODE_REGISTRY);
typing_context.update(&proto_network).ok()?;
typing_context.type_of(proto_network.output).map(|types| types.return_value.clone())
}
/// Whether every scope input in the network is injected by it or a network enclosing it.
fn scope_inputs_resolve(network: &NodeNetwork, enclosing_scopes: &HashSet<String>) -> bool {
let scopes: HashSet<String> = enclosing_scopes.iter().cloned().chain(network.scope_injections.keys().cloned()).collect();
network.nodes.values().all(|node| {
let inputs_resolve = node.inputs.iter().all(|input| !matches!(input, NodeInput::Scope(key) if !scopes.contains(key.as_ref())));
let nested_resolve = match &node.implementation {
DocumentNodeImplementation::Network(nested) => scope_inputs_resolve(nested, &scopes),
_ => true,
};
inputs_resolve && nested_resolve
})
}
/// Rebuilds a removed Copy to Points node as a Repeat on Points, then Vary Rotations and Vary Scales, ending at the original node to keep its downstream wires.
/// The points stay on the primary input so tools still edit them. List content other than a lone layer (or content of an unknown type) is grouped into one item to be repeated, then flattened back out with the node for its type.
fn migrate_copy_to_points(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId], content_type: Option<Type>, document: &mut DocumentMessageHandler) -> Option<()> {
use graphene_std::graphic::{flatten_color, flatten_gradient, flatten_graphic, flatten_raster, flatten_vector, into_group};
use graphene_std::math_nodes::multiply;
use graphene_std::raster_types::{CPU, Raster};
use graphene_std::repeat::repeat_on_points;
use graphene_std::transform_nodes::{vary_rotations, vary_scales};
use graphene_std::vector::Vector;
use graphene_std::vector::style::Gradient;
let number = |input: &NodeInput| match input.as_value() {
Some(TaggedValue::Number(number)) => Some(*number),
_ => None,
};
// A layer with nothing stacked below it gives one group, which is repeated as it is like a single item
let lone_layer = match &node.inputs[1] {
NodeInput::Node { node_id: source, .. } => {
document.network_interface.is_layer(source, network_path)
&& document
.network_interface
.document_node(source, network_path)
.is_some_and(|layer| matches!(layer.inputs.first(), Some(NodeInput::Value { .. })))
}
_ => false,
};
let flatten = match content_type {
_ if lone_layer => None,
Some(Type::Item(_)) => None,
Some(content_type) if content_type == list!(Vector) => Some(flatten_vector::IDENTIFIER),
Some(content_type) if content_type == list!(Raster<CPU>) => Some(flatten_raster::IDENTIFIER),
Some(content_type) if content_type == list!(Color) => Some(flatten_color::IDENTIFIER),
Some(content_type) if content_type == list!(Gradient) => Some(flatten_gradient::IDENTIFIER),
_ => Some(flatten_graphic::IDENTIFIER),
};
// The vary nodes are left out where they would leave every copy unchanged
let rotates = number(&node.inputs[6]) != Some(0.);
let scales = number(&node.inputs[2]) != Some(1.) || number(&node.inputs[3]) != Some(1.);
let mut stages = vec![repeat_on_points::IDENTIFIER];
if rotates {
stages.push(vary_rotations::IDENTIFIER);
}
if scales {
stages.push(vary_scales::IDENTIFIER);
}
stages.extend(flatten.clone());
let last_stage = stages.pop()?;
// Note the nodes laid out along a layer's chain through this one, since rewiring breaks that chain
let position = document.network_interface.position(node_id, network_path).unwrap_or_default();
let chained: Vec<NodeId> = if document.network_interface.is_chain(node_id, network_path) {
document
.network_interface
.upstream_flow_back_from_nodes(vec![*node_id], network_path, FlowType::HorizontalFlow)
.take_while(|upstream| document.network_interface.is_chain(upstream, network_path))
.collect()
} else {
Vec::new()
};
let mut last_stage_template = resolve_proto_node_type(last_stage)?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut last_stage_template);
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut last_stage_template)?;
reset_default_display_name(document, node_id, network_path, "Copy to Points");
let [points, content, scale_min, scale_max, scale_bias, scale_seed, rotation, rotation_seed] = <[NodeInput; 8]>::try_from(old_inputs).ok()?;
let insert = |document: &mut DocumentMessageHandler, identifier: ProtoNodeIdentifier, position: IVec2| -> Option<NodeId> {
let id = NodeId::new();
document.network_interface.insert_node(id, resolve_proto_node_type(identifier)?.default_node_template(), network_path);
document.network_interface.set_absolute_position(&id, position, network_path);
Some(id)
};
// Wire the points through each stage in turn, in a row leading up to the original node
let mut stage_ids = Vec::new();
for (index, identifier) in stages.iter().enumerate() {
stage_ids.push(insert(document, identifier.clone(), position - IVec2::new(7 * (stages.len() - index) as i32, 0))?);
}
stage_ids.push(*node_id);
let points_source = points.as_node();
document
.network_interface
.set_input(&InputConnector::node(stage_ids[0], repeat_on_points::PointsInput), points, network_path);
for pair in stage_ids.windows(2) {
document
.network_interface
.set_input(&InputConnector::node_at_index(pair[1], 0), NodeInput::node(pair[0], 0), network_path);
}
// A hidden node passed its points through, so its stages are hidden to keep doing that
if !node.visible {
for stage_id in &stage_ids {
document.network_interface.set_visibility(stage_id, network_path, false);
}
}
// The stages join the layer's chain if there is one, and the other nodes feeding the row move left to make room
if !chained.is_empty() {
for chain_node_id in stage_ids.iter().chain(&chained) {
document.network_interface.set_chain_position(chain_node_id, network_path);
}
}
let mut upstream = points_source;
while let Some(upstream_id) = upstream
&& !document.network_interface.is_layer(&upstream_id, network_path)
{
if !document.network_interface.is_chain(&upstream_id, network_path)
&& let Some(upstream_position) = document.network_interface.position(&upstream_id, network_path)
{
let shifted = upstream_position - IVec2::new(7 * stages.len() as i32, 0);
document.network_interface.set_absolute_position(&upstream_id, shifted, network_path);
}
upstream = document.network_interface.document_node(&upstream_id, network_path).and_then(|node| node.inputs.first()?.as_node());
}
let offset_from_stage = |document: &DocumentMessageHandler, stage_id: &NodeId, offset: IVec2| document.network_interface.position(stage_id, network_path).unwrap_or(position) + offset;
// Repeat the content at each point, grouped if it's flattened back out at the end
let repeated_content = match flatten {
Some(_) => {
let group_id = insert(document, into_group::IDENTIFIER, offset_from_stage(document, &stage_ids[0], IVec2::new(-7, 3)))?;
document.network_interface.set_input(&InputConnector::node(group_id, into_group::ContentInput), content, network_path);
NodeInput::node(group_id, 0)
}
None => content,
};
document
.network_interface
.set_input(&InputConnector::node(stage_ids[0], repeat_on_points::ContentInput), repeated_content, network_path);
// The rotation range was centered on zero, so a wired one is halved to each side by Multiply nodes
if rotates {
let rotations_id = stage_ids[1];
document
.network_interface
.set_input(&InputConnector::node(rotations_id, vary_rotations::SeedInput), rotation_seed, network_path);
let ends = [
(InputConnector::node(rotations_id, vary_rotations::MinInput), -0.5),
(InputConnector::node(rotations_id, vary_rotations::MaxInput), 0.5),
];
for (index, (end, factor)) in ends.into_iter().enumerate() {
let half_rotation = match number(&rotation) {
Some(rotation) => NodeInput::value(TaggedValue::Number(rotation * factor), false),
None => {
let multiply_id = insert(document, multiply::IDENTIFIER, offset_from_stage(document, &rotations_id, IVec2::new(-7, 3 + 3 * index as i32)))?;
document
.network_interface
.set_input(&InputConnector::node(multiply_id, multiply::MultiplierInput), rotation.clone(), network_path);
document.network_interface.set_input(
&InputConnector::node(multiply_id, multiply::MultiplicandInput),
NodeInput::value(TaggedValue::Number(factor), false),
network_path,
);
NodeInput::node(multiply_id, 0)
}
};
document.network_interface.set_input(&end, half_rotation, network_path);
}
}
// The bias is converted to the one that keeps its average scale, though a wired bias can't be converted and is left at the default
if scales {
let scales_id = stage_ids[1 + rotates as usize];
document.network_interface.set_input(&InputConnector::node(scales_id, vary_scales::MinInput), scale_min, network_path);
document.network_interface.set_input(&InputConnector::node(scales_id, vary_scales::MaxInput), scale_max, network_path);
document.network_interface.set_input(&InputConnector::node(scales_id, vary_scales::SeedInput), scale_seed, network_path);
if let Some(bias) = number(&scale_bias) {
let bias = NodeInput::value(TaggedValue::Number(vary_scales_bias_from_copy_to_points(bias)), false);
document.network_interface.set_input(&InputConnector::node(scales_id, vary_scales::BiasInput), bias, network_path);
}
}
Some(())
}
/// The Vary Scales bias giving the same average scale, as a fraction of its range, that the removed Copy to Points node's random scale distribution had for the scale bias it was given.
fn vary_scales_bias_from_copy_to_points(bias: f64) -> f64 {
if bias.abs() < 1e-6 {
return 0.5;
}
// Its bias curve `log2(1 + r (2^b - 1)) / b` averages `2^b / (2^b - 1) - 1 / (b ln 2)`, written with `x = b ln 2` to stay finite for a large bias
let x = bias * std::f64::consts::LN_2;
let average = -1. / (-x).exp_m1() - 1. / x;
// The new curve averages `k / (k + 1)` for `1 - (1 - t)^k` below a bias of 0.5, where `k = -log2(1 - bias)`, and `1 / (p + 1)` for `t^p` above it, where `p = -log2(bias)`
if average < 0.5 {
let k = average / (1. - average);
1. - (-k).exp2()
} else {
let p = 1. / average - 1.;
(-p).exp2()
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -5186,4 +5566,402 @@ mod tests {
assert_eq!(interface.display_name(&node_id, &[]), "Image", "node {node_id}");
}
}
#[tokio::test]
async fn copy_to_points_opens_as_a_chain_that_compiles() {
use crate::messages::portfolio::ingest::utility_types::IngestAction;
use crate::test_utils::test_prelude::*;
use graphene_std::NodeParameter;
use graphene_std::graphic::{flatten_graphic, flatten_vector, into_group};
use graphene_std::math_nodes::multiply;
use graphene_std::repeat::repeat_on_points;
use graphene_std::transform_nodes::{vary_rotations, vary_scales};
use graphene_std::vector::generator_nodes::{circle, rectangle};
let default_template = |identifier| {
resolve_document_node_type(&DefinitionIdentifier::ProtoNode(identifier))
.expect("the definition should exist")
.default_node_template()
};
let number = |value| NodeInput::value(TaggedValue::Number(value), false);
let integer = |value| NodeInput::value(TaggedValue::Integer(value), false);
let copy_to_points = |[scale_min, scale_max, scale_bias]: [f64; 3], scale_seed, rotation, rotation_seed| {
let wired = || NodeInput::value(TaggedValue::None, false);
let inputs = vec![
wired(),
wired(),
number(scale_min),
number(scale_max),
number(scale_bias),
integer(scale_seed),
number(rotation),
integer(rotation_seed),
];
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::vector::CopyToPointsNode")),
input_metadata: inputs.iter().map(|_| ("Value", "").into()).collect(),
inputs,
display_name: "Copy to Points".to_string(),
..Default::default()
}
};
let (points, content, rotation, layer) = (NodeId(1), NodeId(2), NodeId(3), NodeId(4));
let (stored, wired, unchanged) = (NodeId(5), NodeId(6), NodeId(7));
let (lone_layer, single, layer_below) = (NodeId(8), NodeId(9), NodeId(10));
// Chain the variants so each is evaluated and rebuilt after those it depends on: a vector item with stored values, a list of vectors
// with a wired rotation, then a lone layer and a hidden stack of layers with settings that change nothing
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let interface = &mut editor.active_document_mut().network_interface;
interface.insert_node(unchanged, copy_to_points([1., 1., 0.], 0, 0., 0), &[]);
interface.insert_node(single, copy_to_points([1., 1., 0.], 0, 0., 0), &[]);
interface.insert_node(wired, copy_to_points([1., 1., 0.], 0, 0., 4), &[]);
interface.insert_node(stored, copy_to_points([0.5, 2., -10.], 7, 90., 3), &[]);
interface.insert_node(points, default_template(rectangle::IDENTIFIER), &[]);
interface.insert_node(content, default_template(circle::IDENTIFIER), &[]);
interface.insert_node(rotation, default_template(graphene_std::math_nodes::number_value::IDENTIFIER), &[]);
let merge = resolve_document_node_type(&DefinitionIdentifier::Network("Merge".into())).expect("the Merge definition should exist");
for layer_id in [layer, lone_layer, layer_below] {
interface.insert_node(layer_id, merge.default_node_template(), &[]);
}
interface.set_input(&InputConnector::node_at_index(layer, 1), NodeInput::node(wired, 0), &[]);
interface.set_input(&InputConnector::node_at_index(layer, 0), NodeInput::node(layer_below, 0), &[]);
interface.set_input(&InputConnector::node_at_index(layer_below, 1), NodeInput::node(single, 0), &[]);
for (node_id, content_source) in [(stored, content), (wired, stored), (single, lone_layer), (unchanged, layer)] {
interface.set_input(&InputConnector::node_at_index(node_id, 0), NodeInput::node(points, 0), &[]);
interface.set_input(&InputConnector::node_at_index(node_id, 1), NodeInput::node(content_source, 0), &[]);
}
interface.set_input(&InputConnector::node_at_index(wired, 6), NodeInput::node(rotation, 0), &[]);
interface.create_wire(&OutputConnector::primary_output(unchanged), &InputConnector::Export(0), &[]);
interface.set_visibility(&unchanged, &[], false);
let serialized = editor.active_document().serialize_document();
// Opening migrates the document, then evaluates its graph and checks the interface, failing on any error
editor
.handle_message(IngestMessage::Ingest {
data: serialized.into_bytes(),
action: IngestAction::Open,
mime_type: String::new(),
path: Some("copy-to-points.graphite".into()),
})
.await;
let interface = &editor.active_document().network_interface;
let node = |node_id| interface.document_node(&node_id, &[]).expect("the node should exist");
let upstream = |node_id, index: usize| match &node(node_id).inputs[index] {
NodeInput::Node { node_id, .. } => *node_id,
input => panic!("input {index} of node {node_id} should be wired, found {input:?}"),
};
let proto = DocumentNodeImplementation::ProtoNode;
// The points stay on the primary input, where tools look for the path to edit
let assert_repeats_on_points = |repeat_id, content_source, grouped: bool| {
assert_eq!(node(repeat_id).implementation, proto(repeat_on_points::IDENTIFIER));
assert_eq!(upstream(repeat_id, repeat_on_points::PointsInput::INDEX), points);
let repeated_content = upstream(repeat_id, repeat_on_points::ContentInput::INDEX);
if grouped {
assert_eq!(node(repeated_content).implementation, proto(into_group::IDENTIFIER));
assert_eq!(upstream(repeated_content, 0), content_source);
} else {
assert_eq!(repeated_content, content_source);
}
};
// One item is copied as it is, with the stored rotation range centered on zero and the bias kept as the average scale
assert_eq!(node(stored).implementation, proto(vary_scales::IDENTIFIER));
assert_ne!(interface.display_name(&stored, &[]), "Copy to Points");
assert_eq!(node(stored).input_value(vary_scales::MinInput), Some(&TaggedValue::Number(0.5)));
assert_eq!(node(stored).input_value(vary_scales::MaxInput), Some(&TaggedValue::Number(2.)));
assert_eq!(node(stored).input_value(vary_scales::SeedInput), Some(&TaggedValue::Integer(7)));
assert_eq!(node(stored).input_value(vary_scales::BiasInput), Some(&TaggedValue::Number(vary_scales_bias_from_copy_to_points(-10.))));
let rotations = upstream(stored, 0);
assert_eq!(node(rotations).implementation, proto(vary_rotations::IDENTIFIER));
assert_eq!(node(rotations).input_value(vary_rotations::MinInput), Some(&TaggedValue::Number(-45.)));
assert_eq!(node(rotations).input_value(vary_rotations::MaxInput), Some(&TaggedValue::Number(45.)));
assert_eq!(node(rotations).input_value(vary_rotations::SeedInput), Some(&TaggedValue::Integer(3)));
assert_repeats_on_points(upstream(rotations, 0), content, false);
// A list of vectors is grouped and flattened back out as vectors, a wired rotation is halved to each side of zero, and a scale range of 1 drops Vary Scales
assert_eq!(node(wired).implementation, proto(flatten_vector::IDENTIFIER));
let wired_rotations = upstream(wired, 0);
assert_eq!(node(wired_rotations).implementation, proto(vary_rotations::IDENTIFIER));
assert_eq!(node(wired_rotations).input_value(vary_rotations::SeedInput), Some(&TaggedValue::Integer(4)));
for (end, factor) in [(vary_rotations::MinInput::INDEX, -0.5), (vary_rotations::MaxInput::INDEX, 0.5)] {
let half_rotation = upstream(wired_rotations, end);
assert_eq!(node(half_rotation).implementation, proto(multiply::IDENTIFIER));
assert_eq!(upstream(half_rotation, 0), rotation);
assert_eq!(node(half_rotation).input_value(multiply::MultiplicandInput), Some(&TaggedValue::Number(factor)));
}
assert_repeats_on_points(upstream(wired_rotations, 0), stored, true);
// Feeding the layer, its stages join the layer's chain
assert!(interface.is_chain(&wired, &[]));
assert!(interface.is_chain(&wired_rotations, &[]));
assert!(interface.is_chain(&upstream(wired_rotations, 0), &[]));
// A lone layer is one group, repeated as it is
assert_repeats_on_points(single, lone_layer, false);
// A stack of layers is flattened back out as graphics, with only the Repeat on Points between since the settings change nothing
assert_eq!(node(unchanged).implementation, proto(flatten_graphic::IDENTIFIER));
assert_repeats_on_points(upstream(unchanged, 0), layer, true);
// Its stages are hidden with it, so the row still passes the points through
assert!(!interface.is_visible(&upstream(unchanged, 0), &[]));
}
#[tokio::test]
async fn copy_to_points_in_a_subnetwork_resolves_its_content_type() {
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkTemplate;
use crate::messages::portfolio::document_storage_io::load_legacy_document;
use crate::test_utils::test_prelude::*;
use graph_craft::application_io::resource::HashMapResourceStorage;
use graphene_std::repeat::repeat_on_points;
use graphene_std::vector::generator_nodes::{circle, rectangle};
let default_template = |identifier| {
resolve_document_node_type(&DefinitionIdentifier::ProtoNode(identifier))
.expect("the definition should exist")
.default_node_template()
};
let number = |value| NodeInput::value(TaggedValue::Number(value), false);
let integer = |value| NodeInput::value(TaggedValue::Integer(value), false);
// A subnetwork copying a circle onto a rectangle's corners
let (points, content, copy_to_points, subnetwork) = (NodeId(1), NodeId(2), NodeId(3), NodeId(4));
let copy_to_points_template = NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::vector::CopyToPointsNode")),
inputs: vec![
NodeInput::node(points, 0),
NodeInput::node(content, 0),
number(1.),
number(1.),
number(0.),
integer(0),
number(0.),
integer(0),
],
..Default::default()
};
let subnetwork_template = NodeTemplate {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
exports: vec![NodeInput::node(copy_to_points, 0)],
nodes: [
(points, default_template(rectangle::IDENTIFIER)),
(content, default_template(circle::IDENTIFIER)),
(copy_to_points, copy_to_points_template),
]
.into_iter()
.collect(),
..Default::default()
}),
..Default::default()
};
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let interface = &mut editor.active_document_mut().network_interface;
interface.insert_node(subnetwork, subnetwork_template, &[]);
interface.create_wire(&OutputConnector::primary_output(subnetwork), &InputConnector::Export(0), &[]);
assert!(!interface.document_network().definitions.is_empty(), "the subnetwork should be stored as a shared definition");
let serialized = editor.active_document().serialize_document();
// The circle is one vector item, so it's repeated as it is rather than grouped and flattened back out as graphics
let opened = load_legacy_document(serialized, &HashMapResourceStorage::new(), false).expect("the document should open");
let migrated = opened.network_interface.document_node(&copy_to_points, &[subnetwork]).expect("the node should exist");
assert_eq!(migrated.implementation, DocumentNodeImplementation::ProtoNode(repeat_on_points::IDENTIFIER));
}
#[tokio::test]
async fn copy_to_points_content_from_a_secondary_output_resolves_its_type() {
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkTemplate;
use crate::messages::portfolio::document_storage_io::load_legacy_document;
use crate::test_utils::test_prelude::*;
use graph_craft::application_io::resource::HashMapResourceStorage;
use graphene_std::NodeParameter;
use graphene_std::repeat::repeat_on_points;
use graphene_std::vector::generator_nodes::{circle, rectangle};
let default_template = |identifier| {
resolve_document_node_type(&DefinitionIdentifier::ProtoNode(identifier))
.expect("the definition should exist")
.default_node_template()
};
let number = |value| NodeInput::value(TaggedValue::Number(value), false);
let integer = |value| NodeInput::value(TaggedValue::Integer(value), false);
// A subnetwork exporting a list of circles repeated on a rectangle's corners first, then a lone circle
let (subnetwork_points, subnetwork_content, subnetwork_repeat) = (NodeId(1), NodeId(2), NodeId(3));
let mut repeat_template = default_template(repeat_on_points::IDENTIFIER);
repeat_template.inputs[repeat_on_points::PointsInput::INDEX] = NodeInput::node(subnetwork_points, 0);
repeat_template.inputs[repeat_on_points::ContentInput::INDEX] = NodeInput::node(subnetwork_content, 0);
let subnetwork_template = NodeTemplate {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
exports: vec![NodeInput::node(subnetwork_repeat, 0), NodeInput::node(subnetwork_content, 0)],
nodes: [
(subnetwork_points, default_template(rectangle::IDENTIFIER)),
(subnetwork_content, default_template(circle::IDENTIFIER)),
(subnetwork_repeat, repeat_template),
]
.into_iter()
.collect(),
..Default::default()
}),
..Default::default()
};
// Copy the subnetwork's lone circle onto another rectangle's corners
let (points, subnetwork, copy_to_points) = (NodeId(4), NodeId(5), NodeId(6));
let copy_to_points_template = NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::vector::CopyToPointsNode")),
inputs: vec![
NodeInput::value(TaggedValue::None, false),
NodeInput::value(TaggedValue::None, false),
number(1.),
number(1.),
number(0.),
integer(0),
number(0.),
integer(0),
],
..Default::default()
};
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let interface = &mut editor.active_document_mut().network_interface;
interface.insert_node(points, default_template(rectangle::IDENTIFIER), &[]);
interface.insert_node(subnetwork, subnetwork_template, &[]);
interface.insert_node(copy_to_points, copy_to_points_template, &[]);
interface.set_input(&InputConnector::node_at_index(copy_to_points, 0), NodeInput::node(points, 0), &[]);
interface.set_input(&InputConnector::node_at_index(copy_to_points, 1), NodeInput::node(subnetwork, 1), &[]);
interface.create_wire(&OutputConnector::primary_output(copy_to_points), &InputConnector::Export(0), &[]);
let serialized = editor.active_document().serialize_document();
// The second output is one vector item, so it's repeated as it is rather than grouped and flattened back out
let opened = load_legacy_document(serialized, &HashMapResourceStorage::new(), false).expect("the document should open");
let migrated = opened.network_interface.document_node(&copy_to_points, &[]).expect("the node should exist");
assert_eq!(migrated.implementation, DocumentNodeImplementation::ProtoNode(repeat_on_points::IDENTIFIER));
}
#[tokio::test]
async fn assign_colors_splits_by_its_fill_and_stroke_toggles() {
use crate::messages::portfolio::ingest::utility_types::IngestAction;
use crate::test_utils::test_prelude::*;
use graphene_std::NodeParameter;
use graphene_std::vector::generator_nodes::rectangle;
use graphene_std::vector::{vary_fill_colors, vary_stroke_colors};
let default_template = |identifier| {
resolve_document_node_type(&DefinitionIdentifier::ProtoNode(identifier))
.expect("the definition should exist")
.default_node_template()
};
let gradient = default_template(vary_fill_colors::IDENTIFIER).inputs[vary_fill_colors::GradientInput::INDEX].clone();
let assign_colors = |fill, stroke, seed| {
let boolean = |value| NodeInput::value(TaggedValue::Bool(value), false);
let integer = |value| NodeInput::value(TaggedValue::Integer(value), false);
let inputs = vec![
NodeInput::value(TaggedValue::None, false),
boolean(fill),
boolean(stroke),
gradient.clone(),
boolean(false),
boolean(true),
integer(seed),
integer(0),
];
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::vector::AssignColorsNode")),
input_metadata: inputs.iter().map(|_| ("Value", "").into()).collect(),
inputs,
display_name: "Assign Colors".to_string(),
..Default::default()
}
};
// Chain every combination of the toggles after a rectangle, so the whole row is evaluated
let (shape, fill_only, stroke_only, both, neither) = (NodeId(1), NodeId(2), NodeId(3), NodeId(4), NodeId(5));
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let interface = &mut editor.active_document_mut().network_interface;
interface.insert_node(shape, default_template(rectangle::IDENTIFIER), &[]);
for (node_id, fill, stroke, seed) in [(fill_only, true, false, 1), (stroke_only, false, true, 2), (both, true, true, 3), (neither, false, false, 4)] {
interface.insert_node(node_id, assign_colors(fill, stroke, seed), &[]);
}
for pair in [shape, fill_only, stroke_only, both, neither].windows(2) {
interface.set_input(&InputConnector::node_at_index(pair[1], 0), NodeInput::node(pair[0], 0), &[]);
}
interface.create_wire(&OutputConnector::primary_output(neither), &InputConnector::Export(0), &[]);
let serialized = editor.active_document().serialize_document();
// Opening migrates the document, then evaluates its graph and checks the interface, failing on any error
editor
.handle_message(IngestMessage::Ingest {
data: serialized.into_bytes(),
action: IngestAction::Open,
mime_type: String::new(),
path: Some("assign-colors.graphite".into()),
})
.await;
let interface = &editor.active_document().network_interface;
let node = |node_id| interface.document_node(&node_id, &[]).expect("the node should exist");
let upstream = |node_id| match &node(node_id).inputs[0] {
NodeInput::Node { node_id, .. } => *node_id,
input => panic!("the content of node {node_id} should be wired, found {input:?}"),
};
let proto = DocumentNodeImplementation::ProtoNode;
assert_eq!(node(fill_only).implementation, proto(vary_fill_colors::IDENTIFIER));
assert_eq!(node(fill_only).input_value(vary_fill_colors::SeedInput), Some(&TaggedValue::Integer(1)));
assert_ne!(interface.display_name(&fill_only, &[]), "Assign Colors");
assert_eq!(node(stroke_only).implementation, proto(vary_stroke_colors::IDENTIFIER));
assert_eq!(node(stroke_only).input_value(vary_stroke_colors::SeedInput), Some(&TaggedValue::Integer(2)));
// Styling both puts a Vary Fill Colors node with the same parameters in front of the Vary Stroke Colors node
assert_eq!(node(both).implementation, proto(vary_stroke_colors::IDENTIFIER));
let inserted_fill = upstream(both);
assert_eq!(node(inserted_fill).implementation, proto(vary_fill_colors::IDENTIFIER));
assert_eq!(node(inserted_fill).input_value(vary_fill_colors::SeedInput), Some(&TaggedValue::Integer(3)));
assert_eq!(upstream(inserted_fill), stroke_only);
// Styling neither is kept as a hidden node, which passes its content through as before
assert_eq!(node(neither).implementation, proto(vary_fill_colors::IDENTIFIER));
assert!(!interface.is_visible(&neither, &[]));
}
#[test]
fn copy_to_points_bias_keeps_its_average() {
use graphene_std::core_types::math::midpoint::apply_midpoint_inverse;
// The removed node's bias curve, mapping a uniform random draw to a fraction of its scale range
let legacy_bias_curve = |random: f64, bias: f64| (1. - random * (1. - 2_f64.powf(bias))).log2() / bias;
// Averages a curve over evenly spaced draws from 0 to 1
fn average(curve: impl Fn(f64) -> f64) -> f64 {
const SAMPLES: usize = 100_000;
(0..SAMPLES).map(|i| curve((i as f64 + 0.5) / SAMPLES as f64)).sum::<f64>() / SAMPLES as f64
}
assert_eq!(vary_scales_bias_from_copy_to_points(0.), 0.5);
for bias in [-100., -10., -1., 1., 10., 100.] {
let converted = vary_scales_bias_from_copy_to_points(bias);
let legacy_average = average(|random| legacy_bias_curve(random, bias));
let migrated_average = average(|random| apply_midpoint_inverse(random, converted));
assert!(
(migrated_average - legacy_average).abs() < 1e-4,
"bias {bias} became {converted}, averaging {migrated_average} rather than {legacy_average}"
);
}
for bias in [-2000., 2000.] {
let converted = vary_scales_bias_from_copy_to_points(bias);
assert!(converted > 0. && converted < 1., "bias {bias} became {converted}");
}
}
}
@@ -18,6 +18,7 @@ use document_container::store::{DocumentKey, DocumentStore, MemoryStore};
use document_container::{AnyContainer, AsyncContainer};
use document_format::{Error as DocumentFormatError, GddV1, GddV1Layout, Layout, ReadError};
use document_graph_storage::{Declarations, PeerId};
use graph_craft::application_io::resource::LoadResource;
use graph_craft::application_io::resource::{DataSource, ResourceHash, ResourceStorage};
use std::collections::HashSet;
use std::path::PathBuf;
@@ -118,7 +119,7 @@ pub(super) async fn attach_container(store: DocumentStoreHandle, document_id: Do
.into();
}
};
let gdd = open_storage_or_fallback_to_legacy(container.clone(), document_id).await;
let gdd = open_storage_or_fallback_to_legacy(container.clone(), document_id, &resources).await;
let declarations = load_declarations(gdd.as_ref(), &resources, document_id).await;
PortfolioMessage::StorageAttached {
document_id,
@@ -228,11 +229,11 @@ async fn load_from_container(container: AnyContainer, document_id: DocumentId, r
Ok(mut document) => {
document.set_auto_save_state(true);
document.container = Some(container.clone());
let gdd = open_storage_or_fallback_to_legacy(container, document_id).await;
let gdd = open_storage_or_fallback_to_legacy(container, document_id, resources).await;
(Some(document), gdd)
}
Err(legacy_error) => {
let gdd = match GddV1::open_in(container.clone(), GddV1Layout).await {
let gdd = match open_migrating(container.clone(), resources).await {
Ok(gdd) => gdd,
Err(storage_error) => {
log::error!("Loading {document_id:?} failed. Legacy: {legacy_error}. Storage: {storage_error}");
@@ -249,8 +250,14 @@ async fn load_from_container(container: AnyContainer, document_id: DocumentId, r
}
}
async fn open_storage_or_fallback_to_legacy(container: AnyContainer, document_id: DocumentId) -> Option<GddV1> {
match GddV1::open_in(container.clone(), GddV1Layout).await {
/// Open a document's storage, offering its migrations the compiler and the global cache's declarations.
async fn open_migrating(container: AnyContainer, resources: &dyn LoadResource) -> Result<GddV1, DocumentFormatError> {
let host = migration_compiled::CompilerHost::default();
GddV1::open_in_with(container, GddV1Layout, Some(resources), Some(&host)).await
}
async fn open_storage_or_fallback_to_legacy(container: AnyContainer, document_id: DocumentId, resources: &dyn LoadResource) -> Option<GddV1> {
match open_migrating(container.clone(), resources).await {
Ok(gdd) => return Some(gdd),
Err(DocumentFormatError::MissingManifest) => {}
// Container I/O, newer-format, and migration errors keep the existing files, since a later build can still read them. Anything else is broken data the legacy document replaces.
@@ -427,7 +434,11 @@ mod tests {
gdd.update_manifest(|manifest| manifest.format_version = 0).unwrap();
let files = container.list("").await.unwrap();
assert!(open_storage_or_fallback_to_legacy(container.clone(), DocumentId(1)).await.is_none());
assert!(
open_storage_or_fallback_to_legacy(container.clone(), DocumentId(1), &graph_craft::application_io::resource::HashMapResourceStorage::new())
.await
.is_none()
);
assert_eq!(container.list("").await.unwrap(), files, "the document's files should survive for a build that can migrate them");
let manifest = container
.read(&document_format::io::path_for(GddV1Layout.manifest_basename(), document_format::MANIFEST_CODEC))
+6 -6
View File
@@ -768,7 +768,7 @@ impl NodeGraphExecutor {
self.advance_gradient_migration(document, document_id, responses);
return;
}
if !redirect_export_chain(&mut network, &full_path) {
if !redirect_export_chain(&mut network, &full_path, 0) {
// The fill was deleted or is otherwise unreachable, so drop its stale entry instead of retrying it on every open
log::warn!("Gradient migration: could not redirect the document network's export chain to fill node {fill_node_id:?}; dropping its pending gradient bake");
remove_pending_gradient_bake(document, &network_path, fill_node_id);
@@ -1065,13 +1065,13 @@ fn remove_pending_gradient_bake(document: &mut DocumentMessageHandler, network_p
}
// TODO: Eventually remove this document upgrade code
/// Redirect the primary export at each level of `network` down through the subnetwork nodes named by `full_path`,
/// un-hiding each so the innermost node's branch evaluates. Returns false if any step is missing or not a subnetwork.
fn redirect_export_chain(network: &mut NodeNetwork, full_path: &[NodeId]) -> bool {
/// Redirect the primary export at each level of `network` down through the subnetwork nodes named by `full_path` to the innermost node's `output_index`,
/// un-hiding each so its branch evaluates. Returns false if any step is missing or not a subnetwork.
pub(crate) fn redirect_export_chain(network: &mut NodeNetwork, full_path: &[NodeId], output_index: usize) -> bool {
let Some((node_id, deeper_path)) = full_path.split_first() else { return true };
let Some(export) = network.exports.first_mut() else { return false };
*export = NodeInput::node(*node_id, 0);
*export = NodeInput::node(*node_id, if deeper_path.is_empty() { output_index } else { 0 });
let Some(node) = network.nodes.get_mut(node_id) else { return false };
node.visible = true;
@@ -1080,7 +1080,7 @@ fn redirect_export_chain(network: &mut NodeNetwork, full_path: &[NodeId]) -> boo
return true;
}
match &mut node.implementation {
DocumentNodeImplementation::Network(nested) => redirect_export_chain(nested, deeper_path),
DocumentNodeImplementation::Network(nested) => redirect_export_chain(nested, deeper_path, output_index),
_ => false,
}
}
@@ -767,6 +767,8 @@ mod tests {
async fn editor(clock: &Arc<FakeClock>) -> EditorTestUtils {
let mut editor = EditorTestUtils::create_with(Scheduling::default(), clock.clone());
editor.new_document().await;
// We use the svg pipeline for these tests since we don't read back the result for editor tests anyway
editor.handle_message(DocumentMessage::SetRenderMode { render_mode: RenderMode::SvgPreview }).await;
editor.draw_rect(0., 0., 100., 100.).await;
editor.runtime.async_runtime().retain_sources(&[SOURCE]);
editor.runtime.begin_frame();
+13 -8
View File
@@ -14,13 +14,13 @@ use crate::task::{Scheduling, Spawn, Task};
use crate::test_utils::test_prelude::LayerNodeIdentifier;
use document_container::store::MemoryStore;
use glam::{DVec2, UVec2};
use graph_craft::application_io::PlatformApplicationIo;
use graph_craft::application_io::resource::HashMapResourceStorage;
use graph_craft::application_io::{ApplicationIo, PlatformApplicationIo};
use graphene_std::raster::color::Color;
use graphene_std::runtime::Clock;
use graphene_std::uuid::NodeId;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use std::sync::{Arc, LazyLock, Mutex, PoisonError};
use std::time::Duration;
/// A set of utility functions to make the writing of editor test more declarative
@@ -48,12 +48,7 @@ impl EditorTestUtils {
.with_resource_storage(Arc::new(HashMapResourceStorage::new()))
.with_document_store(Arc::new(MemoryStore::default())),
)
.with_runtime(
RuntimeBuilder::new(clock)
.with_wake(|| {})
.with_application_io(PlatformApplicationIo::default())
.with_scheduling(scheduling),
)
.with_runtime(RuntimeBuilder::new(clock).with_wake(|| {}).with_application_io(gpu_application_io()).with_scheduling(scheduling))
.with_spawner(BlockingSpawner)
.with_random_seed(0)
.build();
@@ -493,6 +488,16 @@ fn init_test_logger() {
});
}
/// Creates application IO with the GPU executor shared by every test in the process, since creating a device and its pipelines for each test is slow.
/// Panics if no adapter is found, since tests render on the GPU like the app does.
fn gpu_application_io() -> PlatformApplicationIo {
static GPU_EXECUTOR: LazyLock<Option<<PlatformApplicationIo as ApplicationIo>::Executor>> = LazyLock::new(|| futures::executor::block_on(PlatformApplicationIo::new()).gpu_executor().cloned());
let executor = GPU_EXECUTOR.clone().expect(
"Editor tests need a GPU adapter. Without a hardware GPU, install Mesa's lavapipe software Vulkan driver and point `VK_ADD_DRIVER_FILES` at its `lvp_icd.<arch>.json` (the Nix dev shell does this).",
);
PlatformApplicationIo::new_with_executor(executor)
}
/// Runs `operation`, returning its result along with the errors it logged.
pub fn capture_logged_errors<T>(operation: impl FnOnce() -> T) -> (T, Vec<String>) {
init_test_logger();
+12 -10
View File
@@ -121,9 +121,8 @@ import NodeAsInteger from "/../branding/assets/16x16-nodes/node-as-integer.svg";
import NodeAsNumber from "/../branding/assets/16x16-nodes/node-as-number.svg";
import NodeAsString from "/../branding/assets/16x16-nodes/node-as-string.svg";
import NodeAsVector from "/../branding/assets/16x16-nodes/node-as-vector.svg";
import NodeAssignColors from "/../branding/assets/16x16-nodes/node-assign-colors.svg";
import NodeAssignRotations from "/../branding/assets/16x16-nodes/node-assign-rotations.svg";
import NodeAssignScales from "/../branding/assets/16x16-nodes/node-assign-scales.svg";
import NodeVaryRotations from "/../branding/assets/16x16-nodes/node-assign-rotations.svg";
import NodeVaryScales from "/../branding/assets/16x16-nodes/node-assign-scales.svg";
import NodeAverage from "/../branding/assets/16x16-nodes/node-average.svg";
import NodeBakeTransform from "/../branding/assets/16x16-nodes/node-bake-transform.svg";
import NodeBasicBrush from "/../branding/assets/16x16-nodes/node-basic-brush.svg";
@@ -189,7 +188,6 @@ import NodeFill from "/../branding/assets/16x16-nodes/node-fill.svg";
import NodeFilter from "/../branding/assets/16x16-nodes/node-filter.svg";
import NodeFlattenColor from "/../branding/assets/16x16-nodes/node-flatten-color.svg";
import NodeFlattenGradient from "/../branding/assets/16x16-nodes/node-flatten-gradient.svg";
import NodeFlattenGraphic from "/../branding/assets/16x16-nodes/node-flatten-graphic.svg";
import NodeFlattenRaster from "/../branding/assets/16x16-nodes/node-flatten-raster.svg";
import NodeFlattenVector from "/../branding/assets/16x16-nodes/node-flatten-vector.svg";
import NodeFloor from "/../branding/assets/16x16-nodes/node-floor.svg";
@@ -215,6 +213,7 @@ import NodeGradientValue from "/../branding/assets/16x16-nodes/node-gradient-val
import NodeGreaterThan from "/../branding/assets/16x16-nodes/node-greater-than.svg";
import NodeGreatestCommonDivisor from "/../branding/assets/16x16-nodes/node-greatest-common-divisor.svg";
import NodeGrid from "/../branding/assets/16x16-nodes/node-grid.svg";
import NodeGroup from "/../branding/assets/16x16-nodes/node-group.svg";
import NodeHeart from "/../branding/assets/16x16-nodes/node-heart.svg";
import NodeHslaToColor from "/../branding/assets/16x16-nodes/node-hsla-to-color.svg";
import NodeHsvaToColor from "/../branding/assets/16x16-nodes/node-hsva-to-color.svg";
@@ -225,7 +224,6 @@ import NodeImageToChannels from "/../branding/assets/16x16-nodes/node-image-to-c
import NodeImage from "/../branding/assets/16x16-nodes/node-image.svg";
import NodeIndexPoints from "/../branding/assets/16x16-nodes/node-index-points.svg";
import NodeIndices from "/../branding/assets/16x16-nodes/node-indices.svg";
import NodeIntoGroup from "/../branding/assets/16x16-nodes/node-into-group.svg";
import NodeInvertTransform from "/../branding/assets/16x16-nodes/node-invert-transform.svg";
import NodeInvert from "/../branding/assets/16x16-nodes/node-invert.svg";
import NodeIsNonzero from "/../branding/assets/16x16-nodes/node-is-nonzero.svg";
@@ -373,7 +371,10 @@ import NodeText from "/../branding/assets/16x16-nodes/node-text.svg";
import NodeThreshold from "/../branding/assets/16x16-nodes/node-threshold.svg";
import NodeTransform from "/../branding/assets/16x16-nodes/node-transform.svg";
import NodeTriangulate from "/../branding/assets/16x16-nodes/node-triangulate.svg";
import NodeUngroup from "/../branding/assets/16x16-nodes/node-ungroup.svg";
import NodeUnweld from "/../branding/assets/16x16-nodes/node-unweld.svg";
import NodeVaryFillColors from "/../branding/assets/16x16-nodes/node-vary-fill-colors.svg";
import NodeVaryStrokeColors from "/../branding/assets/16x16-nodes/node-vary-stroke-colors.svg";
import NodeVec2ToNumbers from "/../branding/assets/16x16-nodes/node-vec2-to-numbers.svg";
import NodeVec2Value from "/../branding/assets/16x16-nodes/node-vec2-value.svg";
import NodeVectorToPoints from "/../branding/assets/16x16-nodes/node-vector-to-points.svg";
@@ -398,9 +399,6 @@ export const ICON_16X16_NODES = {
NodeAsGraphic: { svg: NodeAsGraphic, size: 16 },
NodeAsInteger: { svg: NodeAsInteger, size: 16 },
NodeAsNumber: { svg: NodeAsNumber, size: 16 },
NodeAssignColors: { svg: NodeAssignColors, size: 16 },
NodeAssignRotations: { svg: NodeAssignRotations, size: 16 },
NodeAssignScales: { svg: NodeAssignScales, size: 16 },
NodeAsString: { svg: NodeAsString, size: 16 },
NodeAsVector: { svg: NodeAsVector, size: 16 },
NodeAverage: { svg: NodeAverage, size: 16 },
@@ -468,7 +466,6 @@ export const ICON_16X16_NODES = {
NodeFilter: { svg: NodeFilter, size: 16 },
NodeFlattenColor: { svg: NodeFlattenColor, size: 16 },
NodeFlattenGradient: { svg: NodeFlattenGradient, size: 16 },
NodeFlattenGraphic: { svg: NodeFlattenGraphic, size: 16 },
NodeFlattenRaster: { svg: NodeFlattenRaster, size: 16 },
NodeFlattenVector: { svg: NodeFlattenVector, size: 16 },
NodeFloor: { svg: NodeFloor, size: 16 },
@@ -494,6 +491,7 @@ export const ICON_16X16_NODES = {
NodeGreaterThan: { svg: NodeGreaterThan, size: 16 },
NodeGreatestCommonDivisor: { svg: NodeGreatestCommonDivisor, size: 16 },
NodeGrid: { svg: NodeGrid, size: 16 },
NodeGroup: { svg: NodeGroup, size: 16 },
NodeHeart: { svg: NodeHeart, size: 16 },
NodeHslaToColor: { svg: NodeHslaToColor, size: 16 },
NodeHsvaToColor: { svg: NodeHsvaToColor, size: 16 },
@@ -504,7 +502,6 @@ export const ICON_16X16_NODES = {
NodeImageToChannels: { svg: NodeImageToChannels, size: 16 },
NodeIndexPoints: { svg: NodeIndexPoints, size: 16 },
NodeIndices: { svg: NodeIndices, size: 16 },
NodeIntoGroup: { svg: NodeIntoGroup, size: 16 },
NodeInvert: { svg: NodeInvert, size: 16 },
NodeInvertTransform: { svg: NodeInvertTransform, size: 16 },
NodeIsNonzero: { svg: NodeIsNonzero, size: 16 },
@@ -652,7 +649,12 @@ export const ICON_16X16_NODES = {
NodeThreshold: { svg: NodeThreshold, size: 16 },
NodeTransform: { svg: NodeTransform, size: 16 },
NodeTriangulate: { svg: NodeTriangulate, size: 16 },
NodeUngroup: { svg: NodeUngroup, size: 16 },
NodeUnweld: { svg: NodeUnweld, size: 16 },
NodeVaryFillColors: { svg: NodeVaryFillColors, size: 16 },
NodeVaryRotations: { svg: NodeVaryRotations, size: 16 },
NodeVaryScales: { svg: NodeVaryScales, size: 16 },
NodeVaryStrokeColors: { svg: NodeVaryStrokeColors, size: 16 },
NodeVec2ToNumbers: { svg: NodeVec2ToNumbers, size: 16 },
NodeVec2Value: { svg: NodeVec2Value, size: 16 },
NodeVectorToPoints: { svg: NodeVectorToPoints, size: 16 },
+23 -4
View File
@@ -628,10 +628,15 @@ impl TaggedValue {
}
pub fn from_primitive_string(string: &str, ty: &Type) -> Option<Self> {
fn to_number<T: FromStr>(input: &str) -> Option<T> {
// Stringified tokens separate a negative number's minus sign from its digits (e.g. "- 180.")
input.split_whitespace().collect::<String>().parse().ok()
}
fn to_dvec2(input: &str) -> Option<DVec2> {
let mut split = input.split(',');
let x = split.next()?.trim().parse().ok()?;
let y = split.next()?.trim().parse().ok()?;
let x = to_number(split.next()?)?;
let y = to_number(split.next()?)?;
Some(DVec2::new(x, y))
}
@@ -715,8 +720,8 @@ impl TaggedValue {
let ty = match () {
() if ty == TypeId::of::<()>() => TaggedValue::None,
() if ty == TypeId::of::<String>() => TaggedValue::String(string.into()),
() if ty == TypeId::of::<f64>() => FromStr::from_str(string).map(TaggedValue::Number).ok()?,
() if ty == TypeId::of::<i64>() => FromStr::from_str(string).map(TaggedValue::Integer).ok()?,
() if ty == TypeId::of::<f64>() => to_number(string).map(TaggedValue::Number)?,
() if ty == TypeId::of::<i64>() => to_number(string).map(TaggedValue::Integer)?,
() if ty == TypeId::of::<DVec2>() => to_dvec2(string).map(TaggedValue::DVec2)?,
() if ty == TypeId::of::<bool>() => FromStr::from_str(string).map(TaggedValue::Bool).ok()?,
() if ty == TypeId::of::<Color>() => to_color(string).map(TaggedValue::Color)?,
@@ -1073,6 +1078,20 @@ mod paint_default_parsing {
}
}
#[cfg(test)]
mod number_default_parsing {
use super::*;
use core_types::item;
/// A negative default reaches the parser as stringified tokens, with a space between the minus sign and the digits.
#[test]
fn negative_number_defaults_parse() {
assert_eq!(TaggedValue::from_primitive_string("- 180.", &item!(f64)), Some(TaggedValue::Number(-180.)));
assert_eq!(TaggedValue::from_primitive_string("- 3", &item!(i64)), Some(TaggedValue::Integer(-3)));
assert_eq!(TaggedValue::from_primitive_string("- 1., 2.", &item!(DVec2)), Some(TaggedValue::DVec2(DVec2::new(-1., 2.))));
}
}
#[cfg(test)]
mod gradient_shape_migration {
use graphic_types::vector_types::{GradientSpace, GradientSpread};
+1
View File
@@ -28,6 +28,7 @@ preprocessor = { workspace = true }
document-format = { workspace = true, features = ["zip", "xz", "migrations"] }
document-container = { workspace = true, features = ["zip", "xz"] }
migration-formats = { workspace = true }
migration-compiled = { workspace = true }
migration-nodes = { workspace = true }
# Workspace dependencies
+3 -1
View File
@@ -23,6 +23,7 @@ use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
// Referenced so the linker keeps their self-registering migrations
use migration_compiled as _;
use migration_formats as _;
use migration_nodes as _;
@@ -37,7 +38,8 @@ pub struct OpenedDocument {
/// Open a `.gdd` from its archive bytes into memory, running the migrations this crate links.
pub async fn open_gdd(archive: &[u8]) -> Result<GddV1, Box<dyn Error>> {
let container = AnyContainer::Memory(MemoryBackend::new());
let gdd = GddV1::open_from_archive(archive, container, GddV1Layout)
let host = migration_compiled::CompilerHost::default();
let gdd = GddV1::open_from_archive_with(archive, container, GddV1Layout, None, Some(&host))
.await
.map_err(|error| format!("Failed to open document: {error}"))?;
Ok(gdd)
@@ -0,0 +1,78 @@
/// The effective midpoint domain: NaN reads as the linear default, and extremes are bounded to `0.01..=0.99` so curves stay finite and cheap to subdivide.
pub fn sanitized_midpoint(midpoint: f64) -> f64 {
if midpoint.is_nan() { 0.5 } else { midpoint.clamp(0.01, 0.99) }
}
/// Apply the midpoint curve to a normalized parameter `t` (0 to 1) given a `midpoint` (0 to 1, where 0.5 is linear).
pub fn apply_midpoint(t: f64, midpoint: f64) -> f64 {
let midpoint = sanitized_midpoint(midpoint);
if (midpoint - 0.5).abs() < 1e-6 {
return t;
}
if midpoint < 0.5 {
let q = -1. / (1. - midpoint).log2();
1. - (1. - t).powf(q)
} else {
let p = -1. / midpoint.log2();
t.powf(p)
}
}
/// The inverse of [`apply_midpoint`], which lands a halfway parameter (0.5) at the midpoint.
/// Applied to uniformly distributed values, this makes the midpoint their median.
pub fn apply_midpoint_inverse(t: f64, midpoint: f64) -> f64 {
let midpoint = sanitized_midpoint(midpoint);
if (midpoint - 0.5).abs() < 1e-6 {
return t;
}
if midpoint < 0.5 { 1. - (1. - t).powf(-(1. - midpoint).log2()) } else { t.powf(-midpoint.log2()) }
}
#[cfg(test)]
mod tests {
use super::*;
const MIDPOINTS: [f64; 7] = [0.01, 0.1, 0.3, 0.5, 0.7, 0.9, 0.99];
#[test]
fn inverse_undoes_the_curve() {
for midpoint in MIDPOINTS {
for step in 0..=20 {
let t = step as f64 / 20.;
let round_trip = apply_midpoint(apply_midpoint_inverse(t, midpoint), midpoint);
assert!((round_trip - t).abs() < 1e-9, "midpoint {midpoint} took {t} to {round_trip}");
}
}
}
#[test]
fn inverse_lands_halfway_at_the_midpoint() {
for midpoint in MIDPOINTS {
assert!((apply_midpoint_inverse(0.5, midpoint) - midpoint).abs() < 1e-9);
assert!((apply_midpoint(midpoint, midpoint) - 0.5).abs() < 1e-9);
}
}
#[test]
fn opposite_midpoints_mirror_each_other() {
for midpoint in MIDPOINTS {
for step in 0..=20 {
let t = step as f64 / 20.;
let mirrored = 1. - apply_midpoint_inverse(1. - t, 1. - midpoint);
assert!((apply_midpoint_inverse(t, midpoint) - mirrored).abs() < 1e-9);
}
}
}
#[test]
fn curves_keep_their_endpoints() {
for midpoint in [0., 0.25, 0.5, 0.75, 1., f64::NAN] {
for curve in [apply_midpoint, apply_midpoint_inverse] {
assert_eq!(curve(0., midpoint), 0.);
assert_eq!(curve(1., midpoint), 1.);
}
}
}
}
@@ -1,5 +1,7 @@
pub mod bbox;
pub mod float_noise;
pub mod midpoint;
pub mod polynomial;
pub mod quad;
pub mod rect;
pub mod spread;
@@ -0,0 +1,45 @@
use rand::{Rng, SeedableRng};
/// Gives each of `count` items a factor from 0 to 1, either spread evenly in item order or drawn at random from the `seed`.
/// The even spread restarts after every `repeat_every` items, unless it is 0 to span all the items once.
pub fn spread_factors(count: usize, randomize: bool, seed: u64, repeat_every: u64) -> impl Iterator<Item = f64> {
let mut rng = rand::rngs::StdRng::seed_from_u64(seed);
(0..count).map(move |index| match (randomize, repeat_every) {
(true, _) => rng.random::<f64>(),
(false, 0) => index as f64 / count.saturating_sub(1).max(1) as f64,
(false, 1) => 0.,
(false, _) => (index as u64 % repeat_every) as f64 / (repeat_every - 1) as f64,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn even_spread_spans_the_range_once() {
let factors: Vec<f64> = spread_factors(5, false, 0, 0).collect();
assert_eq!(factors, [0., 0.25, 0.5, 0.75, 1.]);
assert_eq!(spread_factors(1, false, 0, 0).collect::<Vec<_>>(), [0.]);
assert_eq!(spread_factors(0, false, 0, 0).count(), 0);
}
#[test]
fn even_spread_repeats() {
let factors: Vec<f64> = spread_factors(7, false, 0, 3).collect();
assert_eq!(factors, [0., 0.5, 1., 0., 0.5, 1., 0.]);
assert!(spread_factors(4, false, 0, 1).all(|factor| factor == 0.));
}
#[test]
fn random_spread_follows_the_seed() {
let draws = |seed| spread_factors(8, true, seed, 0).collect::<Vec<_>>();
assert_eq!(draws(42), draws(42));
assert_ne!(draws(42), draws(43));
assert!(draws(42).iter().all(|factor| (0. ..1.).contains(factor)));
}
}
@@ -1,6 +1,7 @@
use core_types::Color;
use core_types::color::SRGBA8;
use core_types::list::{ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_MIDPOINT, ATTR_POSITION, Item, List};
use core_types::math::midpoint::{apply_midpoint, sanitized_midpoint};
use dyn_any::DynAny;
use glam::{DAffine2, DVec2};
@@ -323,27 +324,6 @@ impl From<Vec<Color>> for Gradient {
/// deviate by no more than 2 gradations of 8-bit color from the theoretically perfect curve.
const SAMPLE_THRESHOLD: f64 = 2. / 255.;
/// The effective midpoint domain shared by sampling and rendering: NaN reads as the linear default, and extremes are bounded to `0.01..=0.99` so curves stay finite and cheap to subdivide.
fn sanitized_midpoint(midpoint: f64) -> f64 {
if midpoint.is_nan() { 0.5 } else { midpoint.clamp(0.01, 0.99) }
}
/// Apply the midpoint curve to a normalized parameter `t` (0 to 1) given a `midpoint` (0 to 1, where 0.5 is linear).
fn apply_midpoint(t: f64, midpoint: f64) -> f64 {
let midpoint = sanitized_midpoint(midpoint);
if (midpoint - 0.5).abs() < 1e-6 {
return t;
}
if midpoint < 0.5 {
let q = -1. / (1. - midpoint).log2();
1. - (1. - t).powf(q)
} else {
let p = -1. / midpoint.log2();
t.powf(p)
}
}
/// Calls a color-space-generic function with the `color` crate space matching a [`GradientSpace`] variant.
macro_rules! with_space {
($gradient_space:expr, $function:ident $(, $argument:expr)* $(,)?) => {
@@ -406,35 +406,83 @@ fn upload_pixels(device: &wgpu::Device, queue: &wgpu::Queue, pixels: &[u8], widt
let (texture_width, texture_height) = image_texture_size(width, height, max_texture_size);
let pixels = if factor == 1 { premultiplied } else { box_downscale(&premultiplied, width, height, factor) };
let texture = create_texture(
device,
"vello_gpu_image",
UVec2::new(texture_width, texture_height),
wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
);
queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &texture,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
&pixels,
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(4 * texture_width),
rows_per_image: Some(texture_height),
},
wgpu::Extent3d {
// Each mipmap level halves the one before it, so a minified image averages its pixels rather than skipping over them
let level_count = texture_width.max(texture_height).ilog2() + 1;
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("vello_gpu_image"),
size: wgpu::Extent3d {
width: texture_width,
height: texture_height,
depth_or_array_layers: 1,
},
);
mip_level_count: level_count,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: TEXTURE_FORMAT,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
let (mut level_pixels, mut level_width, mut level_height) = (pixels, texture_width, texture_height);
for level in 0..level_count {
if level > 0 {
(level_pixels, level_width, level_height) = halve_for_mipmap(&level_pixels, level_width, level_height);
}
queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &texture,
mip_level: level,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
&level_pixels,
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(4 * level_width),
rows_per_image: Some(level_height),
},
wgpu::Extent3d {
width: level_width,
height: level_height,
depth_or_array_layers: 1,
},
);
}
Some(texture)
}
/// Halves premultiplied RGBA8 pixels to the next mipmap level's size, which rounds down, so the last pixel of each row and column of an odd side averages three.
/// O(width × height).
fn halve_for_mipmap(pixels: &[u8], width: u32, height: u32) -> (Vec<u8>, u32, u32) {
let (half_width, half_height) = ((width / 2).max(1), (height / 2).max(1));
// The source pixels along one side that an output pixel averages
let span = |index: u32, half: u32, full: u32| {
let start = index * 2;
let end = if index + 1 == half { full } else { start + 2 };
start..end.clamp(start + 1, full)
};
let mut output = Vec::with_capacity((half_width * half_height * 4) as usize);
for output_y in 0..half_height {
for output_x in 0..half_width {
let mut sums = [0_u32; 4];
let mut count = 0;
for y in span(output_y, half_height, height) {
for x in span(output_x, half_width, width) {
let index = ((y * width + x) * 4) as usize;
sums.iter_mut().zip(&pixels[index..index + 4]).for_each(|(sum, channel)| *sum += *channel as u32);
count += 1;
}
}
output.extend(sums.map(|sum| ((sum + count / 2) / count) as u8));
}
}
(output, half_width, half_height)
}
/// Averages each `factor` by `factor` block of RGBA8 pixels, letting blocks at the right and bottom edges average only the pixels they have.
fn box_downscale(pixels: &[u8], width: u32, height: u32, factor: u32) -> Vec<u8> {
let (output_width, output_height) = (width.div_ceil(factor), height.div_ceil(factor));
@@ -274,6 +274,32 @@ fn degenerate_strokes_render() {
let Some(_) = render(size, draw) else { return };
}
#[test]
fn minified_images_average_their_pixels() {
use raster_types::{Image, Raster};
// Stripes half black and half white in every eight columns, drawn at an eighth of their size, where sampling only the two
// columns nearest each pixel's center would find black
let stripes = Image {
width: 64,
height: 64,
data: (0..64 * 64)
.map(|index| if (2..6).contains(&(index % 8)) { core_types::Color::BLACK } else { core_types::Color::WHITE })
.collect(),
};
let stripes = Raster::new_cpu(stripes);
let draw = |scene: &mut VelloSceneBuilder| scene.draw_raster(stripes.clone(), peniko::ImageSampler::new(), Affine::scale(1. / 8.));
let size = UVec2::new(8, 8);
let Some(pixels) = render(size, draw) else { return };
for (index, pixel) in pixels.iter().enumerate() {
assert!(
(115..=140).contains(&pixel[0]) && pixel[1] == pixel[0] && pixel[2] == pixel[0] && pixel[3] == 255,
"pixel {index} is {pixel:?} rather than the gray of its average"
);
}
}
#[test]
fn rasters_upload_once_across_scenes_until_modified() {
use raster_types::{Image, Raster};
+2 -2
View File
@@ -956,7 +956,7 @@ fn legacy_layer_extend<T: Send + Clone>(
/// Nests the input graphical content in a wrapper graphic, collecting it all into a single group.
/// The inverse of this node is 'Flatten Graphic'.
#[node_macro::node(category("Graphic"), icon("NodeIntoGroup"))]
#[node_macro::node(category("Graphic"), icon("NodeGroup"))]
fn into_group<T: Into<Graphic>>(
_: impl Ctx,
#[implementations(
@@ -984,7 +984,7 @@ fn as_graphic(_: impl Ctx, value: Item<Graphic>) -> Item<Graphic> {
}
/// Removes a level of nesting from a `Graphic[]`, or all nesting if "Fully Flatten" is enabled.
#[node_macro::node(category("Graphic"), icon("NodeFlattenGraphic"))]
#[node_macro::node(category("Graphic"), icon("NodeUngroup"))]
fn flatten_graphic(_: impl Ctx, content: List<Graphic>, fully_flatten: Item<bool>) -> List<Graphic> {
let fully_flatten = fully_flatten.into_element();
@@ -1,6 +1,8 @@
use core::f64;
use core_types::color::Color;
use core_types::list::{Item, List};
use core_types::math::midpoint::apply_midpoint_inverse;
use core_types::math::spread::spread_factors;
use core_types::transform::{ApplyTransform, ScaleType, Transform};
use core_types::{ATTR_TRANSFORM, CloneVarArgs, Context, Ctx, ExtractAll, InjectFootprint, Interrupt, ModifyFootprint, OwnedContextImpl};
use glam::{DAffine2, DMat2, DVec2};
@@ -216,3 +218,224 @@ fn decompose_scale(_: impl Ctx, transform: Item<DAffine2>, scale_type: Item<Scal
fn decompose_skew(_: impl Ctx, transform: Item<DAffine2>) -> Item<f64> {
Item::new_from_element(transform.into_element().decompose_skew().atan().to_degrees())
}
/// Rotates every item of the content about its origin by its own angle, selected from along a chosen range.
#[node_macro::node(category("Transform"), icon("NodeVaryRotations"))]
fn vary_rotations<T: Send>(
_: impl Ctx,
/// The content with items to rotate individually.
#[implementations(List<Graphic>, List<Vector>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<Gradient>, List<String>)]
content: List<T>,
/// The lower end of the range of angles given to the items.
#[unit("°")]
#[range]
#[soft(-180..180)]
#[default(-180.)]
min: Item<f64>,
/// The upper end of the range of angles given to the items.
#[unit("°")]
#[range]
#[soft(-180..180)]
#[default(180.)]
max: Item<f64>,
/// Where in the range the median angle falls, from its lower end (0) to its upper end (1). The default of 0.5 spreads the angles uniformly, while other values favor angles nearer one end.
#[range]
#[hard(0..1)]
#[default(0.5)]
bias: Item<f64>,
/// Whether to reverse the range.
reverse: Item<bool>,
/// Whether to randomize the angle selection for each item from throughout the range.
#[default(true)]
randomize: Item<bool>,
/// Seed to determine unique variations on the randomized angle selection.
#[widget(ParsedWidgetOverride::Custom = "vary_rotations_seed")]
#[hard(0..)]
seed: Item<i64>,
/// The number of items to span across the range before repeating. A 0 value will span the entire range once.
#[widget(ParsedWidgetOverride::Custom = "vary_rotations_repeat_every")]
#[hard(0..)]
repeat_every: Item<i64>,
) -> List<T> {
let (min, max, bias, reverse) = (min.into_element(), max.into_element(), bias.into_element(), reverse.into_element());
let (randomize, seed, repeat_every) = (randomize.into_element(), seed.into_element(), repeat_every.into_element());
let mut content = content;
let factors = item_factors(content.len(), randomize, seed, repeat_every, reverse);
for (transform, factor) in content.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM).zip(factors) {
let angle = min + (max - min) * apply_midpoint_inverse(factor, bias);
// Turning only the linear part pivots each item about its own origin, in the axes of its parent
transform.matrix2 = DMat2::from_angle(angle.to_radians()) * transform.matrix2;
}
content
}
/// Scales every item of the content about its origin by its own factor, selected from along a chosen range.
#[node_macro::node(category("Transform"), icon("NodeVaryScales"))]
fn vary_scales<T: Send>(
_: impl Ctx,
/// The content with items to scale individually.
#[implementations(List<Graphic>, List<Vector>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<Gradient>, List<String>)]
content: List<T>,
/// The lower end of the range of scale factors given to the items.
#[unit("x")]
#[range]
#[soft(0..2)]
#[default(0.5)]
min: Item<f64>,
/// The upper end of the range of scale factors given to the items.
#[unit("x")]
#[range]
#[soft(0..2)]
#[default(2.)]
max: Item<f64>,
/// Where in the range the median scale factor falls, from its lower end (0) to its upper end (1). The default of 0.5 spreads the scale factors uniformly, while other values favor scale factors nearer one end.
#[range]
#[hard(0..1)]
#[default(0.5)]
bias: Item<f64>,
/// Whether to reverse the range.
reverse: Item<bool>,
/// Whether to randomize the scale factor selection for each item from throughout the range.
#[default(true)]
randomize: Item<bool>,
/// Seed to determine unique variations on the randomized scale factor selection.
#[widget(ParsedWidgetOverride::Custom = "vary_scales_seed")]
#[hard(0..)]
seed: Item<i64>,
/// The number of items to span across the range before repeating. A 0 value will span the entire range once.
#[widget(ParsedWidgetOverride::Custom = "vary_scales_repeat_every")]
#[hard(0..)]
repeat_every: Item<i64>,
) -> List<T> {
let (min, max, bias, reverse) = (min.into_element(), max.into_element(), bias.into_element(), reverse.into_element());
let (randomize, seed, repeat_every) = (randomize.into_element(), seed.into_element(), repeat_every.into_element());
let mut content = content;
let factors = item_factors(content.len(), randomize, seed, repeat_every, reverse);
for (transform, factor) in content.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM).zip(factors) {
let scale = min + (max - min) * apply_midpoint_inverse(factor, bias);
transform.matrix2 *= scale;
}
content
}
/// The spread factor of each item for a vary node, handed out from the last item to the first when reversed.
fn item_factors(count: usize, randomize: bool, seed: i64, repeat_every: i64, reverse: bool) -> Vec<f64> {
let mut factors: Vec<f64> = spread_factors(count, randomize, seed as u64, repeat_every as u64).collect();
if reverse {
factors.reverse();
}
factors
}
#[cfg(test)]
mod test {
use super::*;
fn colors(transforms: &[DAffine2]) -> List<Color> {
transforms
.iter()
.map(|&transform| Item::new_from_element(Color::RED).with_attribute(ATTR_TRANSFORM, transform))
.collect()
}
fn transforms<T>(content: &List<T>) -> Vec<DAffine2> {
(0..content.len()).map(|index| content.attribute_cloned_or_default(ATTR_TRANSFORM, index)).collect()
}
fn item<T>(element: T) -> Item<T> {
Item::new_from_element(element)
}
fn rotate(content: List<Color>, min: f64, max: f64, bias: f64, reverse: bool) -> List<Color> {
vary_rotations((), content, item(min), item(max), item(bias), item(reverse), item(false), item(0), item(0))
}
fn scale(content: List<Color>, min: f64, max: f64, bias: f64, randomize: bool) -> List<Color> {
vary_scales((), content, item(min), item(max), item(bias), item(false), item(randomize), item(0), item(0))
}
fn angles(content: &List<Color>) -> Vec<f64> {
transforms(content).iter().map(|transform| transform.decompose_rotation().to_degrees()).collect()
}
fn assert_near(actual: &[f64], expected: &[f64]) {
assert_eq!(actual.len(), expected.len());
for (actual, expected) in actual.iter().zip(expected) {
assert!((actual - expected).abs() < 1e-9, "expected {expected:?}, found {actual:?}");
}
}
#[test]
fn rotations_spread_evenly_across_the_range() {
let rotated = rotate(colors(&[DAffine2::IDENTITY; 3]), 0., 90., 0.5, false);
assert_near(&angles(&rotated), &[0., 45., 90.]);
let reversed = rotate(colors(&[DAffine2::IDENTITY; 3]), 0., 90., 0.5, true);
assert_near(&angles(&reversed), &[90., 45., 0.]);
}
#[test]
fn reverse_runs_the_randomized_pattern_from_the_other_end() {
let randomized = |reverse| {
angles(&vary_rotations(
(),
colors(&[DAffine2::IDENTITY; 5]),
item(0.),
item(90.),
item(0.3),
item(reverse),
item(true),
item(7),
item(0),
))
};
let mut forward = randomized(false);
forward.reverse();
assert_near(&randomized(true), &forward);
}
#[test]
fn bias_places_the_middle_item() {
let rotated = rotate(colors(&[DAffine2::IDENTITY; 3]), 0., 100., 0.2, false);
assert_near(&angles(&rotated), &[0., 20., 100.]);
}
#[test]
fn rotation_pivots_about_the_item_origin_without_shearing() {
let original = DAffine2::from_translation(DVec2::new(5., 7.)) * DAffine2::from_scale(DVec2::new(2., 1.));
let rotated = transforms(&rotate(colors(&[original]), 90., 90., 0.5, false))[0];
assert_eq!(rotated.translation, original.translation);
assert!(rotated.matrix2.x_axis.abs_diff_eq(DVec2::new(0., 2.), 1e-9));
assert!(rotated.matrix2.y_axis.abs_diff_eq(DVec2::new(-1., 0.), 1e-9));
}
#[test]
fn scales_keep_the_item_origin() {
let original = DAffine2::from_translation(DVec2::new(5., 7.));
let scaled = transforms(&scale(colors(&[original; 2]), 1., 3., 0.5, false));
assert_eq!(scaled[0], original);
assert_eq!(scaled[1], DAffine2::from_scale_angle_translation(DVec2::splat(3.), 0., original.translation));
}
#[test]
fn extreme_biases_stay_within_the_range() {
for bias in [0., 1.] {
for transform in transforms(&scale(colors(&[DAffine2::IDENTITY; 64]), 1., 2., bias, true)) {
let factor = transform.matrix2.x_axis.length();
assert!((1. ..=2.).contains(&factor), "bias {bias} gave scale {factor}");
}
}
}
}
+101 -212
View File
@@ -6,6 +6,7 @@ use core::hash::{Hash, Hasher};
use core_types::blending::BlendMode;
use core_types::bounds::{BoundingBox, RenderBoundingBox};
use core_types::list::{ATTR_APPEARANCE, ATTR_ID, ATTR_PATHS, Item, ItemAttributeValues, List, ListDyn, NodeIdPath};
use core_types::math::spread::spread_factors;
use core_types::transform::{Footprint, Transform};
use core_types::uuid::NodeId;
use core_types::{
@@ -78,7 +79,7 @@ fn next_working_segment_id(working: &WorkingVector) -> SegmentId {
}
/// Implemented for `List` types that contain vector items reachable via mutable access.
/// Used by the whole-collection Assign Colors node so it can apply to either `List<Graphic>` or `List<Vector>`.
/// Used by the whole-collection Vary Fill Colors and Vary Stroke Colors nodes so they can apply to either `List<Graphic>` or `List<Vector>`.
trait VectorListIterMut {
fn for_each_vector_list_mut(&mut self, f: impl FnMut(&mut List<Vector>));
@@ -275,49 +276,87 @@ impl ExpandVectorItems for Graphic {
}
#[derive(Debug, thiserror::Error)]
pub enum AssignColorsError {
pub enum VaryColorsError {
#[error("The gradient has no colors to assign")]
EmptyGradient,
}
/// Uniquely sets the fill and/or stroke style of every vector element to individual colors sampled along a chosen gradient.
#[node_macro::node(category("Vector: Style"), icon("NodeAssignColors"), path(graphene_core::vector))]
fn assign_colors<T>(
/// Uniquely recolors the fill of every vector element to individual colors sampled along a chosen gradient.
#[node_macro::node(category("Vector: Style"), icon("NodeVaryFillColors"), path(graphene_core::vector))]
fn vary_fill_colors<T>(
_: impl Ctx,
/// The content with vector paths to apply the fill and/or stroke style to.
/// The content with vector paths to apply the fill style to.
#[implementations(List<Graphic>, List<Vector>)]
#[widget(ParsedWidgetOverride::Hidden)]
content: T,
/// Whether to style the fill.
#[default(true)]
fill: Item<bool>,
/// Whether to style the stroke.
stroke: Item<bool>,
/// The range of colors to select from.
#[default(Color::BLACK, Color::WHITE)]
#[widget(ParsedWidgetOverride::Custom = "assign_colors_gradient")]
#[widget(ParsedWidgetOverride::Custom = "vary_fill_colors_gradient")]
gradient: Item<Gradient>,
/// Whether to reverse the gradient.
reverse: Item<bool>,
/// Whether to randomize the color selection for each element from throughout the gradient.
randomize: Item<bool>,
/// Seed to determine unique variations on the randomized color selection.
#[widget(ParsedWidgetOverride::Custom = "assign_colors_seed")]
#[widget(ParsedWidgetOverride::Custom = "vary_fill_colors_seed")]
#[hard(0..)]
seed: Item<i64>,
/// 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")]
#[widget(ParsedWidgetOverride::Custom = "vary_fill_colors_repeat_every")]
#[hard(0..)]
repeat_every: Item<i64>,
) -> Result<T, AssignColorsError>
) -> Result<T, VaryColorsError>
where
T: VectorListIterMut + Send,
{
let (fill, stroke, reverse, randomize) = (fill.into_element(), stroke.into_element(), reverse.into_element(), randomize.into_element());
let (seed, repeat_every) = (seed.into_element(), repeat_every.into_element());
vary_cover_colors(content, Cover::Fill, gradient, reverse, randomize, seed, repeat_every)
}
if (fill || stroke) && gradient.element().is_empty() {
return Err(AssignColorsError::EmptyGradient);
/// Uniquely recolors the stroke of every vector element to individual colors sampled along a chosen gradient.
#[node_macro::node(category("Vector: Style"), icon("NodeVaryStrokeColors"), path(graphene_core::vector))]
fn vary_stroke_colors<T>(
_: impl Ctx,
/// The content with vector paths to apply the stroke style to.
#[implementations(List<Graphic>, List<Vector>)]
#[widget(ParsedWidgetOverride::Hidden)]
content: T,
/// The range of colors to select from.
#[default(Color::BLACK, Color::WHITE)]
#[widget(ParsedWidgetOverride::Custom = "vary_stroke_colors_gradient")]
gradient: Item<Gradient>,
/// Whether to reverse the gradient.
reverse: Item<bool>,
/// Whether to randomize the color selection for each element from throughout the gradient.
randomize: Item<bool>,
/// Seed to determine unique variations on the randomized color selection.
#[widget(ParsedWidgetOverride::Custom = "vary_stroke_colors_seed")]
#[hard(0..)]
seed: Item<i64>,
/// The number of elements to span across the gradient before repeating. A 0 value will span the entire gradient once.
#[widget(ParsedWidgetOverride::Custom = "vary_stroke_colors_repeat_every")]
#[hard(0..)]
repeat_every: Item<i64>,
) -> Result<T, VaryColorsError>
where
T: VectorListIterMut + Send,
{
vary_cover_colors(content, Cover::Stroke, gradient, reverse, randomize, seed, repeat_every)
}
/// Paints the fill or stroke of each vector element with its own color from along the gradient, for the Vary Fill Colors and Vary Stroke Colors nodes.
fn vary_cover_colors<T: VectorListIterMut>(
content: T,
cover: Cover,
gradient: Item<Gradient>,
reverse: Item<bool>,
randomize: Item<bool>,
seed: Item<i64>,
repeat_every: Item<i64>,
) -> Result<T, VaryColorsError> {
let (reverse, randomize, seed, repeat_every) = (reverse.into_element(), randomize.into_element(), seed.into_element(), repeat_every.into_element());
if gradient.element().is_empty() {
return Err(VaryColorsError::EmptyGradient);
}
let mut content = content;
@@ -331,42 +370,33 @@ where
let gradient = if reverse { element.reversed(settings.cyclic) } else { element };
let evaluator = gradient.evaluator(settings);
let mut rng = rand::rngs::StdRng::seed_from_u64(seed as u64);
let mut factors = spread_factors(length, randomize, seed as u64, repeat_every as u64);
let mut i: usize = 0;
content.for_each_vector_list_mut(|vector_list| {
for index in 0..vector_list.len() {
let factor = match randomize {
true => rng.random::<f64>(),
false => match repeat_every {
0 => i as f64 / (length - 1).max(1) as f64,
1 => 0.,
_ => i as f64 % repeat_every as f64 / (repeat_every - 1) as f64,
},
};
let factor = factors.next().unwrap_or_default();
let color = evaluator.evaluate(factor);
let color_paint = Graphic::ColorList(List::new_from_element(color));
if fill {
vector_list.with_attribute_mut_or_default::<Appearance, _, _>(ATTR_APPEARANCE, index, |appearance| {
match cover {
Cover::Fill => vector_list.with_attribute_mut_or_default::<Appearance, _, _>(ATTR_APPEARANCE, index, |appearance| {
if !appearance.set_paint_of(Cover::Fill, color_paint.clone()) {
appearance.replace_or_insert(Coverage::new_fill(), color_paint.clone(), CoverPlacement::Below);
}
});
}),
// The stroke recolor is gated on an existing stroke coverage, since restyling never adds a stroke
Cover::Stroke => {
if vector_list
.attribute::<Appearance>(ATTR_APPEARANCE, index)
.is_some_and(|appearance| appearance.has_cover(Cover::Stroke))
{
vector_list.with_attribute_mut_or_default::<Appearance, _, _>(ATTR_APPEARANCE, index, |appearance| {
appearance.set_paint_of(Cover::Stroke, color_paint.clone());
});
}
}
}
// The stroke recolor is gated on an existing stroke coverage, since restyling never adds a stroke
if stroke
&& vector_list
.attribute::<Appearance>(ATTR_APPEARANCE, index)
.is_some_and(|appearance| appearance.has_cover(Cover::Stroke))
{
vector_list.with_attribute_mut_or_default::<Appearance, _, _>(ATTR_APPEARANCE, index, |appearance| {
appearance.set_paint_of(Cover::Stroke, color_paint.clone());
});
}
i += 1;
}
});
@@ -543,103 +573,6 @@ fn dash_pattern(
Item::new_from_element(DashPattern::from(lengths))
}
#[node_macro::node(category("Graphic"), icon("NodeRepeatOnPoints"), name("Copy to Points"), path(core_types::vector))]
fn copy_to_points<I: Send + Clone>(
_: impl Ctx,
points: List<Vector>,
/// Artwork to be copied and placed at each point.
#[expose]
#[implementations(List<Graphic>, List<Vector>, List<String>, List<Raster<CPU>>, List<Color>, List<Gradient>)]
content: List<I>,
/// Minimum range of randomized sizes given to each placed copy.
#[default(1)]
#[range]
#[soft(0..2)]
#[unit("x")]
random_scale_min: Item<f64>,
/// Maximum range of randomized sizes given to each placed copy.
#[default(1)]
#[range]
#[soft(0..2)]
#[unit("x")]
random_scale_max: Item<f64>,
/// Bias for the probability distribution of randomized sizes (0 is uniform, negatives favor more of small sizes, positives favor more of large sizes).
#[range]
#[soft(-50..50)]
random_scale_bias: Item<f64>,
/// Seed to determine unique variations on all the randomized copy sizes.
#[hard(0..)]
random_scale_seed: Item<i64>,
/// Range of randomized angles given to each placed copy, in degrees ranging from furthest clockwise to counterclockwise.
#[unit("°")]
#[range]
#[soft(0..360)]
random_rotation: Item<f64>,
/// Seed to determine unique variations on all the randomized copy angles.
#[hard(0..)]
random_rotation_seed: Item<i64>,
) -> List<I> {
let (random_scale_min, random_scale_max, random_scale_bias) = (random_scale_min.into_element(), random_scale_max.into_element(), random_scale_bias.into_element());
let (random_scale_seed, random_rotation, random_rotation_seed) = (random_scale_seed.into_element(), random_rotation.into_element(), random_rotation_seed.into_element());
let mut result_list = List::new();
let random_scale_difference = random_scale_max - random_scale_min;
for row in points.into_iter() {
let mut scale_rng = rand::rngs::StdRng::seed_from_u64(random_scale_seed as u64);
let mut rotation_rng = rand::rngs::StdRng::seed_from_u64(random_rotation_seed as u64);
let do_scale = random_scale_difference.abs() > 1e-6;
let do_rotation = random_rotation.abs() > 1e-6;
let points_transform: DAffine2 = row.attribute_cloned_or_default(ATTR_TRANSFORM);
let row_paths = shared_paths_from_item_attributes(&row);
for point in row.element().anchor_positions(&row_paths) {
let translation = points_transform.transform_point2(point);
let rotation = if do_rotation {
let degrees = (rotation_rng.random::<f64>() - 0.5) * random_rotation;
degrees / 360. * TAU
} else {
0.
};
let scale = if do_scale {
if random_scale_bias.abs() < 1e-6 {
// Linear
random_scale_min + scale_rng.random::<f64>() * random_scale_difference
} else {
// Weighted (see <https://www.desmos.com/calculator/gmavd3m9bd>)
let random = scale_rng.random::<f64>();
let scale_factor = if random_scale_bias > 0. {
// Rearranged as `b + log2(r + (1 - r) 2^-b)` so a large bias can't overflow `2^b`, with the log floored at `-b` where `2^-b` underflows
1. + (random + (1. - random) * (-random_scale_bias).exp2()).log2().max(-random_scale_bias) / random_scale_bias
} else {
let horizontal_scale_factor = 1. - 2_f64.powf(random_scale_bias);
(1. - random * horizontal_scale_factor).log2() / random_scale_bias
};
random_scale_min + scale_factor * random_scale_difference
}
} else {
random_scale_min
};
let transform = DAffine2::from_scale_angle_translation(DVec2::splat(scale), rotation, translation);
for row_index in 0..content.len() {
let Some(mut row) = content.clone_item(row_index) else { continue };
let row_transform: DAffine2 = row.attribute_cloned_or_default(ATTR_TRANSFORM);
row.set_attribute(ATTR_TRANSFORM, transform * row_transform);
result_list.push(row);
}
}
}
result_list
}
#[node_macro::node(category("Vector: Path"), icon("NodeRoundCorners"), path(core_types::vector))]
fn round_corners<V: MapVectorItems + Send>(
_: impl Ctx,
@@ -4322,43 +4255,6 @@ mod test {
assert_eq!(manipulator_groups_anchors[i], expected_bounding_box[i]);
}
}
#[test]
fn copy_to_points() {
let points = Rect::new(-10., -10., 10., 10.).to_path(DEFAULT_ACCURACY);
let element = Rect::new(-1., -1., 1., 1.).to_path(DEFAULT_ACCURACY);
let expected_points = {
let (vector, paths) = Vector::from_bezpath(&points);
vector.anchor_positions(&paths)
};
let copy_to_points = super::copy_to_points(
Footprint::default(),
vector_node_from_bezpath(points),
vector_node_from_bezpath(element),
Item::new_from_element(1.),
Item::new_from_element(1.),
Item::new_from_element(0.),
Item::new_from_element(0),
Item::new_from_element(0.),
Item::new_from_element(0),
);
let combined = List::new_from_item(super::combine_paths(Footprint::default(), List::new_from_element(Graphic::VectorList(copy_to_points))));
let combined_paths = row_paths(&combined, 0);
let combined_copy_to_points = combined.element(0).unwrap();
assert_eq!(combined_copy_to_points.stroke_manipulator_groups(combined_paths).count(), expected_points.len());
for (index, (manipulator_groups, _)) in combined_copy_to_points.stroke_manipulator_groups(combined_paths).enumerate() {
let offset = expected_points[index];
let manipulator_groups_anchors = manipulator_groups.iter().map(|manipulators| manipulators.anchor).collect::<Vec<DVec2>>();
assert_eq!(
&manipulator_groups_anchors,
&[offset + DVec2::NEG_ONE, offset + DVec2::new(1., -1.), offset + DVec2::ONE, offset + DVec2::new(-1., 1.),]
);
}
}
#[test]
fn vector_to_points() {
let square = Rect::new(-10., -10., 10., 10.).to_path(DEFAULT_ACCURACY);
@@ -4945,15 +4841,13 @@ mod test {
// A rank-0 vector reaches the same per-list styling path as a vector list, rather than being skipped
#[test]
fn assign_colors_reaches_rank_0_vector_graphics() {
fn vary_fill_colors_reaches_rank_0_vector_graphics() {
let leaf = Graphic::Vector(Box::new(vector_item_from_bezpath(Rect::new(0., 0., 10., 10.).to_path(DEFAULT_ACCURACY))));
let content = List::new_from_element(leaf);
let styled = super::assign_colors(
let styled = super::vary_fill_colors(
Footprint::default(),
content,
Item::new_from_element(true),
Item::new_from_element(false),
Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE])),
Item::new_from_element(false),
Item::new_from_element(false),
@@ -5303,25 +5197,33 @@ mod test {
}
#[test]
fn assign_colors_from_an_empty_gradient() {
fn vary_colors_from_an_empty_gradient() {
let content = || List::new_from_item(vector_item_from_bezpath(Rect::new(0., 0., 10., 10.).to_path(DEFAULT_ACCURACY)));
let assign = |fill: bool| {
super::assign_colors(
(),
content(),
item(fill),
item(false),
item(Gradient::from(Vec::<Color>::new())),
item(false),
item(false),
item(0),
item(0),
)
};
let empty = || item(Gradient::from(Vec::<Color>::new()));
assert!(matches!(assign(true), Err(AssignColorsError::EmptyGradient)));
// With neither the fill nor the stroke styled, the gradient goes unused
assert!(assign(false).is_ok());
let fills = super::vary_fill_colors((), content(), empty(), item(false), item(false), item(0), item(0));
let strokes = super::vary_stroke_colors((), content(), empty(), item(false), item(false), item(0), item(0));
assert!(matches!(fills, Err(VaryColorsError::EmptyGradient)));
assert!(matches!(strokes, Err(VaryColorsError::EmptyGradient)));
}
#[test]
fn vary_stroke_colors_recolors_only_existing_strokes() {
let rect = || vector_item_from_bezpath(Rect::new(0., 0., 10., 10.).to_path(DEFAULT_ACCURACY));
let mut stroked = Appearance::default();
stroked.replace_or_insert(Coverage::new_stroke(&Stroke::new(4.)), Graphic::from(List::new_from_element(Color::BLACK)), CoverPlacement::Above);
let content: List<Vector> = [rect().with_attribute(ATTR_APPEARANCE, stroked), rect()].into_iter().collect();
let styled = super::vary_stroke_colors((), content, item(Gradient::from(vec![Color::WHITE])), item(false), item(false), item(0), item(0)).unwrap();
let stroke_paint = styled
.attribute::<Appearance>(ATTR_APPEARANCE, 0)
.and_then(|appearance| appearance.first_paint_of(Cover::Stroke).cloned());
assert_eq!(stroke_paint, Some(Graphic::ColorList(List::new_from_element(Color::WHITE))));
assert!(
!styled.attribute::<Appearance>(ATTR_APPEARANCE, 1).is_some_and(|appearance| appearance.has_cover(Cover::Stroke)),
"an element without a stroke should not gain one"
);
}
#[test]
@@ -5334,17 +5236,4 @@ mod test {
assert_eq!(solidified.element(0), Some(filled.element()));
assert_eq!(solidified.attribute::<Appearance>(ATTR_APPEARANCE, 0), filled.attribute::<Appearance>(ATTR_APPEARANCE));
}
#[test]
fn copy_to_points_with_a_large_scale_bias() {
let points = vector_node_from_bezpath(Rect::new(-10., -10., 10., 10.).to_path(DEFAULT_ACCURACY));
let content = vector_node_from_bezpath(Rect::new(-1., -1., 1., 1.).to_path(DEFAULT_ACCURACY));
let copies = super::copy_to_points((), points, content, item(1.), item(2.), item(2000.), item(0), item(0.), item(0));
for index in 0..copies.len() {
let transform: DAffine2 = copies.attribute_cloned_or_default(ATTR_TRANSFORM, index);
let scale = transform.matrix2.x_axis.length();
assert!((1. ..=2.).contains(&scale), "copy {index} has scale {scale}");
}
}
}
+2
View File
@@ -1,6 +1,8 @@
#[macro_use]
extern crate log;
mod value_types;
use graph_craft::Type;
use graph_craft::application_io::resource::ResourceId;
use graph_craft::document::value::*;
+157
View File
@@ -0,0 +1,157 @@
//! The compiler's answer to what type a wire carries, for document migrations.
use crate::Preprocessor;
use graph_craft::application_io::PlatformEditorApi;
use graph_craft::application_io::resource::ResourceId;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork};
use graph_craft::graphene_compiler::Compiler;
use graph_craft::proto::TypingContext;
use graph_craft::{Type, item};
use graphene_std::RuntimeHandle;
use graphene_std::platform_application_io::ResourceHash;
use interpreted_executor::node_registry::NODE_REGISTRY;
use std::collections::HashSet;
use std::sync::Arc;
impl Preprocessor {
/// The value type slot `slot` of `node` carries in `inlined`, a network with no definitions left, by compiling only what feeds that slot.
/// `None` where that doesn't compile, or where instances of the node in several networks disagree. Costs one compile per instance.
pub fn input_type(&self, inlined: &NodeNetwork, node: NodeId, slot: usize, resource_hash: &dyn Fn(ResourceId) -> Option<ResourceHash>) -> Option<Type> {
let instances: Vec<Vec<NodeId>> = inlined.recursive_nodes().filter(|(id, _, _)| **id == node).map(|(_, _, path)| path).collect();
let mut agreed = None;
for path in instances {
let input = inlined.nested_network(&path)?.nodes.get(&node)?.inputs.get(slot)?.clone();
let value_type = self.type_of_input(inlined, path, input, resource_hash)?;
if agreed.as_ref().is_some_and(|agreed| *agreed != value_type) {
return None;
}
agreed = Some(value_type);
}
agreed
}
/// Follows `input` out of networks and through hidden nodes to the output that gives it its type, then compiles that output alone.
pub fn type_of_input(&self, root: &NodeNetwork, mut path: Vec<NodeId>, mut input: NodeInput, resource_hash: &dyn Fn(ResourceId) -> Option<ResourceHash>) -> Option<Type> {
let (source, output_index) = loop {
match input {
NodeInput::Node { node_id, output_index } => {
let source = root.nested_network(&path)?.nodes.get(&node_id)?;
if source.visible {
break (node_id, output_index);
}
input = source.inputs.first()?.clone();
}
NodeInput::Import { import_index, .. } => {
let caller = path.pop()?;
input = root.nested_network(&path)?.nodes.get(&caller)?.inputs.get(import_index)?.clone();
}
_ => return None,
}
};
let mut pruned = root.clone();
let output_path: Vec<NodeId> = path.iter().copied().chain([source]).collect();
if !redirect_export_chain(&mut pruned, &output_path, output_index) {
return None;
}
pruned.exports.truncate(1);
pruned.remove_dead_nodes(0);
// The compiler asserts every wire resolves, which a stored document doesn't promise
if !wires_resolve(&pruned) {
return None;
}
// The scopes the runtime injects, given only as types since nothing is evaluated
let scope_stand_in = |value_type: Type| DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER),
inputs: vec![NodeInput::value(TaggedValue::TypeDefault(value_type), false)],
..Default::default()
};
let content = DocumentNode {
implementation: DocumentNodeImplementation::Network(pruned),
..Default::default()
};
let mut scoped = NodeNetwork {
exports: vec![NodeInput::node(NodeId(0), 0)],
nodes: [
(NodeId(0), content),
(NodeId(1), scope_stand_in(item!(Arc<PlatformEditorApi>))),
(NodeId(2), scope_stand_in(item!(RuntimeHandle))),
]
.into_iter()
.collect(),
scope_injections: [
("editor-api".to_string(), (NodeId(1), item!(Arc<PlatformEditorApi>))),
("runtime".to_string(), (NodeId(2), item!(RuntimeHandle))),
]
.into_iter()
.collect(),
definitions: Default::default(),
generated: true,
};
self.preprocess(&mut scoped, resource_hash).ok()?;
// The compiler asserts every scope input resolves, so content reading any other scope stays unresolved
if !scope_inputs_resolve(&scoped, &HashSet::new()) {
return None;
}
let proto_network = Compiler {}.compile_single(scoped).ok()?.network;
let mut typing_context = TypingContext::new(&NODE_REGISTRY);
typing_context.update(&proto_network).ok()?;
typing_context.type_of(proto_network.output).map(|types| types.return_value.clone())
}
}
/// Point the primary export at each level of `network` down through the nodes of `path`, unhiding each so the innermost node's output evaluates.
fn redirect_export_chain(network: &mut NodeNetwork, path: &[NodeId], output_index: usize) -> bool {
let Some((node_id, deeper_path)) = path.split_first() else { return true };
let export = NodeInput::node(*node_id, if deeper_path.is_empty() { output_index } else { 0 });
match network.exports.first_mut() {
Some(first) => *first = export,
None => network.exports.push(export),
}
let Some(node) = network.nodes.get_mut(node_id) else { return false };
node.visible = true;
if deeper_path.is_empty() {
return true;
}
match &mut node.implementation {
DocumentNodeImplementation::Network(nested) => redirect_export_chain(nested, deeper_path, output_index),
_ => false,
}
}
fn wires_resolve(network: &NodeNetwork) -> bool {
let resolves = |input: &NodeInput| !matches!(input, NodeInput::Node { node_id, .. } if !network.nodes.contains_key(node_id));
network.exports.iter().all(resolves)
&& network.nodes.values().all(|node| {
let nested_resolve = match &node.implementation {
DocumentNodeImplementation::Network(nested) => wires_resolve(nested),
_ => true,
};
node.inputs.iter().all(resolves) && nested_resolve
})
}
fn scope_inputs_resolve(network: &NodeNetwork, enclosing_scopes: &HashSet<String>) -> bool {
let scopes: HashSet<String> = enclosing_scopes.iter().cloned().chain(network.scope_injections.keys().cloned()).collect();
network.nodes.values().all(|node| {
let inputs_resolve = node.inputs.iter().all(|input| !matches!(input, NodeInput::Scope(key) if !scopes.contains(key.as_ref())));
let nested_resolve = match &node.implementation {
DocumentNodeImplementation::Network(nested) => scope_inputs_resolve(nested, &scopes),
_ => true,
};
inputs_resolve && nested_resolve
})
}
@@ -374,6 +374,16 @@ A naive rewrite evaluates `M` on a full state per delta. Instead, the runner:
A migration whose edits are only `Inputs` operations with constant values, and every rename, is an index map over input slots. The runner applies such migrations per delta without replaying states, remapping `ChangeNodeInput`, `SetNodeInputs`, `ChangeNodeInputAttribute`, `AddNode` payloads, and removal snapshots directly. The commutation test proves this fast path equal to the state path.
## The compiler and whole states
Some migrations need to know what only the compiler or executor can tell, such as the type flowing through a wire or a measurement of evaluated geometry. Storing types to answer this offline isn't an option, since `TypeId`s aren't stable across builds and `type_name` output isn't stable at all. So a migration asks for the compiler with an `Option<&dyn Compiler>` parameter, which the caller opening the document offers through a `MigrationHost`, and these are the costs, paid only by what uses them:
- **Whole states.** A delta in the middle of an interaction can leave a state no one ever saw, with nodes wired to what's not added yet, which reading the graph or compiling can only fail on. So a migration whose footprint reads the network runs at the boundaries undo can land on, the end of an interaction, a change of author, a branch point, or a cursor, and everything since the previous one becomes one chain. A history without interaction ends, such as an imported document's, is one evaluation. Bootstrapping marks its end, so the first edit after it is its own undo step.
- **Order.** The compiler can't describe what the binary no longer implements, so these migrations run as late as their dependencies allow, within the one ordered pass opening runs. Within one, an anchor only runs once no other anchor is upstream of it. The declarations it needs are loaded only then, from the caller's byte store and otherwise the container.
- **Failure.** There may be no compiler, and it may have no answer, so the migration must choose a fallback. A state that doesn't compile usually didn't before either, so there's nothing for a fallback to harm. Without a host the fallback is permanent, so the editor and CLI always offer one. A migration that itself fails falls back to truncating, as below.
- **Determinism.** The result depends on the build, so unlike the rest of this document, two peers can compute different `Rev`s. Such a rewrite only suits a document with one peer until settling is built.
- **Targets.** `Target` lets an anchor switch to any declaration its migration pins, which needs no version step, so documents holding a node that is only a target aren't rewritten for it.
## Errors and the truncate fallback
A migration reports two kinds of failure:
+1
View File
@@ -28,6 +28,7 @@ fn write_frontmatter(page: &mut std::fs::File) {
[extra]
order = 3
css = [\"/page/user-manual/node-catalog.css\"]
development_notice = true
+++
"
);
+1
View File
@@ -29,6 +29,7 @@ fn write_frontmatter(page: &mut std::fs::File, category: &str, order: usize) {
[extra]
order = {order}
css = [\"/page/user-manual/node-category.css\"]
development_notice = true
+++
"
);
+1
View File
@@ -57,6 +57,7 @@ fn write_frontmatter(page: &mut std::fs::File, metadata: &NodeMetadata, order: u
[extra]
order = {order}
css = [\"/page/user-manual/node.css\"]
development_notice = true
+++
"
);
@@ -13,7 +13,7 @@ Most changes need a node migration, written as a function in `document/migration
Bump a node's version when a document saved before your change would load wrongly after it. That includes adding, removing, reordering, or retyping an input, changing what an output means, moving the node to a new identifier, and replacing it with another node. It also includes behavior changes that keep the same inputs, like reading an angle in degrees instead of radians. Internal refactors don't need a bump.
CI compares every node's parameters and output against the base commit. It fails if they differ without a version bump, or if a node disappeared without a migration. It compares names as well as types, so renaming a parameter also asks for a bump. It can't see behavior changes, so those bumps are on you. Run the same check locally with `cargo run migration check --baseline master`.
CI compares every node's parameters and output against the base commit. It reports when they differ without a version bump, or when a node disappeared without a migration. It compares names as well as types, so renaming a parameter also asks for a bump. It can't see behavior changes, so those bumps are on you. Run the same check locally with `cargo run migration check --baseline master`.
### Writing one
@@ -83,9 +83,11 @@ You ask for what you need through the function's parameters, in any order. The f
|---|---|---|
| `&Node` | The anchor before migration | `id()`, `inputs()`, and the stored node's other accessors |
| `&Graph` | The anchor's network before migration | `node(id)`, `declaration(id)`, `consumers(output)` |
| `Option<&dyn Compiler>` | What only the compiler can tell about the state before migration, see [Asking the compiler](#asking-the-compiler) | `input_type(node, slot)` |
| `&mut Inputs` | The anchor's input slots | `set`, `insert`, `push`, `remove`, `truncate`, `len` |
| `&mut Upstream` | Nodes feeding the anchor | `add_node`, `add_node_keyed`, `remove_node` |
| `&mut Downstream` | Whatever reads the anchor's outputs | `consumers`, `add_node`, `add_node_keyed`, `connect` |
| `&mut Target` | Which declaration the anchor becomes, see [Choosing a target](#choosing-a-target) | `set` |
Reads always see the old document. `node.inputs()` returns the old layout however many edits you've made, and nodes you add never show up in `consumers`. `Inputs` edits apply in order to the layout being built. After `inputs.insert(1, ...)`, later `Inputs` calls see the old slot 1 as slot 2. `node.inputs()[1]` is still the old slot 1.
@@ -184,9 +186,42 @@ rename!("graphene_core::ops::AddNode"@1 => "math_nodes::AddNode"@2);
When the replacement also changes the inputs, scaffold a function with `cargo run migration new <old identifier>@<version> <identifier>`. The new node has to be at `version + 1`.
### Choosing a target
When a node splits into several, one target can't fit every anchor. `Target::set` switches this anchor to another declaration instead, named with `decl!` in the function body so the runner can order the migration against it. It can have any version, so a node that is only a target doesn't need a version bump, and documents that hold it but not the old node aren't rewritten. Only the target in the attribute has to be at `version + 1`.
```rust
/// Fill and stroke became separate nodes.
#[migration("vector_nodes::style"@1 => "vector_nodes::vary_fill"@2)]
pub fn vary_from_style(node: &Node, target: &mut Target) {
if literal_of::<Tagged>(&node.inputs()[STROKE].input).is_some_and(|stroke| stroke == Tagged::Bool(true)) {
target.set(decl!("vector_nodes::vary_stroke"@1));
}
}
```
A wire written to a removed node brings that node back, so avoid switching a wire on and off depending on state. Keep the slot reading the same thing, and add nodes downstream of the anchor instead.
### Asking the compiler
Which node a migration inserts can depend on the type flowing through a wire, such as a flatten node restoring what a group erased. Such a migration goes in the `migration-compiled` crate, which links the node crates, and takes `Option<&dyn Compiler>`. It compares with `element_is`, which only compares `type_name`s within the running build, so no type name is ever stored, and removing a type breaks the build rather than changing the result:
```rust
#[migration("vector_nodes::copy"@1 => "vector_nodes::flatten_graphic"@2)]
pub fn flatten_by_type(node: &Node, compiler: Option<&dyn Compiler>, target: &mut Target) {
if compiler.and_then(|compiler| compiler.input_type(node, CONTENT)).is_some_and(|value_type| value_type.element_is::<Vector>()) {
target.set(decl!("vector_nodes::flatten_vector"@1));
}
}
```
There may be no compiler, and it may not have an answer, for a state that doesn't compile or for what only exists at runtime, so always have a fallback. A migration reading `&Graph` or asking the compiler runs on whole states only: the end of each interaction, which is what undo can land on, with everything since the previous one rewritten as one step. A document imported without history is therefore one evaluation. Migrations asking the compiler run as late as their dependencies allow, with upstream anchors first, so what they ask about is usually in its current shape. A document holding none of their nodes never builds the compiler or loads a declaration for it.
Their result depends on the build, so peers on different builds can disagree, which is why other migrations should avoid the compiler wherever they can.
### What the function may depend on
A migration runs many times on one document, once per relevant step of its history, and every collaborator has to get the same result. So it can only depend on its parameters. Randomness, clocks, global state, and calls into live node code are all off limits.
A migration runs many times on one document, once per relevant step of its history, and every collaborator has to get the same result. So it can only depend on its parameters. Randomness, clocks, global state, and calls into live node code outside of the compiler are all off limits.
It also has to handle every state the old version allowed, including wired inputs and exposed literals. Return `MigrationError::invariant` if the old state breaks its own node's rules. Return `MigrationError::unrepresentable` if the new version can't express something the old one could, which usually means the new version should change. Both are bugs. If one fires on an old step of a document's history, the document opens with its history cut off at that point. If it fires on the current state, the document doesn't open.
+5
View File
@@ -38,6 +38,11 @@
width: 100%;
}
.development-notice {
padding: 12px 20px;
background: var(--color-lemon);
}
.prev-next {
display: flex;
justify-content: space-between;
+3
View File
@@ -77,6 +77,9 @@
</h1>
</div>
<article data-article>
{%- if page.extra.development_notice %}
<p class="development-notice">This page documents the development version of Graphite at <a href="https://dev.graphite.art">dev.graphite.art</a>, which may differ from the current release.</p>
{%- endif %}
{{ page.content | safe }}
</article>