Compare commits

..
Author SHA1 Message Date
Keavon Chambers b1db3026a2 Export each artboard as its own page of a PDF from the Export dialog 2026-11-26 02:58:11 -08:00
Keavon Chambers 91c7236e10 Encode one PDF scene into several pages, each showing a region of it 2026-11-26 02:58:11 -08:00
Keavon Chambers fa686d5063 Add PDF as a file type in the Export dialog 2026-11-26 02:58:11 -08:00
Keavon Chambers 7d8f124539 Add a krilla-backed PDF scene builder that the renderer can draw into 2026-11-26 02:58:11 -08:00
Keavon Chambers 78a1be4059 Make the renderer's Vello traversal generic over a scene builder trait 2026-11-26 02:58:10 -08:00
Keavon Chambers a7ed5fcf0f Show length and angle fields for inputs whose node rows call for them 2026-11-26 02:37:51 -08:00
Keavon Chambers 48fe21ebe3 Let the math nodes take lengths and angles and give them where meaningful 2026-11-26 02:37:51 -08:00
Keavon Chambers 0ab2f21e47 Make the Transform node and every pair of lengths or angles typed 2026-11-26 02:37:50 -08:00
Keavon Chambers d73bd34750 Show the units of length and angle parameters' defaults in the node docs 2026-11-26 02:37:14 -08:00
Keavon Chambers 4f999ea73b Show a range slider beside angle parameters bounded at both ends 2026-11-26 02:37:14 -08:00
Keavon Chambers 80f9dbb992 Keep angles typed in degrees exact when tools and fields read and write them 2026-11-26 02:37:14 -08:00
Keavon Chambers 9fd1011e1e Make the 'Blur' and 'Median Filter' nodes' radii typed lengths 2026-11-26 02:37:12 -08:00
Keavon Chambers 3d4d7d1058 Make the 'Brush Strokes' node's diameter a typed length 2026-11-26 02:35:57 -08:00
Keavon Chambers 401cf1419a Make the 'Mirror', 'Repeat', and 'Vary Rotations' nodes' angles and distances typed 2026-11-26 02:35:57 -08:00
Keavon Chambers 369671dc41 Make the 'Text' node's size, letter spacing, and letter tilt typed lengths and angles 2026-11-26 02:35:57 -08:00
Keavon Chambers fe505edeff Make the stroke and path nodes' distances and angles typed lengths and angles 2026-11-26 02:35:57 -08:00
Keavon Chambers 63a8befe4b Make the shape generator nodes' sizes and angles typed lengths and angles 2026-11-26 02:35:56 -08:00
Keavon Chambers 3e380b8cd7 Carry units through the math parser's lone-operator reductions 2026-11-26 02:35:56 -08:00
Keavon Chambers 634c30bebf Give exported SVGs a physical size and let Math f(x) take lengths and angles 2026-11-26 02:35:56 -08:00
Keavon Chambers 1e912de804 Add a resolution and lengths in any unit to the New Document dialog 2026-11-26 02:35:56 -08:00
Keavon Chambers ea9c44e003 Add typed length and angle values with a per-document resolution 2026-11-26 02:35:55 -08:00
Keavon Chambers 6a28b82b91 Add units of measure to the math expression language 2026-11-26 02:34:34 -08:00
Keavon Chambers 30164b921e New node: 'Feather' (#5028) 2026-11-26 02:30:33 -08:00
Keavon Chambers b10aa51efb Allow the 'Mask' node to mask any graphic with any other graphic (#5027) 2026-11-26 00:20:22 -08:00
Keavon Chambers 5d00e45354 Add gloss contours, bevel profiles, and textures to the 'Bevel & Emboss' node (#5026) 2026-11-25 22:16:50 -08:00
Keavon Chambers 69c0dd140d Add support to the 'Outline' node for any graphic as paint, plus contour gradients (#5025)
Allow any paint in the 'Outline' node and add contour gradients
2026-11-25 20:02:34 -08:00
Keavon Chambers 9a8269c953 Add a "Blend Mode" parameter to the 'Drop/Inner Shadow', 'Outer/Inner Glow', 'Satin', and 'Outline' effect nodes (#5024)
Add a "Blend Mode" parameter to the '* Shadow', '* Glow', 'Satin', and 'Outline' effect nodes
2026-11-25 18:59:28 -08:00
Timon 76361baaa1 Replace missing resource warnings with a 'Missing Resource' node that reports an error (#5018)
* Revert "Fix documents not rendering when a font or image is missing or fails to load (#4986)"

* Stop holding back rendering for resources that failed to load

* Recompile the graph when a resource loads

* Place a missing resource node for resources without a hash

* Evaluate a missing resource as the empty resource with its error

* Fix tests
2026-11-26 01:13:19 +00:00
Keavon Chambers f569120bf6 New node: 'Bevel & Emboss' (#5023)
New node: 'Bevel & Emboss', which gives graphics a raised or sunken look
2026-11-25 14:50:50 -08:00
Timon 0df1e16233 Move network output tracking out of the executor into a handle returned by updates (#5019)
* Let the dynamic executor hold several networks, each executed and kept alive by a handle to its output

* Review
2026-11-25 22:19:19 +00:00
Aditya Amol KuchekarandDennis Kobert 65bb0ff838 Fix dangling inputs when a History panel step is removed (#5017)
* Fix dangling inputs when a history step is removed

A node the line never saw gets a placeholder tombstone, which holds no
inputs, so reconnect returned nothing instead of falling back to the
primary input history kept. The input was left naming a node the
document no longer has, and that state is what history folds to.

* Share the history simulation harness and add a regression test

---------

Co-authored-by: Dennis Kobert <[email protected]>
2026-11-25 22:08:20 +00:00
Keavon Chambers d5a7504e3a New nodes: 'Inner Glow', 'Satin', and 'Outline' (#5022) 2026-11-25 14:14:26 -08:00
Keavon Chambers fa65c1f8dc Replace the 'Color Overlay' node with a 'Paint Overlay' node supporting any graphic (#5020)
Replace the 'Color Overlay' node with a 'Paint Overlay' node using any graphic
2026-11-25 13:54:46 -08:00
Keavon Chambers 264d8493ef Fix the color picker's gradient midpoint diamonds being invisible and undraggable 2026-11-25 04:13:33 -08:00
Timon 68b7c25f52 New node: 'SVG to Graphic' (#5016)
* Add svg-convert crate

* Add SVG to Graphic node

* Convert SVG group opacity

* Convert SVG text as outlines

* Convert nested SVG images

* Convert SVG strokes

* Convert SVG paint order

* Convert SVG blend modes

* Convert SVG gradients

* Convert SVG raster images

* Convert SVG clip paths

* Convert SVG even-odd fills

* Convert SVG masks

* Convert SVG blur and drop shadow filters

* Convert SVG patterns

* Paint a zero-length SVG linear gradient as the color of its last stop
2026-11-25 11:40:50 +00:00
Keavon Chambers 10b57c9719 Make the 'Scatter Points' node stable under local shape edits and much faster (#5013) 2026-11-25 02:40:11 -08:00
Keavon Chambers b1c0b6c173 Redesign the 'Mandelbrot' node with advanced fractal controls and deep zoom support (#5010)
Expand the 'Mandelbrot' node with fractal controls and deep zoom
2026-11-25 01:32:57 -08:00
Keavon Chambers 16fc449a3c Raise the canvas zoom limit and fix Ctrl+0 when nothing can be framed (#5015) 2026-11-25 06:18:45 +00:00
Timon 411d9f64b3 Fix the loading indicator not showing, and add a loading progress bar on web (#5012)
* Fix the loading indicator being hidden before the Wasm binary loads

* Center the loading indicator

* Show a download progress bar while the Wasm binary loads

* Show the progress bar as soon as the Wasm download starts

* Check for an update before starting the editor
2026-11-24 18:27:32 +00:00
Timon 637c5fc355 Fix the basic brush not rendering on WebGL2 (#5011)
Split the basic brush scatter into one pass per field so it renders on WebGL2
2026-11-24 03:46:22 -08:00
Keavon Chambers c9c51cb675 Move rendering of the 'Noise Pattern' and 'Mandelbrot' generators to the GPU (#5009) 2026-11-24 03:46:22 -08:00
Keavon Chambers 20f7f72fd4 Add a Generator graphic type that renderers draw at the resolution they need (#5008) 2026-11-23 15:48:05 -08:00
Dennis Kobert e420a87453 Integrate the graph-layout crate into the editor to replace its node graph layout (#5007)
* Place chains and stacks by relative offsets instead of their own placements

* Lay out the editor's node graph with the graph-layout crate

* Store chains and stacks as relative positions and migrate documents to them

* Trim comments

* Convert read nodes to relative positions in the format step

* Re-save the demo artwork with relative positions

* Append the position conversion to history as one interaction

* Address review comments on the position migration

* Format let chains as CI's rustfmt does

* Keep the dragged node's owners in place when a drag starts

* Keep absolute positions in documents with pending edits
2026-11-23 18:43:37 +00:00
Dennis Kobert 1f39cc36ec Add graph-layout crate (#5005)
* Add the graph-layout crate

* Document the graph-layout public API

* Keep layers a drag carries up when keeping the upstream
2026-11-23 14:39:46 +01:00
Timon 73c1da7404 Fix the Collaboration panel's scrollbar being inset from the panel's edge (#5006) 2026-11-23 13:09:54 +00:00
Timon efbd626428 Share one remote cursor overlay between the artwork and the node graph (#5004) 2026-11-23 10:59:59 +00:00
Keavon Chambers 615b4050ba Fix read-only subgraphs offering edits, and add drag toggling to graph layer buttons (#4999)
* Fix read-only subgraphs allowing edit gestures and preview changes

* Make graph layer eye and lock buttons toggle on release or by dragging across them

* Fix New Layer creating stray nodes in the root graph when used in a subgraph

* Make dragging across the Layers panel's eye and lock buttons one undo step

* Fix blocked undo and stuck dragging after Shift-clicking a selected graph node
2026-11-22 23:22:03 +00:00
Keavon ChambersandTimon 920bdc81b8 Make the render node finish SVG renders without caller post-processing (#5000)
* Make the render node finish SVG renders without caller post-processing

* Remove read_back from the wgpu executor

* Cancel the SVG readback when the render node is dropped

* Move the SVG readback slot into a render node submodule

---------

Co-authored-by: Timon <[email protected]>
2026-11-22 22:35:16 +00:00
Timon 23f3a0339c Add an executor update that doesn't free orphaned nodes, and track async sources in the borrow tree (#5002)
Add a non-freeing executor update
2026-11-22 21:47:51 +00:00
Keavon Chambers 82be8c46f7 Allow adjustment nodes to apply to any graphic as render-time effects (#4997)
* Allow adjustments on any graphic, carried out where they're read

* Speed up leading adjustments by folding them into textures and solid paints

* Keep effects stamped on paint wires and correct the GPU rendering guide
2026-11-22 02:21:07 -08:00
Keavon Chambers 764775f6c0 Fix SVG Preview missing overlays, remove no-GPU SVG fallbacks, and show a startup error when the browser lacks GPU support (#4996)
* Fix missing overlays in SVG Preview and over-bright translucent overlays

* Make the Eyedropper sample a Vello render in SVG Preview on web too

* Fix raster exports depending on the viewport's render mode

* Require WebGL2 on web with a clear error and drop no-GPU fallbacks
2026-11-22 00:00:58 +00:00
Keavon Chambers f7e045d03b Raise layer and effect rendering precision to 16 bits per channel to avoid 8-bit banding (#4995)
Draw layers and the content effects process at 16 bits per channel
2026-11-21 14:30:16 -08:00
Dennis Kobert d4a49ee5f8 Report incomplete or failed renders to the user (#4993)
* Report partial and fallback renders as their own render status

* Outline the viewport in yellow while it shows a partial render and in red for fallbacks and errors
2026-11-21 22:07:40 +00:00
418 changed files with 46797 additions and 7460 deletions

No files matched your search

+2 -2
View File
@@ -1,2 +1,2 @@
https://github.com/Keavon/graphite-branded-assets/archive/38176c494d7cf0bde3bdf45e6a318ae6a9d89229.tar.gz
2ae24506ff786b2b684f5d23bd326a69f5f4551855f19e4ef2b0324f9ec14e5d
https://github.com/Keavon/graphite-branded-assets/archive/9d0fa5caefd7d28f51b55220b405b7d76d05a991.tar.gz
a146abe79fa20b6d96f8009279a5a3342dd01596e5eb6a43e4c1f5e1199f1d9f
+7
View File
@@ -36,6 +36,13 @@ let
cargoLockList = [
"${info.src}/Cargo.lock"
];
# FastNoise Lite's WGSL port sits outside its crate folder, so place it beside Cargo.toml like its publish workflow does
overrideVendorGitCheckout =
packages: checkout:
if lib.any (package: package.name == "fastnoise-lite") packages then
checkout.overrideAttrs { preInstall = "cp WGSL/FastNoiseLite.wgsl Rust/"; }
else
checkout;
}
);
buildInputs = libs;
Generated
+201 -18
View File
@@ -588,6 +588,7 @@ dependencies = [
"glam",
"graphic-types",
"node-macro",
"raster-kernels",
"serde",
"vector-types",
]
@@ -1225,6 +1226,7 @@ dependencies = [
"kurbo",
"log",
"lyon_geom",
"math-parser",
"node-macro",
"num-derive",
"num-traits",
@@ -1237,7 +1239,7 @@ dependencies = [
"rustc-hash 2.1.3",
"serde",
"serde_json",
"skrifa",
"skrifa 0.44.0",
"tinyvec",
"tsify",
"wasm-bindgen",
@@ -2022,9 +2024,8 @@ dependencies = [
[[package]]
name = "fastnoise-lite"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e5f3c3cc9081e5d0e18bcd50e80cd33cba47fc22f88a9da9c33ecd1c87ea5c0"
version = "1.2.0"
source = "git+https://github.com/Keavon/FastNoiseLite.git?rev=26c1ac62e124d68ff970c2423dcda2ef24344060#26c1ac62e124d68ff970c2423dcda2ef24344060"
dependencies = [
"num-traits",
]
@@ -2135,6 +2136,9 @@ name = "float-cmp"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"
dependencies = [
"num-traits",
]
[[package]]
name = "fnv"
@@ -2154,6 +2158,15 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
[[package]]
name = "font-types"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b38ad915f6dadd993ced50848a8291a543bd41ca62bc10740d5e64e2ab4cfd7"
dependencies = [
"bytemuck",
]
[[package]]
name = "font-types"
version = "0.12.7"
@@ -2195,7 +2208,7 @@ dependencies = [
"linebender_resource_handle",
"memmap2",
"parlance",
"read-fonts",
"read-fonts 0.41.0",
"smallvec",
]
@@ -2525,6 +2538,15 @@ dependencies = [
"wgpu-executor",
]
[[package]]
name = "graph-layout"
version = "0.0.0"
dependencies = [
"criterion",
"glam",
"smallvec",
]
[[package]]
name = "graphene-animation"
version = "0.0.0"
@@ -2652,6 +2674,7 @@ dependencies = [
"bytemuck",
"core-types",
"dyn-any",
"futures",
"glam",
"graph-craft",
"graphene-application-io",
@@ -2669,6 +2692,7 @@ dependencies = [
"rendering",
"repeat-nodes",
"reqwest",
"svg-convert",
"text-nodes",
"thiserror 2.0.21",
"tokio",
@@ -2696,6 +2720,7 @@ dependencies = [
"graphic-types",
"node-macro",
"rand",
"raster-kernels",
"raster-types",
"serde",
"thiserror 2.0.21",
@@ -2859,6 +2884,7 @@ dependencies = [
"futures",
"glam",
"graph-craft",
"graph-layout",
"graphene-hash",
"graphene-std",
"graphite-proc-macros",
@@ -3026,7 +3052,7 @@ checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9"
dependencies = [
"bitflags 2.13.2",
"bytemuck",
"read-fonts",
"read-fonts 0.41.0",
"smallvec",
]
@@ -3061,6 +3087,40 @@ dependencies = [
"foldhash 0.2.0",
]
[[package]]
name = "hayro-ccitt"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adbed896e99325bc312778bb9c9c289d795d51c12775c44dd5e4352f679c7e46"
[[package]]
name = "hayro-jbig2"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eb5c7f3a4eb551c2bb7fa16e268f728d4bc2a5c9b090554b8dc0ee2503fb5840"
dependencies = [
"hayro-ccitt",
]
[[package]]
name = "hayro-jpeg2000"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e5e5f2b3de970707fc22fd956d8f44211602939d5e4588603afa919cb7b3740"
[[package]]
name = "hayro-syntax"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6ced8279487b029813f6cc05399099fa34df6fa23d8f7b0d41d972c49d5b30d"
dependencies = [
"hayro-jbig2",
"hayro-jpeg2000",
"rustc-hash 2.1.3",
"smallvec",
"zune-jpeg",
]
[[package]]
name = "heck"
version = "0.5.0"
@@ -3414,6 +3474,12 @@ dependencies = [
"quick-error",
]
[[package]]
name = "imagesize"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09e54e57b4c48b40f7aec75635392b12b3421fa26fe8b4332e63138ed278459c"
[[package]]
name = "imagesize"
version = "0.15.0"
@@ -3786,6 +3852,33 @@ dependencies = [
"libc",
]
[[package]]
name = "krilla"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27da593198b20eeba65caeb73c2bbeec3e53ab08fa549898312ce81c4fce5e33"
dependencies = [
"base64 0.22.1",
"bumpalo",
"flate2",
"float-cmp",
"gif",
"image-webp",
"imagesize 0.14.0",
"indexmap",
"pdf-writer",
"png 0.18.1",
"rustc-hash 2.1.3",
"siphasher",
"skrifa 0.42.1",
"smallvec",
"subsetter",
"tiny-skia-path",
"xmp-writer",
"yoke",
"zune-jpeg",
]
[[package]]
name = "kurbo"
version = "0.13.1"
@@ -4164,6 +4257,7 @@ dependencies = [
"math-parser",
"node-macro",
"rand",
"raster-kernels",
"thiserror 2.0.21",
"vector-types",
]
@@ -4842,9 +4936,9 @@ dependencies = [
[[package]]
name = "ollev"
version = "0.2.0"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e858a872f7e5f74992f283fe52d9c184234e8505f316e6aa7822fa394b39d0a"
checksum = "d77164e6c8fb386ee064104ab480578451b0fd106ca4c0a6988eb7ca4ed9ec4b"
dependencies = [
"glam",
]
@@ -5018,7 +5112,7 @@ dependencies = [
"parlance",
"parley_data",
"parley_emoji",
"skrifa",
"skrifa 0.44.0",
]
[[package]]
@@ -5049,6 +5143,18 @@ dependencies = [
"vector-types",
]
[[package]]
name = "pdf-writer"
version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f5e456864a7a304047bff84977dc6fb162bd956475d40ba50b2dcecaada7f753"
dependencies = [
"bitflags 2.13.2",
"itoa",
"memchr",
"ryu",
]
[[package]]
name = "peer-transport"
version = "0.0.0"
@@ -5851,6 +5957,16 @@ dependencies = [
"yasna",
]
[[package]]
name = "read-fonts"
version = "0.39.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4ed38b89c2c77ff968c524145ad65fb010f38af5c7a224b53b81d47ac2daa81"
dependencies = [
"bytemuck",
"font-types 0.11.3",
]
[[package]]
name = "read-fonts"
version = "0.41.0"
@@ -5858,7 +5974,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709"
dependencies = [
"bytemuck",
"font-types",
"font-types 0.12.7",
"once_cell",
]
@@ -5963,6 +6079,7 @@ name = "regression"
version = "0.0.0"
dependencies = [
"clap",
"document-container",
"document-format",
"document-loader",
"fern",
@@ -6003,12 +6120,15 @@ dependencies = [
"graphene-hash",
"graphene-resource",
"graphic-types",
"hayro-syntax",
"krilla",
"kurbo",
"log",
"num-traits",
"parley",
"raster-kernels",
"serde",
"skrifa",
"skrifa 0.44.0",
"text-nodes",
"usvg",
"vector-types",
@@ -6586,6 +6706,12 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
[[package]]
name = "ryu"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
[[package]]
name = "same-file"
version = "1.0.6"
@@ -6947,6 +7073,16 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256"
[[package]]
name = "skrifa"
version = "0.42.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c34617370ae968efb7161bb2beb517d9084659aae19e24b89e3db25b46e4564"
dependencies = [
"bytemuck",
"read-fonts 0.39.2",
]
[[package]]
name = "skrifa"
version = "0.44.0"
@@ -6954,7 +7090,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68"
dependencies = [
"bytemuck",
"read-fonts",
"read-fonts 0.41.0",
]
[[package]]
@@ -7133,6 +7269,18 @@ version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "subsetter"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38803281d1c23166c5ebcb455439a5d2afe711cc909cf88af72448c297756ad6"
dependencies = [
"kurbo",
"rustc-hash 2.1.3",
"skrifa 0.42.1",
"write-fonts",
]
[[package]]
name = "substring"
version = "1.4.5"
@@ -7148,6 +7296,18 @@ version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "svg-convert"
version = "0.0.0"
dependencies = [
"core-types",
"glam",
"graphic-types",
"kurbo",
"linesweeper",
"usvg",
]
[[package]]
name = "svgtypes"
version = "0.16.2"
@@ -7303,7 +7463,7 @@ dependencies = [
"rand",
"serde",
"serde_json",
"skrifa",
"skrifa 0.44.0",
"thiserror 2.0.21",
"titlecase",
"tsify",
@@ -7903,14 +8063,14 @@ dependencies = [
"flate2",
"fontdb",
"harfrust",
"imagesize",
"imagesize 0.15.0",
"kurbo",
"log",
"pico-args",
"roxmltree 0.21.2",
"simplecss",
"siphasher",
"skrifa",
"skrifa 0.44.0",
"strict-num",
"svgtypes",
"tiny-skia-path",
@@ -7991,6 +8151,7 @@ dependencies = [
"node-macro",
"qrcodegen",
"rand",
"raster-kernels",
"repeat-nodes",
"rustc-hash 2.1.3",
"serde",
@@ -8052,7 +8213,7 @@ dependencies = [
[[package]]
name = "vello_common"
version = "0.3.0"
source = "git+https://github.com/Keavon/vello.git?rev=4df331db2a02cb0f1cef4a0190dbbb2a00f4b075#4df331db2a02cb0f1cef4a0190dbbb2a00f4b075"
source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07"
dependencies = [
"bytemuck",
"fearless_simd",
@@ -8067,7 +8228,7 @@ dependencies = [
[[package]]
name = "vello_gpu"
version = "0.3.0"
source = "git+https://github.com/Keavon/vello.git?rev=4df331db2a02cb0f1cef4a0190dbbb2a00f4b075#4df331db2a02cb0f1cef4a0190dbbb2a00f4b075"
source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07"
dependencies = [
"bytemuck",
"hashbrown 0.17.1",
@@ -8081,7 +8242,7 @@ dependencies = [
[[package]]
name = "vello_gpu_shaders"
version = "0.3.0"
source = "git+https://github.com/Keavon/vello.git?rev=4df331db2a02cb0f1cef4a0190dbbb2a00f4b075#4df331db2a02cb0f1cef4a0190dbbb2a00f4b075"
source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07"
dependencies = [
"naga",
"wesl",
@@ -8539,12 +8700,15 @@ dependencies = [
"bytemuck",
"core-types",
"dyn-any",
"fastnoise-lite",
"futures",
"glam",
"graphene-application-io",
"graphene-resource",
"graphic-types",
"half",
"log",
"naga",
"node-macro",
"raster-kernels",
"raster-types",
@@ -9249,6 +9413,19 @@ dependencies = [
"toml 0.5.11",
]
[[package]]
name = "write-fonts"
version = "0.48.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb731d4c4d93eacc69a1ad2f270f905788a98e4a3438267bcafbe08d3431c8d8"
dependencies = [
"font-types 0.11.3",
"indexmap",
"kurbo",
"log",
"read-fonts 0.39.2",
]
[[package]]
name = "writeable"
version = "0.6.4"
@@ -9389,6 +9566,12 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
[[package]]
name = "xmp-writer"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
[[package]]
name = "yansi"
version = "1.0.1"
+12 -6
View File
@@ -27,6 +27,7 @@ members = [
"libraries/math-parser",
"libraries/ipsum",
"libraries/snapping",
"libraries/graph-layout",
"libraries/wgpu-sync",
"libraries/control-protocol",
"node-graph/libraries/graphene-hash",
@@ -98,6 +99,7 @@ graphic-types = { path = "node-graph/libraries/graphic-types" }
raster-kernels = { path = "node-graph/libraries/raster-kernels" }
brush-types = { path = "node-graph/libraries/brush-types" }
rendering = { path = "node-graph/libraries/rendering" }
svg-convert = { path = "node-graph/libraries/svg-convert" }
brush-nodes = { path = "node-graph/nodes/brush" }
blending-nodes = { path = "node-graph/nodes/blending" }
graphene-core = { path = "node-graph/nodes/gcore" }
@@ -134,6 +136,7 @@ control-protocol = { path = "libraries/control-protocol" }
graphene-canvas-utils = { path = "node-graph/libraries/canvas-utils" }
ipsum = { path = "libraries/ipsum" }
snapping = { path = "libraries/snapping" }
graph-layout = { path = "libraries/graph-layout" }
# Workspace dependencies
rustc-hash = "2.0"
@@ -163,7 +166,7 @@ proc-macro2 = { version = "1", features = ["span-locations"] }
quote = "1.0"
chrono = "0.4"
ron = "0.12"
fastnoise-lite = "1.1"
fastnoise-lite = "1.2"
wgpu = { version = "30.0", default-features = false, features = [
"std",
"parking_lot",
@@ -196,8 +199,8 @@ web-sys = { version = "=0.3.106", features = [
"IdleRequestOptions",
"ImageData",
"Navigator",
"WebGl2RenderingContext",
"Gpu",
"HtmlImageElement",
"ImageBitmapRenderingContext",
"Lock",
"LockInfo",
@@ -220,6 +223,8 @@ skrifa = "0.44"
polycool = "0.4"
color = "0.3"
# Linebender ecosystem (END)
krilla = { version = "0.8", default-features = false, features = ["raster-images"] }
hayro-syntax = { version = "0.9", default-features = false, features = ["std"] }
rand = { version = "0.10", default-features = false, features = ["std_rng"] }
rand_chacha = "0.10"
glam = { version = "0.34", default-features = false, features = [
@@ -271,7 +276,7 @@ tinyvec = { version = "1", features = ["std"] }
criterion = { version = "0.8", features = ["html_reports"] }
gungraun = { version = "0.20" }
ndarray = "0.17"
ollev = "0.2.0"
ollev = "0.1.2"
dirs = "7.0"
cef = "156"
cef-dll-sys = "156"
@@ -310,7 +315,8 @@ 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
fastnoise-lite = { git = "https://github.com/Keavon/FastNoiseLite.git", rev = "26c1ac62e124d68ff970c2423dcda2ef24344060" } # TODO: Remove this once the WGSL port is upstreamed and released in version 1.2
# TODO: Remove these once the fork's fixes are upstreamed and released
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" }
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
+1 -1
View File
@@ -9,7 +9,7 @@ use crate::{DEFAULT_HISTORY_CODEC, DEFAULT_HOT_LOG_CODEC, DEFAULT_REGISTRY_CODEC
pub const FORMAT_MAGIC: &str = "gdd";
/// Newest format version this build can open, which older documents migrate to. `cargo run migration snapshot` bumps it when the stored types change.
pub const SUPPORTED_FORMAT_VERSION: u32 = 4;
pub const SUPPORTED_FORMAT_VERSION: u32 = 5;
/// The on-disk codec for each working-copy payload, recorded so reads/writes never have to probe
/// the filesystem to discover it. The manifest itself is excluded: it is always JSON, since it must
+4 -4
View File
@@ -7,13 +7,13 @@ use std::collections::{BTreeMap, btree_map};
/// keys live on `Node.inputs_attributes[i]`; per-network keys live on `Network.attributes`.
pub mod attr;
/// Unified storage-side position. The valid variants depend on `attr::node::ui::IS_LAYER`:
/// layers use `Absolute` or `Stack`; non-layer nodes use `Absolute` or `Chain`.
/// Where a node or layer is stored, in grid cells.
#[derive(Copy, Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum Position {
/// A position of its own, starting a tree of its own.
Absolute([i32; 2]),
Chain,
Stack(u32),
/// An offset from the top left corner of the bounding box of the positions of the nodes reading this one.
Relative([i32; 2]),
}
impl AttributeValue {
@@ -57,6 +57,10 @@ pub mod network {
pub const IMPORT_METADATA: &str = "ui::import_metadata";
pub const EXPORT_NAMES: &str = "ui::export_names";
pub const EXPORT_DESCRIPTIONS: &str = "ui::export_descriptions";
/// How many pixels make an inch in the network's document, which sizes lengths typed in a physical unit. Absent where it
/// is the default, CSS's 96. Only the root network's applies.
pub const PIXELS_PER_INCH: &str = "pixels_per_inch";
}
pub mod delta {
@@ -473,6 +473,12 @@ fn write_ui_network_attributes<M: NodeMetadataSource + ?Sized>(
.map_err(map_serialization_error(network::PINNED_ORDER))?;
}
if let Some(pixels_per_inch) = metadata.pixels_per_inch(location) {
attributes
.set_serialized(network::PIXELS_PER_INCH, &pixels_per_inch, timestamp)
.map_err(map_serialization_error(network::PIXELS_PER_INCH))?;
}
Ok(())
}
+2
View File
@@ -52,9 +52,11 @@ pub use to_runtime::{Declarations, ProjectedNetwork, ProjectedNode, RuntimeProje
#[cfg(test)]
mod tests {
mod bookkeeping;
mod branch_simulation;
mod crdt;
mod history_simulation;
mod projection;
mod round_trip;
mod sessions;
mod simulation;
}
@@ -38,6 +38,8 @@ pub struct NetworkMetadataEntry {
pub import_metadata: Vec<InputMetadataEntry>,
pub export_names: Vec<String>,
pub export_descriptions: Vec<String>,
/// The document's pixels per inch, where it differs from the default.
pub pixels_per_inch: Option<f64>,
}
/// Editor metadata for one import of a subgraph. Mirrors `InputPersistentMetadata` but wraps strings in `Option` so
@@ -78,6 +80,11 @@ pub trait NodeMetadataSource {
Vec::new()
}
/// The network's pixels per inch, where it differs from the default.
fn pixels_per_inch(&self, _network: NetworkLocation) -> Option<f64> {
None
}
fn import_metadata(&self, _network: NetworkLocation) -> Vec<InputMetadataEntry> {
Vec::new()
}
+2 -1
View File
@@ -382,7 +382,8 @@ fn reconnect(registry: &Registry, removed: NodeId, network: Option<NetworkId>, k
if !visited.insert(current) {
return None;
}
let (in_network, input) = match registry.removed_nodes.get(&current) {
// A placeholder knows nothing of the node's network or primary input, so what history kept decides instead
let (in_network, input) = match registry.removed_nodes.get(&current).filter(|tombstone| !tombstone.placeholder) {
Some(tombstone) => (tombstone.content.network, tombstone.content.inputs.first()?.input.clone()),
None => known.primary.get(&current).cloned()?,
};
@@ -0,0 +1,238 @@
//! Deterministic simulation of a document whose chains branch off inputs past the primary one, with every history
//! operation mixed in. After every operation nothing may name a node the document no longer has.
use super::simulation::{LEAF, Random, Scenario, below, empty_export, from_env, on, simulate, stack, value};
use crate::{Implementation, Network, Node, NodeId, NodeInput, ROOT_NETWORK, Registry, RegistryDelta, Session};
/// A slot that can name a node.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum Place {
Export(u32),
Input(NodeId, u32),
}
fn place_value(registry: &Registry, place: Place) -> Option<NodeInput> {
match place {
Place::Input(id, index) => registry.node_instances.get(&id)?.inputs.get(index as usize).map(|slot| slot.input.clone()),
Place::Export(index) => registry.networks.get(&ROOT_NETWORK)?.exports.get(index as usize)?.target.clone(),
}
}
fn set_place(place: Place, input: NodeInput) -> RegistryDelta {
match place {
Place::Input(id, index) => RegistryDelta::ChangeNodeInput { id, index, new_input: input },
Place::Export(index) => RegistryDelta::SetNetworkExport {
id: ROOT_NETWORK,
index,
export: Some(input),
},
}
}
/// Every slot naming a node, and the node it names, in a fixed order.
fn naming_places(registry: &Registry) -> Vec<(Place, NodeId)> {
let mut places = Vec::new();
for (&id, node) in &registry.node_instances {
for (index, slot) in node.inputs.iter().enumerate() {
if let NodeInput::Node { id: named, .. } = slot.input {
places.push((Place::Input(id, index as u32), named));
}
}
}
if let Some(network) = registry.networks.get(&ROOT_NETWORK) {
for (index, slot) in network.exports.iter().enumerate() {
if let Some(NodeInput::Node { id: named, .. }) = slot.target {
places.push((Place::Export(index as u32), named));
}
}
}
places.sort();
places
}
/// The slot naming `node`, of which a document built this way has one.
fn consumer_place(registry: &Registry, node: NodeId) -> Option<Place> {
naming_places(registry).into_iter().find(|(_, named)| *named == node).map(|(place, _)| place)
}
/// Every node under `place`, through any input.
fn under(registry: &Registry, place: Place) -> Vec<NodeId> {
let mut seen: Vec<NodeId> = Vec::new();
let mut queue: Vec<NodeId> = Vec::new();
if let Some(NodeInput::Node { id, .. }) = place_value(registry, place) {
queue.push(id);
}
while let Some(id) = queue.pop() {
if seen.contains(&id) || !registry.node_instances.contains_key(&id) {
continue;
}
seen.push(id);
for slot in &registry.node_instances[&id].inputs {
if let NodeInput::Node { id: next, .. } = slot.input {
queue.push(next);
}
}
}
seen
}
/// Nodes chained off the export and off inputs past the primary one.
struct Branching;
impl Scenario for Branching {
fn random_edit(random: &mut Random, session: &mut Session) -> Vec<RegistryDelta> {
let registry = session.registry().clone();
let layers = stack(&registry);
let nodes = under(&registry, Place::Export(0));
let leaf = (!registry.networks.contains_key(&LEAF)).then(|| RegistryDelta::AddNetwork {
id: LEAF,
network: Network::default(),
});
let make = |first: NodeInput, second: NodeInput| {
let mut node = Node::new(ROOT_NETWORK, Implementation::Network(LEAF), 2);
node.inputs[0].input = first;
node.inputs[1].input = second;
node
};
// Nodes with nothing hanging off their second input, so taking one does not leave a chain behind
let plain: Vec<NodeId> = nodes
.iter()
.copied()
.filter(|id| !matches!(place_value(&registry, Place::Input(*id, 1)), Some(NodeInput::Node { .. })))
.collect();
match random.below(12) {
// Draw a node on top of the chain off the export
0..=2 => {
let id = session.next_node_id();
let node = make(layers.first().map_or_else(|| value(0), |&top| on(top)), value(random.below(100)));
let mut ops: Vec<RegistryDelta> = leaf.into_iter().collect();
ops.extend([
RegistryDelta::AddNode { id, node },
RegistryDelta::SetNetworkExport {
id: ROOT_NETWORK,
index: 0,
export: Some(on(id)),
},
]);
if let Some(&under) = layers.first() {
ops.push(super::crdt::change_node_attribute(under, "position", serde_json::json!(random.below(100))));
}
ops
}
// Hang a node on an input past the primary one, over whatever is there already
3..=5 => {
let Some(host) = random.pick(&nodes) else { return Vec::new() };
let id = session.next_node_id();
let first = match place_value(&registry, Place::Input(host, 1)) {
Some(NodeInput::Node { id: under, index }) => NodeInput::Node { id: under, index },
_ => value(0),
};
let node = make(first, value(random.below(100)));
let mut ops: Vec<RegistryDelta> = leaf.into_iter().collect();
ops.extend([
RegistryDelta::AddNode { id, node },
RegistryDelta::ChangeNodeInput {
id: host,
index: 1,
new_input: on(id),
},
]);
ops
}
// Delete a node, reconnecting everything that named it to what it rested on
6..=7 => {
let Some(node) = random.pick(&plain) else { return Vec::new() };
let snapshot = registry.node_instances[&node].clone();
let mut ops: Vec<RegistryDelta> = naming_places(&registry)
.into_iter()
.filter(|(_, named)| *named == node)
.map(|(place, _)| set_place(place, below(&registry, node)))
.collect();
ops.push(RegistryDelta::RemoveNode { id: node, snapshot });
ops
}
// Move a node to the top of the chain off the export
8 => {
let Some(layer) = random.pick(&layers[layers.len().min(1)..]) else { return Vec::new() };
let Some(place) = consumer_place(&registry, layer) else { return Vec::new() };
vec![
set_place(place, below(&registry, layer)),
RegistryDelta::ChangeNodeInput {
id: layer,
index: 0,
new_input: on(layers[0]),
},
RegistryDelta::SetNetworkExport {
id: ROOT_NETWORK,
index: 0,
export: Some(on(layer)),
},
]
}
// Change a node's value
9..=10 => {
let Some(node) = random.pick(&plain) else { return Vec::new() };
vec![RegistryDelta::ChangeNodeInput {
id: node,
index: 1,
new_input: value(random.below(100)),
}]
}
// Cut the chain off an input past the primary one, taking its nodes with it
_ => {
let hosts: Vec<NodeId> = nodes
.iter()
.copied()
.filter(|id| matches!(place_value(&registry, Place::Input(*id, 1)), Some(NodeInput::Node { .. })))
.collect();
let Some(host) = random.pick(&hosts) else { return Vec::new() };
let mut gone = under(&registry, Place::Input(host, 1));
// Nothing outside the cut may name a node inside it, or taking them would leave that naming nothing
let held = naming_places(&registry)
.into_iter()
.any(|(place, named)| gone.contains(&named) && place != Place::Input(host, 1) && !matches!(place, Place::Input(owner, _) if gone.contains(&owner)));
if held {
return Vec::new();
}
let mut ops = vec![RegistryDelta::ChangeNodeInput {
id: host,
index: 1,
new_input: value(random.below(100)),
}];
gone.sort();
for id in gone {
ops.push(RegistryDelta::RemoveNode {
id,
snapshot: registry.node_instances[&id].clone(),
});
}
ops
}
}
}
/// Nothing names a node the document no longer has, every node is built from a network it still has, and no node
/// input holds the empty export's value. A node may feed nothing or more than one input.
fn assert_well_formed(context: &str, registry: &Registry) {
for (place, named) in naming_places(registry) {
assert!(registry.node_instances.contains_key(&named), "{context}: {place:?} names {named:?}, which is gone");
}
for (id, node) in &registry.node_instances {
if let Implementation::Network(network) = &node.implementation {
assert!(registry.networks.contains_key(network), "{context}: {id:?} is built from {network:?}, which is gone");
}
for (index, slot) in node.inputs.iter().enumerate() {
assert_ne!(slot.input, empty_export(), "{context}: input {index} of {id:?} holds the empty export's value");
}
}
}
}
#[test]
fn history_operations_keep_a_branching_document_whole() {
let (seeds, steps) = (from_env("SEEDS", 200), from_env("STEPS", 80));
for seed in 0..seeds {
simulate::<Branching>(seed, steps, &mut Vec::new());
}
}
@@ -1,64 +1,12 @@
//! Deterministic simulation of a layer stack edited the way the editor does, with every history operation the History
//! panel offers mixed in: undo, redo, going back, removing a step and bringing one back. After every operation the
//! document must still be a well-formed stack, the snapshot must be what history folds to, and a peer following the
//! head moves must hold the same document.
//! Deterministic simulation of a layer stack edited the way the editor does, with every history operation mixed in.
//! After every operation the document must still be a well-formed stack.
//!
//! Inspect one run with `SEED=<n> cargo test -p document-graph-storage history_simulation::inspect_seed -- --ignored --nocapture`.
use crate::{Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ROOT_NETWORK, Registry, RegistryDelta, Rev, Session, UserId, Value};
use super::simulation::{LEAF, Random, Scenario, below, empty_export, from_env, on, simulate, stack, value};
use crate::{Implementation, Network, Node, NodeId, NodeInput, ROOT_NETWORK, Registry, RegistryDelta, Session};
use std::collections::HashSet;
/// What every layer's implementation names, so nodes need no proto-node declarations. The first layer drawn brings it,
/// as the editor's first layer brings the subgraph every later one is built from.
const LEAF: NetworkId = NetworkId(1);
/// What the export holds while the stack is empty, of another type than what the bottom layer rests on.
fn empty_export() -> NodeInput {
NodeInput::Value {
value: Value::from(serde_json::json!("empty")),
exposed: false,
}
}
/// A small xorshift generator, so a seed fixes the run.
struct Random(u64);
impl Random {
fn new(seed: u64) -> Self {
Self(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1)
}
fn below(&mut self, bound: usize) -> usize {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
(self.0 % bound as u64) as usize
}
fn pick<T: Copy>(&mut self, options: &[T]) -> Option<T> {
(!options.is_empty()).then(|| options[self.below(options.len())])
}
}
/// The layers from the top of the stack down, following each layer's first input.
fn stack(registry: &Registry) -> Vec<NodeId> {
let mut layers = Vec::new();
let mut below = registry.networks.get(&ROOT_NETWORK).and_then(|network| network.exports.first()).and_then(|slot| slot.target.clone());
while let Some(NodeInput::Node { id, .. }) = below {
if layers.contains(&id) || layers.len() > registry.node_instances.len() {
break;
}
layers.push(id);
below = registry.node_instances.get(&id).and_then(|node| node.inputs.first()).map(|slot| slot.input.clone());
}
layers
}
/// What feeds into `layer` from below.
fn below(registry: &Registry, layer: NodeId) -> NodeInput {
registry.node_instances[&layer].inputs[0].input.clone()
}
/// Points what sits directly above `layer`, a layer or the export, at `input`.
fn rewire_above(registry: &Registry, layer: NodeId, input: NodeInput) -> RegistryDelta {
let layers = stack(registry);
@@ -76,365 +24,124 @@ fn rewire_above(registry: &Registry, layer: NodeId, input: NodeInput) -> Registr
}
}
fn on(id: NodeId) -> NodeInput {
NodeInput::Node { id, index: 0 }
}
/// A single stack of layers off the export.
struct Stack;
fn value(number: usize) -> NodeInput {
NodeInput::Value {
value: Value::from(serde_json::json!(number)),
exposed: false,
}
}
/// One interaction's ops, as the editor would stage them for a random edit of the stack.
fn random_edit(random: &mut Random, session: &mut Session) -> Vec<RegistryDelta> {
let registry = session.registry().clone();
let layers = stack(&registry);
match random.below(10) {
// Draw a layer on top
0..=3 => {
let id = session.next_node_id();
let mut node = Node::new(ROOT_NETWORK, Implementation::Network(LEAF), 2);
node.inputs[0].input = layers.first().map_or_else(|| value(0), |&top| on(top));
node.inputs[1].input = value(random.below(100));
let leaf = (!registry.networks.contains_key(&LEAF)).then(|| RegistryDelta::AddNetwork {
id: LEAF,
network: Network::default(),
});
let mut ops: Vec<RegistryDelta> = leaf.into_iter().collect();
ops.extend([
RegistryDelta::AddNode { id, node },
RegistryDelta::SetNetworkExport {
id: ROOT_NETWORK,
index: 0,
export: Some(on(id)),
},
]);
// The layer below moves into the stack under the new one, as the editor records with its position
if let Some(&below) = layers.first() {
ops.push(super::crdt::change_node_attribute(below, "position", serde_json::json!(random.below(100))));
}
ops
}
// Delete a layer, reconnecting what was above it to what was below
4..=5 => {
let Some(layer) = random.pick(&layers) else { return Vec::new() };
let snapshot = registry.node_instances[&layer].clone();
vec![rewire_above(&registry, layer, below(&registry, layer)), RegistryDelta::RemoveNode { id: layer, snapshot }]
}
// Move a layer to the top
6 => {
let Some(layer) = random.pick(&layers[layers.len().min(1)..]) else { return Vec::new() };
vec![
rewire_above(&registry, layer, below(&registry, layer)),
RegistryDelta::ChangeNodeInput {
id: layer,
index: 0,
new_input: on(layers[0]),
},
RegistryDelta::SetNetworkExport {
id: ROOT_NETWORK,
index: 0,
export: Some(on(layer)),
},
]
}
// Change a layer's value
_ => {
let Some(layer) = random.pick(&layers) else { return Vec::new() };
vec![RegistryDelta::ChangeNodeInput {
id: layer,
index: 1,
new_input: value(random.below(100)),
}]
}
}
}
/// The ops of an edit, short enough to read in a failing run's log.
fn summarize(ops: &[RegistryDelta]) -> String {
let short = |id: &NodeId| id.0 % 1000;
let input = |input: &NodeInput| match input {
NodeInput::Node { id, .. } => format!("{}", short(id)),
_ => "value".to_string(),
};
ops.iter()
.map(|op| match op {
RegistryDelta::AddNode { id, node } => format!("add {} on {}", short(id), input(&node.inputs[0].input)),
RegistryDelta::RemoveNode { id, .. } => format!("remove {}", short(id)),
RegistryDelta::ChangeNodeInput { id, index, new_input } => format!("{}.{index} = {}", short(id), input(new_input)),
RegistryDelta::SetNetworkExport { export, .. } => format!("export = {}", export.as_ref().map_or("none".to_string(), input)),
RegistryDelta::AddNetwork { id, .. } => format!("add network {}", id.0),
other => format!("{other:?}"),
})
.collect::<Vec<_>>()
.join(", ")
}
/// The revs closing each interaction on the head's line, newest first.
fn line_steps(session: &Session) -> Vec<Rev> {
let mut steps = Vec::new();
let mut current = session.head_rev();
while let Some(delta) = current.and_then(|rev| session.delta(rev)) {
if delta.is_interaction_end() {
steps.push(delta.id);
}
current = delta.parent;
}
steps
}
/// The revs closing interactions left behind on branches.
fn branch_steps(session: &Session) -> Vec<Rev> {
let line: HashSet<Rev> = {
let mut line = HashSet::new();
let mut current = session.head_rev();
while let Some(delta) = current.and_then(|rev| session.delta(rev)) {
line.insert(delta.id);
current = delta.parent;
}
line
};
let mut steps: Vec<Rev> = session
.history()
.filter(|delta| delta.is_interaction_end() && !line.contains(&delta.id))
.map(|delta| delta.id)
.collect();
steps.sort();
steps
}
/// The layers the interaction ending at `end` added and deleted, by what it did in all.
fn added_and_removed(session: &Session, end: Rev) -> (Vec<NodeId>, Vec<NodeId>) {
let (mut added, mut removed) = (Vec::new(), Vec::new());
let mut current = session.delta(end);
while let Some(delta) = current {
match &delta.kind {
RegistryDelta::AddNode { id, .. } => added.push(*id),
RegistryDelta::RemoveNode { id, .. } => removed.push(*id),
_ => {}
}
current = delta.parent.and_then(|parent| session.delta(parent)).filter(|parent| !parent.is_interaction_end());
}
let net = |these: &[NodeId], those: &[NodeId]| these.iter().filter(|id| !those.contains(id)).copied().collect();
(net(&added, &removed), net(&removed, &added))
}
/// The layers the step ending at `end` added that a newer deletion on its own line had taken again.
fn lost_on_its_line(session: &Session, end: Rev, added: &[NodeId]) -> HashSet<NodeId> {
let mut lost = HashSet::new();
let mut added_at = std::collections::HashMap::new();
let mut line = Vec::new();
let mut current = session.delta(end);
while let Some(delta) = current {
line.push(delta);
current = delta.parent.and_then(|parent| session.delta(parent));
}
for delta in &line {
if let RegistryDelta::AddNode { id, .. } = &delta.kind {
added_at.entry(*id).or_insert(delta.timestamp);
}
}
for delta in &line {
if let RegistryDelta::RemoveNode { id, .. } = &delta.kind
&& added.contains(id)
&& added_at.get(id).is_some_and(|stamp| *stamp < delta.timestamp)
{
lost.insert(*id);
}
}
lost
}
/// The layers live on the line just before the interaction ending at `end`.
fn live_before(session: &Session, end: Rev) -> HashSet<NodeId> {
let mut current = session.delta(end);
while let Some(delta) = current.filter(|delta| delta.id == end || !delta.is_interaction_end()) {
current = delta.parent.and_then(|parent| session.delta(parent));
}
let mut line = Vec::new();
while let Some(delta) = current {
line.push(delta.clone());
current = delta.parent.and_then(|parent| session.delta(parent));
}
line.reverse();
let replayed = Session::replay_from_history(PeerId(3), UserId(3), line, 0).expect("the line replays");
replayed.retired_registry().node_instances.keys().copied().collect()
}
/// Every layer input and the export name a live layer, nothing loops, and every layer is in the stack, so none is
/// left drawn by nothing.
fn assert_well_formed(context: &str, registry: &Registry) {
let exports = registry.networks.get(&ROOT_NETWORK).map(|network| network.exports.clone()).unwrap_or_default();
let export = exports.first().and_then(|slot| slot.target.clone());
if let Some(NodeInput::Node { id, .. }) = &export {
assert!(registry.node_instances.contains_key(id), "{context}: the export names {id:?}, which is gone");
}
for (id, node) in &registry.node_instances {
for (index, slot) in node.inputs.iter().enumerate() {
if let NodeInput::Node { id: named, .. } = &slot.input {
assert!(registry.node_instances.contains_key(named), "{context}: input {index} of {id:?} names {named:?}, which is gone");
}
}
}
let mut stacked_on = HashSet::new();
let primary_inputs = registry.node_instances.values().filter_map(|node| node.inputs.first()).map(|slot| &slot.input);
for input in primary_inputs.chain(export.iter()) {
if let NodeInput::Node { id, .. } = input {
assert!(stacked_on.insert(*id), "{context}: two layers or the export sit on {id:?}");
}
}
for (id, node) in &registry.node_instances {
if let Implementation::Network(network) = &node.implementation {
assert!(registry.networks.contains_key(network), "{context}: {id:?} is built from {network:?}, which is gone");
}
}
let layers = stack(registry);
if let Some(bottom) = layers.last() {
assert_ne!(below(registry, *bottom), empty_export(), "{context}: the bottom layer {bottom:?} rests on the empty export's value");
}
let unique: HashSet<NodeId> = layers.iter().copied().collect();
assert_eq!(unique.len(), layers.len(), "{context}: the stack loops: {layers:?}");
let stray: Vec<&NodeId> = registry.node_instances.keys().filter(|id| !unique.contains(id)).collect();
assert!(stray.is_empty(), "{context}: layers {stray:?} are in no stack (stack {layers:?})");
}
fn assert_consistent(context: &str, session: &Session) {
assert!(session.hot_log().is_empty(), "{context}: everything retires before history changes");
assert!(session.registry().value_equal(session.retired_registry()), "{context}: working and snapshot differ");
let folded = session.snapshot_from_history().expect("history folds");
assert!(folded.value_equal(session.retired_registry()), "{context}: the snapshot is not what history folds to");
assert_well_formed(context, session.retired_registry());
}
/// Closes the open interaction and retires it as one step.
fn retire_step(session: &mut Session) {
session.end_interaction().expect("close");
for interaction in session.closed_interactions() {
session.retire_interaction(&interaction).expect("retire");
}
}
/// Brings `follower` up to the host's history and head, as the room does with what the host broadcasts.
fn catch_up(follower: &mut Session, host: &Session) {
let missing: Vec<_> = host.cloned_deltas().into_iter().filter(|delta| follower.delta(delta.id).is_none()).collect();
follower.follow(missing, host.head_rev()).expect("follow");
}
/// A peer that joins now and holds what the host holds.
fn fresh_follower(host: &Session) -> Session {
Session::load(PeerId(2), UserId(2), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0)
}
fn simulate(seed: u64, steps: usize, log: &mut Vec<String>) -> Session {
let mut random = Random::new(seed);
let mut host = Session::with_identity(PeerId(1), UserId(1));
let document = [
RegistryDelta::AddNetwork {
id: ROOT_NETWORK,
network: Network::default(),
},
RegistryDelta::SetNetworkExport {
id: ROOT_NETWORK,
index: 0,
export: Some(empty_export()),
},
];
host.stage_ops(document).expect("stage the document");
retire_step(&mut host);
let mut follower = fresh_follower(&host);
for step in 0..steps {
let context = |what: &str, log: &[String]| format!("seed {seed}, step {step}, {what}\n{}", log.join("\n"));
match random.below(12) {
0..=5 => {
let ops = random_edit(&mut random, &mut host);
if ops.is_empty() {
continue;
impl Scenario for Stack {
fn random_edit(random: &mut Random, session: &mut Session) -> Vec<RegistryDelta> {
let registry = session.registry().clone();
let layers = stack(&registry);
match random.below(10) {
// Draw a layer on top
0..=3 => {
let id = session.next_node_id();
let mut node = Node::new(ROOT_NETWORK, Implementation::Network(LEAF), 2);
node.inputs[0].input = layers.first().map_or_else(|| value(0), |&top| on(top));
node.inputs[1].input = value(random.below(100));
let leaf = (!registry.networks.contains_key(&LEAF)).then(|| RegistryDelta::AddNetwork {
id: LEAF,
network: Network::default(),
});
let mut ops: Vec<RegistryDelta> = leaf.into_iter().collect();
ops.extend([
RegistryDelta::AddNode { id, node },
RegistryDelta::SetNetworkExport {
id: ROOT_NETWORK,
index: 0,
export: Some(on(id)),
},
]);
// The layer below moves into the stack under the new one, as the editor records with its position
if let Some(&below) = layers.first() {
ops.push(super::crdt::change_node_attribute(below, "position", serde_json::json!(random.below(100))));
}
log.push(format!("{step}: edit {}", summarize(&ops)));
host.stage_ops(ops).expect("stage");
retire_step(&mut host);
catch_up(&mut follower, &host);
ops
}
6 if host.can_undo() => {
log.push(format!("{step}: undo"));
host.undo().expect("undo");
follower = fresh_follower(&host);
// Delete a layer, reconnecting what was above it to what was below
4..=5 => {
let Some(layer) = random.pick(&layers) else { return Vec::new() };
let snapshot = registry.node_instances[&layer].clone();
vec![rewire_above(&registry, layer, below(&registry, layer)), RegistryDelta::RemoveNode { id: layer, snapshot }]
}
7 if host.can_redo() => {
log.push(format!("{step}: redo"));
host.redo().expect("redo");
follower = fresh_follower(&host);
// Move a layer to the top
6 => {
let Some(layer) = random.pick(&layers[layers.len().min(1)..]) else { return Vec::new() };
vec![
rewire_above(&registry, layer, below(&registry, layer)),
RegistryDelta::ChangeNodeInput {
id: layer,
index: 0,
new_input: on(layers[0]),
},
RegistryDelta::SetNetworkExport {
id: ROOT_NETWORK,
index: 0,
export: Some(on(layer)),
},
]
}
8 => {
// Not the newest step, which going back to would leave everything as it is
let Some(target) = random.pick(&line_steps(&host)[1.min(line_steps(&host).len())..]) else {
continue;
};
log.push(format!("{step}: go back to {target:?}"));
let (moved, _) = host.move_head_to(target).expect("go back");
follower.apply_head_move(&moved).expect("follow the move");
// Change a layer's value
_ => {
let Some(layer) = random.pick(&layers) else { return Vec::new() };
vec![RegistryDelta::ChangeNodeInput {
id: layer,
index: 1,
new_input: value(random.below(100)),
}]
}
9 => {
let steps = line_steps(&host);
// The first step makes the document, which nothing can do without
let Some(target) = random.pick(&steps[..steps.len().saturating_sub(1)]) else { continue };
log.push(format!("{step}: remove {target:?}"));
let (mut added, _) = added_and_removed(&host, target);
// A layer the line had before the step stays
let earlier = live_before(&host, target);
added.retain(|id| !earlier.contains(id));
let (moved, _) = host.drop_interaction(target).expect("remove the step");
follower.apply_head_move(&moved).expect("follow the removal");
let kept: Vec<&NodeId> = added.iter().filter(|id| host.retired_registry().node_instances.contains_key(id)).collect();
assert!(kept.is_empty(), "{}", context(&format!("the removed step's layers {kept:?} are still there"), log));
}
10 | 11 => {
let Some(target) = random.pick(&branch_steps(&host)) else { continue };
log.push(format!("{step}: bring back {target:?}"));
let (mut added, removed) = added_and_removed(&host, target);
// A layer the line already had from this step and deleted since stays deleted
added.retain(|id| !host.retired_registry().removed_nodes.contains_key(id));
// As does one a newer deletion took on the step's own line
let lost = lost_on_its_line(&host, target, &added);
added.retain(|id| !lost.contains(id));
host.restore_interaction(target).expect("bring back");
catch_up(&mut follower, &host);
let registry = host.retired_registry();
let missing: Vec<&NodeId> = added.iter().filter(|id| !registry.node_instances.contains_key(id)).collect();
let kept: Vec<&NodeId> = removed.iter().filter(|id| registry.node_instances.contains_key(id)).collect();
assert!(missing.is_empty(), "{}", context(&format!("the brought back step's layers {missing:?} are missing"), log));
assert!(kept.is_empty(), "{}", context(&format!("the layers {kept:?} the brought back step deleted are still there"), log));
}
_ => continue,
}
let what = log.last().cloned().unwrap_or_default();
assert_consistent(&context(&what, log), &host);
assert_eq!(follower.head_rev(), host.head_rev(), "{}", context("the follower is on another head", log));
assert!(
follower.retired_registry().value_equal(host.retired_registry()),
"{}",
context("the follower holds another document", log)
);
}
host
/// Every layer input and the export name a live layer, nothing loops, and every layer is in the stack, so none is
/// left drawn by nothing.
fn assert_well_formed(context: &str, registry: &Registry) {
let exports = registry.networks.get(&ROOT_NETWORK).map(|network| network.exports.clone()).unwrap_or_default();
let export = exports.first().and_then(|slot| slot.target.clone());
if let Some(NodeInput::Node { id, .. }) = &export {
assert!(registry.node_instances.contains_key(id), "{context}: the export names {id:?}, which is gone");
}
for (id, node) in &registry.node_instances {
for (index, slot) in node.inputs.iter().enumerate() {
if let NodeInput::Node { id: named, .. } = &slot.input {
assert!(registry.node_instances.contains_key(named), "{context}: input {index} of {id:?} names {named:?}, which is gone");
}
}
}
let mut stacked_on = HashSet::new();
let primary_inputs = registry.node_instances.values().filter_map(|node| node.inputs.first()).map(|slot| &slot.input);
for input in primary_inputs.chain(export.iter()) {
if let NodeInput::Node { id, .. } = input {
assert!(stacked_on.insert(*id), "{context}: two layers or the export sit on {id:?}");
}
}
for (id, node) in &registry.node_instances {
if let Implementation::Network(network) = &node.implementation {
assert!(registry.networks.contains_key(network), "{context}: {id:?} is built from {network:?}, which is gone");
}
}
let layers = stack(registry);
if let Some(bottom) = layers.last() {
assert_ne!(below(registry, *bottom), empty_export(), "{context}: the bottom layer {bottom:?} rests on the empty export's value");
}
let unique: HashSet<NodeId> = layers.iter().copied().collect();
assert_eq!(unique.len(), layers.len(), "{context}: the stack loops: {layers:?}");
let stray: Vec<&NodeId> = registry.node_instances.keys().filter(|id| !unique.contains(id)).collect();
assert!(stray.is_empty(), "{context}: layers {stray:?} are in no stack (stack {layers:?})");
}
}
#[test]
fn history_operations_keep_the_stack_whole_and_peers_converged() {
let seeds: u64 = std::env::var("SEEDS").ok().and_then(|seeds| seeds.parse().ok()).unwrap_or(200);
let steps = std::env::var("STEPS").ok().and_then(|steps| steps.parse().ok()).unwrap_or(80);
let (seeds, steps) = (from_env("SEEDS", 200), from_env("STEPS", 80));
for seed in 0..seeds {
simulate(seed, steps, &mut Vec::new());
simulate::<Stack>(seed, steps, &mut Vec::new());
}
}
/// A seed fixes the run, so one that fails can be replayed.
#[test]
fn a_seed_fixes_the_history_run() {
let histories = |seed| simulate(seed, 60, &mut Vec::new()).history().map(|delta| delta.id).collect::<Vec<_>>();
let histories = |seed| simulate::<Stack>(seed, 60, &mut Vec::new()).history().map(|delta| delta.id).collect::<Vec<_>>();
for seed in 0..5 {
assert_eq!(histories(seed), histories(seed), "seed {seed}");
}
@@ -443,9 +150,7 @@ fn a_seed_fixes_the_history_run() {
#[test]
#[ignore]
fn inspect_seed() {
let seed = std::env::var("SEED").ok().and_then(|seed| seed.parse().ok()).unwrap_or(0);
let mut log = Vec::new();
let steps = std::env::var("STEPS").ok().and_then(|steps| steps.parse().ok()).unwrap_or(80);
let host = simulate(seed, steps, &mut log);
let host = simulate::<Stack>(from_env("SEED", 0), from_env("STEPS", 80), &mut log);
println!("{}\nstack {:?}", log.join("\n"), stack(host.retired_registry()));
}
+20 -4
View File
@@ -12,9 +12,25 @@ use crate::{NetworkId, NodeMetadataSource, PeerId, Position, Registry, from_valu
/// Note: This only works for complete networks with all inputs resolved.
/// Test networks with Import inputs will fail compilation (which is expected).
fn verify_network_compiles(network: &NodeNetwork) -> Result<(), String> {
use graph_craft::document::value::TaggedValue;
let mut network = network.clone();
network.inline_definitions().map_err(|e| format!("Inlining failed: {e}"))?;
// Nodes measuring in physical units read the document's resolution from the scope the runtime wraps every document in
let resolution_node = NodeId(u64::MAX);
network.nodes.insert(
resolution_node,
DocumentNode {
inputs: vec![NodeInput::value(TaggedValue::Number(core_types::units::DEFAULT_PIXELS_PER_INCH), false)],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::ops::PassthroughNode")),
..Default::default()
},
);
network
.scope_injections
.insert(core_types::units::PIXELS_PER_INCH_SCOPE.to_string(), (resolution_node, core_types::item!(f64)));
let compiler = Compiler {};
compiler.compile_single(network).map_err(|e| format!("Compilation failed: {:?}", e))?;
Ok(())
@@ -444,7 +460,7 @@ fn test_ui_metadata_round_trip() {
None,
NodeId(1),
UiState {
position: Some(Position::Chain),
position: Some(Position::Relative([-7, 0])),
..Default::default()
},
);
@@ -454,7 +470,7 @@ fn test_ui_metadata_round_trip() {
Some(NESTED),
NodeId(10),
UiState {
position: Some(Position::Stack(7)),
position: Some(Position::Relative([0, 10])),
is_layer: true,
..Default::default()
},
@@ -484,14 +500,14 @@ fn test_ui_metadata_round_trip() {
assert!(!root_layer.pinned);
let root_node = lookup.get(&(NetworkLocation::default(), NodeId(1))).expect("entry for root-network chain node missing");
assert_eq!(root_node.position, Some(Position::Chain));
assert_eq!(root_node.position, Some(Position::Relative([-7, 0])));
assert!(!root_node.is_layer);
let DocumentNodeImplementation::Definition(nested) = converted.nodes[&NodeId(0)].implementation else {
panic!("the nested network converts back as a table entry")
};
let nested_layer = lookup.get(&(Some(nested), NodeId(10))).expect("entry for nested layer-in-stack missing");
assert_eq!(nested_layer.position, Some(Position::Stack(7)));
assert_eq!(nested_layer.position, Some(Position::Relative([0, 10])));
assert!(nested_layer.is_layer);
}
@@ -1033,6 +1033,33 @@ fn deleting_a_node_without_inputs_gives_the_input_it_fed_its_earlier_value() {
assert_eq!(registry.node_instances[&consumer].inputs()[1].input, earlier_value);
}
/// Bringing back a step that writes to a node the line never had reconnects an input naming that node to what history
/// holds as its primary input, though the write leaves only a placeholder of it.
#[test]
fn bringing_back_a_step_reconnects_past_a_node_the_line_never_had() {
let (source, consumer) = (NodeId(1), NodeId(2));
let source_value = NodeInput::Value {
value: Value::from(serde_json::json!("under the source")),
exposed: false,
};
let mut source_node = Node::new(NetworkId(5), Implementation::ProtoNode(ResourceId::new()), 1);
source_node.inputs[0].input = source_value.clone();
let mut consumer_node = Node::new(NetworkId(5), Implementation::ProtoNode(ResourceId::new()), 1);
consumer_node.inputs[0].input = NodeInput::Node { id: source, index: 0 };
let mut session = Session::with_peer(PeerId(1));
let base = step(&mut session, add_network(5));
step(&mut session, RegistryDelta::AddNode { id: source, node: source_node });
session.commit_op_for_test(RegistryDelta::AddNode { id: consumer, node: consumer_node }).expect("commit");
let consumed = step(&mut session, change_node_attribute(source, "position", serde_json::json!(1)));
session.move_head_to(base).expect("go back to before the source");
session.restore_interaction(consumed).expect("bring the consumer back");
let registry = session.retired_registry();
assert!(registry.removed_nodes.get(&source).is_some_and(|tombstone| tombstone.placeholder));
assert_eq!(registry.node_instances[&consumer].inputs()[0].input, source_value);
}
/// Undo of a retired step names the person's latest step, not the device's. A fresh copy of the document under a new
/// peer id still undoes what its user did from the old one, and nobody else's.
#[test]
@@ -0,0 +1,315 @@
//! Shared harness of the deterministic history simulations: a seeded generator, every history operation the History
//! panel offers, and the checks each run makes after every operation.
use crate::{Network, NetworkId, NodeId, NodeInput, PeerId, ROOT_NETWORK, Registry, RegistryDelta, Rev, Session, UserId, Value};
use std::collections::{HashMap, HashSet};
/// What every node's implementation names, so nodes need no proto-node declarations. The first node drawn brings it,
/// as the editor's first layer brings the subgraph every later one is built from.
pub(super) const LEAF: NetworkId = NetworkId(1);
/// What the export holds while the document is empty, of another type than what a chain's bottom rests on.
pub(super) fn empty_export() -> NodeInput {
NodeInput::Value {
value: Value::from(serde_json::json!("empty")),
exposed: false,
}
}
/// A small xorshift generator, so a seed fixes the run.
pub(super) struct Random(u64);
impl Random {
fn new(seed: u64) -> Self {
Self(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1)
}
pub(super) fn below(&mut self, bound: usize) -> usize {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
(self.0 % bound as u64) as usize
}
pub(super) fn pick<T: Copy>(&mut self, options: &[T]) -> Option<T> {
(!options.is_empty()).then(|| options[self.below(options.len())])
}
}
/// A kind of document the simulation edits.
pub(super) trait Scenario {
/// One interaction's ops for a random edit, as the editor would stage them.
fn random_edit(random: &mut Random, session: &mut Session) -> Vec<RegistryDelta>;
/// Panics with `context` when `registry` is not a document this scenario allows.
fn assert_well_formed(context: &str, registry: &Registry);
}
/// The nodes down the chain off the export, following each one's primary input.
pub(super) fn stack(registry: &Registry) -> Vec<NodeId> {
let mut nodes = Vec::new();
let mut below = registry.networks.get(&ROOT_NETWORK).and_then(|network| network.exports.first()).and_then(|slot| slot.target.clone());
while let Some(NodeInput::Node { id, .. }) = below {
if nodes.contains(&id) {
break;
}
nodes.push(id);
below = registry.node_instances.get(&id).and_then(|node| node.inputs.first()).map(|slot| slot.input.clone());
}
nodes
}
/// What feeds into `node` from below.
pub(super) fn below(registry: &Registry, node: NodeId) -> NodeInput {
registry.node_instances[&node].inputs[0].input.clone()
}
pub(super) fn on(id: NodeId) -> NodeInput {
NodeInput::Node { id, index: 0 }
}
pub(super) fn value(number: usize) -> NodeInput {
NodeInput::Value {
value: Value::from(serde_json::json!(number)),
exposed: false,
}
}
/// Reads a number from the environment variable `name`, so a run can be widened or replayed.
pub(super) fn from_env<T: std::str::FromStr>(name: &str, default: T) -> T {
std::env::var(name).ok().and_then(|text| text.parse().ok()).unwrap_or(default)
}
/// The ops of an edit, short enough to read in a failing run's log.
fn summarize(ops: &[RegistryDelta]) -> String {
let short = |id: &NodeId| id.0 % 1000;
let input = |input: &NodeInput| match input {
NodeInput::Node { id, .. } => format!("{}", short(id)),
_ => "value".to_string(),
};
ops.iter()
.map(|op| match op {
RegistryDelta::AddNode { id, node } => format!("add {} on {}", short(id), input(&node.inputs[0].input)),
RegistryDelta::RemoveNode { id, .. } => format!("remove {}", short(id)),
RegistryDelta::ChangeNodeInput { id, index, new_input } => format!("{}.{index} = {}", short(id), input(new_input)),
RegistryDelta::SetNetworkExport { export, .. } => format!("export = {}", export.as_ref().map_or("none".to_string(), input)),
RegistryDelta::AddNetwork { id, .. } => format!("add network {}", id.0),
other => format!("{other:?}"),
})
.collect::<Vec<_>>()
.join(", ")
}
/// The revs closing each interaction on the head's line, newest first.
fn line_steps(session: &Session) -> Vec<Rev> {
let mut steps = Vec::new();
let mut current = session.head_rev();
while let Some(delta) = current.and_then(|rev| session.delta(rev)) {
if delta.is_interaction_end() {
steps.push(delta.id);
}
current = delta.parent;
}
steps
}
/// The revs closing interactions left behind on branches.
fn branch_steps(session: &Session) -> Vec<Rev> {
let line: HashSet<Rev> = {
let mut line = HashSet::new();
let mut current = session.head_rev();
while let Some(delta) = current.and_then(|rev| session.delta(rev)) {
line.insert(delta.id);
current = delta.parent;
}
line
};
let mut steps: Vec<Rev> = session
.history()
.filter(|delta| delta.is_interaction_end() && !line.contains(&delta.id))
.map(|delta| delta.id)
.collect();
steps.sort();
steps
}
/// The nodes the interaction ending at `end` added and deleted, by what it did in all.
fn added_and_removed(session: &Session, end: Rev) -> (Vec<NodeId>, Vec<NodeId>) {
let (mut added, mut removed) = (Vec::new(), Vec::new());
let mut current = session.delta(end);
while let Some(delta) = current {
match &delta.kind {
RegistryDelta::AddNode { id, .. } => added.push(*id),
RegistryDelta::RemoveNode { id, .. } => removed.push(*id),
_ => {}
}
current = delta.parent.and_then(|parent| session.delta(parent)).filter(|parent| !parent.is_interaction_end());
}
let net = |these: &[NodeId], those: &[NodeId]| these.iter().filter(|id| !those.contains(id)).copied().collect();
(net(&added, &removed), net(&removed, &added))
}
/// The nodes the step ending at `end` added that a newer deletion on its own line had taken again.
fn lost_on_its_line(session: &Session, end: Rev, added: &[NodeId]) -> HashSet<NodeId> {
let mut lost = HashSet::new();
let mut added_at = HashMap::new();
let mut line = Vec::new();
let mut current = session.delta(end);
while let Some(delta) = current {
line.push(delta);
current = delta.parent.and_then(|parent| session.delta(parent));
}
for delta in &line {
if let RegistryDelta::AddNode { id, .. } = &delta.kind {
added_at.entry(*id).or_insert(delta.timestamp);
}
}
for delta in &line {
if let RegistryDelta::RemoveNode { id, .. } = &delta.kind
&& added.contains(id)
&& added_at.get(id).is_some_and(|stamp| *stamp < delta.timestamp)
{
lost.insert(*id);
}
}
lost
}
/// The nodes live on the line just before the interaction ending at `end`.
fn live_before(session: &Session, end: Rev) -> HashSet<NodeId> {
let mut current = session.delta(end);
while let Some(delta) = current.filter(|delta| delta.id == end || !delta.is_interaction_end()) {
current = delta.parent.and_then(|parent| session.delta(parent));
}
let mut line = Vec::new();
while let Some(delta) = current {
line.push(delta.clone());
current = delta.parent.and_then(|parent| session.delta(parent));
}
line.reverse();
let replayed = Session::replay_from_history(PeerId(3), UserId(3), line, 0).expect("the line replays");
replayed.retired_registry().node_instances.keys().copied().collect()
}
fn assert_consistent<S: Scenario>(context: &str, session: &Session) {
assert!(session.hot_log().is_empty(), "{context}: everything retires before history changes");
assert!(session.registry().value_equal(session.retired_registry()), "{context}: working and snapshot differ");
let folded = session.snapshot_from_history().expect("history folds");
assert!(folded.value_equal(session.retired_registry()), "{context}: the snapshot is not what history folds to");
S::assert_well_formed(context, session.retired_registry());
}
/// Closes the open interaction and retires it as one step.
fn retire_step(session: &mut Session) {
session.end_interaction().expect("close");
for interaction in session.closed_interactions() {
session.retire_interaction(&interaction).expect("retire");
}
}
/// Brings `follower` up to the host's history and head, as the room does with what the host broadcasts.
fn catch_up(follower: &mut Session, host: &Session) {
let missing: Vec<_> = host.cloned_deltas().into_iter().filter(|delta| follower.delta(delta.id).is_none()).collect();
follower.follow(missing, host.head_rev()).expect("follow");
}
/// A peer that joins now and holds what the host holds.
fn fresh_follower(host: &Session) -> Session {
Session::load(PeerId(2), UserId(2), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0)
}
/// Runs `steps` random edits and history operations from `seed`. After each one the document must be well formed, the
/// snapshot must be what history folds to, and a peer following the host must hold the same document.
pub(super) fn simulate<S: Scenario>(seed: u64, steps: usize, log: &mut Vec<String>) -> Session {
let mut random = Random::new(seed);
let mut host = Session::with_identity(PeerId(1), UserId(1));
let document = [
RegistryDelta::AddNetwork {
id: ROOT_NETWORK,
network: Network::default(),
},
RegistryDelta::SetNetworkExport {
id: ROOT_NETWORK,
index: 0,
export: Some(empty_export()),
},
];
host.stage_ops(document).expect("stage the document");
retire_step(&mut host);
let mut follower = fresh_follower(&host);
for step in 0..steps {
let context = |what: &str, log: &[String]| format!("seed {seed}, step {step}, {what}\n{}", log.join("\n"));
match random.below(12) {
0..=5 => {
let ops = S::random_edit(&mut random, &mut host);
if ops.is_empty() {
continue;
}
log.push(format!("{step}: edit {}", summarize(&ops)));
host.stage_ops(ops).expect("stage");
retire_step(&mut host);
catch_up(&mut follower, &host);
}
6 if host.can_undo() => {
log.push(format!("{step}: undo"));
host.undo().expect("undo");
follower = fresh_follower(&host);
}
7 if host.can_redo() => {
log.push(format!("{step}: redo"));
host.redo().expect("redo");
follower = fresh_follower(&host);
}
8 => {
let steps = line_steps(&host);
// Not the newest step, which going back to would leave everything as it is
let Some(target) = random.pick(&steps[1.min(steps.len())..]) else { continue };
log.push(format!("{step}: go back to {target:?}"));
let (moved, _) = host.move_head_to(target).expect("go back");
follower.apply_head_move(&moved).expect("follow the move");
}
9 => {
let steps = line_steps(&host);
// The first step makes the document, which nothing can do without
let Some(target) = random.pick(&steps[..steps.len().saturating_sub(1)]) else { continue };
log.push(format!("{step}: remove {target:?}"));
let (mut added, _) = added_and_removed(&host, target);
// A node the line had before the step stays
let earlier = live_before(&host, target);
added.retain(|id| !earlier.contains(id));
let (moved, _) = host.drop_interaction(target).expect("remove the step");
follower.apply_head_move(&moved).expect("follow the removal");
let kept: Vec<&NodeId> = added.iter().filter(|id| host.retired_registry().node_instances.contains_key(id)).collect();
assert!(kept.is_empty(), "{}", context(&format!("the removed step's nodes {kept:?} are still there"), log));
}
10 | 11 => {
let Some(target) = random.pick(&branch_steps(&host)) else { continue };
log.push(format!("{step}: bring back {target:?}"));
let (mut added, removed) = added_and_removed(&host, target);
// A node the line already had from this step and deleted since stays deleted
added.retain(|id| !host.retired_registry().removed_nodes.contains_key(id));
// As does one a newer deletion took on the step's own line
let lost = lost_on_its_line(&host, target, &added);
added.retain(|id| !lost.contains(id));
host.restore_interaction(target).expect("bring back");
catch_up(&mut follower, &host);
let registry = host.retired_registry();
let missing: Vec<&NodeId> = added.iter().filter(|id| !registry.node_instances.contains_key(id)).collect();
let kept: Vec<&NodeId> = removed.iter().filter(|id| registry.node_instances.contains_key(id)).collect();
assert!(missing.is_empty(), "{}", context(&format!("the brought back step's nodes {missing:?} are missing"), log));
assert!(kept.is_empty(), "{}", context(&format!("the nodes {kept:?} the brought back step deleted are still there"), log));
}
_ => continue,
}
let what = log.last().cloned().unwrap_or_default();
assert_consistent::<S>(&context(&what, log), &host);
assert_eq!(follower.head_rev(), host.head_rev(), "{}", context("the follower is on another head", log));
assert!(
follower.retired_registry().value_equal(host.retired_registry()),
"{}",
context("the follower holds another document", log)
);
}
host
}
+1
View File
@@ -417,6 +417,7 @@ fn extract_network_metadata(registry: &Registry, attributes: &crate::Attributes,
import_metadata: attributes.get_or_default(network::IMPORT_METADATA),
export_names: attributes.get_or_default(network::EXPORT_NAMES),
export_descriptions: attributes.get_or_default(network::EXPORT_DESCRIPTIONS),
pixels_per_inch: attributes.get_typed(network::PIXELS_PER_INCH),
}
}
@@ -185,7 +185,7 @@ mod tests {
use crate::CompilerHost;
use document_graph_storage::attr::node::ui::POSITION;
use document_graph_storage::{NodeId, Position, TimeStamp, Value, to_value};
use migration_core::Declaration;
use migration_core::{CHAIN_WIDTH, Declaration, FEEDER_ROW_HEIGHT};
use migration_runner::testing::{Fixture, Random, SourceContract, check_commutation_with, check_undo_with};
const COPY_TO_POINTS: Declaration = decl!("core_types::vector::CopyToPointsNode"@1);
@@ -318,8 +318,8 @@ mod tests {
panic!("the repeat reads the group")
};
assert_eq!(stages, [-1, 6, 13].map(|x| Some(Position::Absolute([x, 10]))));
assert_eq!(position_of(group), Some(Position::Absolute([-8, 13])));
assert_eq!(stages, [Some(Position::Relative([-CHAIN_WIDTH, 0])); 3]);
assert_eq!(position_of(group), Some(Position::Relative([-CHAIN_WIDTH, FEEDER_ROW_HEIGHT])));
}
#[test]
+2 -1
View File
@@ -8,6 +8,7 @@ pub mod v1;
pub mod v2;
pub mod v3;
pub mod v4;
pub use v4 as latest;
pub mod v5;
pub use v5 as latest;
mod steps;
@@ -3,3 +3,4 @@
mod v1_to_v2;
mod v2_to_v3;
mod v3_to_v4;
mod v4_to_v5;
@@ -0,0 +1,330 @@
//! Format step 4 to 5: every node another node reads is stored as an offset from the top left corner of its readers, which draws it where it was.
use crate::v4::{AttributeDelta, AttributeValue, Attributes, Delta, Node, NodeField, NodeId, NodeInput, Prior, Registry, RegistryDelta, Rev, TimeStamp, Value};
use crate::{v4, v5};
use migration_core::{DocumentPayloads, MigrationError, Payload, Upgrade, format_migration};
use std::collections::{HashMap, HashSet};
use std::num::NonZeroU128;
format_migration! {
4 => 5,
registry: v4::Registry,
delta: v4::Delta,
hot_op: v4::HotOp,
document: relative_to_readers,
}
const POSITION: &str = "ui::position";
const INTERACTION_END: &str = "interaction_end";
const CHAIN_WIDTH: i128 = 7;
const LAYER_HEIGHT: i128 = 2;
const LAYER_BOTTOM_GAP: i128 = 1;
impl Upgrade for v4::Registry {
type Next = v5::Registry;
fn upgrade(mut self) -> Result<Self::Next, MigrationError> {
convert_registry(&mut self);
Ok(self)
}
}
impl Upgrade for v4::Delta {
type Next = v5::Delta;
fn upgrade(mut self) -> Result<Self::Next, MigrationError> {
convert_delta(&mut self);
Ok(self)
}
}
impl Upgrade for v4::HotOp {
type Next = v5::HotOp;
fn upgrade(mut self) -> Result<Self::Next, MigrationError> {
convert_operation(&mut self.op);
Ok(self)
}
}
fn convert_registry(registry: &mut Registry) {
for node in registry.node_instances.values_mut() {
convert_node(node);
}
for tombstone in registry.removed_nodes.values_mut() {
convert_node(&mut tombstone.content);
}
}
fn convert_delta(delta: &mut Delta) {
convert_operation(&mut delta.kind);
for prior in &mut delta.reverse {
convert_prior(prior);
}
}
fn convert_operation(operation: &mut RegistryDelta) {
match operation {
RegistryDelta::AddNode { node, .. } | RegistryDelta::RemoveNode { snapshot: node, .. } => convert_node(node),
RegistryDelta::ChangeNodeAttribute { delta, .. } if delta.key == POSITION => {
if let Some(position) = &mut delta.value {
convert_position(position);
}
}
_ => {}
}
}
fn convert_prior(prior: &mut Prior) {
match prior {
Prior::Node { node, .. } => convert_node(node),
Prior::RemovedNode { tombstone, .. } => convert_node(&mut tombstone.content),
Prior::NodeField {
field: NodeField::Attribute { key, previous: Some(previous) },
..
} if key == POSITION => convert_position(&mut previous.value),
_ => {}
}
}
fn convert_node(node: &mut Node) {
convert_attributes(&mut node.attributes);
}
fn convert_attributes(attributes: &mut Attributes) {
if let Some(entry) = attributes.entries.get_mut(POSITION) {
convert_position(&mut entry.value);
}
}
fn convert_position(position: &mut Value) {
let offset = match position {
Value::Str(variant) if variant == "Chain" => [-CHAIN_WIDTH, 0],
Value::Object(fields) => match fields.as_slice() {
[(variant, Value::Int(gap))] if variant == "Stack" => [0, LAYER_HEIGHT + LAYER_BOTTOM_GAP + gap],
_ => return,
},
_ => return,
};
*position = Value::Object(vec![("Relative".to_string(), Value::Array(offset.map(Value::Int).to_vec()))]);
}
fn relative_to_readers(document: &mut DocumentPayloads) -> Result<(), MigrationError> {
let Some(registry_record) = document.registry.clone() else { return Ok(()) };
if !document.hot_log.is_empty() {
return Ok(());
}
let mut registry: v5::Registry = registry_record.decode()?;
let mut conversions = StoredPositions::new(&registry).relative_to_readers();
conversions.sort_by_key(|(id, _)| *id);
if document.history.is_empty() {
for (id, position) in conversions {
if let Some(entry) = registry.node_instances.get_mut(&id).and_then(|node| node.attributes.entries.get_mut(POSITION)) {
entry.value = position.into_value();
}
}
} else if !append_as_one_interaction(document, &mut registry, &conversions)? {
return Ok(());
}
document.registry = Some(registry_record.encode_as(&registry)?);
Ok(())
}
fn append_as_one_interaction(document: &mut DocumentPayloads, registry: &mut v5::Registry, conversions: &[(NodeId, Position)]) -> Result<bool, MigrationError> {
let (Some(session_record), Some(template)) = (document.session.clone(), document.history.first().cloned()) else {
return Ok(false);
};
let mut session: v5::SessionState = session_record.decode()?;
let history: Vec<v5::Delta> = document.history.iter().map(Payload::decode).collect::<Result<_, _>>()?;
let mut counter = history.iter().map(|delta| delta.timestamp.counter).fold(session.clock_counter, u64::max);
let taken: HashSet<Rev> = history.iter().map(|delta| delta.id).collect();
let mut placeholders = (1..=u128::MAX).rev().filter_map(NonZeroU128::new).map(Rev).filter(|rev| !taken.contains(rev));
let retired_at_ms = history.iter().find(|delta| Some(delta.id) == session.head_rev).map_or(0, |delta| delta.retired_at_ms);
let mut parent = session.head_rev;
for (index, (id, position)) in conversions.iter().enumerate() {
let Some(node) = registry.node_instances.get_mut(id) else { continue };
counter += 1;
let timestamp = TimeStamp { counter, peer: session.peer_id };
let value = position.into_value();
let previous = node.attributes.entries.insert(
POSITION.to_string(),
AttributeValue {
value: value.clone(),
timestamp,
deleted: false,
},
);
let mut attributes = Attributes::default();
if index + 1 == conversions.len() {
attributes.entries.insert(
INTERACTION_END.to_string(),
AttributeValue {
value: Value::Bool(true),
timestamp,
deleted: false,
},
);
}
let rev = placeholders.next().ok_or_else(|| MigrationError::Encode("no placeholder revision is left".to_string()))?;
let delta = v5::Delta {
id: rev,
parent,
author: session.peer_id,
timestamp,
kind: RegistryDelta::ChangeNodeAttribute {
id: *id,
delta: AttributeDelta {
key: POSITION.to_string(),
value: Some(value),
},
},
reverse: vec![Prior::NodeField {
id: *id,
presence: node.presence,
field: NodeField::Attribute { key: POSITION.to_string(), previous },
}],
attributes,
retired_at_ms,
};
document.history.push(template.encode_as(&delta)?);
parent = Some(rev);
}
session.head_rev = parent;
session.redo_stack.clear();
session.clock_counter = counter;
document.session = Some(session_record.encode_as(&session)?);
Ok(true)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Position {
Absolute([i128; 2]),
Relative([i128; 2]),
}
impl Position {
fn from_value(value: &Value) -> Option<Self> {
let Value::Object(fields) = value else { return None };
let [(variant, Value::Array(coordinates))] = fields.as_slice() else { return None };
let [Value::Int(x), Value::Int(y)] = coordinates.as_slice() else { return None };
match variant.as_str() {
"Absolute" => Some(Self::Absolute([*x, *y])),
"Relative" => Some(Self::Relative([*x, *y])),
_ => None,
}
}
fn into_value(self) -> Value {
let (variant, [x, y]) = match self {
Self::Absolute(position) => ("Absolute", position),
Self::Relative(offset) => ("Relative", offset),
};
Value::Object(vec![(variant.to_string(), Value::Array(vec![Value::Int(x), Value::Int(y)]))])
}
}
struct StoredPositions {
stored: HashMap<NodeId, Position>,
readers: HashMap<NodeId, Vec<NodeId>>,
drawn: HashMap<NodeId, [i128; 2]>,
visiting: HashSet<NodeId>,
}
impl StoredPositions {
fn new(registry: &v5::Registry) -> Self {
let stored = registry
.node_instances
.iter()
.filter_map(|(id, node)| Some((*id, Position::from_value(&node.attributes.entries.get(POSITION)?.value)?)))
.collect();
let mut readers: HashMap<NodeId, Vec<NodeId>> = HashMap::new();
for (reader, node) in &registry.node_instances {
let read_in_the_same_network = node.inputs.iter().filter_map(|slot| match slot.input {
NodeInput::Node { id, .. } => registry.node_instances.get(&id).is_some_and(|source| source.network == node.network).then_some(id),
_ => None,
});
for source in read_in_the_same_network {
readers.entry(source).or_default().push(*reader);
}
}
Self {
stored,
readers,
drawn: HashMap::new(),
visiting: HashSet::new(),
}
}
fn relative_to_readers(mut self) -> Vec<(NodeId, Position)> {
let nodes: Vec<(NodeId, Position)> = self.stored.iter().map(|(id, position)| (*id, *position)).collect();
nodes
.into_iter()
.filter_map(|(id, stored)| match (stored, self.readers_top_left(id)) {
(Position::Absolute([x, y]), Some([left, top])) => Some((id, Position::Relative([x - left, y - top]))),
(Position::Relative(_), None) => Some((id, Position::Absolute([0, 0]))),
_ => None,
})
.collect()
}
fn readers_top_left(&mut self, id: NodeId) -> Option<[i128; 2]> {
let readers = self.readers.get(&id)?.clone();
readers.into_iter().map(|reader| self.drawn(reader)).reduce(|[left, top], [x, y]| [left.min(x), top.min(y)])
}
fn drawn(&mut self, id: NodeId) -> [i128; 2] {
if let Some(position) = self.drawn.get(&id) {
return *position;
}
if !self.visiting.insert(id) {
return [0, 0];
}
let position = match self.stored.get(&id).copied() {
Some(Position::Absolute(position)) => position,
Some(Position::Relative([x, y])) => self.readers_top_left(id).map_or([0, 0], |[left, top]| [left + x, top + y]),
None => [0, 0],
};
self.visiting.remove(&id);
self.drawn.insert(id, position);
position
}
}
#[cfg(test)]
mod tests {
use super::*;
fn relative(x: i128, y: i128) -> Value {
Value::Object(vec![("Relative".to_string(), Value::Array(vec![Value::Int(x), Value::Int(y)]))])
}
#[test]
fn a_chained_position_becomes_one_chain_width_left_of_its_reader() {
let mut position = Value::Str("Chain".to_string());
convert_position(&mut position);
assert_eq!(position, relative(-CHAIN_WIDTH, 0));
}
#[test]
fn a_stacked_position_becomes_its_gap_below_the_layer_reading_it() {
let mut position = Value::Object(vec![("Stack".to_string(), Value::Int(2))]);
convert_position(&mut position);
assert_eq!(position, relative(0, 5));
}
#[test]
fn absolute_and_relative_positions_stay_as_they_are() {
for stored in [Value::Object(vec![("Absolute".to_string(), Value::Array(vec![Value::Int(3), Value::Int(4)]))]), relative(-7, 3)] {
let mut position = stored.clone();
convert_position(&mut position);
assert_eq!(position, stored);
}
}
}
+8
View File
@@ -0,0 +1,8 @@
//! Format version 5. No stored type changed: every node another node reads stores its position as an offset from the top left corner
//! of its readers, so the `ui::position` attribute no longer holds `Chain` or `Stack`. Never edit it: old documents decode through these definitions.
pub use super::v4::{
AttributeDelta, AttributeValue, Attributes, BlobHash, Delta, ExportSlot, HotOp, HotOpId, HotSequence, Implementation, InputSlot, Network, NetworkField, NetworkId, Node, NodeField, NodeId,
NodeInput, NonFinitePriority, PeerId, PeerRegistration, Prior, Priority, ProtoNode, Registry, RegistryDelta, ResourceEntry, ResourceStore, RetiredMarks, Rev, SessionState, SourceKey, SourceValue,
TimeStamp, Tombstone, UserId, Value,
};
@@ -0,0 +1,157 @@
//! The step to version 5 stores every node another node reads relative to its readers, appending the conversion to history as one interaction.
use document_graph_storage::{
AttributeDelta, Delta, Implementation, Network, Node, NodeId, NodeInput, PeerId, ROOT_NETWORK, Registry, RegistryDelta, ResourceId, Session, SessionState, UserId, rehash_deltas, to_value,
};
use migration_core::{DocumentPayloads, Payload, PayloadCodec};
use serde::{Deserialize, Serialize};
// Format steps register when linked
use migration_formats as _;
const POSITION: &str = "ui::position";
const PEER: PeerId = PeerId(1);
const USER: UserId = UserId(1);
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
enum Position {
Absolute([i32; 2]),
Chain,
Stack(u32),
Relative([i32; 2]),
}
fn postcard_payload(value: &impl Serialize) -> Payload {
Payload::encode(value, PayloadCodec::Postcard).unwrap()
}
fn position_of(registry: &Registry, id: NodeId) -> Option<Position> {
registry.node_instances.get(&id)?.attributes().get_typed(POSITION)
}
fn set_position(id: NodeId, position: Position) -> RegistryDelta {
RegistryDelta::ChangeNodeAttribute {
id,
delta: AttributeDelta {
key: POSITION.to_string(),
value: Some(to_value(&position).unwrap()),
},
}
}
fn reading(read: NodeId) -> Node {
let mut reader = Node::new(ROOT_NETWORK, Implementation::ProtoNode(ResourceId::from(1)), 2);
reader.inputs_mut()[1].input = NodeInput::Node { id: read, index: 0 };
reader
}
/// A node at `reader_position` reading a node stored at `read_position`, each added and placed as one interaction.
fn session_at_version_four(reader: NodeId, reader_position: Position, read: NodeId, read_position: Position) -> Session {
let mut session = Session::with_identity(PEER, USER);
let network = RegistryDelta::AddNetwork {
id: ROOT_NETWORK,
network: Network::default(),
};
let source = Node::new(ROOT_NETWORK, Implementation::ProtoNode(ResourceId::from(2)), 1);
let interactions = [
vec![network, RegistryDelta::AddNode { id: read, node: source }, set_position(read, read_position)],
vec![RegistryDelta::AddNode { id: reader, node: reading(read) }, set_position(reader, reader_position)],
];
for operations in interactions {
session.stage_computed_ops(operations).unwrap();
let retired = session.retire_all().unwrap();
session.mark_interaction_end(*retired.last().unwrap());
}
session
}
/// A layer at (30, 10) reading a node stored at the absolute position (23, 10).
fn version_four_session(layer: NodeId, read: NodeId) -> Session {
session_at_version_four(layer, Position::Absolute([30, 10]), read, Position::Absolute([23, 10]))
}
/// Runs the step into version 5 on `session` saved at version 4, then opens the result the way the load path does.
fn open_at_version_five(session: &Session) -> (Session, Vec<Delta>) {
let state = SessionState {
peer_id: PEER,
user_id: USER,
head_rev: session.head_rev(),
clock_counter: session.clock_counter(),
..Default::default()
};
let mut document = DocumentPayloads {
format_version: 4,
registry: Some(postcard_payload(session.retired_registry())),
history: session.history().map(postcard_payload).collect(),
hot_log: session.hot_log().iter().map(postcard_payload).collect(),
session: Some(postcard_payload(&state)),
..Default::default()
};
let steps = migration_core::registered_format_migrations();
let step = steps.iter().find(|step| step.migrates_from() == 4).expect("the step into version 5");
document.registry = Some(step.migrate_registry(document.registry.as_ref().unwrap()).unwrap());
document.history = document.history.iter().map(|record| step.migrate_delta(record).unwrap()).collect();
document.hot_log = document.hot_log.iter().map(|record| step.migrate_hot_op(record).unwrap()).collect();
step.migrate_document(&mut document).unwrap();
let mut history: Vec<Delta> = document.history.iter().map(|record| record.decode().unwrap()).collect();
let revs = rehash_deltas(&mut history);
let state: SessionState = document.session.unwrap().decode().unwrap();
let head = state.head_rev.map(|rev| revs.get(&rev).copied().unwrap_or(rev));
let registry: Registry = document.registry.unwrap().decode().unwrap();
(Session::load(PEER, USER, registry, history.clone(), head, state.redo_stack, 0), history)
}
#[test]
fn a_read_node_becomes_relative_to_its_reader_where_it_was_drawn() {
let (layer, read) = (NodeId(1), NodeId(2));
let (migrated, _) = open_at_version_five(&version_four_session(layer, read));
assert_eq!(position_of(migrated.retired_registry(), read), Some(Position::Relative([-7, 0])));
assert_eq!(position_of(migrated.retired_registry(), layer), Some(Position::Absolute([30, 10])));
}
#[test]
fn replaying_the_migrated_history_reaches_the_migrated_registry() {
let (layer, read) = (NodeId(1), NodeId(2));
let (migrated, history) = open_at_version_five(&version_four_session(layer, read));
let replayed = Session::replay_from_history(PEER, USER, history, 0).unwrap();
for id in [layer, read] {
assert_eq!(position_of(replayed.retired_registry(), id), position_of(migrated.retired_registry(), id));
}
}
#[test]
fn undo_takes_back_the_conversion_as_one_interaction() {
let (layer, read) = (NodeId(1), NodeId(2));
let (mut migrated, _) = open_at_version_five(&version_four_session(layer, read));
migrated.undo().unwrap();
assert_eq!(position_of(migrated.retired_registry(), read), Some(Position::Absolute([23, 10])));
assert!(migrated.retired_registry().node_instances.contains_key(&layer), "the undo should stop at the conversion");
}
#[test]
fn a_node_read_by_an_unread_chain_node_is_placed_from_where_that_node_was_drawn() {
let (chained, read) = (NodeId(1), NodeId(2));
let (migrated, _) = open_at_version_five(&session_at_version_four(chained, Position::Chain, read, Position::Absolute([-7, 0])));
assert_eq!(position_of(migrated.retired_registry(), chained), Some(Position::Absolute([0, 0])));
assert_eq!(position_of(migrated.retired_registry(), read), Some(Position::Relative([-7, 0])));
}
#[test]
fn a_document_with_pending_edits_keeps_its_absolute_positions() {
let (layer, read) = (NodeId(1), NodeId(2));
let mut session = version_four_session(layer, read);
session.stage_computed_ops(vec![set_position(layer, Position::Absolute([40, 10]))]).unwrap();
let (migrated, _) = open_at_version_five(&session);
assert_eq!(position_of(migrated.retired_registry(), read), Some(Position::Absolute([23, 10])));
}
@@ -0,0 +1,80 @@
use migration_core::{Inputs, NodeInput, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
Number(f64),
Bool(bool),
TransferCurve(Vec<[f64; 2]>),
TypeDefault(Type),
}
/// Frozen mirror of the `Type` a paint input's lack of a paint stores.
#[derive(Serialize, Deserialize)]
enum Type {
Concrete(TypeDescriptor),
Item(Box<Type>),
}
#[derive(Serialize, Deserialize)]
struct TypeDescriptor {
name: String,
}
/// 'Bevel & Emboss' gained a texture with its depth, and a gloss contour and a slope contour with its range, set to no texture and straight contours across the whole slope to keep the bevel as it was.
#[migration("blending_nodes::effects::BevelAndEmbossNode"@1 => @2)]
pub fn bevel_and_emboss_v1(inputs: &mut Inputs) {
for input in added_inputs() {
inputs.push(input);
}
}
/// The texture, its depth, the slope contour's range, the gloss and slope contours' antialiasing, and the gloss and slope contours.
fn added_inputs() -> [NodeInput; 7] {
let straight = || literal(Tagged::TransferCurve(vec![[0., 0.], [1., 1.]]));
let no_paint = Tagged::TypeDefault(Type::Item(Box::new(Type::Concrete(TypeDescriptor {
name: "graphic_types::graphic::Graphic".to_string(),
}))));
[
literal(no_paint),
literal(Tagged::Number(100.)),
literal(Tagged::Number(100.)),
literal(Tagged::Bool(false)),
literal(Tagged::Bool(false)),
straight(),
straight(),
]
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(13, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&BevelAndEmbossV1, &contract());
check_undo(&BevelAndEmbossV1, &contract());
}
#[test]
fn keeps_the_inputs_and_adds_options_that_leave_the_bevel_as_it_was() {
let inputs: Vec<_> = (0..13).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&BevelAndEmbossV1);
let bevel = fixture.add(decl!("blending_nodes::effects::BevelAndEmbossNode"@1), inputs.clone());
let migrated = fixture.migrate(&BevelAndEmbossV1).unwrap();
let mut expected = inputs;
expected.extend(added_inputs());
assert_eq!(fixture.declaration_of(&migrated, bevel), Some(decl!("blending_nodes::effects::BevelAndEmbossNode"@2)));
assert_eq!(fixture.inputs(&migrated, bevel), expected);
}
}
@@ -0,0 +1,66 @@
use migration_core::{Inputs, Node, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const RADIUS: usize = 1;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The radius is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
#[migration("blending_nodes::effects::BlurNode"@2 => @3)]
pub fn blur_v2(node: &Node, inputs: &mut Inputs) {
let Some(slot) = node.inputs().get(RADIUS) else { return };
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
inputs.set(
RADIUS as u32,
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
})),
);
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(4, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&BlurV2, &contract());
check_undo(&BlurV2, &contract());
}
#[test]
fn a_number_of_pixels_becomes_a_length_in_pixels() {
let mut fixture = Fixture::new(&BlurV2);
let number = |number: f64| literal(Tagged::Number(number));
let blur = fixture.add(decl!("blending_nodes::effects::BlurNode"@2), vec![literal(Tagged::None), number(10.), number(0.), number(0.)]);
let migrated = fixture.migrate(&BlurV2).unwrap();
let radius = literal(Tagged::Length(TypedLength { value: 10., unit: LengthUnit::Pixel }));
assert_eq!(fixture.inputs(&migrated, blur), [literal(Tagged::None), radius, number(0.), number(0.)]);
}
}
@@ -0,0 +1,50 @@
use migration_core::{Inputs, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variant this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
BlendMode(BlendMode),
}
#[derive(Serialize, Deserialize)]
enum BlendMode {
Normal,
}
/// 'Drop Shadow' gained a blend mode after its color, set to Normal to keep compositing the shadow as before.
#[migration("blending_nodes::effects::DropShadowNode"@1 => @2)]
pub fn drop_shadow_v1(inputs: &mut Inputs) {
inputs.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(8, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&DropShadowV1, &contract());
check_undo(&DropShadowV1, &contract());
}
#[test]
fn keeps_the_inputs_and_inserts_normal_after_the_color() {
let inputs: Vec<_> = (0..8).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&DropShadowV1);
let drop_shadow = fixture.add(decl!("blending_nodes::effects::DropShadowNode"@1), inputs.clone());
let migrated = fixture.migrate(&DropShadowV1).unwrap();
let mut expected = inputs;
expected.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
assert_eq!(fixture.declaration_of(&migrated, drop_shadow), Some(decl!("blending_nodes::effects::DropShadowNode"@2)));
assert_eq!(fixture.inputs(&migrated, drop_shadow), expected);
}
}
@@ -0,0 +1,50 @@
use migration_core::{Inputs, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variant this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
BlendMode(BlendMode),
}
#[derive(Serialize, Deserialize)]
enum BlendMode {
Normal,
}
/// 'Inner Glow' gained a blend mode after its color, set to Normal to keep compositing the glow as before.
#[migration("blending_nodes::effects::InnerGlowNode"@1 => @2)]
pub fn inner_glow_v1(inputs: &mut Inputs) {
inputs.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(8, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&InnerGlowV1, &contract());
check_undo(&InnerGlowV1, &contract());
}
#[test]
fn keeps_the_inputs_and_inserts_normal_after_the_color() {
let inputs: Vec<_> = (0..8).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&InnerGlowV1);
let inner_glow = fixture.add(decl!("blending_nodes::effects::InnerGlowNode"@1), inputs.clone());
let migrated = fixture.migrate(&InnerGlowV1).unwrap();
let mut expected = inputs;
expected.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
assert_eq!(fixture.declaration_of(&migrated, inner_glow), Some(decl!("blending_nodes::effects::InnerGlowNode"@2)));
assert_eq!(fixture.inputs(&migrated, inner_glow), expected);
}
}
@@ -0,0 +1,50 @@
use migration_core::{Inputs, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variant this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
BlendMode(BlendMode),
}
#[derive(Serialize, Deserialize)]
enum BlendMode {
Normal,
}
/// 'Inner Shadow' gained a blend mode after its color, set to Normal to keep compositing the shadow as before.
#[migration("blending_nodes::effects::InnerShadowNode"@1 => @2)]
pub fn inner_shadow_v1(inputs: &mut Inputs) {
inputs.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(7, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&InnerShadowV1, &contract());
check_undo(&InnerShadowV1, &contract());
}
#[test]
fn keeps_the_inputs_and_inserts_normal_after_the_color() {
let inputs: Vec<_> = (0..7).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&InnerShadowV1);
let inner_shadow = fixture.add(decl!("blending_nodes::effects::InnerShadowNode"@1), inputs.clone());
let migrated = fixture.migrate(&InnerShadowV1).unwrap();
let mut expected = inputs;
expected.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
assert_eq!(fixture.declaration_of(&migrated, inner_shadow), Some(decl!("blending_nodes::effects::InnerShadowNode"@2)));
assert_eq!(fixture.inputs(&migrated, inner_shadow), expected);
}
}
@@ -0,0 +1,59 @@
use migration_core::{Inputs, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
Number(f64),
Bool(bool),
MaskMode(MaskMode),
}
#[derive(Serialize, Deserialize)]
enum MaskMode {
Luminance,
}
/// 'Mask' became an effect masking any graphic by any other, keeping its content and mask and gaining its mode, density, feather, and invert at their defaults.
#[migration("raster_nodes::std_nodes::MaskNode"@1 => "blending_nodes::masks::MaskNode"@2)]
pub fn mask_by_any_graphic(inputs: &mut Inputs) {
inputs.push(literal(Tagged::MaskMode(MaskMode::Luminance)));
inputs.push(literal(Tagged::Number(100.)));
inputs.push(literal(Tagged::Number(0.)));
inputs.push(literal(Tagged::Bool(false)));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&MaskByAnyGraphic, &contract());
check_undo(&MaskByAnyGraphic, &contract());
}
#[test]
fn keeps_the_content_and_mask_and_adds_the_defaults() {
let (content, stencil) = (literal(1.), literal(2.));
let mut fixture = Fixture::new(&MaskByAnyGraphic);
let mask = fixture.add(decl!("raster_nodes::std_nodes::MaskNode"@1), vec![content.clone(), stencil.clone()]);
let migrated = fixture.migrate(&MaskByAnyGraphic).unwrap();
assert_eq!(fixture.declaration_of(&migrated, mask), Some(decl!("blending_nodes::masks::MaskNode"@2)));
let defaults = [
literal(Tagged::MaskMode(MaskMode::Luminance)),
literal(Tagged::Number(100.)),
literal(Tagged::Number(0.)),
literal(Tagged::Bool(false)),
];
assert_eq!(fixture.inputs(&migrated, mask), [[content, stencil].as_slice(), &defaults].concat());
}
}
@@ -1,3 +1,14 @@
//! Migrations of the nodes in `blending_nodes`.
mod bevel_and_emboss_v1;
mod blur_v2;
mod drop_shadow_v1;
mod inner_glow_v1;
mod inner_shadow_v1;
mod mask_by_any_graphic;
mod outer_glow_v1;
mod outline_v1;
mod outline_v2;
mod paint_overlay_from_color_overlay;
mod renames;
mod satin_v1;
@@ -0,0 +1,50 @@
use migration_core::{Inputs, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variant this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
BlendMode(BlendMode),
}
#[derive(Serialize, Deserialize)]
enum BlendMode {
Normal,
}
/// 'Outer Glow' gained a blend mode after its color, set to Normal to keep compositing the glow as before.
#[migration("blending_nodes::effects::OuterGlowNode"@1 => @2)]
pub fn outer_glow_v1(inputs: &mut Inputs) {
inputs.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(7, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&OuterGlowV1, &contract());
check_undo(&OuterGlowV1, &contract());
}
#[test]
fn keeps_the_inputs_and_inserts_normal_after_the_color() {
let inputs: Vec<_> = (0..7).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&OuterGlowV1);
let outer_glow = fixture.add(decl!("blending_nodes::effects::OuterGlowNode"@1), inputs.clone());
let migrated = fixture.migrate(&OuterGlowV1).unwrap();
let mut expected = inputs;
expected.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
assert_eq!(fixture.declaration_of(&migrated, outer_glow), Some(decl!("blending_nodes::effects::OuterGlowNode"@2)));
assert_eq!(fixture.inputs(&migrated, outer_glow), expected);
}
}
@@ -0,0 +1,50 @@
use migration_core::{Inputs, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variant this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
BlendMode(BlendMode),
}
#[derive(Serialize, Deserialize)]
enum BlendMode {
Normal,
}
/// 'Outline' gained a blend mode after its color, set to Normal, which composites the outline as before.
#[migration("blending_nodes::effects::OutlineNode"@1 => @2)]
pub fn outline_v1(inputs: &mut Inputs) {
inputs.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(4, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&OutlineV1, &contract());
check_undo(&OutlineV1, &contract());
}
#[test]
fn keeps_the_inputs_and_inserts_normal_after_the_color() {
let inputs: Vec<_> = (0..4).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&OutlineV1);
let outline = fixture.add(decl!("blending_nodes::effects::OutlineNode"@1), inputs.clone());
let migrated = fixture.migrate(&OutlineV1).unwrap();
let mut expected = inputs;
expected.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
assert_eq!(fixture.declaration_of(&migrated, outline), Some(decl!("blending_nodes::effects::OutlineNode"@2)));
assert_eq!(fixture.inputs(&migrated, outline), expected);
}
}
@@ -0,0 +1,45 @@
use migration_core::{Inputs, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variant this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
Bool(bool),
}
/// 'Outline' takes its color as any paint now, and gained a Contour Gradient option, set off to keep painting by the paint's own placement.
#[migration("blending_nodes::effects::OutlineNode"@2 => @3)]
pub fn outline_v2(inputs: &mut Inputs) {
inputs.push(literal(Tagged::Bool(false)));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(5, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&OutlineV2, &contract());
check_undo(&OutlineV2, &contract());
}
#[test]
fn keeps_the_inputs_and_adds_contour_gradient_off() {
let inputs: Vec<_> = (0..5).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&OutlineV2);
let outline = fixture.add(decl!("blending_nodes::effects::OutlineNode"@2), inputs.clone());
let migrated = fixture.migrate(&OutlineV2).unwrap();
let mut expected = inputs;
expected.push(literal(Tagged::Bool(false)));
assert_eq!(fixture.declaration_of(&migrated, outline), Some(decl!("blending_nodes::effects::OutlineNode"@3)));
assert_eq!(fixture.inputs(&migrated, outline), expected);
}
}
@@ -0,0 +1,43 @@
use migration_core::attr::node::ui::DISPLAY_NAME;
use migration_core::{Attributes, Node, migration};
/// 'Color Overlay' became the 'Paint Overlay' effect, which takes its color as a solid paint. A name it stored as its default would misname it.
#[migration("raster_nodes::blending_nodes::ColorOverlayNode"@1 => "blending_nodes::effects::PaintOverlayNode"@2)]
pub fn paint_overlay_from_color_overlay(node: &Node, attributes: &mut Attributes) {
if node.attributes().get_typed::<String>(DISPLAY_NAME).as_deref() == Some("Color Overlay") {
attributes.remove(node.id(), DISPLAY_NAME);
}
}
#[cfg(test)]
mod tests {
use super::*;
use document_graph_storage::TimeStamp;
use migration_core::{decl, literal};
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
#[test]
fn rewrites_history() {
let contract = SourceContract {
display_names: &["Color Overlay"],
..SourceContract::new(4, |random, _| literal(random.below(10) as f64))
};
check_commutation(&PaintOverlayFromColorOverlay, &contract);
check_undo(&PaintOverlayFromColorOverlay, &contract);
}
#[test]
fn only_the_old_default_name_is_cleared() {
for (name, kept) in [("Color Overlay", None), ("Tint", Some("Tint"))] {
let mut fixture = Fixture::new(&PaintOverlayFromColorOverlay);
let overlay = fixture.add(decl!("raster_nodes::blending_nodes::ColorOverlayNode"@1), Vec::new());
let attributes = fixture.registry.node_instances.get_mut(&overlay).unwrap().attributes_mut();
attributes.set_serialized(DISPLAY_NAME, &name, TimeStamp::ORIGIN).unwrap();
let migrated = fixture.migrate(&PaintOverlayFromColorOverlay).unwrap();
assert_eq!(fixture.declaration_of(&migrated, overlay), Some(decl!("blending_nodes::effects::PaintOverlayNode"@2)));
assert_eq!(migrated.node_instances[&overlay].attributes().get_typed::<String>(DISPLAY_NAME).as_deref(), kept);
}
}
}
@@ -0,0 +1,50 @@
use migration_core::{Inputs, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variant this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
BlendMode(BlendMode),
}
#[derive(Serialize, Deserialize)]
enum BlendMode {
Normal,
}
/// 'Satin' gained a blend mode after its color, set to Normal to keep compositing the shading as before.
#[migration("blending_nodes::effects::SatinNode"@1 => @2)]
pub fn satin_v1(inputs: &mut Inputs) {
inputs.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(7, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&SatinV1, &contract());
check_undo(&SatinV1, &contract());
}
#[test]
fn keeps_the_inputs_and_inserts_normal_after_the_color() {
let inputs: Vec<_> = (0..7).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&SatinV1);
let satin = fixture.add(decl!("blending_nodes::effects::SatinNode"@1), inputs.clone());
let migrated = fixture.migrate(&SatinV1).unwrap();
let mut expected = inputs;
expected.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
assert_eq!(fixture.declaration_of(&migrated, satin), Some(decl!("blending_nodes::effects::SatinNode"@2)));
assert_eq!(fixture.inputs(&migrated, satin), expected);
}
}
@@ -0,0 +1,66 @@
use migration_core::{Inputs, Node, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const DIAMETER: usize = 2;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The diameter is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
#[migration("brush_nodes::BrushStrokesNode"@1 => @2)]
pub fn brush_strokes_v1(node: &Node, inputs: &mut Inputs) {
let Some(slot) = node.inputs().get(DIAMETER) else { return };
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
inputs.set(
DIAMETER as u32,
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
})),
);
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(5, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&BrushStrokesV1, &contract());
check_undo(&BrushStrokesV1, &contract());
}
#[test]
fn a_number_of_pixels_becomes_a_length_in_pixels() {
let mut fixture = Fixture::new(&BrushStrokesV1);
let number = |number: f64| literal(Tagged::Number(number));
let brush_strokes = fixture.add(decl!("brush_nodes::BrushStrokesNode"@1), vec![literal(Tagged::None), number(0.), number(40.), number(0.), number(100.)]);
let migrated = fixture.migrate(&BrushStrokesV1).unwrap();
let diameter = literal(Tagged::Length(TypedLength { value: 40., unit: LengthUnit::Pixel }));
assert_eq!(fixture.inputs(&migrated, brush_strokes), [literal(Tagged::None), number(0.), diameter, number(0.), number(100.)]);
}
}
@@ -0,0 +1,3 @@
//! Migrations of the nodes in `brush_nodes`.
mod brush_strokes_v1;
@@ -0,0 +1,66 @@
use migration_core::{Inputs, Node, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const DISTANCE: usize = 1;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The distance is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
#[migration("core_types::vector::BevelNode"@1 => @2)]
pub fn bevel_v1(node: &Node, inputs: &mut Inputs) {
let Some(slot) = node.inputs().get(DISTANCE) else { return };
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
inputs.set(
DISTANCE as u32,
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
})),
);
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&BevelV1, &contract());
check_undo(&BevelV1, &contract());
}
#[test]
fn a_number_of_pixels_becomes_a_length_in_pixels() {
let mut fixture = Fixture::new(&BevelV1);
let number = |number: f64| literal(Tagged::Number(number));
let bevel = fixture.add(decl!("core_types::vector::BevelNode"@1), vec![literal(Tagged::None), number(10.)]);
let migrated = fixture.migrate(&BevelV1).unwrap();
let distance = literal(Tagged::Length(TypedLength { value: 10., unit: LengthUnit::Pixel }));
assert_eq!(fixture.inputs(&migrated, bevel), [literal(Tagged::None), distance]);
}
}
@@ -0,0 +1,66 @@
use migration_core::{Inputs, Node, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const TOLERANCE: usize = 1;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The tolerance is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
#[migration("core_types::vector::DecimateNode"@1 => @2)]
pub fn decimate_v1(node: &Node, inputs: &mut Inputs) {
let Some(slot) = node.inputs().get(TOLERANCE) else { return };
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
inputs.set(
TOLERANCE as u32,
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
})),
);
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&DecimateV1, &contract());
check_undo(&DecimateV1, &contract());
}
#[test]
fn a_number_of_pixels_becomes_a_length_in_pixels() {
let mut fixture = Fixture::new(&DecimateV1);
let number = |number: f64| literal(Tagged::Number(number));
let decimate = fixture.add(decl!("core_types::vector::DecimateNode"@1), vec![literal(Tagged::None), number(5.)]);
let migrated = fixture.migrate(&DecimateV1).unwrap();
let tolerance = literal(Tagged::Length(TypedLength { value: 5., unit: LengthUnit::Pixel }));
assert_eq!(fixture.inputs(&migrated, decimate), [literal(Tagged::None), tolerance]);
}
}
@@ -0,0 +1,71 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const DIRECTION: usize = 1;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
DVec2([f64; 2]),
LengthVec2(TypedLengthVec2),
}
#[derive(Serialize, Deserialize)]
struct TypedLengthVec2 {
value: [f64; 2],
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The direction is a pair of lengths, which keeps the pixels it held. A wired Vec2 still feeds it, read as pixels.
#[migration("core_types::vector::ExtrudeNode"@1 => @2)]
pub fn extrude_v1(node: &Node, inputs: &mut Inputs) {
let Some(slot) = node.inputs().get(DIRECTION) else { return };
let Some(Tagged::DVec2(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
inputs.set(DIRECTION as u32, lengths(pixels));
}
fn lengths(pixels: [f64; 2]) -> NodeInput {
literal(Tagged::LengthVec2(TypedLengthVec2 {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(3, |random, slot| match slot {
DIRECTION => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
_ => literal(Tagged::None),
})
}
#[test]
fn rewrites_history() {
check_commutation(&ExtrudeV1, &contract());
check_undo(&ExtrudeV1, &contract());
}
#[test]
fn a_vec2_of_pixels_becomes_lengths_in_pixels() {
let mut fixture = Fixture::new(&ExtrudeV1);
let node = fixture.add(
decl!("core_types::vector::ExtrudeNode"@1),
vec![literal(Tagged::None), literal(Tagged::DVec2([30., 40.])), literal(Tagged::None)],
);
let migrated = fixture.migrate(&ExtrudeV1).unwrap();
assert_eq!(fixture.inputs(&migrated, node), [literal(Tagged::None), lengths([30., 40.]), literal(Tagged::None)]);
}
}
@@ -0,0 +1,66 @@
use migration_core::{Inputs, Node, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const MAX_DISTANCE: usize = 1;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The max distance is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
#[migration("core_types::vector::JitterPointsNode"@1 => @2)]
pub fn jitter_points_v1(node: &Node, inputs: &mut Inputs) {
let Some(slot) = node.inputs().get(MAX_DISTANCE) else { return };
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
inputs.set(
MAX_DISTANCE as u32,
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
})),
);
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(4, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&JitterPointsV1, &contract());
check_undo(&JitterPointsV1, &contract());
}
#[test]
fn a_number_of_pixels_becomes_a_length_in_pixels() {
let mut fixture = Fixture::new(&JitterPointsV1);
let number = |number: f64| literal(Tagged::Number(number));
let jitter_points = fixture.add(decl!("core_types::vector::JitterPointsNode"@1), vec![literal(Tagged::None), number(5.), number(0.), number(1.)]);
let migrated = fixture.migrate(&JitterPointsV1).unwrap();
let max_distance = literal(Tagged::Length(TypedLength { value: 5., unit: LengthUnit::Pixel }));
assert_eq!(fixture.inputs(&migrated, jitter_points), [literal(Tagged::None), max_distance, number(0.), number(1.)]);
}
}
@@ -0,0 +1,14 @@
//! Migrations of the nodes in `core_types`.
mod bevel_v1;
mod decimate_v1;
mod extrude_v1;
mod jitter_points_v1;
mod offset_path_v1;
mod offset_points_v1;
mod point_inside_v1;
mod round_corners_v1;
mod sample_polyline_v1;
mod scatter_points_v2;
mod simplify_v1;
mod weld_v1;
@@ -0,0 +1,66 @@
use migration_core::{Inputs, Node, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const DISTANCE: usize = 1;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The distance is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
#[migration("core_types::vector::OffsetPathNode"@1 => @2)]
pub fn offset_path_v1(node: &Node, inputs: &mut Inputs) {
let Some(slot) = node.inputs().get(DISTANCE) else { return };
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
inputs.set(
DISTANCE as u32,
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
})),
);
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(4, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&OffsetPathV1, &contract());
check_undo(&OffsetPathV1, &contract());
}
#[test]
fn a_number_of_pixels_becomes_a_length_in_pixels() {
let mut fixture = Fixture::new(&OffsetPathV1);
let number = |number: f64| literal(Tagged::Number(number));
let offset_path = fixture.add(decl!("core_types::vector::OffsetPathNode"@1), vec![literal(Tagged::None), number(10.), number(0.), number(4.)]);
let migrated = fixture.migrate(&OffsetPathV1).unwrap();
let distance = literal(Tagged::Length(TypedLength { value: 10., unit: LengthUnit::Pixel }));
assert_eq!(fixture.inputs(&migrated, offset_path), [literal(Tagged::None), distance, number(0.), number(4.)]);
}
}
@@ -0,0 +1,66 @@
use migration_core::{Inputs, Node, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const DISTANCE: usize = 1;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The distance is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
#[migration("core_types::vector::OffsetPointsNode"@1 => @2)]
pub fn offset_points_v1(node: &Node, inputs: &mut Inputs) {
let Some(slot) = node.inputs().get(DISTANCE) else { return };
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
inputs.set(
DISTANCE as u32,
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
})),
);
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&OffsetPointsV1, &contract());
check_undo(&OffsetPointsV1, &contract());
}
#[test]
fn a_number_of_pixels_becomes_a_length_in_pixels() {
let mut fixture = Fixture::new(&OffsetPointsV1);
let number = |number: f64| literal(Tagged::Number(number));
let offset_points = fixture.add(decl!("core_types::vector::OffsetPointsNode"@1), vec![literal(Tagged::None), number(10.)]);
let migrated = fixture.migrate(&OffsetPointsV1).unwrap();
let distance = literal(Tagged::Length(TypedLength { value: 10., unit: LengthUnit::Pixel }));
assert_eq!(fixture.inputs(&migrated, offset_points), [literal(Tagged::None), distance]);
}
}
@@ -0,0 +1,68 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const POINT: usize = 1;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
DVec2([f64; 2]),
LengthVec2(TypedLengthVec2),
}
#[derive(Serialize, Deserialize)]
struct TypedLengthVec2 {
value: [f64; 2],
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The point is a pair of lengths, which keeps the pixels it held. A wired Vec2 still feeds it, read as pixels.
#[migration("core_types::vector::PointInsideNode"@1 => @2)]
pub fn point_inside_v1(node: &Node, inputs: &mut Inputs) {
let Some(slot) = node.inputs().get(POINT) else { return };
let Some(Tagged::DVec2(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
inputs.set(POINT as u32, lengths(pixels));
}
fn lengths(pixels: [f64; 2]) -> NodeInput {
literal(Tagged::LengthVec2(TypedLengthVec2 {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, slot| match slot {
POINT => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
_ => literal(Tagged::None),
})
}
#[test]
fn rewrites_history() {
check_commutation(&PointInsideV1, &contract());
check_undo(&PointInsideV1, &contract());
}
#[test]
fn a_vec2_of_pixels_becomes_lengths_in_pixels() {
let mut fixture = Fixture::new(&PointInsideV1);
let node = fixture.add(decl!("core_types::vector::PointInsideNode"@1), vec![literal(Tagged::None), literal(Tagged::DVec2([30., 40.]))]);
let migrated = fixture.migrate(&PointInsideV1).unwrap();
assert_eq!(fixture.inputs(&migrated, node), [literal(Tagged::None), lengths([30., 40.])]);
}
}
@@ -0,0 +1,96 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const RADIUS: usize = 1;
const MIN_ANGLE_THRESHOLD: usize = 4;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
Angle(TypedAngle),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
#[derive(Serialize, Deserialize)]
struct TypedAngle {
value: f64,
unit: AngleUnit,
}
#[derive(Serialize, Deserialize)]
enum AngleUnit {
Degree,
}
/// The radius is a length and the minimum angle threshold is an angle, which keep the numbers of pixels and degrees they held. Wired numbers still feed them, read as pixels and degrees.
#[migration("core_types::vector::RoundCornersNode"@1 => @2)]
pub fn round_corners_v1(node: &Node, inputs: &mut Inputs) {
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
Some(Tagged::Number(number)) => Some(number),
_ => None,
};
if let Some(pixels) = number_at(RADIUS) {
inputs.set(RADIUS as u32, length(pixels));
}
if let Some(degrees) = number_at(MIN_ANGLE_THRESHOLD) {
inputs.set(MIN_ANGLE_THRESHOLD as u32, angle(degrees));
}
}
fn length(pixels: f64) -> NodeInput {
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
fn angle(degrees: f64) -> NodeInput {
literal(Tagged::Angle(TypedAngle {
value: degrees,
unit: AngleUnit::Degree,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(5, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&RoundCornersV1, &contract());
check_undo(&RoundCornersV1, &contract());
}
#[test]
fn numbers_of_pixels_and_degrees_become_a_length_and_an_angle() {
let mut fixture = Fixture::new(&RoundCornersV1);
let number = |number: f64| literal(Tagged::Number(number));
let round_corners = fixture.add(
decl!("core_types::vector::RoundCornersNode"@1),
vec![literal(Tagged::None), number(10.), number(0.5), number(100.), number(5.)],
);
let migrated = fixture.migrate(&RoundCornersV1).unwrap();
assert_eq!(fixture.inputs(&migrated, round_corners), [literal(Tagged::None), length(10.), number(0.5), number(100.), angle(5.)]);
}
}
@@ -0,0 +1,80 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const SEPARATION: usize = 2;
const START_OFFSET: usize = 4;
const STOP_OFFSET: usize = 5;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The separation and start and stop offsets are lengths, which keep the numbers of pixels they held. Wired numbers still feed them, read as pixels.
#[migration("core_types::vector::SamplePolylineNode"@1 => @2)]
pub fn sample_polyline_v1(node: &Node, inputs: &mut Inputs) {
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
Some(Tagged::Number(number)) => Some(number),
_ => None,
};
for slot in [SEPARATION, START_OFFSET, STOP_OFFSET] {
if let Some(pixels) = number_at(slot) {
inputs.set(slot as u32, length(pixels));
}
}
}
fn length(pixels: f64) -> NodeInput {
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(7, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&SamplePolylineV1, &contract());
check_undo(&SamplePolylineV1, &contract());
}
#[test]
fn numbers_of_pixels_become_lengths_in_pixels() {
let mut fixture = Fixture::new(&SamplePolylineV1);
let number = |number: f64| literal(Tagged::Number(number));
let sample_polyline = fixture.add(
decl!("core_types::vector::SamplePolylineNode"@1),
vec![literal(Tagged::None), number(0.), number(100.), number(100.), number(10.), number(20.), number(0.)],
);
let migrated = fixture.migrate(&SamplePolylineV1).unwrap();
assert_eq!(
fixture.inputs(&migrated, sample_polyline),
[literal(Tagged::None), number(0.), length(100.), number(100.), length(10.), length(20.), number(0.)]
);
}
}
@@ -0,0 +1,66 @@
use migration_core::{Inputs, Node, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const SEPARATION: usize = 1;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The separation is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
#[migration("core_types::vector::ScatterPointsNode"@2 => @3)]
pub fn scatter_points_v2(node: &Node, inputs: &mut Inputs) {
let Some(slot) = node.inputs().get(SEPARATION) else { return };
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
inputs.set(
SEPARATION as u32,
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
})),
);
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(3, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&ScatterPointsV2, &contract());
check_undo(&ScatterPointsV2, &contract());
}
#[test]
fn a_number_of_pixels_becomes_a_length_in_pixels() {
let mut fixture = Fixture::new(&ScatterPointsV2);
let number = |number: f64| literal(Tagged::Number(number));
let scatter_points = fixture.add(decl!("core_types::vector::ScatterPointsNode"@2), vec![literal(Tagged::None), number(10.), number(0.)]);
let migrated = fixture.migrate(&ScatterPointsV2).unwrap();
let separation = literal(Tagged::Length(TypedLength { value: 10., unit: LengthUnit::Pixel }));
assert_eq!(fixture.inputs(&migrated, scatter_points), [literal(Tagged::None), separation, number(0.)]);
}
}
@@ -0,0 +1,66 @@
use migration_core::{Inputs, Node, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const TOLERANCE: usize = 1;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The tolerance is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
#[migration("core_types::vector::SimplifyNode"@1 => @2)]
pub fn simplify_v1(node: &Node, inputs: &mut Inputs) {
let Some(slot) = node.inputs().get(TOLERANCE) else { return };
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
inputs.set(
TOLERANCE as u32,
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
})),
);
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&SimplifyV1, &contract());
check_undo(&SimplifyV1, &contract());
}
#[test]
fn a_number_of_pixels_becomes_a_length_in_pixels() {
let mut fixture = Fixture::new(&SimplifyV1);
let number = |number: f64| literal(Tagged::Number(number));
let simplify = fixture.add(decl!("core_types::vector::SimplifyNode"@1), vec![literal(Tagged::None), number(5.)]);
let migrated = fixture.migrate(&SimplifyV1).unwrap();
let tolerance = literal(Tagged::Length(TypedLength { value: 5., unit: LengthUnit::Pixel }));
assert_eq!(fixture.inputs(&migrated, simplify), [literal(Tagged::None), tolerance]);
}
}
@@ -0,0 +1,66 @@
use migration_core::{Inputs, Node, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const DISTANCE: usize = 1;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The distance is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
#[migration("core_types::vector::WeldNode"@1 => @2)]
pub fn weld_v1(node: &Node, inputs: &mut Inputs) {
let Some(slot) = node.inputs().get(DISTANCE) else { return };
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
inputs.set(
DISTANCE as u32,
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
})),
);
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(3, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&WeldV1, &contract());
check_undo(&WeldV1, &contract());
}
#[test]
fn a_number_of_pixels_becomes_a_length_in_pixels() {
let mut fixture = Fixture::new(&WeldV1);
let number = |number: f64| literal(Tagged::Number(number));
let weld = fixture.add(decl!("core_types::vector::WeldNode"@1), vec![literal(Tagged::None), number(0.1), number(0.)]);
let migrated = fixture.migrate(&WeldV1).unwrap();
let distance = literal(Tagged::Length(TypedLength { value: 0.1, unit: LengthUnit::Pixel }));
assert_eq!(fixture.inputs(&migrated, weld), [literal(Tagged::None), distance, number(0.)]);
}
}
@@ -1,5 +1,7 @@
//! Migrations of the nodes in `graphene_core`.
mod pack_strips_v1;
mod passthrough_from_upload_texture_node;
mod renames;
mod stroke_v1;
mod vary_colors_from_assign_colors;
@@ -0,0 +1,73 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const SEPARATION: usize = 1;
const STRIP_MAX_LENGTH: usize = 2;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The separation and strip max length are lengths, which keep the numbers of pixels they held. Wired numbers still feed them, read as pixels.
#[migration("graphene_core::vector::PackStripsNode"@1 => @2)]
pub fn pack_strips_v1(node: &Node, inputs: &mut Inputs) {
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
Some(Tagged::Number(number)) => Some(number),
_ => None,
};
for slot in [SEPARATION, STRIP_MAX_LENGTH] {
if let Some(pixels) = number_at(slot) {
inputs.set(slot as u32, length(pixels));
}
}
}
fn length(pixels: f64) -> NodeInput {
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(4, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&PackStripsV1, &contract());
check_undo(&PackStripsV1, &contract());
}
#[test]
fn numbers_of_pixels_become_lengths_in_pixels() {
let mut fixture = Fixture::new(&PackStripsV1);
let number = |number: f64| literal(Tagged::Number(number));
let pack_strips = fixture.add(decl!("graphene_core::vector::PackStripsNode"@1), vec![literal(Tagged::None), number(10.), number(1000.), number(0.)]);
let migrated = fixture.migrate(&PackStripsV1).unwrap();
assert_eq!(fixture.inputs(&migrated, pack_strips), [literal(Tagged::None), length(10.), length(1000.), number(0.)]);
}
}
@@ -0,0 +1,79 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const WEIGHT: usize = 2;
const DASH_OFFSET: usize = 8;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The weight and dash offset are lengths, which keep the numbers of pixels they held. Wired numbers still feed them, read as pixels.
#[migration("graphene_core::vector::StrokeNode"@1 => @2)]
pub fn stroke_v1(node: &Node, inputs: &mut Inputs) {
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
Some(Tagged::Number(number)) => Some(number),
_ => None,
};
for slot in [WEIGHT, DASH_OFFSET] {
if let Some(pixels) = number_at(slot) {
inputs.set(slot as u32, length(pixels));
}
}
}
fn length(pixels: f64) -> NodeInput {
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(9, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&StrokeV1, &contract());
check_undo(&StrokeV1, &contract());
}
#[test]
fn numbers_of_pixels_become_lengths_in_pixels() {
let mut fixture = Fixture::new(&StrokeV1);
let number = |number: f64| literal(Tagged::Number(number));
let stroke = fixture.add(
decl!("graphene_core::vector::StrokeNode"@1),
vec![literal(Tagged::None), number(0.), number(2.), number(0.), number(0.), number(0.), number(4.), number(0.), number(5.)],
);
let migrated = fixture.migrate(&StrokeV1).unwrap();
assert_eq!(
fixture.inputs(&migrated, stroke),
[literal(Tagged::None), number(0.), length(2.), number(0.), number(0.), number(0.), number(4.), number(0.), length(5.)]
);
}
}
@@ -1,3 +1,4 @@
//! Migrations of the nodes in `graphene_std`.
mod renames;
mod text_v1;
@@ -8,3 +8,6 @@ rename!("graphene_std::render_background::RenderBackgroundNode"@1 => @2);
rename!("graphene_std::render_cache::RenderOutputCacheNode"@1 => @2);
rename!("graphene_std::render_node::RenderNode"@1 => @2);
rename!("graphene_std::render_pixel_preview::RenderPixelPreviewNode"@1 => @2);
// Version 3 adds the scope and source ID inputs the render node spawns its readbacks with, which the compiler inserts along with the node
rename!("graphene_std::render_node::RenderNode"@2 => @3);
@@ -0,0 +1,130 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const SIZE: usize = 3;
const LETTER_SPACING: usize = 5;
const LETTER_TILT: usize = 6;
const MAX_WIDTH: usize = 8;
const MAX_HEIGHT: usize = 10;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
Angle(TypedAngle),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
#[derive(Serialize, Deserialize)]
struct TypedAngle {
value: f64,
unit: AngleUnit,
}
#[derive(Serialize, Deserialize)]
enum AngleUnit {
Degree,
}
/// The size, letter spacing, and max sizes are lengths and the letter tilt is an angle, which keep the numbers of pixels and degrees they held. Wired numbers still feed them, read as pixels and degrees.
#[migration("graphene_std::text::TextNode"@1 => @2)]
pub fn text_v1(node: &Node, inputs: &mut Inputs) {
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
Some(Tagged::Number(number)) => Some(number),
_ => None,
};
for slot in [SIZE, LETTER_SPACING, MAX_WIDTH, MAX_HEIGHT] {
if let Some(pixels) = number_at(slot) {
inputs.set(slot as u32, length(pixels));
}
}
if let Some(degrees) = number_at(LETTER_TILT) {
inputs.set(LETTER_TILT as u32, angle(degrees));
}
}
fn length(pixels: f64) -> NodeInput {
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
fn angle(degrees: f64) -> NodeInput {
literal(Tagged::Angle(TypedAngle {
value: degrees,
unit: AngleUnit::Degree,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(12, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&TextV1, &contract());
check_undo(&TextV1, &contract());
}
#[test]
fn numbers_of_pixels_and_degrees_become_lengths_and_an_angle() {
let mut fixture = Fixture::new(&TextV1);
let number = |number: f64| literal(Tagged::Number(number));
let text = fixture.add(
decl!("graphene_std::text::TextNode"@1),
vec![
literal(Tagged::None),
number(0.),
number(0.),
number(24.),
number(1.2),
number(2.),
number(10.),
number(0.),
number(100.),
number(0.),
number(100.),
number(0.),
],
);
let migrated = fixture.migrate(&TextV1).unwrap();
assert_eq!(
fixture.inputs(&migrated, text),
[
literal(Tagged::None),
number(0.),
number(0.),
length(24.),
number(1.2),
length(2.),
angle(10.),
number(0.),
length(100.),
number(0.),
length(100.),
number(0.)
]
);
}
}
@@ -0,0 +1,74 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const LOCATION: usize = 1;
const DIMENSIONS: usize = 2;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
DVec2([f64; 2]),
LengthVec2(TypedLengthVec2),
}
#[derive(Serialize, Deserialize)]
struct TypedLengthVec2 {
value: [f64; 2],
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The location and dimensions are pairs of lengths, which keep the pixels they held. Wired Vec2s still feed them, read as pixels.
#[migration("graphic_nodes::artboard::CreateArtboardNode"@1 => @2)]
pub fn create_artboard_v1(node: &Node, inputs: &mut Inputs) {
for slot in [LOCATION, DIMENSIONS] {
if let Some(Tagged::DVec2(pixels)) = node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
inputs.set(slot as u32, lengths(pixels));
}
}
}
fn lengths(pixels: [f64; 2]) -> NodeInput {
literal(Tagged::LengthVec2(TypedLengthVec2 {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(5, |random, slot| match slot {
LOCATION | DIMENSIONS => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
_ => literal(Tagged::None),
})
}
#[test]
fn rewrites_history() {
check_commutation(&CreateArtboardV1, &contract());
check_undo(&CreateArtboardV1, &contract());
}
#[test]
fn vec2s_of_pixels_become_lengths_in_pixels() {
let mut fixture = Fixture::new(&CreateArtboardV1);
let none = || literal(Tagged::None);
let artboard = fixture.add(
decl!("graphic_nodes::artboard::CreateArtboardNode"@1),
vec![none(), literal(Tagged::DVec2([10., 20.])), literal(Tagged::DVec2([1920., 1080.])), none(), none()],
);
let migrated = fixture.migrate(&CreateArtboardV1).unwrap();
assert_eq!(fixture.inputs(&migrated, artboard), [none(), lengths([10., 20.]), lengths([1920., 1080.]), none(), none()]);
}
}
@@ -0,0 +1,96 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const OFFSET: usize = 2;
const ANGLE: usize = 3;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
Angle(TypedAngle),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
#[derive(Serialize, Deserialize)]
struct TypedAngle {
value: f64,
unit: AngleUnit,
}
#[derive(Serialize, Deserialize)]
enum AngleUnit {
Degree,
}
/// The offset is a length and the angle is an angle, which keep the numbers of pixels and degrees they held. Wired numbers still feed them, read as pixels and degrees.
#[migration("graphic_nodes::graphic::MirrorNode"@1 => @2)]
pub fn mirror_v1(node: &Node, inputs: &mut Inputs) {
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
Some(Tagged::Number(number)) => Some(number),
_ => None,
};
if let Some(pixels) = number_at(OFFSET) {
inputs.set(OFFSET as u32, length(pixels));
}
if let Some(degrees) = number_at(ANGLE) {
inputs.set(ANGLE as u32, angle(degrees));
}
}
fn length(pixels: f64) -> NodeInput {
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
fn angle(degrees: f64) -> NodeInput {
literal(Tagged::Angle(TypedAngle {
value: degrees,
unit: AngleUnit::Degree,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(5, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&MirrorV1, &contract());
check_undo(&MirrorV1, &contract());
}
#[test]
fn numbers_of_pixels_and_degrees_become_a_length_and_an_angle() {
let mut fixture = Fixture::new(&MirrorV1);
let number = |number: f64| literal(Tagged::Number(number));
let mirror = fixture.add(
decl!("graphic_nodes::graphic::MirrorNode"@1),
vec![literal(Tagged::None), number(0.), number(20.), number(45.), number(1.)],
);
let migrated = fixture.migrate(&MirrorV1).unwrap();
assert_eq!(fixture.inputs(&migrated, mirror), [literal(Tagged::None), number(0.), length(20.), angle(45.), number(1.)]);
}
}
@@ -0,0 +1,4 @@
//! Migrations of the nodes in `graphic_nodes`.
mod create_artboard_v1;
mod mirror_v1;
+5
View File
@@ -2,8 +2,13 @@
//! `cargo run migration new <identifier>` after bumping a node's `version(N)`.
mod blending_nodes;
mod brush_nodes;
mod core_types;
mod graphene_core;
mod graphene_std;
mod graphic_nodes;
mod math_nodes;
mod raster_nodes;
mod repeat_nodes;
mod transform_nodes;
mod vector_nodes;
@@ -0,0 +1,47 @@
use migration_core::{Inputs, NodeInput, migration};
/// Reads the document's resolution from the scope, which sizes the physical lengths an expression measures.
#[migration("math_nodes::MathFormulaNode"@2 => @3)]
pub fn math_formula_v2(inputs: &mut Inputs) {
inputs.push(NodeInput::Scope("pixels-per-inch".into()));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::{decl, literal};
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants the node's inputs hold in version 2.
#[derive(Serialize, Deserialize)]
enum Tagged {
Number(f64),
String(String),
}
fn contract() -> SourceContract {
SourceContract::new(3, |random, slot| match slot {
1 => literal(Tagged::String("a + b".to_string())),
_ => literal(Tagged::Number(random.below(10) as f64)),
})
}
#[test]
fn rewrites_history() {
check_commutation(&MathFormulaV2, &contract());
check_undo(&MathFormulaV2, &contract());
}
#[test]
fn the_resolution_is_read_from_the_scope() {
let inputs = vec![literal(Tagged::Number(2.)), literal(Tagged::String("a * 2".to_string())), literal(Tagged::Number(0.))];
let mut fixture = Fixture::new(&MathFormulaV2);
let formula = fixture.add(decl!("math_nodes::MathFormulaNode"@2), inputs.clone());
let migrated = fixture.migrate(&MathFormulaV2).unwrap();
let expected: Vec<NodeInput> = inputs.into_iter().chain([NodeInput::Scope("pixels-per-inch".into())]).collect();
assert_eq!(fixture.inputs(&migrated, formula), expected);
}
}
@@ -0,0 +1,47 @@
use migration_core::{Inputs, NodeInput, migration};
/// Reads the document's resolution from the scope, which sizes the physical lengths an expression measures.
#[migration("math_nodes::MathFunctionNode"@2 => @3)]
pub fn math_function_v2(inputs: &mut Inputs) {
inputs.push(NodeInput::Scope("pixels-per-inch".into()));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::{decl, literal};
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants the node's inputs hold in version 2.
#[derive(Serialize, Deserialize)]
enum Tagged {
Number(f64),
String(String),
}
fn contract() -> SourceContract {
SourceContract::new(3, |random, slot| match slot {
1 => literal(Tagged::String("x".to_string())),
_ => literal(Tagged::Number(random.below(10) as f64)),
})
}
#[test]
fn rewrites_history() {
check_commutation(&MathFunctionV2, &contract());
check_undo(&MathFunctionV2, &contract());
}
#[test]
fn the_resolution_is_read_from_the_scope() {
let inputs = vec![literal(Tagged::Number(2.)), literal(Tagged::String("x * 2".to_string())), literal(Tagged::Number(0.))];
let mut fixture = Fixture::new(&MathFunctionV2);
let function = fixture.add(decl!("math_nodes::MathFunctionNode"@2), inputs.clone());
let migrated = fixture.migrate(&MathFunctionV2).unwrap();
let expected: Vec<NodeInput> = inputs.into_iter().chain([NodeInput::Scope("pixels-per-inch".into())]).collect();
assert_eq!(fixture.inputs(&migrated, function), expected);
}
}
@@ -1,4 +1,6 @@
//! Migrations of the nodes in `math_nodes`.
mod math_formula_from_math_f;
mod math_formula_v2;
mod math_function_v2;
mod renames;
@@ -3,3 +3,21 @@
use migration_core::rename;
rename!("math_nodes::MathFxNode"@1 => "math_nodes::MathFunctionNode"@2);
// Version 2 takes lengths and angles too, with its output type following them, and stored nodes already have its layout
rename!("math_nodes::SineNode"@1 => @2);
rename!("math_nodes::CosineNode"@1 => @2);
rename!("math_nodes::TangentNode"@1 => @2);
rename!("math_nodes::SignNode"@1 => @2);
rename!("math_nodes::SumNode"@1 => @2);
rename!("math_nodes::AverageNode"@1 => @2);
rename!("math_nodes::MinimumNode"@1 => @2);
rename!("math_nodes::MaximumNode"@1 => @2);
// Version 2 reads a number beside a length or angle in pixels or degrees, and stored nodes already have its layout
rename!("math_nodes::LerpNode"@1 => @2);
rename!("math_nodes::ClampNode"@1 => @2);
rename!("math_nodes::LessThanNode"@1 => @2);
rename!("math_nodes::GreaterThanNode"@1 => @2);
rename!("math_nodes::EqualsNode"@1 => @2);
rename!("math_nodes::NotEqualsNode"@1 => @2);
@@ -0,0 +1,96 @@
use super::pattern_square::{SquareNodes, Tagged, fill_square_with_pattern};
use migration_core::{Attributes, Downstream, Inputs, Node, decl, literal, migration};
/// The pattern fills the plane rather than being cut off at the unit square, so it's read through that square filled with it, and the node gained a
/// primary input.
#[migration("raster_nodes::std_nodes::MandelbrotNode"@1 => @2)]
pub fn mandelbrot_v1(node: &Node, inputs: &mut Inputs, downstream: &mut Downstream, attributes: &mut Attributes) {
inputs.insert(0, literal(Tagged::None));
let nodes = SquareNodes {
rectangle: decl!("vector_nodes::generator_nodes::RectangleNode"@1),
fill: decl!("graphene_core::vector::FillNode"@1),
transform: decl!("transform_nodes::transform_nodes::TransformNode"@1),
};
fill_square_with_pattern(node, downstream, attributes, nodes, 1.);
}
#[cfg(test)]
mod tests {
use super::*;
use document_graph_storage::{ROOT_NETWORK, TimeStamp};
use migration_core::attr::node::ui::{IS_LAYER, POSITION};
use migration_core::{CHAIN_WIDTH, FEEDER_ROW_HEIGHT, NodeInput, Position};
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(0, |_, _| literal(Tagged::None))
}
#[test]
fn rewrites_history() {
check_commutation(&MandelbrotV1, &contract());
check_undo(&MandelbrotV1, &contract());
}
#[test]
fn the_export_reads_a_unit_square_filled_with_the_pattern() {
let mut fixture = Fixture::new(&MandelbrotV1);
let mandelbrot = fixture.add(decl!("raster_nodes::std_nodes::MandelbrotNode"@1), Vec::new());
fixture.export(NodeInput::Node { id: mandelbrot, index: 0 });
let migrated = fixture.migrate(&MandelbrotV1).unwrap();
assert_eq!(fixture.inputs(&migrated, mandelbrot), [literal(Tagged::None)]);
let Some(NodeInput::Node { id: placement, .. }) = migrated.networks[&ROOT_NETWORK].exports[0].target else {
panic!("the export should read a node")
};
assert_eq!(fixture.declaration_of(&migrated, placement), Some(decl!("transform_nodes::transform_nodes::TransformNode"@1)));
assert_eq!(fixture.inputs(&migrated, placement)[1], literal(Tagged::DVec2([0.5, 0.5])));
}
/// The positions of the pattern, its paint, the rectangle, the fill, and the placement after migrating a pattern at `position`.
fn placed_square(position: Position, layer: Option<[i32; 2]>) -> [Option<Position>; 5] {
let mut fixture = Fixture::new(&MandelbrotV1);
let mandelbrot = fixture.add(decl!("raster_nodes::std_nodes::MandelbrotNode"@1), Vec::new());
let place = |fixture: &mut Fixture, node, position: Position| {
let attributes = fixture.registry.node_instances.get_mut(&node).unwrap().attributes_mut();
attributes.set_serialized(POSITION, &position, TimeStamp::ORIGIN).unwrap();
};
place(&mut fixture, mandelbrot, position);
let reader = match layer {
Some(layer_position) => {
let layer = fixture.add(decl!("graphic_nodes::layer"@1), vec![literal(Tagged::None), NodeInput::Node { id: mandelbrot, index: 0 }]);
place(&mut fixture, layer, Position::Absolute(layer_position));
let attributes = fixture.registry.node_instances.get_mut(&layer).unwrap().attributes_mut();
attributes.set_serialized(IS_LAYER, &true, TimeStamp::ORIGIN).unwrap();
layer
}
None => fixture.add(decl!("migration_testing::consumer"@1), vec![NodeInput::Node { id: mandelbrot, index: 0 }]),
};
let migrated = fixture.migrate(&MandelbrotV1).unwrap();
let reads = |node, slot: usize| match fixture.inputs(&migrated, node)[slot] {
NodeInput::Node { id, .. } => id,
_ => panic!("slot {slot} of {node:?} should read a node"),
};
let placement = reads(reader, if layer.is_some() { 1 } else { 0 });
let fill = reads(placement, 0);
let (rectangle, paint) = (reads(fill, 0), reads(fill, 1));
[mandelbrot, paint, rectangle, fill, placement].map(|node| migrated.node_instances[&node].attributes().get_typed::<Position>(POSITION))
}
#[test]
fn the_filled_rectangle_takes_the_place_of_a_chained_or_placed_pattern() {
let chained = Position::Relative([-CHAIN_WIDTH, 0]);
for (position, layer) in [(chained, Some([30, 10])), (Position::Absolute([5, 5]), None)] {
let [pattern, paint, rectangle, fill, placement] = placed_square(position, layer);
assert_eq!(placement, Some(position));
assert_eq!([rectangle, fill, pattern], [Some(chained); 3]);
assert_eq!(paint, Some(Position::Relative([-CHAIN_WIDTH, FEEDER_ROW_HEIGHT])));
}
}
}
@@ -0,0 +1,131 @@
use migration_core::attr::node::ui::POSITION;
use migration_core::{Attributes, CHAIN_WIDTH, Downstream, Inputs, NewNode, Node, NodeInput, OutputConnector, Position, decl, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Integer(i64),
DVec2([f64; 2]),
MandelbrotFractal(MandelbrotFractal),
MandelbrotExterior(MandelbrotExterior),
MandelbrotInterior(MandelbrotInterior),
}
#[derive(Serialize, Deserialize)]
enum MandelbrotFractal {
ClassicMandelbrot,
}
#[derive(Serialize, Deserialize)]
enum MandelbrotExterior {
SmoothEscape,
}
#[derive(Serialize, Deserialize)]
enum MandelbrotInterior {
Flat,
}
/// How far the old unit square, which spanned the complex plane from -2 to 1, placed the plane's origin from the pattern's.
const OLD_ORIGIN: [f64; 2] = [2. / 3., 0.5];
/// 'Mandelbrot' gained a scale and settings for its fractal, its slice toward the Julia set, and its interior and exterior, and the complex plane's origin moved to the pattern's.
/// A third of a unit's scale and a Transform moving the pattern back to the old origin keep its look.
#[migration("raster_nodes::std_nodes::MandelbrotNode"@2 => @3)]
pub fn mandelbrot_v2(node: &Node, inputs: &mut Inputs, downstream: &mut Downstream, attributes: &mut Attributes) {
for input in new_inputs() {
inputs.push(input);
}
let consumers = downstream.consumers(0);
if consumers.is_empty() {
return;
}
let origin = downstream.add_node_keyed(
NewNode {
declaration: decl!("transform_nodes::transform_nodes::TransformNode"@1),
inputs: vec![
NodeInput::Node { id: node.id(), index: 0 },
literal(Tagged::DVec2(OLD_ORIGIN)),
literal(Tagged::Number(0.)),
literal(Tagged::DVec2([1., 1.])),
literal(Tagged::DVec2([0., 0.])),
],
},
"origin",
);
for consumer in consumers {
downstream.connect(OutputConnector { node: origin, output: 0 }, consumer);
}
// The Transform takes the pattern's place, with the pattern before it
if let Some(stored) = node.attributes().get_typed::<Position>(POSITION) {
attributes.set(origin, POSITION, &stored);
}
attributes.set(node.id(), POSITION, &Position::Relative([-CHAIN_WIDTH, 0]));
}
/// The settings 'Mandelbrot' gained, in the order of its parameters, with the scale matching the old unit square's three units of the plane.
fn new_inputs() -> [NodeInput; 10] {
[
literal(Tagged::MandelbrotFractal(MandelbrotFractal::ClassicMandelbrot)),
literal(Tagged::MandelbrotExterior(MandelbrotExterior::SmoothEscape)),
literal(Tagged::MandelbrotInterior(MandelbrotInterior::Flat)),
literal(Tagged::Integer(1)),
literal(Tagged::Number(1. / 3.)),
literal(Tagged::Integer(256)),
literal(Tagged::Number(2.)),
literal(Tagged::Number(0.)),
literal(Tagged::DVec2([0., 0.])),
literal(Tagged::DVec2([-0.8, 0.156])),
]
}
#[cfg(test)]
mod tests {
use super::*;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(1, |_, _| literal(Tagged::None))
}
#[test]
fn rewrites_history() {
check_commutation(&MandelbrotV2, &contract());
check_undo(&MandelbrotV2, &contract());
}
#[test]
fn keeps_the_primary_input_and_adds_the_settings() {
let mut fixture = Fixture::new(&MandelbrotV2);
let mandelbrot = fixture.add(decl!("raster_nodes::std_nodes::MandelbrotNode"@2), vec![literal(Tagged::None)]);
let migrated = fixture.migrate(&MandelbrotV2).unwrap();
let mut expected = vec![literal(Tagged::None)];
expected.extend(new_inputs());
assert_eq!(fixture.declaration_of(&migrated, mandelbrot), Some(decl!("raster_nodes::std_nodes::MandelbrotNode"@3)));
assert_eq!(fixture.inputs(&migrated, mandelbrot), expected);
}
#[test]
fn whatever_read_the_pattern_reads_it_moved_back_to_the_old_origin() {
let mut fixture = Fixture::new(&MandelbrotV2);
let mandelbrot = fixture.add(decl!("raster_nodes::std_nodes::MandelbrotNode"@2), vec![literal(Tagged::None)]);
let consumer = fixture.add(decl!("migration_testing::consumer"@1), vec![NodeInput::Node { id: mandelbrot, index: 0 }]);
let migrated = fixture.migrate(&MandelbrotV2).unwrap();
let NodeInput::Node { id: origin, .. } = fixture.inputs(&migrated, consumer)[0] else {
panic!("the consumer should read a node")
};
assert_eq!(fixture.declaration_of(&migrated, origin), Some(decl!("transform_nodes::transform_nodes::TransformNode"@1)));
let inputs = fixture.inputs(&migrated, origin);
assert_eq!(inputs[0], NodeInput::Node { id: mandelbrot, index: 0 });
assert_eq!(inputs[1], literal(Tagged::DVec2(OLD_ORIGIN)));
}
}
@@ -0,0 +1,66 @@
use migration_core::{Inputs, Node, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const RADIUS: usize = 1;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The radius is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
#[migration("raster_nodes::filter::MedianFilterNode"@1 => @2)]
pub fn median_filter_v1(node: &Node, inputs: &mut Inputs) {
let Some(slot) = node.inputs().get(RADIUS) else { return };
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
inputs.set(
RADIUS as u32,
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
})),
);
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&MedianFilterV1, &contract());
check_undo(&MedianFilterV1, &contract());
}
#[test]
fn a_number_of_pixels_becomes_a_length_in_pixels() {
let mut fixture = Fixture::new(&MedianFilterV1);
let number = |number: f64| literal(Tagged::Number(number));
let median_filter = fixture.add(decl!("raster_nodes::filter::MedianFilterNode"@1), vec![literal(Tagged::None), number(5.)]);
let migrated = fixture.migrate(&MedianFilterV1).unwrap();
let radius = literal(Tagged::Length(TypedLength { value: 5., unit: LengthUnit::Pixel }));
assert_eq!(fixture.inputs(&migrated, median_filter), [literal(Tagged::None), radius]);
}
}
@@ -1,4 +1,9 @@
//! Migrations of the nodes in `raster_nodes`.
mod mandelbrot_v1;
mod mandelbrot_v2;
mod median_filter_v1;
mod mix_colors_from_mix_node;
mod noise_pattern_v1;
mod pattern_square;
mod renames;
@@ -0,0 +1,97 @@
use super::pattern_square::{SquareNodes, Tagged, fill_square_with_pattern};
use migration_core::{Attributes, Downstream, Inputs, MigrationError, Node, decl, literal_of, migration};
const CLIP: u32 = 1;
/// The pattern fills the plane, so the Clip toggle that cut it off at a 100-unit square is gone, and a clipped pattern is read through that square
/// filled with it. A wired toggle counts as clipped.
#[migration("raster_nodes::std_nodes::NoisePatternNode"@1 => @2)]
pub fn noise_pattern_v1(node: &Node, inputs: &mut Inputs, downstream: &mut Downstream, attributes: &mut Attributes) -> Result<(), MigrationError> {
let Some(clip) = node.inputs().get(CLIP as usize) else {
return Err(MigrationError::invariant("Noise Pattern has a Clip input"));
};
let clipped = !matches!(literal_of::<Tagged>(&clip.input), Some(Tagged::Bool(false)));
inputs.remove(CLIP);
if clipped {
let nodes = SquareNodes {
rectangle: decl!("vector_nodes::generator_nodes::RectangleNode"@1),
fill: decl!("graphene_core::vector::FillNode"@1),
transform: decl!("transform_nodes::transform_nodes::TransformNode"@1),
};
fill_square_with_pattern(node, downstream, attributes, nodes, 100.);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::{Declaration, NodeInput, literal};
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
const NOISE_PATTERN: Declaration = decl!("raster_nodes::std_nodes::NoisePatternNode"@1);
const CONSUMER: Declaration = decl!("migration_testing::consumer"@1);
fn contract() -> SourceContract {
SourceContract {
// The toggle a clipped pattern's readers move off of can't be reading that pattern, since its own migration removes it
reads_own_output: |slot| slot != CLIP as usize,
..SourceContract::new(16, |random, slot| match slot {
1 => literal(Tagged::Bool(random.below(2) == 0)),
_ => literal(Tagged::Number(random.below(10) as f64)),
})
}
}
fn noise_inputs(clip: bool) -> Vec<NodeInput> {
let mut inputs: Vec<NodeInput> = (0..16).map(|slot| literal(Tagged::Number(slot as f64))).collect();
inputs[CLIP as usize] = literal(Tagged::Bool(clip));
inputs
}
#[test]
fn rewrites_history() {
check_commutation(&NoisePatternV1, &contract());
check_undo(&NoisePatternV1, &contract());
}
#[test]
fn a_clipped_pattern_is_read_through_a_square_filled_with_it() {
let mut fixture = Fixture::new(&NoisePatternV1);
let noise = fixture.add(NOISE_PATTERN, noise_inputs(true));
let consumer = fixture.add(CONSUMER, vec![NodeInput::Node { id: noise, index: 0 }]);
let migrated = fixture.migrate(&NoisePatternV1).unwrap();
// The settings after the removed toggle move down a slot
let inputs = fixture.inputs(&migrated, noise);
assert_eq!(inputs.len(), 15);
assert_eq!(inputs[CLIP as usize], literal(Tagged::Number(2.)));
let reads = |node, slot: usize| match fixture.inputs(&migrated, node)[slot] {
NodeInput::Node { id, .. } => id,
_ => panic!("slot {slot} of {node:?} should read a node"),
};
let placement = reads(consumer, 0);
let fill = reads(placement, 0);
let paint = reads(fill, 1);
assert_eq!(reads(paint, 0), noise);
assert_eq!(fixture.declaration_of(&migrated, reads(fill, 0)), Some(decl!("vector_nodes::generator_nodes::RectangleNode"@1)));
assert_eq!(fixture.inputs(&migrated, placement)[1], literal(Tagged::DVec2([50., 50.])));
assert_eq!(fixture.inputs(&migrated, paint)[1], literal(Tagged::DVec2([-50., -50.])));
}
#[test]
fn an_unclipped_pattern_keeps_its_readers() {
let mut fixture = Fixture::new(&NoisePatternV1);
let noise = fixture.add(NOISE_PATTERN, noise_inputs(false));
let consumer = fixture.add(CONSUMER, vec![NodeInput::Node { id: noise, index: 0 }]);
let migrated = fixture.migrate(&NoisePatternV1).unwrap();
assert_eq!(fixture.inputs(&migrated, noise).len(), 15);
assert_eq!(fixture.inputs(&migrated, consumer), [NodeInput::Node { id: noise, index: 0 }]);
assert_eq!(migrated.node_instances.len(), 2);
}
}
@@ -0,0 +1,141 @@
//! The square that Noise Pattern and Mandelbrot were cut off at before their patterns filled the plane, which their migrations keep.
use migration_core::attr::node::ui::POSITION;
use migration_core::{Attributes, CHAIN_WIDTH, Declaration, Downstream, FEEDER_ROW_HEIGHT, NewNode, Node, NodeInput, OutputConnector, Position, literal};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants these migrations use.
#[derive(Serialize, Deserialize)]
pub(super) enum Tagged {
None,
Number(f64),
Bool(bool),
BoxCorners(Vec<f64>),
Color(Color),
GradientRamp(GradientRamp),
GradientForm(GradientForm),
DVec2([f64; 2]),
DAffine2([f64; 6]),
}
#[derive(Serialize, Deserialize)]
pub(super) struct Color {
red: f32,
green: f32,
blue: f32,
alpha: f32,
linear: bool,
}
impl Color {
fn new(red: f32, green: f32, blue: f32, alpha: f32) -> Self {
Self {
red,
green,
blue,
alpha,
linear: true,
}
}
}
#[derive(Serialize, Deserialize)]
pub(super) struct GradientRamp {
stops: GradientStops,
gradient_space: GradientSpace,
}
#[derive(Serialize, Deserialize)]
pub(super) struct GradientStops {
color: Vec<Color>,
}
#[derive(Serialize, Deserialize)]
pub(super) enum GradientSpace {
OkLab,
}
#[derive(Serialize, Deserialize)]
pub(super) enum GradientForm {
Linear,
}
/// The declarations the square is built from, which each migration names itself so the runner orders it against them.
pub(super) struct SquareNodes {
pub rectangle: Declaration,
pub fill: Declaration,
pub transform: Declaration,
}
/// Makes everything reading the pattern read a rectangle filled with it instead, covering the square from the origin of the pattern's space out to `size`.
/// The rectangle is centered on its origin, so a Transform moves it onto the square, and the paint is moved back by the same amount to stay in place.
pub(super) fn fill_square_with_pattern(node: &Node, downstream: &mut Downstream, attributes: &mut Attributes, nodes: SquareNodes, size: f64) {
let consumers = downstream.consumers(0);
if consumers.is_empty() {
return;
}
let number = |number| literal(Tagged::Number(number));
let pair = |value| literal(Tagged::DVec2([value, value]));
let wire = |id| NodeInput::Node { id, index: 0 };
let transform = |content, translation| vec![content, pair(translation), number(0.), pair(1.), pair(0.)];
let rectangle = downstream.add_node(NewNode {
declaration: nodes.rectangle,
inputs: vec![
literal(Tagged::None),
number(size),
number(size),
literal(Tagged::BoxCorners(Vec::new())),
literal(Tagged::Bool(true)),
literal(Tagged::Bool(false)),
],
});
let paint = downstream.add_node_keyed(
NewNode {
declaration: nodes.transform,
inputs: transform(wire(node.id()), -size / 2.),
},
"paint",
);
// Past the rectangle and its paint, the Fill holds the defaults its definition gives a new node
let backup_gradient = GradientRamp {
stops: GradientStops {
color: vec![Color::new(0., 0., 0., 1.), Color::new(1., 1., 1., 1.)],
},
gradient_space: GradientSpace::OkLab,
};
let fill = downstream.add_node(NewNode {
declaration: nodes.fill,
inputs: vec![
wire(rectangle),
wire(paint),
literal(Tagged::Color(Color::new(0., 0., 0., 0.))),
literal(Tagged::GradientRamp(backup_gradient)),
literal(Tagged::GradientForm(GradientForm::Linear)),
literal(Tagged::Bool(false)),
literal(Tagged::DAffine2([1., 0., 0., 1., 0., 0.])),
],
});
let placement = downstream.add_node_keyed(
NewNode {
declaration: nodes.transform,
inputs: transform(wire(fill), size / 2.),
},
"placement",
);
for consumer in consumers {
downstream.connect(OutputConnector { node: placement, output: 0 }, consumer);
}
// The placement takes the pattern's place, with the paint feeding the fill from a row below
if let Some(stored) = node.attributes().get_typed::<Position>(POSITION) {
attributes.set(placement, POSITION, &stored);
}
for id in [fill, rectangle, node.id()] {
attributes.set(id, POSITION, &Position::Relative([-CHAIN_WIDTH, 0]));
}
attributes.set(paint, POSITION, &Position::Relative([-CHAIN_WIDTH, FEEDER_ROW_HEIGHT]));
}
@@ -0,0 +1,4 @@
//! Migrations of the nodes in `repeat_nodes`.
mod repeat_array_v1;
mod repeat_radial_v1;
@@ -0,0 +1,98 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const DIRECTION: usize = 1;
const ANGLE: usize = 2;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
DVec2([f64; 2]),
Angle(TypedAngle),
LengthVec2(TypedLengthVec2),
}
#[derive(Serialize, Deserialize)]
struct TypedLengthVec2 {
value: [f64; 2],
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
#[derive(Serialize, Deserialize)]
struct TypedAngle {
value: f64,
unit: AngleUnit,
}
#[derive(Serialize, Deserialize)]
enum AngleUnit {
Degree,
}
/// The direction is a pair of lengths and the angle is an angle, which keep the pixels and degrees they held. Wired values still feed them, read in those units.
#[migration("repeat_nodes::repeat_nodes::RepeatArrayNode"@1 => @2)]
pub fn repeat_array_v1(node: &Node, inputs: &mut Inputs) {
let literal_at = |slot: usize| node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input));
if let Some(Tagged::DVec2(pixels)) = literal_at(DIRECTION) {
inputs.set(DIRECTION as u32, direction(pixels));
}
if let Some(Tagged::Number(degrees)) = literal_at(ANGLE) {
inputs.set(ANGLE as u32, angle(degrees));
}
}
fn direction(pixels: [f64; 2]) -> NodeInput {
literal(Tagged::LengthVec2(TypedLengthVec2 {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
fn angle(degrees: f64) -> NodeInput {
literal(Tagged::Angle(TypedAngle {
value: degrees,
unit: AngleUnit::Degree,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(4, |random, slot| match slot {
0 => literal(Tagged::None),
DIRECTION => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
_ => literal(Tagged::Number(random.below(100) as f64)),
})
}
#[test]
fn rewrites_history() {
check_commutation(&RepeatArrayV1, &contract());
check_undo(&RepeatArrayV1, &contract());
}
#[test]
fn a_number_of_degrees_becomes_an_angle_in_degrees() {
let mut fixture = Fixture::new(&RepeatArrayV1);
let number = |number: f64| literal(Tagged::Number(number));
let repeat_array = fixture.add(
decl!("repeat_nodes::repeat_nodes::RepeatArrayNode"@1),
vec![literal(Tagged::None), literal(Tagged::DVec2([100., 50.])), number(90.), number(5.)],
);
let migrated = fixture.migrate(&RepeatArrayV1).unwrap();
assert_eq!(fixture.inputs(&migrated, repeat_array), [literal(Tagged::None), direction([100., 50.]), angle(90.), number(5.)]);
}
}
@@ -0,0 +1,96 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const START_ANGLE: usize = 1;
const RADIUS: usize = 2;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
Angle(TypedAngle),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
#[derive(Serialize, Deserialize)]
struct TypedAngle {
value: f64,
unit: AngleUnit,
}
#[derive(Serialize, Deserialize)]
enum AngleUnit {
Degree,
}
/// The start angle is an angle and the radius is a length, which keep the numbers of degrees and pixels they held. Wired numbers still feed them, read as degrees and pixels.
#[migration("repeat_nodes::repeat_nodes::RepeatRadialNode"@1 => @2)]
pub fn repeat_radial_v1(node: &Node, inputs: &mut Inputs) {
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
Some(Tagged::Number(number)) => Some(number),
_ => None,
};
if let Some(pixels) = number_at(RADIUS) {
inputs.set(RADIUS as u32, length(pixels));
}
if let Some(degrees) = number_at(START_ANGLE) {
inputs.set(START_ANGLE as u32, angle(degrees));
}
}
fn length(pixels: f64) -> NodeInput {
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
fn angle(degrees: f64) -> NodeInput {
literal(Tagged::Angle(TypedAngle {
value: degrees,
unit: AngleUnit::Degree,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(4, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&RepeatRadialV1, &contract());
check_undo(&RepeatRadialV1, &contract());
}
#[test]
fn numbers_of_degrees_and_pixels_become_an_angle_and_a_length() {
let mut fixture = Fixture::new(&RepeatRadialV1);
let number = |number: f64| literal(Tagged::Number(number));
let repeat_radial = fixture.add(
decl!("repeat_nodes::repeat_nodes::RepeatRadialNode"@1),
vec![literal(Tagged::None), number(45.), number(5.), number(5.)],
);
let migrated = fixture.migrate(&RepeatRadialV1).unwrap();
assert_eq!(fixture.inputs(&migrated, repeat_radial), [literal(Tagged::None), angle(45.), length(5.), number(5.)]);
}
}
@@ -0,0 +1,4 @@
//! Migrations of the nodes in `transform_nodes`.
mod transform_v1;
mod vary_rotations_v2;
@@ -0,0 +1,125 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const TRANSLATION: usize = 1;
const ROTATION: usize = 2;
const SKEW: usize = 4;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
DVec2([f64; 2]),
Angle(TypedAngle),
LengthVec2(TypedLengthVec2),
AngleVec2(TypedAngleVec2),
}
#[derive(Serialize, Deserialize)]
struct TypedAngle {
value: f64,
unit: AngleUnit,
}
#[derive(Serialize, Deserialize)]
struct TypedLengthVec2 {
value: [f64; 2],
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
struct TypedAngleVec2 {
value: [f64; 2],
unit: AngleUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
#[derive(Serialize, Deserialize)]
enum AngleUnit {
Degree,
}
/// The translation is a pair of lengths and the rotation and skew are angles, which keep the pixels and degrees they held. Wired values still feed them, read in those units.
#[migration("transform_nodes::transform_nodes::TransformNode"@1 => @2)]
pub fn transform_v1(node: &Node, inputs: &mut Inputs) {
let literal_at = |slot: usize| node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input));
if let Some(Tagged::DVec2(pixels)) = literal_at(TRANSLATION) {
inputs.set(TRANSLATION as u32, translation(pixels));
}
if let Some(Tagged::Number(degrees)) = literal_at(ROTATION) {
inputs.set(ROTATION as u32, rotation(degrees));
}
if let Some(Tagged::DVec2(degrees)) = literal_at(SKEW) {
inputs.set(SKEW as u32, skew(degrees));
}
}
/// The whole-list counterpart of the Transform node, with parameters that migrate the same way.
#[migration("transform_nodes::transform_nodes::TransformListNode"@1 => @2)]
pub fn transform_list_v1(node: &Node, inputs: &mut Inputs) {
transform_v1(node, inputs);
}
fn translation(pixels: [f64; 2]) -> NodeInput {
literal(Tagged::LengthVec2(TypedLengthVec2 {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
fn rotation(degrees: f64) -> NodeInput {
literal(Tagged::Angle(TypedAngle {
value: degrees,
unit: AngleUnit::Degree,
}))
}
fn skew(degrees: [f64; 2]) -> NodeInput {
literal(Tagged::AngleVec2(TypedAngleVec2 {
value: degrees,
unit: AngleUnit::Degree,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(5, |random, slot| match slot {
0 => literal(Tagged::None),
ROTATION => literal(Tagged::Number(random.below(360) as f64)),
_ => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
})
}
#[test]
fn rewrites_history() {
check_commutation(&TransformV1, &contract());
check_undo(&TransformV1, &contract());
}
#[test]
fn pixels_and_degrees_become_typed_lengths_and_angles() {
let mut fixture = Fixture::new(&TransformV1);
let vec2 = |x: f64, y: f64| literal(Tagged::DVec2([x, y]));
let transform = fixture.add(
decl!("transform_nodes::transform_nodes::TransformNode"@1),
vec![literal(Tagged::None), vec2(10., 20.), literal(Tagged::Number(45.)), vec2(2., 3.), vec2(15., 0.)],
);
let migrated = fixture.migrate(&TransformV1).unwrap();
assert_eq!(
fixture.inputs(&migrated, transform),
[literal(Tagged::None), translation([10., 20.]), rotation(45.), vec2(2., 3.), skew([15., 0.])]
);
}
}
@@ -0,0 +1,79 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const MIN: usize = 1;
const MAX: usize = 2;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Angle(TypedAngle),
}
#[derive(Serialize, Deserialize)]
struct TypedAngle {
value: f64,
unit: AngleUnit,
}
#[derive(Serialize, Deserialize)]
enum AngleUnit {
Degree,
}
/// The ends of the range are angles, which keep the numbers of degrees they held. Wired numbers still feed them, read as degrees.
#[migration("transform_nodes::transform_nodes::VaryRotationsNode"@2 => @3)]
pub fn vary_rotations_v2(node: &Node, inputs: &mut Inputs) {
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
Some(Tagged::Number(number)) => Some(number),
_ => None,
};
for slot in [MIN, MAX] {
if let Some(degrees) = number_at(slot) {
inputs.set(slot as u32, angle(degrees));
}
}
}
fn angle(degrees: f64) -> NodeInput {
literal(Tagged::Angle(TypedAngle {
value: degrees,
unit: AngleUnit::Degree,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(8, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&VaryRotationsV2, &contract());
check_undo(&VaryRotationsV2, &contract());
}
#[test]
fn numbers_of_degrees_become_angles_in_degrees() {
let mut fixture = Fixture::new(&VaryRotationsV2);
let number = |number: f64| literal(Tagged::Number(number));
let vary_rotations = fixture.add(
decl!("transform_nodes::transform_nodes::VaryRotationsNode"@2),
vec![literal(Tagged::None), number(-180.), number(180.), number(0.5), number(0.), number(1.), number(0.), number(0.)],
);
let migrated = fixture.migrate(&VaryRotationsV2).unwrap();
assert_eq!(
fixture.inputs(&migrated, vary_rotations),
[literal(Tagged::None), angle(-180.), angle(180.), number(0.5), number(0.), number(1.), number(0.), number(0.)]
);
}
}
@@ -0,0 +1,99 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const RADIUS: usize = 1;
const START_ANGLE: usize = 2;
const SWEEP_ANGLE: usize = 3;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
Angle(TypedAngle),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
#[derive(Serialize, Deserialize)]
struct TypedAngle {
value: f64,
unit: AngleUnit,
}
#[derive(Serialize, Deserialize)]
enum AngleUnit {
Degree,
}
/// The radius is a length and the start and sweep angles are angles, which keep the numbers of pixels and degrees they held. Wired numbers still feed them, read as pixels and degrees.
#[migration("vector_nodes::generator_nodes::ArcNode"@1 => @2)]
pub fn arc_v1(node: &Node, inputs: &mut Inputs) {
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
Some(Tagged::Number(number)) => Some(number),
_ => None,
};
if let Some(pixels) = number_at(RADIUS) {
inputs.set(RADIUS as u32, length(pixels));
}
for slot in [START_ANGLE, SWEEP_ANGLE] {
if let Some(degrees) = number_at(slot) {
inputs.set(slot as u32, angle(degrees));
}
}
}
fn length(pixels: f64) -> NodeInput {
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
fn angle(degrees: f64) -> NodeInput {
literal(Tagged::Angle(TypedAngle {
value: degrees,
unit: AngleUnit::Degree,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(5, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&ArcV1, &contract());
check_undo(&ArcV1, &contract());
}
#[test]
fn numbers_of_pixels_and_degrees_become_a_length_and_angles() {
let mut fixture = Fixture::new(&ArcV1);
let number = |number: f64| literal(Tagged::Number(number));
let arc = fixture.add(
decl!("vector_nodes::generator_nodes::ArcNode"@1),
vec![literal(Tagged::None), number(50.), number(0.), number(270.), number(1.)],
);
let migrated = fixture.migrate(&ArcV1).unwrap();
assert_eq!(fixture.inputs(&migrated, arc), [literal(Tagged::None), length(50.), angle(0.), angle(270.), number(1.)]);
}
}
@@ -0,0 +1,100 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const ARROW_TO: usize = 1;
const SHAFT_WIDTH: usize = 2;
const HEAD_WIDTH: usize = 3;
const HEAD_LENGTH: usize = 4;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
DVec2([f64; 2]),
Length(TypedLength),
LengthVec2(TypedLengthVec2),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
struct TypedLengthVec2 {
value: [f64; 2],
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The end point is a pair of lengths and the shaft and head sizes are lengths, which keep the pixels they held. Wired values still feed them, read as pixels.
#[migration("vector_nodes::generator_nodes::ArrowNode"@1 => @2)]
pub fn arrow_v1(node: &Node, inputs: &mut Inputs) {
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
Some(Tagged::Number(number)) => Some(number),
_ => None,
};
if let Some(Tagged::DVec2(pixels)) = node.inputs().get(ARROW_TO).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
inputs.set(ARROW_TO as u32, lengths(pixels));
}
for slot in [SHAFT_WIDTH, HEAD_WIDTH, HEAD_LENGTH] {
if let Some(pixels) = number_at(slot) {
inputs.set(slot as u32, length(pixels));
}
}
}
fn lengths(pixels: [f64; 2]) -> NodeInput {
literal(Tagged::LengthVec2(TypedLengthVec2 {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
fn length(pixels: f64) -> NodeInput {
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(5, |random, slot| match slot {
0 => literal(Tagged::None),
ARROW_TO => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
_ => literal(Tagged::Number(random.below(100) as f64)),
})
}
#[test]
fn rewrites_history() {
check_commutation(&ArrowV1, &contract());
check_undo(&ArrowV1, &contract());
}
#[test]
fn numbers_of_pixels_become_lengths_in_pixels() {
let mut fixture = Fixture::new(&ArrowV1);
let number = |number: f64| literal(Tagged::Number(number));
let arrow = fixture.add(
decl!("vector_nodes::generator_nodes::ArrowNode"@1),
vec![literal(Tagged::None), literal(Tagged::DVec2([100., 0.])), number(10.), number(30.), number(20.)],
);
let migrated = fixture.migrate(&ArrowV1).unwrap();
assert_eq!(fixture.inputs(&migrated, arrow), [literal(Tagged::None), lengths([100., 0.]), length(10.), length(30.), length(20.)]);
}
}
@@ -0,0 +1,65 @@
use migration_core::{Inputs, Node, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const RADIUS: usize = 1;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The radius is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
#[migration("vector_nodes::generator_nodes::CircleNode"@1 => @2)]
pub fn circle_v1(node: &Node, inputs: &mut Inputs) {
let Some(slot) = node.inputs().get(RADIUS) else { return };
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
inputs.set(
RADIUS as u32,
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
})),
);
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&CircleV1, &contract());
check_undo(&CircleV1, &contract());
}
#[test]
fn a_number_of_pixels_becomes_a_length_in_pixels() {
let mut fixture = Fixture::new(&CircleV1);
let circle = fixture.add(decl!("vector_nodes::generator_nodes::CircleNode"@1), vec![literal(Tagged::None), literal(Tagged::Number(50.))]);
let migrated = fixture.migrate(&CircleV1).unwrap();
let radius = literal(Tagged::Length(TypedLength { value: 50., unit: LengthUnit::Pixel }));
assert_eq!(fixture.inputs(&migrated, circle), [literal(Tagged::None), radius]);
}
}
@@ -0,0 +1,73 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const RADIUS_X: usize = 1;
const RADIUS_Y: usize = 2;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The radii are lengths, which keep the numbers of pixels they held. Wired numbers still feed them, read as pixels.
#[migration("vector_nodes::generator_nodes::EllipseNode"@1 => @2)]
pub fn ellipse_v1(node: &Node, inputs: &mut Inputs) {
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
Some(Tagged::Number(number)) => Some(number),
_ => None,
};
for slot in [RADIUS_X, RADIUS_Y] {
if let Some(pixels) = number_at(slot) {
inputs.set(slot as u32, length(pixels));
}
}
}
fn length(pixels: f64) -> NodeInput {
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(3, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&EllipseV1, &contract());
check_undo(&EllipseV1, &contract());
}
#[test]
fn numbers_of_pixels_become_lengths_in_pixels() {
let mut fixture = Fixture::new(&EllipseV1);
let number = |number: f64| literal(Tagged::Number(number));
let ellipse = fixture.add(decl!("vector_nodes::generator_nodes::EllipseNode"@1), vec![literal(Tagged::None), number(50.), number(25.)]);
let migrated = fixture.migrate(&EllipseV1).unwrap();
assert_eq!(fixture.inputs(&migrated, ellipse), [literal(Tagged::None), length(50.), length(25.)]);
}
}
@@ -0,0 +1,111 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const SPACING: usize = 6;
const ANGLES: usize = 7;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
DVec2([f64; 2]),
LengthVec2(TypedLengthVec2),
AngleVec2(TypedAngleVec2),
}
#[derive(Serialize, Deserialize)]
struct TypedLengthVec2 {
value: [f64; 2],
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
struct TypedAngleVec2 {
value: [f64; 2],
unit: AngleUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
#[derive(Serialize, Deserialize)]
enum AngleUnit {
Degree,
}
/// The spacing is a pair of lengths, filled from one number in both axes, and the isometric angles are a pair of angles, which keep the pixels and degrees they held. Wired values still feed them, read in those units.
#[migration("vector_nodes::generator_nodes::GridNode"@1 => @2)]
pub fn grid_v1(node: &Node, inputs: &mut Inputs) {
let literal_at = |slot: usize| node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input));
match literal_at(SPACING) {
Some(Tagged::Number(pixels)) => inputs.set(SPACING as u32, lengths([pixels, pixels])),
Some(Tagged::DVec2(pixels)) => inputs.set(SPACING as u32, lengths(pixels)),
_ => {}
}
if let Some(Tagged::DVec2(degrees)) = literal_at(ANGLES) {
inputs.set(ANGLES as u32, angles(degrees));
}
}
fn lengths(pixels: [f64; 2]) -> NodeInput {
literal(Tagged::LengthVec2(TypedLengthVec2 {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
fn angles(degrees: [f64; 2]) -> NodeInput {
literal(Tagged::AngleVec2(TypedAngleVec2 {
value: degrees,
unit: AngleUnit::Degree,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(8, |random, slot| match slot {
SPACING if random.below(2) == 0 => literal(Tagged::Number(random.below(100) as f64)),
SPACING | ANGLES => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
_ => literal(Tagged::None),
})
}
#[test]
fn rewrites_history() {
check_commutation(&GridV1, &contract());
check_undo(&GridV1, &contract());
}
#[test]
fn pixels_and_degrees_become_typed_lengths_and_angles() {
let mut fixture = Fixture::new(&GridV1);
let none = || literal(Tagged::None);
let square = fixture.add(
decl!("vector_nodes::generator_nodes::GridNode"@1),
vec![none(), none(), none(), none(), none(), none(), literal(Tagged::Number(10.)), literal(Tagged::DVec2([30., 30.]))],
);
let rectangular = fixture.add(
decl!("vector_nodes::generator_nodes::GridNode"@1),
vec![none(), none(), none(), none(), none(), none(), literal(Tagged::DVec2([10., 20.])), literal(Tagged::DVec2([30., 60.]))],
);
let migrated = fixture.migrate(&GridV1).unwrap();
assert_eq!(
fixture.inputs(&migrated, square),
[none(), none(), none(), none(), none(), none(), lengths([10., 10.]), angles([30., 30.])]
);
assert_eq!(
fixture.inputs(&migrated, rectangular),
[none(), none(), none(), none(), none(), none(), lengths([10., 20.]), angles([30., 60.])]
);
}
}
@@ -0,0 +1,72 @@
use migration_core::{Inputs, Node, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const TIP_ANGLE: usize = 6;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Angle(TypedAngle),
}
#[derive(Serialize, Deserialize)]
struct TypedAngle {
value: f64,
unit: AngleUnit,
}
#[derive(Serialize, Deserialize)]
enum AngleUnit {
Degree,
}
/// The tip angle is an angle, which keeps the number of degrees it held. A wired number still feeds it, read as degrees.
#[migration("vector_nodes::generator_nodes::HeartNode"@1 => @2)]
pub fn heart_v1(node: &Node, inputs: &mut Inputs) {
let Some(slot) = node.inputs().get(TIP_ANGLE) else { return };
let Some(Tagged::Number(degrees)) = literal_of::<Tagged>(&slot.input) else { return };
inputs.set(
TIP_ANGLE as u32,
literal(Tagged::Angle(TypedAngle {
value: degrees,
unit: AngleUnit::Degree,
})),
);
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(7, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&HeartV1, &contract());
check_undo(&HeartV1, &contract());
}
#[test]
fn a_number_of_degrees_becomes_an_angle_in_degrees() {
let mut fixture = Fixture::new(&HeartV1);
let number = |number: f64| literal(Tagged::Number(number));
let heart = fixture.add(
decl!("vector_nodes::generator_nodes::HeartNode"@1),
vec![literal(Tagged::None), number(70.), number(0.), number(0.), number(70.), number(50.), number(75.)],
);
let migrated = fixture.migrate(&HeartV1).unwrap();
let tip_angle = literal(Tagged::Angle(TypedAngle { value: 75., unit: AngleUnit::Degree }));
assert_eq!(
fixture.inputs(&migrated, heart),
[literal(Tagged::None), number(70.), number(0.), number(0.), number(70.), number(50.), tip_angle]
);
}
}
@@ -0,0 +1,68 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const LINE_TO: usize = 1;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
DVec2([f64; 2]),
LengthVec2(TypedLengthVec2),
}
#[derive(Serialize, Deserialize)]
struct TypedLengthVec2 {
value: [f64; 2],
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The end point is a pair of lengths, which keeps the pixels it held. A wired Vec2 still feeds it, read as pixels.
#[migration("vector_nodes::generator_nodes::LineNode"@1 => @2)]
pub fn line_v1(node: &Node, inputs: &mut Inputs) {
let Some(slot) = node.inputs().get(LINE_TO) else { return };
let Some(Tagged::DVec2(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
inputs.set(LINE_TO as u32, lengths(pixels));
}
fn lengths(pixels: [f64; 2]) -> NodeInput {
literal(Tagged::LengthVec2(TypedLengthVec2 {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, slot| match slot {
LINE_TO => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
_ => literal(Tagged::None),
})
}
#[test]
fn rewrites_history() {
check_commutation(&LineV1, &contract());
check_undo(&LineV1, &contract());
}
#[test]
fn a_vec2_of_pixels_becomes_lengths_in_pixels() {
let mut fixture = Fixture::new(&LineV1);
let node = fixture.add(decl!("vector_nodes::generator_nodes::LineNode"@1), vec![literal(Tagged::None), literal(Tagged::DVec2([30., 40.]))]);
let migrated = fixture.migrate(&LineV1).unwrap();
assert_eq!(fixture.inputs(&migrated, node), [literal(Tagged::None), lengths([30., 40.])]);
}
}
@@ -1,4 +1,16 @@
//! Migrations of the nodes in `vector_nodes`.
mod arc_v1;
mod arrow_v1;
mod circle_v1;
mod ellipse_v1;
mod grid_v1;
mod heart_v1;
mod line_v1;
mod path_from_path_network;
mod qr_code_v1;
mod rectangle_v1;
mod regular_polygon_v1;
mod renames;
mod spiral_v1;
mod star_v1;
@@ -0,0 +1,69 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const SIZE: usize = 3;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The size is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
#[migration("vector_nodes::generator_nodes::QrCodeNode"@1 => @2)]
pub fn qr_code_v1(node: &Node, inputs: &mut Inputs) {
let Some(slot) = node.inputs().get(SIZE) else { return };
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
inputs.set(SIZE as u32, length(pixels));
}
fn length(pixels: f64) -> NodeInput {
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(6, |random, slot| if slot == SIZE { literal(Tagged::Number(random.below(100) as f64)) } else { literal(Tagged::None) })
}
#[test]
fn rewrites_history() {
check_commutation(&QrCodeV1, &contract());
check_undo(&QrCodeV1, &contract());
}
#[test]
fn a_number_of_pixels_becomes_a_length_in_pixels() {
let mut fixture = Fixture::new(&QrCodeV1);
let none = || literal(Tagged::None);
let qr_code = fixture.add(
decl!("vector_nodes::generator_nodes::QrCodeNode"@1),
vec![none(), none(), none(), literal(Tagged::Number(200.)), none(), none()],
);
let migrated = fixture.migrate(&QrCodeV1).unwrap();
assert_eq!(fixture.inputs(&migrated, qr_code), [none(), none(), none(), length(200.), none(), none()]);
}
}
@@ -0,0 +1,79 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const WIDTH: usize = 1;
const HEIGHT: usize = 2;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The width and height are lengths, which keep the numbers of pixels they held. Wired numbers still feed them, read as pixels.
#[migration("vector_nodes::generator_nodes::RectangleNode"@1 => @2)]
pub fn rectangle_v1(node: &Node, inputs: &mut Inputs) {
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
Some(Tagged::Number(number)) => Some(number),
_ => None,
};
for slot in [WIDTH, HEIGHT] {
if let Some(pixels) = number_at(slot) {
inputs.set(slot as u32, length(pixels));
}
}
}
fn length(pixels: f64) -> NodeInput {
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(6, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&RectangleV1, &contract());
check_undo(&RectangleV1, &contract());
}
#[test]
fn numbers_of_pixels_become_lengths_in_pixels() {
let mut fixture = Fixture::new(&RectangleV1);
let number = |number: f64| literal(Tagged::Number(number));
let rectangle = fixture.add(
decl!("vector_nodes::generator_nodes::RectangleNode"@1),
vec![literal(Tagged::None), number(100.), number(80.), number(0.), number(1.), number(0.)],
);
let migrated = fixture.migrate(&RectangleV1).unwrap();
assert_eq!(
fixture.inputs(&migrated, rectangle),
[literal(Tagged::None), length(100.), length(80.), number(0.), number(1.), number(0.)]
);
}
}
@@ -0,0 +1,66 @@
use migration_core::{Inputs, Node, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const RADIUS: usize = 2;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The radius is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
#[migration("vector_nodes::generator_nodes::RegularPolygonNode"@1 => @2)]
pub fn regular_polygon_v1(node: &Node, inputs: &mut Inputs) {
let Some(slot) = node.inputs().get(RADIUS) else { return };
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
inputs.set(
RADIUS as u32,
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
})),
);
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(3, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&RegularPolygonV1, &contract());
check_undo(&RegularPolygonV1, &contract());
}
#[test]
fn a_number_of_pixels_becomes_a_length_in_pixels() {
let mut fixture = Fixture::new(&RegularPolygonV1);
let number = |number: f64| literal(Tagged::Number(number));
let polygon = fixture.add(decl!("vector_nodes::generator_nodes::RegularPolygonNode"@1), vec![literal(Tagged::None), number(6.), number(50.)]);
let migrated = fixture.migrate(&RegularPolygonV1).unwrap();
let radius = literal(Tagged::Length(TypedLength { value: 50., unit: LengthUnit::Pixel }));
assert_eq!(fixture.inputs(&migrated, polygon), [literal(Tagged::None), number(6.), radius]);
}
}
@@ -6,3 +6,5 @@ rename!("vector_nodes::vector_modification_nodes::PathModifyNode"@1 => "vector_n
// Version 2 only adds `InjectFootprint` to the context bounds, so stored nodes keep their layout
rename!("core_types::vector::AreaNode"@1 => @2);
rename!("core_types::vector::CentroidNode"@1 => @2);
// Version 2 only lets its output carry an error, so stored nodes keep their layout
rename!("core_types::vector::ScatterPointsNode"@1 => @2);
@@ -0,0 +1,105 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const START_ANGLE: usize = 3;
const INNER_RADIUS: usize = 4;
const OUTER_RADIUS: usize = 5;
const ANGULAR_RESOLUTION: usize = 6;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
Angle(TypedAngle),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
#[derive(Serialize, Deserialize)]
struct TypedAngle {
value: f64,
unit: AngleUnit,
}
#[derive(Serialize, Deserialize)]
enum AngleUnit {
Degree,
}
/// The radii are lengths and the start angle and angular resolution are angles, which keep the numbers of pixels and degrees they held. Wired numbers still feed them, read as pixels and degrees.
#[migration("vector_nodes::generator_nodes::SpiralNode"@1 => @2)]
pub fn spiral_v1(node: &Node, inputs: &mut Inputs) {
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
Some(Tagged::Number(number)) => Some(number),
_ => None,
};
for slot in [INNER_RADIUS, OUTER_RADIUS] {
if let Some(pixels) = number_at(slot) {
inputs.set(slot as u32, length(pixels));
}
}
for slot in [START_ANGLE, ANGULAR_RESOLUTION] {
if let Some(degrees) = number_at(slot) {
inputs.set(slot as u32, angle(degrees));
}
}
}
fn length(pixels: f64) -> NodeInput {
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
fn angle(degrees: f64) -> NodeInput {
literal(Tagged::Angle(TypedAngle {
value: degrees,
unit: AngleUnit::Degree,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(7, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&SpiralV1, &contract());
check_undo(&SpiralV1, &contract());
}
#[test]
fn numbers_of_pixels_and_degrees_become_lengths_and_angles() {
let mut fixture = Fixture::new(&SpiralV1);
let number = |number: f64| literal(Tagged::Number(number));
let spiral = fixture.add(
decl!("vector_nodes::generator_nodes::SpiralNode"@1),
vec![literal(Tagged::None), number(0.), number(5.), number(0.), number(0.), number(25.), number(90.)],
);
let migrated = fixture.migrate(&SpiralV1).unwrap();
assert_eq!(
fixture.inputs(&migrated, spiral),
[literal(Tagged::None), number(0.), number(5.), angle(0.), length(0.), length(25.), angle(90.)]
);
}
}
@@ -0,0 +1,73 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const RADIUS_1: usize = 2;
const RADIUS_2: usize = 3;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The radii are lengths, which keep the numbers of pixels they held. Wired numbers still feed them, read as pixels.
#[migration("vector_nodes::generator_nodes::StarNode"@1 => @2)]
pub fn star_v1(node: &Node, inputs: &mut Inputs) {
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
Some(Tagged::Number(number)) => Some(number),
_ => None,
};
for slot in [RADIUS_1, RADIUS_2] {
if let Some(pixels) = number_at(slot) {
inputs.set(slot as u32, length(pixels));
}
}
}
fn length(pixels: f64) -> NodeInput {
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(4, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&StarV1, &contract());
check_undo(&StarV1, &contract());
}
#[test]
fn numbers_of_pixels_become_lengths_in_pixels() {
let mut fixture = Fixture::new(&StarV1);
let number = |number: f64| literal(Tagged::Number(number));
let star = fixture.add(decl!("vector_nodes::generator_nodes::StarNode"@1), vec![literal(Tagged::None), number(5.), number(50.), number(25.)]);
let migrated = fixture.migrate(&StarV1).unwrap();
assert_eq!(fixture.inputs(&migrated, star), [literal(Tagged::None), number(5.), length(50.), length(25.)]);
}
}
+24 -27
View File
@@ -334,9 +334,6 @@ fn add_nodes(target: &mut Registry, runs: &[(NodeId, Edits)], resolver: &dyn Dec
Ok(())
}
/// Default positions for the nodes one run adds, read from the anchor's own position only. The nodes leading up to the anchor's
/// chain input form a row, or join the chain of a chained or layer anchor. Each other node sits below the first one reading it,
/// or on the anchor when none does. Without absolute coordinates for the anchor, only the chain is placed.
fn place_added_nodes(target: &mut Registry, anchor: NodeId, edits: &Edits) {
let Some(anchor_node) = target.node_instances.get(&anchor) else { return };
let stored = anchor_node.attributes().get_typed::<Position>(POSITION);
@@ -360,37 +357,37 @@ fn place_added_nodes(target: &mut Registry, anchor: NodeId, edits: &Edits) {
next = inputs.first();
}
let joins_chain = is_layer || stored == Some(Position::Chain);
let coordinates = match stored {
Some(Position::Absolute(coordinates)) => Some(coordinates),
_ => None,
};
let mut positions = Vec::new();
for (step, id) in chain.iter().enumerate() {
match coordinates {
_ if joins_chain => positions.push((*id, Position::Chain)),
Some([x, y]) => positions.push((*id, Position::Absolute([x - CHAIN_WIDTH * (step as i32 + 1), y]))),
None => {}
}
}
let mut positions: Vec<(NodeId, Position)> = chain.iter().map(|id| (*id, Position::Relative([-CHAIN_WIDTH, 0]))).collect();
if let Some([x, y]) = coordinates {
let readers: Vec<(&[NodeInput], i32)> = std::iter::once((anchor_inputs.as_slice(), x))
.chain(chain.iter().enumerate().map(|(step, id)| (added_inputs[id], x - CHAIN_WIDTH * (step as i32 + 1))))
.collect();
let mut feeders_below = vec![0; readers.len()];
let readers: Vec<(NodeId, &[NodeInput])> = std::iter::once((anchor, anchor_inputs.as_slice()))
.chain(edits.added_nodes.iter().map(|added| (added.id, added.node.inputs.as_slice())))
.collect();
let mut feeders_below: HashMap<NodeId, i32> = HashMap::new();
for added in edits.added_nodes.iter().filter(|added| !chain.contains(&added.id)) {
let position = match readers.iter().position(|(inputs, _)| reads(inputs, added.id)) {
Some(reader) => {
feeders_below[reader] += 1;
[readers[reader].1 - CHAIN_WIDTH, y + FEEDER_ROW_HEIGHT * feeders_below[reader]]
}
None => [x, y],
};
positions.push((added.id, Position::Absolute(position)));
}
for added in edits.added_nodes.iter().filter(|added| !chain.contains(&added.id)) {
let reader = readers.iter().find(|(_, inputs)| reads(inputs, added.id)).map(|(reader, _)| *reader);
let downstream_consumer = edits.connections.iter().find_map(|(output, input)| match input {
InputConnector::Node { node, .. } if output.node == added.id => Some(*node),
_ => None,
});
let connected_downstream = edits.connections.iter().any(|(output, _)| output.node == added.id);
let position = match (reader.or(downstream_consumer), coordinates) {
(Some(consumer), _) => {
let row = feeders_below.entry(consumer).or_default();
*row += 1;
Position::Relative([-CHAIN_WIDTH, FEEDER_ROW_HEIGHT * *row])
}
_ if connected_downstream => Position::Relative([-CHAIN_WIDTH, FEEDER_ROW_HEIGHT]),
(None, Some(coordinates)) => Position::Absolute(coordinates),
(None, None) => continue,
};
positions.push((added.id, position));
}
for (id, position) in positions {
+3 -2
View File
@@ -293,9 +293,10 @@ impl Generator<'_> {
(DISPLAY_NAME, name.map(|name| Value::Str(name.to_string())))
}
1 => {
let coordinates = [self.random.below(20) as i32, self.random.below(20) as i32];
let position = match self.random.below(3) {
0 => Position::Chain,
_ => Position::Absolute([self.random.below(20) as i32, self.random.below(20) as i32]),
0 => Position::Relative(coordinates),
_ => Position::Absolute(coordinates),
};
(POSITION, Some(to_value(&position).expect("positions serialize")))
}
Loaded 100 of 418 files, more files were not shown because too many files have changed in this diff. Show more