mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f2e2c7abcd | ||
|
|
f6804d9443 | ||
|
|
5471774764 | ||
|
|
f1ca7e7ab2 | ||
|
|
07ddc86fc2 | ||
|
|
3134753d07 | ||
|
|
cece2e9957 | ||
|
|
620f8d992b | ||
|
|
db2d8625a6 | ||
|
|
c6686a65c3 | ||
|
|
455008de2e | ||
|
|
48cf345355 | ||
|
|
a102519e39 | ||
|
|
508d67f5b3 | ||
|
|
fd9da9d56c | ||
|
|
4b62b39c74 | ||
|
|
b822b64e96 | ||
|
|
617ce90276 |
No files matched your search
@@ -20,6 +20,9 @@ on:
|
||||
linux:
|
||||
description: "Linux"
|
||||
type: boolean
|
||||
flatpak:
|
||||
description: "Flatpak (with the Linux build)"
|
||||
type: boolean
|
||||
debug:
|
||||
description: "Debug build"
|
||||
type: boolean
|
||||
@@ -33,6 +36,8 @@ on:
|
||||
type: boolean
|
||||
linux:
|
||||
type: boolean
|
||||
flatpak:
|
||||
type: boolean
|
||||
debug:
|
||||
type: boolean
|
||||
checkout_repo:
|
||||
@@ -815,7 +820,7 @@ jobs:
|
||||
path: target/artifacts
|
||||
|
||||
linux:
|
||||
if: (github.event_name == 'push' && github.ref != 'refs/tags/latest-stable') || inputs.linux
|
||||
if: (github.event_name == 'push' && github.ref != 'refs/tags/latest-stable') || inputs.linux || inputs.flatpak
|
||||
runs-on: ${{ (github.event.pull_request.head.repo.fork || (inputs.checkout_repo && inputs.checkout_repo != github.repository)) && 'ubuntu-latest' || vars.LINUX_RUNNER || 'ubuntu-latest' }}
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -892,12 +897,14 @@ jobs:
|
||||
fi
|
||||
|
||||
- name: 🔧 Install Flatpak tooling
|
||||
if: github.event_name == 'push' || inputs.flatpak
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y flatpak flatpak-builder
|
||||
flatpak --user remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo
|
||||
|
||||
- name: 🏗 Build Flatpak
|
||||
if: github.event_name == 'push' || inputs.flatpak
|
||||
run: |
|
||||
nix build .#graphite-flatpak-manifest${{ inputs.debug && '-dev' || '' }}
|
||||
|
||||
@@ -914,6 +921,7 @@ jobs:
|
||||
flatpak build-bundle repo Graphite.flatpak art.graphite.Graphite --runtime-repo=https://flathub.org/repo/flathub.flatpakrepo
|
||||
|
||||
- name: 📦 Upload Flatpak package
|
||||
if: github.event_name == 'push' || inputs.flatpak
|
||||
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
|
||||
with:
|
||||
name: graphite-flatpak
|
||||
@@ -921,7 +929,7 @@ jobs:
|
||||
compression-level: 0
|
||||
|
||||
- name: 💬 Update PR comment with Flatpak artifact link
|
||||
if: github.event_name != 'push' && steps.linux-comment.outputs.comment_id
|
||||
if: inputs.flatpak && steps.linux-comment.outputs.comment_id
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
|
||||
@@ -1,16 +1,22 @@
|
||||
# USAGE:
|
||||
# After reviewing the code, core team members may comment on a PR with `!build` followed by optional `<target>` and `<profile>` arguments.
|
||||
# This matches the syntax of the `cargo run build` CLI command, but allows platforms to be specified.
|
||||
# This extends the syntax of the `cargo run build` CLI command, allowing several targets and specific platforms to be built at once.
|
||||
#
|
||||
# `<target>`: `web` (default), `desktop` (all platforms), or `desktop:<platforms>` (subset of `windows+mac+linux`)
|
||||
# `<target>`: any of `web`, `desktop` (all platforms), `desktop:<platforms>`, or a bare platform (`windows`, `mac`, `linux`), joined by spaces or `+` (default: `web`)
|
||||
# `flatpak` additionally packages the Linux build as a Flatpak, which `desktop` and `linux` leave out
|
||||
# `<profile>`: `release` (default) or `debug`
|
||||
#
|
||||
# Only the comment's first line is parsed, so notes may follow on the lines below it.
|
||||
#
|
||||
# Examples:
|
||||
# - !build
|
||||
# - !build debug
|
||||
# - !build desktop
|
||||
# - !build web desktop
|
||||
# - !build linux
|
||||
# - !build linux+flatpak
|
||||
# - !build desktop:windows+mac
|
||||
# - !build desktop:linux debug
|
||||
# - !build web+desktop:linux debug
|
||||
name: "!build PR Command"
|
||||
|
||||
on:
|
||||
@@ -37,6 +43,7 @@ jobs:
|
||||
windows: ${{ steps.pr_info.outputs.windows }}
|
||||
mac: ${{ steps.pr_info.outputs.mac }}
|
||||
linux: ${{ steps.pr_info.outputs.linux }}
|
||||
flatpak: ${{ steps.pr_info.outputs.flatpak }}
|
||||
debug: ${{ steps.pr_info.outputs.debug }}
|
||||
|
||||
steps:
|
||||
@@ -46,8 +53,8 @@ jobs:
|
||||
# Passed through the environment so the comment text can't inject shell syntax
|
||||
COMMENT: ${{ github.event.comment.body }}
|
||||
run: |
|
||||
# Split into space-separated words
|
||||
read -ra WORDS <<< "$COMMENT"
|
||||
# Split the first line into space-separated words (comments posted from the web UI have CRLF line endings)
|
||||
read -ra WORDS <<< "${COMMENT%%$'\r'*}"
|
||||
|
||||
# First word must be "!build"
|
||||
if [[ "${WORDS[0]}" != "!build" ]]; then
|
||||
@@ -55,49 +62,47 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Initialize build flags (web defaults to true, matching the CLI default target)
|
||||
WEB="true"
|
||||
# Initialize build flags
|
||||
WEB="false"
|
||||
WINDOWS="false"
|
||||
MAC="false"
|
||||
LINUX="false"
|
||||
FLATPAK="false"
|
||||
DEBUG="false"
|
||||
PROFILE=""
|
||||
|
||||
# Parse target (optional, defaults to `web` if omitted)
|
||||
IDX=1
|
||||
case "${WORDS[$IDX]:-}" in
|
||||
# Target: `web` enables just the web build (already the default, but accepted explicitly)
|
||||
"web")
|
||||
((IDX++)) ;;
|
||||
# Target: `desktop` enables all three desktop platforms
|
||||
"desktop")
|
||||
WEB="false"; WINDOWS="true"; MAC="true"; LINUX="true"; ((IDX++)) ;;
|
||||
# Target: `desktop:<platforms>` enables a subset of desktop platforms, split by `+`
|
||||
desktop:*)
|
||||
WEB="false"
|
||||
PLATFORMS="${WORDS[$IDX]#desktop:}"
|
||||
IFS='+' read -ra PARTS <<< "$PLATFORMS"
|
||||
for PART in "${PARTS[@]}"; do
|
||||
case "$PART" in
|
||||
"windows") WINDOWS="true" ;;
|
||||
"mac") MAC="true" ;;
|
||||
"linux") LINUX="true" ;;
|
||||
*) echo "::error::Unrecognized platform: $PART"; exit 1 ;;
|
||||
esac
|
||||
done
|
||||
((IDX++))
|
||||
;;
|
||||
esac
|
||||
# Every remaining word is either the profile or a `+`-separated list of targets
|
||||
for WORD in "${WORDS[@]:1}"; do
|
||||
case "$WORD" in
|
||||
"debug" | "release")
|
||||
if [[ -n "$PROFILE" ]]; then
|
||||
echo "::error::Profile given more than once: $WORD"
|
||||
exit 1
|
||||
fi
|
||||
PROFILE="$WORD"
|
||||
if [[ "$WORD" == "debug" ]]; then DEBUG="true"; fi
|
||||
continue
|
||||
;;
|
||||
esac
|
||||
|
||||
# Parse profile (optional, defaults to `release` if omitted)
|
||||
case "${WORDS[$IDX]:-}" in
|
||||
"debug") DEBUG="true"; ((IDX++)) ;;
|
||||
"release") ((IDX++)) ;;
|
||||
esac
|
||||
IFS='+' read -ra PARTS <<< "$WORD"
|
||||
for PART in "${PARTS[@]}"; do
|
||||
# In `desktop:<platforms>`, the prefix only matters on the first platform since the others are split off as bare platforms
|
||||
case "$PART" in
|
||||
"web") WEB="true" ;;
|
||||
"desktop") WINDOWS="true"; MAC="true"; LINUX="true" ;;
|
||||
"windows" | "desktop:windows") WINDOWS="true" ;;
|
||||
"mac" | "desktop:mac") MAC="true" ;;
|
||||
"linux" | "desktop:linux") LINUX="true" ;;
|
||||
"flatpak" | "desktop:flatpak") LINUX="true"; FLATPAK="true" ;;
|
||||
*) echo "::error::Unrecognized argument: $PART"; exit 1 ;;
|
||||
esac
|
||||
done
|
||||
done
|
||||
|
||||
# Reject any unexpected trailing words
|
||||
if [[ $IDX -lt ${#WORDS[@]} ]]; then
|
||||
echo "::error::Unexpected argument: ${WORDS[$IDX]}"
|
||||
exit 1
|
||||
# Without any target, build for web to match the CLI default target
|
||||
if [[ "$WEB$WINDOWS$MAC$LINUX" != *true* ]]; then
|
||||
WEB="true"
|
||||
fi
|
||||
|
||||
# Write parsed build flags to job outputs
|
||||
@@ -105,6 +110,7 @@ jobs:
|
||||
echo "windows=$WINDOWS" >> $GITHUB_OUTPUT
|
||||
echo "mac=$MAC" >> $GITHUB_OUTPUT
|
||||
echo "linux=$LINUX" >> $GITHUB_OUTPUT
|
||||
echo "flatpak=$FLATPAK" >> $GITHUB_OUTPUT
|
||||
echo "debug=$DEBUG" >> $GITHUB_OUTPUT
|
||||
|
||||
# Fetch the PR's head branch and repo (needed for forked PRs where the code lives in another repo)
|
||||
@@ -139,6 +145,7 @@ jobs:
|
||||
windows: ${{ needs.setup.outputs.windows == 'true' }}
|
||||
mac: ${{ needs.setup.outputs.mac == 'true' }}
|
||||
linux: ${{ needs.setup.outputs.linux == 'true' }}
|
||||
flatpak: ${{ needs.setup.outputs.flatpak == 'true' }}
|
||||
debug: ${{ needs.setup.outputs.debug == 'true' }}
|
||||
checkout_repo: ${{ needs.setup.outputs.repo }}
|
||||
checkout_ref: ${{ needs.setup.outputs.ref }}
|
||||
|
||||
Generated
+31
-7
@@ -588,6 +588,7 @@ dependencies = [
|
||||
"glam",
|
||||
"graphic-types",
|
||||
"node-macro",
|
||||
"raster-kernels",
|
||||
"serde",
|
||||
"vector-types",
|
||||
]
|
||||
@@ -2664,6 +2665,7 @@ dependencies = [
|
||||
"math-nodes",
|
||||
"node-macro",
|
||||
"path-bool-nodes",
|
||||
"raster-kernels",
|
||||
"raster-nodes",
|
||||
"rendering",
|
||||
"repeat-nodes",
|
||||
@@ -2695,6 +2697,7 @@ dependencies = [
|
||||
"graphic-types",
|
||||
"node-macro",
|
||||
"rand",
|
||||
"raster-kernels",
|
||||
"raster-types",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2710,10 +2713,12 @@ dependencies = [
|
||||
"dyn-any",
|
||||
"glam",
|
||||
"graphene-hash",
|
||||
"graphene-resource",
|
||||
"node-macro",
|
||||
"raster-types",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tsify",
|
||||
"vector-types",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
@@ -4161,6 +4166,7 @@ dependencies = [
|
||||
"math-parser",
|
||||
"node-macro",
|
||||
"rand",
|
||||
"raster-kernels",
|
||||
"thiserror 2.0.21",
|
||||
"vector-types",
|
||||
]
|
||||
@@ -5719,6 +5725,20 @@ dependencies = [
|
||||
"rustversion",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raster-kernels"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"core-types",
|
||||
"fastnoise-lite",
|
||||
"glam",
|
||||
"graphene-resource",
|
||||
"graphic-types",
|
||||
"raster-types",
|
||||
"thiserror 2.0.21",
|
||||
"vector-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raster-nodes"
|
||||
version = "0.0.0"
|
||||
@@ -5727,18 +5747,16 @@ dependencies = [
|
||||
"color",
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"fastnoise-lite",
|
||||
"futures",
|
||||
"glam",
|
||||
"graphene-core",
|
||||
"graphene-hash",
|
||||
"graphene-resource",
|
||||
"graphic-types",
|
||||
"image",
|
||||
"ndarray",
|
||||
"node-macro",
|
||||
"num_enum",
|
||||
"rand",
|
||||
"rand_chacha",
|
||||
"raster-kernels",
|
||||
"raster-types",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -5991,12 +6009,14 @@ dependencies = [
|
||||
"log",
|
||||
"num-traits",
|
||||
"parley",
|
||||
"raster-kernels",
|
||||
"serde",
|
||||
"skrifa",
|
||||
"text-nodes",
|
||||
"usvg",
|
||||
"vector-types",
|
||||
"vello_gpu",
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7974,6 +7994,7 @@ dependencies = [
|
||||
"node-macro",
|
||||
"qrcodegen",
|
||||
"rand",
|
||||
"raster-kernels",
|
||||
"repeat-nodes",
|
||||
"rustc-hash 2.1.3",
|
||||
"serde",
|
||||
@@ -8034,7 +8055,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=41dfe98e61b6322db38301025cc7eff51d6e9844#41dfe98e61b6322db38301025cc7eff51d6e9844"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"fearless_simd",
|
||||
@@ -8049,7 +8070,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=41dfe98e61b6322db38301025cc7eff51d6e9844#41dfe98e61b6322db38301025cc7eff51d6e9844"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"hashbrown 0.17.1",
|
||||
@@ -8063,7 +8084,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=41dfe98e61b6322db38301025cc7eff51d6e9844#41dfe98e61b6322db38301025cc7eff51d6e9844"
|
||||
dependencies = [
|
||||
"naga",
|
||||
"wesl",
|
||||
@@ -8524,8 +8545,11 @@ dependencies = [
|
||||
"futures",
|
||||
"glam",
|
||||
"graphene-application-io",
|
||||
"graphic-types",
|
||||
"half",
|
||||
"log",
|
||||
"node-macro",
|
||||
"raster-kernels",
|
||||
"raster-types",
|
||||
"rendering",
|
||||
"thiserror 2.0.21",
|
||||
|
||||
+4
-3
@@ -95,6 +95,7 @@ core-types = { path = "node-graph/libraries/core-types" }
|
||||
raster-types = { path = "node-graph/libraries/raster-types" }
|
||||
vector-types = { path = "node-graph/libraries/vector-types" }
|
||||
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" }
|
||||
brush-nodes = { path = "node-graph/nodes/brush" }
|
||||
@@ -310,6 +311,6 @@ debug = true
|
||||
[patch.crates-io]
|
||||
rfd = { git = "https://github.com/timon-schelling/rfd.git", branch = "graphite" } # TODO: Remove this once https://github.com/PolyMeilex/rfd/pull/317 is merged and released
|
||||
# TODO: Remove these once the fork's fixes are upstreamed and released
|
||||
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "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 = "41dfe98e61b6322db38301025cc7eff51d6e9844" }
|
||||
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "41dfe98e61b6322db38301025cc7eff51d6e9844" }
|
||||
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "41dfe98e61b6322db38301025cc7eff51d6e9844" }
|
||||
@@ -21,7 +21,7 @@ pub(crate) struct RenderState {
|
||||
ui_texture: Option<wgpu::Texture>,
|
||||
bind_group: Option<wgpu::BindGroup>,
|
||||
#[derivative(Debug = "ignore")]
|
||||
overlays_scene: Option<VelloSceneBuilder>,
|
||||
overlays_scene: Option<VelloSceneBuilder<'static>>,
|
||||
#[derivative(Debug = "ignore")]
|
||||
overlays_canvas: VelloCanvas,
|
||||
surface_outdated: bool,
|
||||
@@ -220,7 +220,7 @@ impl RenderState {
|
||||
self.viewport_offset = offset;
|
||||
}
|
||||
|
||||
pub(crate) fn set_overlays_scene(&mut self, scene: VelloSceneBuilder) {
|
||||
pub(crate) fn set_overlays_scene(&mut self, scene: VelloSceneBuilder<'static>) {
|
||||
self.surface_outdated = true;
|
||||
self.overlays_scene = Some(scene);
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ pub enum DesktopFrontendMessage {
|
||||
WindowUpdateDirectInput {
|
||||
enabled: bool,
|
||||
},
|
||||
UpdateOverlays(Box<wgpu_executor::VelloSceneBuilder>),
|
||||
UpdateOverlays(Box<wgpu_executor::VelloSceneBuilder<'static>>),
|
||||
PersistenceUpdatePreferences {
|
||||
preferences: Preferences,
|
||||
},
|
||||
|
||||
@@ -252,16 +252,19 @@ impl<L: Layout> Gdd<L> {
|
||||
let mut entries: std::collections::BTreeMap<String, Option<Resource>> = std::collections::BTreeMap::new();
|
||||
let directories = self.working.list_dirs("").await?;
|
||||
let has_directory = |directory: &str| directories.iter().any(|name| name == directory);
|
||||
if has_directory(self.layout.resources_dir()) {
|
||||
if flat.is_none() && has_directory(self.layout.resources_dir()) {
|
||||
entries.extend(self.working.list(self.layout.resources_dir()).await?.into_iter().map(|path| (path, None)));
|
||||
}
|
||||
for (hash, resource) in embedded_bytes {
|
||||
entries.entry(self.layout.resource_path(&hash)).or_insert(Some(resource));
|
||||
}
|
||||
|
||||
// A copy without history has no older blobs to use as bases, so each blob is written in full
|
||||
match &flat {
|
||||
Some(flat) => {
|
||||
let named = flat.registry().resources.values().filter_map(|entry| entry.hash);
|
||||
for hash in named.filter(|hash| working_copy_hashes.contains(hash)) {
|
||||
entries.insert(self.layout.resource_path(&hash), None);
|
||||
}
|
||||
for hash in flat.registry().blob_hashes() {
|
||||
let record = self.blobs.full_record(&hash).ok_or(Error::MissingResource(hash.into()))?;
|
||||
entries.insert(self.layout.blob_path(&hash), Some(Resource::new_unchecked(record, hash.into())));
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
//! Finds the path of every layer in a runtime network, once for each instance of the networks holding it.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use document_graph_storage::NodeMetadataEntry;
|
||||
use graph_craft::document::{DocumentNodeImplementation, NetworkLocation, NodeId, NodeNetwork};
|
||||
|
||||
/// The path of every node its metadata marks as a layer.
|
||||
pub fn layer_paths(network: &NodeNetwork, node_metadata: &[NodeMetadataEntry]) -> Vec<Vec<NodeId>> {
|
||||
let layers: HashSet<(NetworkLocation, NodeId)> = node_metadata.iter().filter(|node| node.is_layer).map(|node| (node.network, node.local_id)).collect();
|
||||
|
||||
let mut layer_paths = Vec::new();
|
||||
for_each_network_instance(network, |network_path, nested| {
|
||||
let Some(location) = network.locate(network_path) else { return };
|
||||
let nested_layers = nested.nodes.keys().filter(|node_id| layers.contains(&(location, **node_id)));
|
||||
layer_paths.extend(nested_layers.map(|node_id| [network_path, &[*node_id]].concat()));
|
||||
});
|
||||
layer_paths
|
||||
}
|
||||
|
||||
/// Visits every network with its path, once for each instance of it.
|
||||
/// A definition is not entered again from inside itself.
|
||||
pub fn for_each_network_instance(network: &NodeNetwork, mut visit: impl FnMut(&[NodeId], &NodeNetwork)) {
|
||||
let mut stack = vec![(Vec::new(), Vec::new())];
|
||||
while let Some((network_path, enclosing_definitions)) = stack.pop() {
|
||||
let Some(nested) = network.nested_network(&network_path) else { continue };
|
||||
visit(&network_path, nested);
|
||||
|
||||
for (node_id, node) in &nested.nodes {
|
||||
let mut enclosing_definitions = enclosing_definitions.clone();
|
||||
match node.implementation {
|
||||
DocumentNodeImplementation::Definition(id) if enclosing_definitions.contains(&id) => continue,
|
||||
DocumentNodeImplementation::Definition(id) => enclosing_definitions.push(id),
|
||||
DocumentNodeImplementation::Network(_) => {}
|
||||
_ => continue,
|
||||
}
|
||||
stack.push(([network_path.as_slice(), &[*node_id]].concat(), enclosing_definitions));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use graph_craft::document::{DocumentNode, NetworkId};
|
||||
|
||||
const DEFINITION: NetworkId = NetworkId(9);
|
||||
|
||||
fn node_metadata(network: NetworkLocation, local_id: u64, is_layer: bool) -> NodeMetadataEntry {
|
||||
NodeMetadataEntry {
|
||||
network,
|
||||
local_id: NodeId(local_id),
|
||||
position: None,
|
||||
is_layer,
|
||||
display_name: None,
|
||||
locked: false,
|
||||
pinned: false,
|
||||
input_metadata: Vec::new(),
|
||||
output_names: Vec::new(),
|
||||
output_descriptions: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layer_inside_a_definition_is_found_through_each_instance() {
|
||||
let instance = DocumentNode {
|
||||
implementation: DocumentNodeImplementation::Definition(DEFINITION),
|
||||
..Default::default()
|
||||
};
|
||||
let definition = NodeNetwork {
|
||||
nodes: [3, 4].map(|id| (NodeId(id), DocumentNode::default())).into_iter().collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let network = NodeNetwork {
|
||||
nodes: [1, 2].map(|id| (NodeId(id), instance.clone())).into_iter().collect(),
|
||||
definitions: [(DEFINITION, definition)].into_iter().collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let metadata = [(None, 1, true), (None, 2, false), (Some(DEFINITION), 3, true), (Some(DEFINITION), 4, false)];
|
||||
let metadata: Vec<_> = metadata.into_iter().map(|(location, local_id, is_layer)| node_metadata(location, local_id, is_layer)).collect();
|
||||
|
||||
let mut layer_paths = layer_paths(&network, &metadata);
|
||||
layer_paths.sort();
|
||||
|
||||
assert_eq!(layer_paths, vec![vec![NodeId(1)], vec![NodeId(1), NodeId(3)], vec![NodeId(2), NodeId(3)]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_definition_holding_itself_is_entered_once() {
|
||||
let recursive = DocumentNode {
|
||||
implementation: DocumentNodeImplementation::Definition(DEFINITION),
|
||||
..Default::default()
|
||||
};
|
||||
let network = NodeNetwork {
|
||||
nodes: [(NodeId(1), recursive.clone())].into_iter().collect(),
|
||||
definitions: [(
|
||||
DEFINITION,
|
||||
NodeNetwork {
|
||||
nodes: [(NodeId(2), recursive)].into_iter().collect(),
|
||||
..Default::default()
|
||||
},
|
||||
)]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut network_paths = Vec::new();
|
||||
for_each_network_instance(&network, |network_path, _| network_paths.push(network_path.to_vec()));
|
||||
|
||||
assert_eq!(network_paths, vec![vec![], vec![NodeId(1)]]);
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,8 @@ pub mod codec;
|
||||
pub mod error;
|
||||
pub mod export;
|
||||
pub mod io;
|
||||
#[cfg(feature = "conversion")]
|
||||
pub mod layers;
|
||||
pub mod layout;
|
||||
mod load;
|
||||
pub mod manifest;
|
||||
|
||||
@@ -104,7 +104,7 @@ impl<L: Layout> Gdd<L> {
|
||||
Ok(rewritten) => rewritten,
|
||||
Err(error) => {
|
||||
log::warn!("Migrating this document's history failed, so undo can't reach before this point: {error}");
|
||||
(self.session_with_truncated_history(migrated)?, remap_metadata(&self.metadata, |_| None))
|
||||
(session_with_truncated_history(&self.session, migrated)?, remap_metadata(&self.metadata, |_| None))
|
||||
}
|
||||
};
|
||||
self.keep_blobs_durably(blobs.into_added()).await?;
|
||||
@@ -189,19 +189,24 @@ impl<L: Layout> Gdd<L> {
|
||||
session.absorb_retired_marks(previous.retired_marks());
|
||||
Ok((session, remap_metadata(&self.metadata, remap)))
|
||||
}
|
||||
}
|
||||
|
||||
/// A session whose history restarts from `migrated`.
|
||||
fn session_with_truncated_history(&self, migrated: Registry) -> Result<Session, Error> {
|
||||
let previous = &self.session;
|
||||
let restarted = Session::bootstrap_from_registry(previous.peer(), previous.user(), migrated.clone())?;
|
||||
/// A session continuing `previous` whose history restarts from `migrated`.
|
||||
fn session_with_truncated_history(previous: &Session, migrated: Registry) -> Result<Session, Error> {
|
||||
let peer_users = migrated.peer_users.clone();
|
||||
let restarted = Session::bootstrap_from_registry(previous.peer(), previous.user(), migrated)?;
|
||||
|
||||
let history: Vec<Delta> = restarted.history().cloned().collect();
|
||||
let mut session = Session::load(previous.peer(), previous.user(), migrated, history, restarted.head_rev(), Vec::new(), previous.next_node_counter());
|
||||
session.restore_hot_sequence(previous.last_hot_sequence());
|
||||
session.restore_clock_counter(previous.clock_counter().max(restarted.clock_counter()));
|
||||
session.absorb_retired_marks(previous.retired_marks());
|
||||
Ok(session)
|
||||
}
|
||||
// The bootstrap re-stamps every value, so its registry is the one matching its history. Its deltas leave out
|
||||
// which user each device belongs to, so those registrations carry over directly.
|
||||
let mut registry = restarted.retired_registry().clone();
|
||||
registry.peer_users = peer_users;
|
||||
let history: Vec<Delta> = restarted.history().cloned().collect();
|
||||
|
||||
let mut session = Session::load(previous.peer(), previous.user(), registry, history, restarted.head_rev(), Vec::new(), previous.next_node_counter());
|
||||
session.restore_hot_sequence(previous.last_hot_sequence());
|
||||
session.restore_clock_counter(previous.clock_counter().max(restarted.clock_counter()));
|
||||
session.absorb_retired_marks(previous.retired_marks());
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
/// Resolves declaration resources to the declarations migrations name. A declaration's resource derives from its identifier and version
|
||||
@@ -269,3 +274,41 @@ impl DeclarationResolver for DocumentDeclarations {
|
||||
Some(self.encoded.get(self.known.get(&resource)?)?.proto.clone())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use document_graph_storage::{AttributeDelta, RegistryDelta, Value};
|
||||
|
||||
#[test]
|
||||
fn a_truncated_history_matches_its_registry_and_keeps_device_registrations() {
|
||||
let other_device = PeerId(2);
|
||||
let mut previous = Session::with_peer(PeerId(1));
|
||||
previous
|
||||
.stage_computed_ops(vec![RegistryDelta::RegisterPeer {
|
||||
peer: other_device,
|
||||
user: previous.user(),
|
||||
}])
|
||||
.unwrap();
|
||||
previous.retire_all().unwrap();
|
||||
|
||||
// Each edit stamps the value later than a fresh bootstrap would
|
||||
for edit in 0..10 {
|
||||
let delta = AttributeDelta {
|
||||
key: "edit".to_string(),
|
||||
value: Some(Value::Str(edit.to_string())),
|
||||
};
|
||||
previous.stage_computed_ops(vec![RegistryDelta::ChangeDocumentAttribute { delta }]).unwrap();
|
||||
previous.retire_all().unwrap();
|
||||
}
|
||||
|
||||
let session = session_with_truncated_history(&previous, previous.retired_registry().clone()).unwrap();
|
||||
assert_eq!(session.user_of(other_device), Some(previous.user()));
|
||||
|
||||
// Device registrations carry over apart from the history, so everything else must match its replay
|
||||
let replayed = Session::replay_from_history(session.peer(), session.user(), session.history().cloned(), session.next_node_counter()).unwrap();
|
||||
let mut registry = session.retired_registry().clone();
|
||||
registry.peer_users = replayed.retired_registry().peer_users.clone();
|
||||
assert_eq!(®istry, replayed.retired_registry());
|
||||
}
|
||||
}
|
||||
@@ -578,6 +578,50 @@ fn export_with_history_carries_history_only_resources() {
|
||||
});
|
||||
}
|
||||
|
||||
/// An export without history leaves behind the working copy's bytes of a resource only history still names.
|
||||
#[test]
|
||||
fn export_without_history_drops_history_only_resources() {
|
||||
use document_format::{ExportFormat, ExportOptions};
|
||||
use document_graph_storage::NoMetadata;
|
||||
use graphene_resource::{DataSource, ResourceHash, ResourceId, ResourceRegistry};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(9), UserId(9), 0xBEEF, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let byte_store = empty_byte_store();
|
||||
|
||||
let removed_payload = b"bytes of a removed resource";
|
||||
let removed_hash = ResourceHash::from(&removed_payload[..]);
|
||||
gdd.add_resource(ResourceId::new(), removed_payload).unwrap_or_else(|error| panic!("add_resource failed: {error:?}"));
|
||||
|
||||
let kept_payload = b"bytes of a kept resource";
|
||||
let kept_hash = ResourceHash::from(&kept_payload[..]);
|
||||
let kept_id = ResourceId::new();
|
||||
gdd.add_resource(kept_id, kept_payload).unwrap_or_else(|error| panic!("add_resource failed: {error:?}"));
|
||||
|
||||
let mut resources = ResourceRegistry::new();
|
||||
resources.push_source_back(&kept_id, DataSource::Embedded);
|
||||
resources.resolve(&kept_id, kept_hash);
|
||||
gdd.commit_from_runtime(&network_referencing_resource(kept_id), &NoMetadata, &resources, &byte_store)
|
||||
.unwrap_or_else(|error| panic!("commit_from_runtime failed: {error:?}"));
|
||||
|
||||
assert!(gdd.has_resource(&removed_hash).await, "the working copy should still hold the removed resource's bytes");
|
||||
|
||||
let options = ExportOptions {
|
||||
include_history: false,
|
||||
..Default::default()
|
||||
};
|
||||
let archive = gdd
|
||||
.export_to_bytes(ExportFormat::Zip, options, &byte_store, None)
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("export failed: {error:?}"));
|
||||
let reopened = GddV1::open_from_archive(&archive, empty_container(), GddV1Layout)
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("reopen failed: {error:?}"));
|
||||
assert!(reopened.has_resource(&kept_hash).await, "bytes the registry names should travel with the export");
|
||||
assert!(!reopened.has_resource(&removed_hash).await, "history-only bytes should stay behind");
|
||||
});
|
||||
}
|
||||
|
||||
/// A document with un-retired hot ops (e.g. a freshly converted document saved without an interaction
|
||||
/// boundary, or a save mid-drag) must export losslessly: the hot log travels alongside history and the
|
||||
/// reopened document reflects the staged edits. Regression for the converted-artwork "no history"
|
||||
|
||||
@@ -7,6 +7,15 @@ 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`.
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum Position {
|
||||
Absolute([i32; 2]),
|
||||
Chain,
|
||||
Stack(u32),
|
||||
}
|
||||
|
||||
impl AttributeValue {
|
||||
pub fn new(value: Value, timestamp: TimeStamp) -> Self {
|
||||
Self { value, timestamp, deleted: false }
|
||||
|
||||
@@ -44,7 +44,7 @@ pub use from_runtime::{
|
||||
encode_node_ui_attributes, node_value_resource_refs, storage_location_id, storage_node_id, value_resource_ref,
|
||||
};
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
pub use metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NoMetadata, NodeMetadataEntry, NodeMetadataSource, Position};
|
||||
pub use metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NoMetadata, NodeMetadataEntry, NodeMetadataSource};
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
pub use to_runtime::{Declarations, ProjectedNetwork, ProjectedNode, RuntimeProjection};
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ use std::collections::{BTreeMap, HashMap};
|
||||
use core_types::uuid::NodeId as RuntimeNodeId;
|
||||
use graph_craft::document::NetworkLocation;
|
||||
|
||||
use crate::{NetworkReference, Value};
|
||||
use crate::{NetworkReference, Position, Value};
|
||||
|
||||
/// One node's editor-side metadata, produced by `Registry::to_runtime_with_metadata`. One entry per
|
||||
/// node, since every node carries an identity to restore even when it carries no `ui::*` attribute.
|
||||
@@ -124,12 +124,3 @@ pub trait NodeMetadataSource {
|
||||
pub struct NoMetadata;
|
||||
|
||||
impl NodeMetadataSource for NoMetadata {}
|
||||
|
||||
/// 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`.
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum Position {
|
||||
Absolute([i32; 2]),
|
||||
Chain,
|
||||
Stack(u32),
|
||||
}
|
||||
@@ -22,6 +22,9 @@ impl Node {
|
||||
pub fn inputs_mut(&mut self) -> &mut Vec<InputSlot> {
|
||||
&mut self.inputs
|
||||
}
|
||||
pub fn attributes_mut(&mut self) -> &mut Attributes {
|
||||
&mut self.attributes
|
||||
}
|
||||
|
||||
/// True if both nodes agree on every value-bearing field, ignoring slot/attribute timestamps.
|
||||
pub fn value_equal(&self, other: &Self) -> bool {
|
||||
|
||||
@@ -5,7 +5,7 @@ use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{GddV1, GddV1Layout};
|
||||
use document_graph_storage::{PeerId, UserId};
|
||||
use graph_craft::application_io::resource::ResourceHash;
|
||||
use graph_craft::document::NodeNetwork;
|
||||
use graph_craft::document::{NodeId, NodeNetwork};
|
||||
use peer_transport::{Room, SyncTarget};
|
||||
|
||||
pub use document_format::Error as FormatError;
|
||||
@@ -97,10 +97,12 @@ impl LiveDocument {
|
||||
&mut self.gdd
|
||||
}
|
||||
|
||||
pub async fn network(&self) -> Result<NodeNetwork, LiveError> {
|
||||
/// The document's runtime network, with the path of every layer in it.
|
||||
pub async fn network_with_layers(&self) -> Result<(NodeNetwork, Vec<Vec<NodeId>>), LiveError> {
|
||||
let declarations = self.gdd.declarations(&self.gdd).await;
|
||||
let (network, _metadata) = self.gdd.registry().to_runtime_with_metadata(&declarations, self.gdd.blobs())?;
|
||||
Ok(network)
|
||||
let (network, node_metadata) = self.gdd.registry().to_runtime_with_metadata(&declarations, self.gdd.blobs())?;
|
||||
let layers = document_format::layers::layer_paths(&network, &node_metadata);
|
||||
Ok((network, layers))
|
||||
}
|
||||
|
||||
pub fn leave(&mut self) {
|
||||
|
||||
+115
-4
@@ -5,7 +5,8 @@ use document_container::archive::ArchiveFormat;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{GddV1, GddV1Layout};
|
||||
use document_graph_storage::{NetworkMetadataEntry, NodeMetadataEntry};
|
||||
use graph_craft::document::NodeNetwork;
|
||||
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeNetwork};
|
||||
use std::collections::HashMap;
|
||||
use std::error::Error;
|
||||
use std::path::Path;
|
||||
|
||||
@@ -17,6 +18,8 @@ use migration_nodes as _;
|
||||
/// A document's runtime network, with the file it was opened from.
|
||||
pub struct LoadedDocument {
|
||||
pub network: NodeNetwork,
|
||||
/// The path of every layer in `network`, once for each instance of the networks holding it.
|
||||
pub layers: Vec<Vec<NodeId>>,
|
||||
pub origin: DocumentOrigin,
|
||||
}
|
||||
|
||||
@@ -58,9 +61,13 @@ pub async fn open_document(path: &Path) -> Result<LoadedDocument, Box<dyn Error>
|
||||
let named_gdd = path.extension().is_some_and(|extension| extension.eq_ignore_ascii_case("gdd"));
|
||||
if !named_gdd && ArchiveFormat::detect(&bytes).is_none() {
|
||||
let document_string = String::from_utf8(bytes).map_err(|error| format!("Document {} is neither a .gdd archive nor text: {error}", path.display()))?;
|
||||
let network = legacy_network(&document_string).map_err(|error| format!("Failed to parse legacy document {}: {error}", path.display()))?;
|
||||
let parse_error = |error| format!("Failed to parse legacy document {}: {error}", path.display());
|
||||
let document: serde_json::Value = serde_json::from_str(&document_string).map_err(parse_error)?;
|
||||
let network = legacy_network(&document).map_err(parse_error)?;
|
||||
let layers = legacy_layer_paths(&network, &document);
|
||||
return Ok(LoadedDocument {
|
||||
network,
|
||||
layers,
|
||||
origin: DocumentOrigin::Legacy(document_string),
|
||||
});
|
||||
}
|
||||
@@ -68,14 +75,118 @@ pub async fn open_document(path: &Path) -> Result<LoadedDocument, Box<dyn Error>
|
||||
let gdd = open_gdd(&bytes).await?;
|
||||
let declarations = gdd.declarations(&gdd).await;
|
||||
let (network, nodes, networks) = gdd.registry().to_runtime_with_full_metadata(&declarations, gdd.blobs())?;
|
||||
let layers = document_format::layers::layer_paths(&network, &nodes);
|
||||
Ok(LoadedDocument {
|
||||
network,
|
||||
layers,
|
||||
origin: DocumentOrigin::Gdd { gdd: Box::new(gdd), nodes, networks },
|
||||
})
|
||||
}
|
||||
|
||||
fn legacy_network(document_string: &str) -> Result<NodeNetwork, serde_json::Error> {
|
||||
let document: serde_json::Value = serde_json::from_str(document_string)?;
|
||||
fn legacy_network(document: &serde_json::Value) -> Result<NodeNetwork, serde_json::Error> {
|
||||
let network = document["network_interface"]["network"].to_string();
|
||||
serde_json::from_str(&network)
|
||||
}
|
||||
|
||||
/// The path of every node a legacy document's metadata marks as a layer.
|
||||
fn legacy_layer_paths(network: &NodeNetwork, document: &serde_json::Value) -> Vec<Vec<NodeId>> {
|
||||
let mut layer_paths = Vec::new();
|
||||
document_format::layers::for_each_network_instance(network, |network_path, _| {
|
||||
let Some(network_metadata) = legacy_network_metadata(network, document, network_path) else {
|
||||
return;
|
||||
};
|
||||
let is_layer = |node_metadata: &serde_json::Value| node_metadata["node_type_metadata"]["Layer"].is_object();
|
||||
let layers = legacy_node_metadata(network_metadata).into_iter().filter(|(_, node_metadata)| is_layer(node_metadata));
|
||||
layer_paths.extend(layers.map(|(node_id, _)| [network_path, &[node_id]].concat()));
|
||||
});
|
||||
layer_paths
|
||||
}
|
||||
|
||||
/// The metadata of the network at this path in a legacy document.
|
||||
/// Older documents keep a held network's metadata inside its node's metadata, newer ones keep a definition's in a table.
|
||||
fn legacy_network_metadata<'a>(network: &NodeNetwork, document: &'a serde_json::Value, network_path: &[NodeId]) -> Option<&'a serde_json::Value> {
|
||||
let document_network_metadata = &document["network_interface"]["network_metadata"];
|
||||
let definitions = &document_network_metadata["persistent_metadata"]["definitions"];
|
||||
|
||||
let mut current = network;
|
||||
let mut network_metadata = document_network_metadata;
|
||||
for node_id in network_path {
|
||||
let node = current.nodes.get(node_id)?;
|
||||
network_metadata = match node.implementation {
|
||||
DocumentNodeImplementation::Definition(id) => &definitions[id.0.to_string()],
|
||||
DocumentNodeImplementation::Network(_) => &legacy_node_metadata(network_metadata).remove(node_id)?["network_metadata"],
|
||||
_ => return None,
|
||||
};
|
||||
current = network.implementation_network(&node.implementation)?;
|
||||
}
|
||||
|
||||
Some(network_metadata)
|
||||
}
|
||||
|
||||
/// The metadata of each node in a legacy network, by ID.
|
||||
fn legacy_node_metadata(network_metadata: &serde_json::Value) -> HashMap<NodeId, &serde_json::Value> {
|
||||
let entries = network_metadata["persistent_metadata"]["node_metadata"].as_array().into_iter().flatten();
|
||||
entries.filter_map(|entry| Some((NodeId(entry[0].as_u64()?), &entry[1]["persistent_metadata"]))).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use graph_craft::document::{DocumentNode, NetworkId};
|
||||
|
||||
fn node(implementation: DocumentNodeImplementation) -> DocumentNode {
|
||||
DocumentNode { implementation, ..Default::default() }
|
||||
}
|
||||
|
||||
/// A network holding the nodes 3 and 4.
|
||||
fn inner_network() -> NodeNetwork {
|
||||
NodeNetwork {
|
||||
nodes: [3, 4].map(|id| (NodeId(id), DocumentNode::default())).into_iter().collect(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn sorted_legacy_layer_paths(network: &NodeNetwork, document: &str) -> Vec<Vec<NodeId>> {
|
||||
let document = serde_json::from_str(document).expect("The test document should be valid JSON");
|
||||
let mut layer_paths = legacy_layer_paths(network, &document);
|
||||
layer_paths.sort();
|
||||
layer_paths
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layer_inside_a_definition_is_found_through_each_instance() {
|
||||
let definition = NetworkId(9);
|
||||
let network = NodeNetwork {
|
||||
nodes: [1, 2].map(|id| (NodeId(id), node(DocumentNodeImplementation::Definition(definition)))).into_iter().collect(),
|
||||
definitions: [(definition, inner_network())].into_iter().collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let document = r#"{ "network_interface": { "network_metadata": { "persistent_metadata": {
|
||||
"node_metadata": [[1, { "persistent_metadata": { "node_type_metadata": { "Layer": {} } } }], [2, { "persistent_metadata": { "node_type_metadata": { "Node": {} } } }]],
|
||||
"definitions": { "9": { "persistent_metadata": {
|
||||
"node_metadata": [[3, { "persistent_metadata": { "node_type_metadata": { "Layer": {} } } }], [4, { "persistent_metadata": { "node_type_metadata": { "Node": {} } } }]]
|
||||
} } }
|
||||
} } } }"#;
|
||||
|
||||
let expected = vec![vec![NodeId(1)], vec![NodeId(1), NodeId(3)], vec![NodeId(2), NodeId(3)]];
|
||||
assert_eq!(sorted_legacy_layer_paths(&network, document), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layer_inside_a_held_network_is_found() {
|
||||
let network = NodeNetwork {
|
||||
nodes: [(NodeId(1), node(DocumentNodeImplementation::Network(inner_network())))].into_iter().collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let document = r#"{ "network_interface": { "network_metadata": { "persistent_metadata": {
|
||||
"node_metadata": [[1, { "persistent_metadata": {
|
||||
"node_type_metadata": { "Layer": {} },
|
||||
"network_metadata": { "persistent_metadata": {
|
||||
"node_metadata": [[3, { "persistent_metadata": { "node_type_metadata": { "Layer": {} } } }], [4, { "persistent_metadata": { "node_type_metadata": { "Node": {} } } }]]
|
||||
} }
|
||||
} }]]
|
||||
} } } }"#;
|
||||
|
||||
assert_eq!(sorted_legacy_layer_paths(&network, document), vec![vec![NodeId(1)], vec![NodeId(1), NodeId(3)]]);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
use document_graph_storage::attr::node::VISIBLE;
|
||||
use document_graph_storage::attr::node::ui::DISPLAY_NAME;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::raster_types::{CPU, Raster};
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::vector::style::Gradient;
|
||||
use migration_core::{Compiler, Inputs, MigrationError, NewNode, Node, NodeInput, Target, Upstream, decl, literal, literal_of, migration};
|
||||
use migration_core::{Attributes, Compiler, Inputs, MigrationError, NewNode, Node, NodeInput, Target, Upstream, decl, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const CONTENT: usize = 1;
|
||||
@@ -29,11 +30,23 @@ fn number(input: &NodeInput) -> Option<f64> {
|
||||
/// Repeat on Points overwrites. Content that doesn't compile takes Flatten Graphic, which can't make that state any worse. A hidden node only passes
|
||||
/// its points through, so it needs nothing past the repeat, and its unused scale and rotation are dropped.
|
||||
#[migration("core_types::vector::CopyToPointsNode"@1 => "transform_nodes::transform_nodes::VaryRotationsNode"@2)]
|
||||
pub fn vary_nodes_from_copy_to_points(node: &Node, compiler: Option<&dyn Compiler>, inputs: &mut Inputs, upstream: &mut Upstream, target: &mut Target) -> Result<(), MigrationError> {
|
||||
pub fn vary_nodes_from_copy_to_points(
|
||||
node: &Node,
|
||||
compiler: Option<&dyn Compiler>,
|
||||
inputs: &mut Inputs,
|
||||
upstream: &mut Upstream,
|
||||
target: &mut Target,
|
||||
attributes: &mut Attributes,
|
||||
) -> Result<(), MigrationError> {
|
||||
let slots: Vec<NodeInput> = node.inputs().iter().map(|slot| slot.input.clone()).collect();
|
||||
let [points, content, scale_min, scale_max, scale_bias, scale_seed, rotation, rotation_seed] =
|
||||
<[NodeInput; 8]>::try_from(slots).map_err(|_| MigrationError::invariant("Copy to Points has eight inputs"))?;
|
||||
|
||||
// A stored default name would misname the new node
|
||||
if node.attributes().get_typed::<String>(DISPLAY_NAME).as_deref() == Some("Copy to Points") {
|
||||
attributes.remove(node.id(), DISPLAY_NAME);
|
||||
}
|
||||
|
||||
let repeat = decl!("repeat_nodes::repeat_nodes::RepeatOnPointsNode"@1);
|
||||
let unset = || literal(Tagged::Bool(false));
|
||||
|
||||
@@ -170,6 +183,8 @@ fn bias_keeping_average_scale(bias: f64) -> f64 {
|
||||
mod tests {
|
||||
use super::*;
|
||||
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_runner::testing::{Fixture, Random, SourceContract, check_commutation_with, check_undo_with};
|
||||
|
||||
@@ -184,10 +199,13 @@ mod tests {
|
||||
}
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(8, |random: &mut Random, slot| match slot {
|
||||
2 | 3 | 4 | 6 => literal(Tagged::Number(random.below(3) as f64)),
|
||||
_ => literal(Tagged::Integer(random.below(3) as i64)),
|
||||
})
|
||||
SourceContract {
|
||||
display_names: &["Copy to Points"],
|
||||
..SourceContract::new(8, |random: &mut Random, slot| match slot {
|
||||
2 | 3 | 4 | 6 => literal(Tagged::Number(random.below(3) as f64)),
|
||||
_ => literal(Tagged::Integer(random.below(3) as i64)),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn star_inputs() -> Vec<NodeInput> {
|
||||
@@ -262,6 +280,48 @@ mod tests {
|
||||
assert_eq!(number(&fixture.inputs(&migrated, rotations)[2]), Some(45.));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_name_is_cleared() {
|
||||
let mut fixture = Fixture::new(&VaryNodesFromCopyToPoints);
|
||||
let star = fixture.add(STAR, star_inputs());
|
||||
let copies = fixture.add(COPY_TO_POINTS, inputs(NodeInput::Node { id: star, index: 0 }, 2., 90.));
|
||||
let name = Value::Str("Copy to Points".to_string());
|
||||
fixture.registry.node_instances.get_mut(&copies).unwrap().attributes_mut().set(DISPLAY_NAME, name, TimeStamp::ORIGIN);
|
||||
|
||||
let migrated = fixture.migrate_with(&VaryNodesFromCopyToPoints, Some(&host())).unwrap();
|
||||
|
||||
assert!(migrated.node_instances[&copies].attributes().get_typed::<String>(DISPLAY_NAME).is_none());
|
||||
}
|
||||
|
||||
/// Matches the layout the legacy migration gives a star copied at a scale of 2 with random rotations spanning 90°.
|
||||
#[test]
|
||||
fn stages_lead_up_to_a_placed_node_in_a_row() {
|
||||
let mut fixture = Fixture::new(&VaryNodesFromCopyToPoints);
|
||||
let star = fixture.add(STAR, star_inputs());
|
||||
let copies = fixture.add(COPY_TO_POINTS, inputs(NodeInput::Node { id: star, index: 0 }, 2., 90.));
|
||||
let position = to_value(&Position::Absolute([20, 10])).unwrap();
|
||||
fixture.registry.node_instances.get_mut(&copies).unwrap().attributes_mut().set(POSITION, position, TimeStamp::ORIGIN);
|
||||
|
||||
let migrated = fixture.migrate_with(&VaryNodesFromCopyToPoints, Some(&host())).unwrap();
|
||||
let position_of = |node: NodeId| migrated.node_instances[&node].attributes().get_typed::<Position>(POSITION);
|
||||
|
||||
// Walk back from the anchor through each stage's points
|
||||
let mut stages = Vec::new();
|
||||
let mut stage = copies;
|
||||
while let NodeInput::Node { id, .. } = fixture.inputs(&migrated, stage)[0]
|
||||
&& id != star
|
||||
{
|
||||
stages.insert(0, position_of(id));
|
||||
stage = id;
|
||||
}
|
||||
let NodeInput::Node { id: group, .. } = fixture.inputs(&migrated, stage)[1] else {
|
||||
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])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bias_keeps_its_average() {
|
||||
assert_eq!(bias_keeping_average_scale(0.), 0.5);
|
||||
|
||||
@@ -29,7 +29,7 @@ pub use connector::{InputConnector, NewNode, OutputConnector};
|
||||
#[cfg(feature = "typed")]
|
||||
pub use declaration::{Declaration, DeclarationKind, DeclarationResolver};
|
||||
#[cfg(feature = "typed")]
|
||||
pub use document_graph_storage::NodeInput;
|
||||
pub use document_graph_storage::{NodeInput, Position, attr};
|
||||
pub use error::MigrationError;
|
||||
pub use format::{DocumentPayloads, FormatMigration, HistoryPolicy, Upgrade};
|
||||
#[cfg(feature = "typed")]
|
||||
@@ -44,7 +44,7 @@ pub use registry::{register_migration, registered_migrations};
|
||||
#[cfg(feature = "typed")]
|
||||
pub use value::{encode, literal, literal_of};
|
||||
#[cfg(feature = "typed")]
|
||||
pub use view::{AddedNode, AnchorContext, Downstream, Edits, Graph, Inputs, InputsEdit, Node, Region, Target, Upstream, View, implements};
|
||||
pub use view::{AddedNode, AnchorContext, AttributeWrite, Attributes, CHAIN_WIDTH, Downstream, Edits, FEEDER_ROW_HEIGHT, Graph, Inputs, InputsEdit, Node, Region, Target, Upstream, View, implements};
|
||||
|
||||
// For the registration `#[migration]`, `rename!`, and `format_migration!` generate
|
||||
#[doc(hidden)]
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
use crate::{Compiler, Declaration, DeclarationResolver, InputConnector, MigrationError, NewNode, OutputConnector, encode};
|
||||
use document_graph_storage::attributes::attr::node::REFLECTION_METADATA;
|
||||
use document_graph_storage::{Implementation, InputSlot, NetworkId, NodeId, NodeInput, Registry, TimeStamp};
|
||||
use document_graph_storage::{Implementation, InputSlot, NetworkId, NodeId, NodeInput, Registry, TimeStamp, Value};
|
||||
use serde::Serialize;
|
||||
use std::ops::Deref;
|
||||
|
||||
/// How many grid cells the editor's layout steps left for each node of a layer's chain.
|
||||
pub const CHAIN_WIDTH: i32 = 7;
|
||||
/// How many grid cells apart the rows of nodes feeding a node from below are.
|
||||
pub const FEEDER_ROW_HEIGHT: i32 = 3;
|
||||
|
||||
/// Which part of the registry around an anchor a view reads or edits. A migration's footprint is the union of its views' regions.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Region(u8);
|
||||
@@ -16,6 +21,8 @@ impl Region {
|
||||
pub const DOWNSTREAM: Self = Self(1 << 3);
|
||||
/// The anchor's whole network, as read through [`Graph`].
|
||||
pub const NETWORK: Self = Self(1 << 4);
|
||||
/// Attributes of the anchor and of the nodes the run adds, such as their positions and display names.
|
||||
pub const ATTRIBUTES: Self = Self(1 << 5);
|
||||
|
||||
pub const fn union(self, other: Self) -> Self {
|
||||
Self(self.0 | other.0)
|
||||
@@ -225,6 +232,8 @@ pub struct Edits {
|
||||
pub connections: Vec<(OutputConnector, InputConnector)>,
|
||||
/// The declaration this anchor switches to, when not the migration's target.
|
||||
pub target: Option<Declaration>,
|
||||
/// Attribute writes to the anchor and the nodes this run adds.
|
||||
pub attributes: Vec<AttributeWrite>,
|
||||
}
|
||||
|
||||
impl Edits {
|
||||
@@ -236,6 +245,57 @@ impl Edits {
|
||||
self.removed_nodes.extend(other.removed_nodes);
|
||||
self.connections.extend(other.connections);
|
||||
self.target = other.target.or(self.target);
|
||||
self.attributes.extend(other.attributes);
|
||||
}
|
||||
}
|
||||
|
||||
/// One attribute of the anchor or of a node the run adds. A run's writes apply in the order it recorded them.
|
||||
#[derive(Debug)]
|
||||
pub struct AttributeWrite {
|
||||
pub node: NodeId,
|
||||
pub key: String,
|
||||
/// `None` deletes the key.
|
||||
pub value: Option<Value>,
|
||||
}
|
||||
|
||||
/// Attributes of the anchor and of the nodes this run adds, such as where they sit and what they're named.
|
||||
#[derive(Default)]
|
||||
pub struct Attributes {
|
||||
writes: Vec<AttributeWrite>,
|
||||
}
|
||||
|
||||
impl Attributes {
|
||||
/// Write `value` under `key` on the anchor or on a node this run adds.
|
||||
pub fn set<T: Serialize>(&mut self, node: NodeId, key: &str, value: &T) {
|
||||
self.writes.push(AttributeWrite {
|
||||
node,
|
||||
key: key.to_string(),
|
||||
value: Some(encode(value)),
|
||||
});
|
||||
}
|
||||
|
||||
/// Delete `key` from the anchor or from a node this run adds.
|
||||
pub fn remove(&mut self, node: NodeId, key: &str) {
|
||||
self.writes.push(AttributeWrite {
|
||||
node,
|
||||
key: key.to_string(),
|
||||
value: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> View<'a> for Attributes {
|
||||
const REGION: Region = Region::ATTRIBUTES;
|
||||
|
||||
fn extract(_context: &AnchorContext<'a>) -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
fn into_edits(self) -> Result<Edits, MigrationError> {
|
||||
Ok(Edits {
|
||||
attributes: self.writes,
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ use syn::{Error, FnArg, Ident, ItemFn, ReturnType, Type, parse_macro_input};
|
||||
/// A `network` prefix names a built-in network definition, as in `#[migration(network "Merge"@1 => "module::merge"@2)]`.
|
||||
///
|
||||
/// Parameters state what the migration reads and writes: `&Node` and `&Graph` read the source state, `Option<&dyn Compiler>` asks what only the
|
||||
/// compiler can tell about it, and each `&mut` parameter is a view (`Inputs`, `Upstream`, `Downstream`, `Target`) recording edits to its region. The function may return `()` or `Result<(), MigrationError>`.
|
||||
/// compiler can tell about it, and each `&mut` parameter is a view (`Inputs`, `Upstream`, `Downstream`, `Target`, `Attributes`) recording edits to its region. The function may return `()` or `Result<(), MigrationError>`.
|
||||
///
|
||||
/// Generates a unit struct named after the function in Pascal case implementing `NodeMigration`, and registers it.
|
||||
#[proc_macro_attribute]
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
//! Migrations of the nodes in `blending_nodes`.
|
||||
|
||||
mod paint_overlay_from_color_overlay;
|
||||
mod renames;
|
||||
@@ -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,5 @@
|
||||
//! Nodes that only moved to a new identifier.
|
||||
|
||||
use migration_core::rename;
|
||||
|
||||
rename!("raster_nodes::filter::BlurNode"@1 => "blending_nodes::effects::BlurNode"@2);
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Node migrations, in a module per node crate and a file per step, each registering itself. Scaffold one with
|
||||
//! `cargo run migration new <identifier>` after bumping a node's `version(N)`.
|
||||
|
||||
mod blending_nodes;
|
||||
mod graphene_core;
|
||||
mod math_nodes;
|
||||
mod raster_nodes;
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
use migration_core::attr::node::ui::DISPLAY_NAME;
|
||||
use migration_core::{Attributes, Inputs, MigrationError, Node, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration uses.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
Number(f64),
|
||||
GradientForm(GradientForm),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum GradientForm {
|
||||
Linear,
|
||||
Radial,
|
||||
}
|
||||
|
||||
const FORM: u32 = 1;
|
||||
|
||||
/// 'Gradient Form' became 'Gradient Curvature', whose start and end curvatures take the presets of the form it set: 0 and 0 for linear, 1 and 0.5 for
|
||||
/// radial. A wired form becomes linear, and a name it stored as its default is cleared.
|
||||
#[migration("math_nodes::GradientFormNode"@1 => "math_nodes::GradientCurvatureNode"@2)]
|
||||
pub fn gradient_curvature_from_gradient_form(node: &Node, inputs: &mut Inputs, attributes: &mut Attributes) -> Result<(), MigrationError> {
|
||||
let [_, form] = node.inputs() else {
|
||||
return Err(MigrationError::invariant("Gradient Form has two inputs"));
|
||||
};
|
||||
let [start, end] = match literal_of::<Tagged>(&form.input) {
|
||||
Some(Tagged::GradientForm(GradientForm::Radial)) => [1., 0.5],
|
||||
_ => [0., 0.],
|
||||
};
|
||||
|
||||
inputs.set(FORM, literal(Tagged::Number(start)));
|
||||
inputs.push(literal(Tagged::Number(end)));
|
||||
|
||||
if node.attributes().get_typed::<String>(DISPLAY_NAME).as_deref() == Some("Gradient Form") {
|
||||
attributes.remove(node.id(), DISPLAY_NAME);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use document_graph_storage::TimeStamp;
|
||||
use migration_core::{NodeInput, decl};
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn form(form: GradientForm) -> NodeInput {
|
||||
literal(Tagged::GradientForm(form))
|
||||
}
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract {
|
||||
display_names: &["Gradient Form"],
|
||||
..SourceContract::new(2, |random, slot| match slot {
|
||||
1 if random.below(2) == 0 => form(GradientForm::Radial),
|
||||
1 => form(GradientForm::Linear),
|
||||
_ => literal(Tagged::Number(random.below(10) as f64)),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&GradientCurvatureFromGradientForm, &contract());
|
||||
check_undo(&GradientCurvatureFromGradientForm, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forms_become_their_curvature_presets() {
|
||||
let gradient = literal(Tagged::Number(0.));
|
||||
for (old_form, [start, end]) in [
|
||||
(form(GradientForm::Linear), [0., 0.]),
|
||||
(form(GradientForm::Radial), [1., 0.5]),
|
||||
(NodeInput::Import { index: 0 }, [0., 0.]),
|
||||
] {
|
||||
let mut fixture = Fixture::new(&GradientCurvatureFromGradientForm);
|
||||
let node = fixture.add(decl!("math_nodes::GradientFormNode"@1), vec![gradient.clone(), old_form]);
|
||||
let migrated = fixture.migrate(&GradientCurvatureFromGradientForm).unwrap();
|
||||
|
||||
assert_eq!(fixture.declaration_of(&migrated, node), Some(decl!("math_nodes::GradientCurvatureNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, node), [gradient.clone(), literal(Tagged::Number(start)), literal(Tagged::Number(end))]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_old_default_name_is_cleared() {
|
||||
for (name, kept) in [("Gradient Form", None), ("Spotlight", Some("Spotlight"))] {
|
||||
let mut fixture = Fixture::new(&GradientCurvatureFromGradientForm);
|
||||
let node = fixture.add(decl!("math_nodes::GradientFormNode"@1), vec![literal(Tagged::Number(0.)), form(GradientForm::Linear)]);
|
||||
let attributes = fixture.registry.node_instances.get_mut(&node).unwrap().attributes_mut();
|
||||
attributes.set_serialized(DISPLAY_NAME, &name, TimeStamp::ORIGIN).unwrap();
|
||||
|
||||
let migrated = fixture.migrate(&GradientCurvatureFromGradientForm).unwrap();
|
||||
|
||||
assert_eq!(migrated.node_instances[&node].attributes().get_typed::<String>(DISPLAY_NAME).as_deref(), kept);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Migrations of the nodes in `math_nodes`.
|
||||
|
||||
mod gradient_curvature_from_gradient_form;
|
||||
mod math_formula_from_math_f;
|
||||
mod renames;
|
||||
@@ -0,0 +1,104 @@
|
||||
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::{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 a_chained_pattern_gives_its_place_to_the_filled_rectangle() {
|
||||
let [pattern, paint, rectangle, fill, placement] = placed_square(Position::Chain, Some([30, 10]));
|
||||
|
||||
assert_eq!([rectangle, fill, placement], [Some(Position::Chain); 3]);
|
||||
assert_eq!(pattern, Some(Position::Absolute([0, 0])));
|
||||
assert_eq!(paint, Some(Position::Absolute([7, 0])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placed_pattern_gets_its_square_to_the_right() {
|
||||
let [pattern, paint, rectangle, fill, placement] = placed_square(Position::Absolute([5, 5]), None);
|
||||
|
||||
assert_eq!(pattern, Some(Position::Absolute([5, 5])));
|
||||
assert_eq!(paint, Some(Position::Absolute([12, 5])));
|
||||
assert_eq!(rectangle, Some(Position::Absolute([12, 2])));
|
||||
assert_eq!(fill, Some(Position::Absolute([19, 5])));
|
||||
assert_eq!(placement, Some(Position::Absolute([26, 5])));
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
//! Migrations of the nodes in `raster_nodes`.
|
||||
|
||||
mod mandelbrot_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,152 @@
|
||||
//! 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, Declaration, Downstream, 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);
|
||||
}
|
||||
|
||||
// In a layer's chain, the filled rectangle takes the pattern's place. The pattern and its paint leave the chain with no coordinates to go by,
|
||||
// so they start at the graph's origin. Elsewhere the square sits to the pattern's right.
|
||||
let stored = node.attributes().get_typed::<Position>(POSITION);
|
||||
if stored == Some(Position::Chain) {
|
||||
for id in [placement, fill, rectangle] {
|
||||
attributes.set(id, POSITION, &Position::Chain);
|
||||
}
|
||||
|
||||
attributes.set(node.id(), POSITION, &Position::Absolute([0, 0]));
|
||||
attributes.set(paint, POSITION, &Position::Absolute([7, 0]));
|
||||
} else {
|
||||
let [x, y] = match stored {
|
||||
Some(Position::Absolute(coordinates)) => coordinates,
|
||||
_ => [0, 0],
|
||||
};
|
||||
for (id, [x_offset, y_offset]) in [(paint, [7, 0]), (rectangle, [7, -3]), (fill, [14, 0]), (placement, [21, 0])] {
|
||||
attributes.set(id, POSITION, &Position::Absolute([x + x_offset, y + y_offset]));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -40,6 +40,8 @@ pub enum RunnerError {
|
||||
DuplicateAddedNode { anchor: NodeId, declaration: Declaration, key: String },
|
||||
#[error("added node {0:?} already exists")]
|
||||
AddedNodeExists(NodeId),
|
||||
#[error("node {anchor:?} writes attributes of {node:?}, which is neither it nor a node it adds")]
|
||||
AttributesOutsideRegion { anchor: NodeId, node: NodeId },
|
||||
#[error("{0:?} is rewired by one anchor while its own migration replaces or removes it")]
|
||||
ConflictingSlot(InputConnector),
|
||||
#[error("{0:?} does not exist in the migrated state")]
|
||||
|
||||
@@ -2,10 +2,12 @@
|
||||
|
||||
use crate::{MigrationBlobs, RunnerError};
|
||||
use document_graph_storage::TimeStamp;
|
||||
use document_graph_storage::attributes::attr::node::ui::REFERENCE;
|
||||
use document_graph_storage::attributes::attr::node::ui::{IS_LAYER, POSITION, REFERENCE};
|
||||
use document_graph_storage::delta::compute_deltas;
|
||||
use document_graph_storage::{Delta, Implementation, NetworkId, Node, NodeId, NodeInput, ProtoNode, Registry, RegistryDelta, ResourceHash, ResourceId, Rev, apply_retired_op};
|
||||
use migration_core::{AnchorContext, Compiler, Declaration, DeclarationResolver, Edits, InputConnector, InputsEdit, MigrationHost, NodeMigration, OutputConnector, implements};
|
||||
use document_graph_storage::{Delta, Implementation, NetworkId, Node, NodeId, NodeInput, Position, ProtoNode, Registry, RegistryDelta, ResourceHash, ResourceId, Rev, apply_retired_op};
|
||||
use migration_core::{
|
||||
AnchorContext, CHAIN_WIDTH, Compiler, Declaration, DeclarationResolver, Edits, FEEDER_ROW_HEIGHT, InputConnector, InputsEdit, MigrationHost, NodeMigration, OutputConnector, encode, implements,
|
||||
};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
/// A [`DeclarationResolver`] over a fixed set of declarations for tests, whose resource IDs derive from `identifier@version` rather than the encoded declarations documents store.
|
||||
@@ -173,6 +175,10 @@ fn apply_runs(migration: &dyn NodeMigration, source: &Registry, anchors: &[NodeI
|
||||
}
|
||||
|
||||
add_nodes(&mut target, &runs, resolver)?;
|
||||
for (anchor, edits) in &runs {
|
||||
place_added_nodes(&mut target, *anchor, edits);
|
||||
write_attributes(&mut target, *anchor, edits)?;
|
||||
}
|
||||
|
||||
let input_edits: HashMap<NodeId, &InputsEdit> = runs.iter().filter_map(|(anchor, edits)| Some((*anchor, edits.inputs.as_ref()?))).collect();
|
||||
for (anchor, inputs) in &input_edits {
|
||||
@@ -328,6 +334,90 @@ 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);
|
||||
let is_layer = anchor_node.attributes().get_or(IS_LAYER, false);
|
||||
let anchor_inputs: Vec<NodeInput> = match &edits.inputs {
|
||||
Some(inputs) => inputs.slots.iter().map(|slot| slot.input.clone()).collect(),
|
||||
None => anchor_node.inputs().iter().map(|slot| slot.input.clone()).collect(),
|
||||
};
|
||||
|
||||
let added_inputs: HashMap<NodeId, &[NodeInput]> = edits.added_nodes.iter().map(|added| (added.id, added.node.inputs.as_slice())).collect();
|
||||
let reads = |inputs: &[NodeInput], node: NodeId| inputs.iter().any(|input| matches!(input, NodeInput::Node { id, .. } if *id == node));
|
||||
|
||||
let chain_input = if is_layer { 1 } else { 0 };
|
||||
let mut chain = Vec::new();
|
||||
let mut next = anchor_inputs.get(chain_input);
|
||||
while let Some(NodeInput::Node { id, .. }) = next
|
||||
&& let Some(inputs) = added_inputs.get(id)
|
||||
&& !chain.contains(id)
|
||||
{
|
||||
chain.push(*id);
|
||||
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 => {}
|
||||
}
|
||||
}
|
||||
|
||||
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()];
|
||||
|
||||
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 (id, position) in positions {
|
||||
if let Some(node) = target.node_instances.get_mut(&id) {
|
||||
node.attributes_mut().set(POSITION, encode(&position), TimeStamp::ORIGIN);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply one run's attribute writes, which may only name its anchor and the nodes it adds.
|
||||
fn write_attributes(target: &mut Registry, anchor: NodeId, edits: &Edits) -> Result<(), RunnerError> {
|
||||
for write in &edits.attributes {
|
||||
let in_region = write.node == anchor || edits.added_nodes.iter().any(|added| added.id == write.node);
|
||||
let node = target.node_instances.get_mut(&write.node).filter(|_| in_region);
|
||||
let node = node.ok_or(RunnerError::AttributesOutsideRegion { anchor, node: write.node })?;
|
||||
|
||||
match &write.value {
|
||||
Some(value) => node.attributes_mut().set(&write.key, value.clone(), TimeStamp::ORIGIN),
|
||||
None => {
|
||||
node.attributes_mut().remove(&write.key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Make `consumer`, named in the source layout, read `output` in the target layout. Fails when the consumer's own migration replaced or
|
||||
/// removed that slot, since two runs then disagree on what it should read.
|
||||
fn connect(target: &mut Registry, output: OutputConnector, consumer: InputConnector, input_edits: &HashMap<NodeId, &InputsEdit>) -> Result<(), RunnerError> {
|
||||
|
||||
@@ -3,9 +3,10 @@
|
||||
|
||||
use crate::node::{apply_migration, needs_whole_states, rewrite_history};
|
||||
use crate::{DeclarationTable, MigrationBlobs, RunnerError, references, registry_at};
|
||||
use document_graph_storage::attributes::attr::node::ui::REFERENCE;
|
||||
use document_graph_storage::attributes::attr::node::ui::{DISPLAY_NAME, IS_LAYER, POSITION, REFERENCE};
|
||||
use document_graph_storage::{
|
||||
Delta, ExportSlot, Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ROOT_NETWORK, Registry, RegistryDelta, Session, TimeStamp, UserId, apply_retired_op,
|
||||
AttributeDelta, Delta, ExportSlot, Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, Position, ROOT_NETWORK, Registry, RegistryDelta, Session, TimeStamp, UserId, Value,
|
||||
apply_retired_op, to_value,
|
||||
};
|
||||
use migration_core::{Declaration, DeclarationResolver, MigrationHost, NodeMigration, decl, implements, literal, registered_migrations};
|
||||
use std::collections::HashSet;
|
||||
@@ -138,6 +139,8 @@ pub struct SourceContract {
|
||||
pub literal: fn(&mut Random, usize) -> NodeInput,
|
||||
/// Whether a slot may read an output of another node of the source declaration.
|
||||
pub reads_own_output: fn(usize) -> bool,
|
||||
/// Display names, besides a custom one, that generated histories give nodes, such as a default the migration clears.
|
||||
pub display_names: &'static [&'static str],
|
||||
}
|
||||
|
||||
impl SourceContract {
|
||||
@@ -146,6 +149,7 @@ impl SourceContract {
|
||||
input_count,
|
||||
literal,
|
||||
reads_own_output: |_| true,
|
||||
display_names: &[],
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -276,11 +280,36 @@ impl Generator<'_> {
|
||||
self.commit_interaction(ops);
|
||||
}
|
||||
|
||||
/// A name, position, or layer flag, written or deleted.
|
||||
fn attribute(&mut self) -> AttributeDelta {
|
||||
let (key, value) = match self.random.below(3) {
|
||||
0 => {
|
||||
let names = self.contract.display_names;
|
||||
let name = match self.random.below(names.len() + 2) {
|
||||
index if index < names.len() => Some(names[index]),
|
||||
index if index == names.len() => Some("Renamed"),
|
||||
_ => None,
|
||||
};
|
||||
(DISPLAY_NAME, name.map(|name| Value::Str(name.to_string())))
|
||||
}
|
||||
1 => {
|
||||
let position = match self.random.below(3) {
|
||||
0 => Position::Chain,
|
||||
_ => Position::Absolute([self.random.below(20) as i32, self.random.below(20) as i32]),
|
||||
};
|
||||
(POSITION, Some(to_value(&position).expect("positions serialize")))
|
||||
}
|
||||
_ => (IS_LAYER, (self.random.below(2) == 0).then_some(Value::Bool(true))),
|
||||
};
|
||||
|
||||
AttributeDelta { key: key.to_string(), value }
|
||||
}
|
||||
|
||||
fn step(&mut self) {
|
||||
let nodes = self.live_nodes();
|
||||
let root_nodes = self.live_nodes_in(ROOT_NETWORK);
|
||||
|
||||
match self.random.below(11) {
|
||||
match self.random.below(13) {
|
||||
0..=3 => {
|
||||
let (declaration, input_count) = if self.random.below(3) == 0 {
|
||||
(self.source, self.contract.input_count)
|
||||
@@ -335,6 +364,11 @@ impl Generator<'_> {
|
||||
self.session.undo().expect("an interaction is left to undo");
|
||||
self.undoable -= 1;
|
||||
}
|
||||
11 | 12 if !nodes.is_empty() => {
|
||||
let id = self.random.pick(&nodes);
|
||||
let delta = self.attribute();
|
||||
self.commit(RegistryDelta::ChangeNodeAttribute { id, delta });
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
//! Attribute writes on the anchor and the nodes it adds, and the positions added nodes get by default.
|
||||
|
||||
use document_graph_storage::attr::node::ui::{DISPLAY_NAME, POSITION};
|
||||
use document_graph_storage::{NodeId, NodeInput, Position, Value, to_value};
|
||||
use migration_core::{Attributes, CHAIN_WIDTH, Downstream, FEEDER_ROW_HEIGHT, Inputs, NewNode, Node, Upstream, decl, migration};
|
||||
use migration_runner::RunnerError;
|
||||
use migration_runner::testing::Fixture;
|
||||
|
||||
/// Clears the anchor's old default name and places a node it adds.
|
||||
#[migration("attributes::renamed"@1 => @2)]
|
||||
pub fn renamed(node: &Node, downstream: &mut Downstream, attributes: &mut Attributes) {
|
||||
if node.attributes().get_typed::<String>(DISPLAY_NAME).as_deref() == Some("Old name") {
|
||||
attributes.remove(node.id(), DISPLAY_NAME);
|
||||
}
|
||||
|
||||
let added = downstream.add_node(NewNode {
|
||||
declaration: decl!("math_nodes::add"@1),
|
||||
inputs: vec![],
|
||||
});
|
||||
attributes.set(added, POSITION, &Position::Absolute([3, 4]));
|
||||
}
|
||||
|
||||
/// Renames the node its first input reads, which it neither is nor adds.
|
||||
#[migration("attributes::outside"@1 => @2)]
|
||||
pub fn outside(node: &Node, attributes: &mut Attributes) {
|
||||
if let Some(NodeInput::Node { id, .. }) = node.inputs().first().map(|slot| &slot.input) {
|
||||
attributes.set(*id, DISPLAY_NAME, &"Renamed");
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds two nodes leading up to the anchor's first input, and one feeding the nearer of them from below.
|
||||
#[migration("attributes::placed"@1 => @2)]
|
||||
pub fn placed(node: &Node, inputs: &mut Inputs, upstream: &mut Upstream) {
|
||||
let add = decl!("math_nodes::add"@1);
|
||||
let source = node.inputs().first().map_or(NodeInput::Import { index: 0 }, |slot| slot.input.clone());
|
||||
|
||||
let far = upstream.add_node_keyed(
|
||||
NewNode {
|
||||
declaration: add,
|
||||
inputs: vec![source],
|
||||
},
|
||||
"far",
|
||||
);
|
||||
let below = upstream.add_node_keyed(NewNode { declaration: add, inputs: vec![] }, "below");
|
||||
let near = upstream.add_node_keyed(
|
||||
NewNode {
|
||||
declaration: add,
|
||||
inputs: vec![wire(far), wire(below)],
|
||||
},
|
||||
"near",
|
||||
);
|
||||
inputs.set(0, wire(near));
|
||||
}
|
||||
|
||||
fn set_name(fixture: &mut Fixture, node: NodeId, name: &str) {
|
||||
let name = Value::Str(name.to_string());
|
||||
fixture.registry.node_instances.get_mut(&node).unwrap().attributes_mut().set(DISPLAY_NAME, name, Default::default());
|
||||
}
|
||||
|
||||
/// The positions of the far, near, and below nodes `Placed` adds for an anchor stored at `position`.
|
||||
fn placed_around(position: Position) -> [Option<Position>; 3] {
|
||||
let migration = &Placed;
|
||||
let mut fixture = Fixture::new(migration);
|
||||
let anchor = fixture.add(decl!("attributes::placed"@1), vec![NodeInput::Import { index: 0 }]);
|
||||
let position = to_value(&position).unwrap();
|
||||
fixture.registry.node_instances.get_mut(&anchor).unwrap().attributes_mut().set(POSITION, position, Default::default());
|
||||
|
||||
let migrated = fixture.migrate(migration).unwrap();
|
||||
let position_of = |id: NodeId| migrated.node_instances[&id].attributes().get_typed::<Position>(POSITION);
|
||||
|
||||
let NodeInput::Node { id: near, .. } = fixture.inputs(&migrated, anchor)[0] else {
|
||||
panic!("the anchor reads the near node")
|
||||
};
|
||||
let [NodeInput::Node { id: far, .. }, NodeInput::Node { id: below, .. }] = fixture.inputs(&migrated, near)[..] else {
|
||||
panic!("the near node reads the far and below nodes")
|
||||
};
|
||||
[position_of(far), position_of(near), position_of(below)]
|
||||
}
|
||||
|
||||
fn wire(id: NodeId) -> NodeInput {
|
||||
NodeInput::Node { id, index: 0 }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_writes_its_anchor_and_the_nodes_it_adds() {
|
||||
let migration = &Renamed;
|
||||
let mut fixture = Fixture::new(migration);
|
||||
let anchor = fixture.add(decl!("attributes::renamed"@1), vec![]);
|
||||
set_name(&mut fixture, anchor, "Old name");
|
||||
fixture.export(wire(anchor));
|
||||
|
||||
let migrated = fixture.migrate(migration).unwrap();
|
||||
|
||||
assert!(migrated.node_instances[&anchor].attributes().get(DISPLAY_NAME).is_none());
|
||||
let added = migrated.node_instances.iter().find(|(id, _)| **id != anchor).map(|(_, node)| node).expect("the run adds a node");
|
||||
assert_eq!(added.attributes().get_typed::<Position>(POSITION), Some(Position::Absolute([3, 4])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_given_by_the_user_is_kept() {
|
||||
let migration = &Renamed;
|
||||
let mut fixture = Fixture::new(migration);
|
||||
let anchor = fixture.add(decl!("attributes::renamed"@1), vec![]);
|
||||
set_name(&mut fixture, anchor, "Mine");
|
||||
|
||||
let migrated = fixture.migrate(migration).unwrap();
|
||||
|
||||
assert_eq!(migrated.node_instances[&anchor].attributes().get_typed::<String>(DISPLAY_NAME).as_deref(), Some("Mine"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn added_nodes_lead_up_to_a_placed_anchor() {
|
||||
let [far, near, below] = placed_around(Position::Absolute([20, 10]));
|
||||
|
||||
assert_eq!(far, Some(Position::Absolute([20 - 2 * CHAIN_WIDTH, 10])));
|
||||
assert_eq!(near, Some(Position::Absolute([20 - CHAIN_WIDTH, 10])));
|
||||
assert_eq!(below, Some(Position::Absolute([20 - 2 * CHAIN_WIDTH, 10 + FEEDER_ROW_HEIGHT])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn added_nodes_join_a_chained_anchors_chain() {
|
||||
let [far, near, below] = placed_around(Position::Chain);
|
||||
|
||||
assert_eq!([far, near], [Some(Position::Chain); 2]);
|
||||
assert_eq!(below, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writing_another_nodes_attributes_fails() {
|
||||
let migration = &Outside;
|
||||
let mut fixture = Fixture::new(migration);
|
||||
let other = fixture.add(decl!("math_nodes::add"@1), vec![]);
|
||||
fixture.add(decl!("attributes::outside"@1), vec![wire(other)]);
|
||||
|
||||
let error = fixture.migrate(migration).unwrap_err();
|
||||
assert!(matches!(error, RunnerError::AttributesOutsideRegion { node, .. } if node == other), "{error}");
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
mod attributes;
|
||||
mod blobs;
|
||||
mod compiler;
|
||||
mod examples;
|
||||
|
||||
@@ -13,6 +13,9 @@ fn every_migration_registers_once() {
|
||||
sources.sort();
|
||||
|
||||
let mut expected = vec![
|
||||
decl!("attributes::outside"@1),
|
||||
decl!("attributes::placed"@1),
|
||||
decl!("attributes::renamed"@1),
|
||||
decl!("blending_nodes::opacity"@1),
|
||||
decl!("blob_nodes::text"@1),
|
||||
decl!("compiler::anchor"@1),
|
||||
|
||||
@@ -12,7 +12,7 @@ pub(crate) struct NodeSource {
|
||||
pub version: u32,
|
||||
pub function: String,
|
||||
pub file: PathBuf,
|
||||
/// The parameters and output as written, without their attributes. Comparing it tells whether stored inputs still fit.
|
||||
/// The parameters and output as written, without their attributes or `#[data]` fields. Comparing it tells whether stored inputs still fit.
|
||||
pub signature: String,
|
||||
}
|
||||
|
||||
@@ -131,7 +131,10 @@ fn node_source(function: &syn::ItemFn, file: &Path, module_path: &[String]) -> O
|
||||
}
|
||||
|
||||
let function_name = function.sig.ident.to_string();
|
||||
let parameters = function.sig.inputs.iter().map(|parameter| match parameter {
|
||||
|
||||
// A `#[data]` field is the node's own state rather than a stored input, so documents don't notice it changing
|
||||
let is_data_field = |parameter: &&syn::FnArg| matches!(parameter, syn::FnArg::Typed(typed) if typed.attrs.iter().any(|attribute| attribute.path().is_ident("data")));
|
||||
let parameters = function.sig.inputs.iter().filter(|parameter| !is_data_field(parameter)).map(|parameter| match parameter {
|
||||
syn::FnArg::Typed(typed) => {
|
||||
let (pattern, ty) = (&typed.pat, &typed.ty);
|
||||
quote::quote!(#pattern: #ty).to_string()
|
||||
@@ -149,3 +152,23 @@ fn node_source(function: &syn::ItemFn, file: &Path, module_path: &[String]) -> O
|
||||
signature,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn data_fields_are_left_out_of_the_signature() {
|
||||
let function: syn::ItemFn = syn::parse_quote! {
|
||||
#[node_macro::node(category("Raster"))]
|
||||
fn lookup(_: impl Ctx, image: Item<Color>, #[data] cache: Cache) -> Item<Color> {
|
||||
image
|
||||
}
|
||||
};
|
||||
let node = node_source(&function, Path::new("lib.rs"), &["raster_nodes".to_string()]).expect("the function is a node");
|
||||
|
||||
assert_eq!(node.identifier, "raster_nodes::LookupNode");
|
||||
assert!(!node.signature.contains("cache"), "{}", node.signature);
|
||||
assert!(node.signature.contains("image"), "{}", node.signature);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Scaffolds node migrations into `migration-nodes`, one file per step, in a module per node crate.
|
||||
|
||||
use crate::lineage::{MigrationStep, find_migrations};
|
||||
use crate::lineage::{MigrationStep, find_all_migrations};
|
||||
use crate::nodes::{NodeSource, find_nodes};
|
||||
use convert_case::{Case, Casing};
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -18,7 +18,7 @@ pub(crate) fn scaffold(workspace: &Path, command: &str, arguments: &[String]) ->
|
||||
|
||||
match (command, arguments) {
|
||||
("new", []) => {
|
||||
let steps = missing_steps(&nodes, &find_migrations(&migrations)?);
|
||||
let steps = missing_steps(&nodes, &find_all_migrations(workspace, &MIGRATION_CRATES)?);
|
||||
if steps.is_empty() {
|
||||
println!("Every node version already has a migration leading to it");
|
||||
return Ok(());
|
||||
@@ -35,7 +35,7 @@ pub(crate) fn scaffold(workspace: &Path, command: &str, arguments: &[String]) ->
|
||||
));
|
||||
}
|
||||
|
||||
let steps = missing_steps(std::slice::from_ref(node), &find_migrations(&migrations)?);
|
||||
let steps = missing_steps(std::slice::from_ref(node), &find_all_migrations(workspace, &MIGRATION_CRATES)?);
|
||||
if steps.is_empty() {
|
||||
return Err(format!("migrations up to `{}`@{} already exist", node.identifier, node.version));
|
||||
}
|
||||
@@ -168,7 +168,7 @@ fn write_step(migrations: &Path, node: &NodeSource, name: &str, step: &str, from
|
||||
/// Describe what changed from version {from}.\n\
|
||||
#[migration({step})]\n\
|
||||
pub fn {name}(inputs: &mut Inputs) {{\n\
|
||||
\tcompile_error!(\"Migrate from version {from} here. Read the source state with `&Node` or `&Graph`, and edit it through `&mut Inputs`, `&mut Upstream`, or `&mut Downstream`\");\n\
|
||||
\tcompile_error!(\"Migrate from version {from} here. Read the source state with `&Node` or `&Graph`, and edit it through `&mut Inputs`, `&mut Upstream`, `&mut Downstream`, or `&mut Attributes`\");\n\
|
||||
}}\n\n\
|
||||
#[cfg(test)]\n\
|
||||
mod tests {{\n\
|
||||
@@ -242,6 +242,7 @@ fn declare_module(file: &Path, module: &str) -> Result<(), String> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::lineage::find_migrations;
|
||||
|
||||
/// A workspace with one node crate and an empty `migration-nodes`, removed on drop.
|
||||
struct Workspace(PathBuf);
|
||||
@@ -329,6 +330,22 @@ mod tests {
|
||||
assert!(missing_steps(&nodes, &found).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_version_reached_from_a_compiled_migration_needs_no_step() {
|
||||
let workspace = Workspace::new("compiled");
|
||||
let compiled = workspace.0.join("document/migrations/compiled/src");
|
||||
std::fs::create_dir_all(&compiled).unwrap();
|
||||
std::fs::write(
|
||||
compiled.join("lib.rs"),
|
||||
"#[migration(\"old::Node\"@1 => \"blending_nodes::OpacityNode\"@2)]\npub fn opacity_from_node(inputs: &mut Inputs) {}\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
scaffold(&workspace.0, "new", &[]).unwrap();
|
||||
assert!(!workspace.0.join(MIGRATIONS).join("blending_nodes/opacity_v1.rs").exists());
|
||||
assert!(workspace.read("legacy/brighten_v1.rs").contains("\"legacy::adjust::BrightenNode\"@1 => @2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_no_module_declares_is_no_migration() {
|
||||
let workspace = Workspace::new("undeclared");
|
||||
|
||||
@@ -987,17 +987,17 @@ mod test {
|
||||
.iter()
|
||||
.find_map(|(id, node)| (node.implementation == graph_craft::document::DocumentNodeImplementation::Definition(entry)).then_some(*id))
|
||||
.expect("the pasted layer");
|
||||
let (inner, input_index) = interface.document_network().definitions[&entry]
|
||||
let extend = graph_craft::document::DocumentNodeImplementation::ProtoNode(graphene_std::graphic::extend::IDENTIFIER);
|
||||
let inner = interface.document_network().definitions[&entry]
|
||||
.nodes
|
||||
.iter()
|
||||
.find_map(|(id, node)| node.inputs.iter().position(|input| matches!(input, NodeInput::Value { .. })).map(|index| (*id, index)))
|
||||
.expect("the entry should have a value input");
|
||||
.find_map(|(id, node)| (node.implementation == extend).then_some(*id))
|
||||
.expect("the entry should have an Extend node");
|
||||
let before = interface.document_network().definitions[&entry].clone();
|
||||
let NodeInput::Value { tagged_value, exposed } = &before.nodes[&inner].inputs[input_index] else {
|
||||
unreachable!("the input was found as a value")
|
||||
};
|
||||
let flipped = NodeInput::value((**tagged_value).clone(), !exposed);
|
||||
interface.set_input(&InputConnector::node_at_index(inner, input_index), flipped, &[layer]);
|
||||
|
||||
// Leaving out the stack below keeps the entry a working layer
|
||||
let no_base = NodeInput::type_default(graphene_std::list!(graphene_std::Graphic), false);
|
||||
interface.set_input(&InputConnector::node_at_index(inner, 0), no_base, &[layer]);
|
||||
assert_ne!(interface.document_network().definitions[&entry], before, "the edit should change the pasted entry");
|
||||
|
||||
editor.paste_from_clipboard(clipboard.clone()).await;
|
||||
|
||||
@@ -64,6 +64,9 @@ pub struct DropdownInput {
|
||||
// This uses `u32` instead of `usize` since it will be serialized as a normal JS number (we can replace this with `usize` if we switch to a Rust-based GUI)
|
||||
#[serde(rename = "selectedIndex")]
|
||||
pub selected_index: Option<u32>,
|
||||
// Shown while no entry is selected
|
||||
#[derivative(Default(value = "\"-\".to_string()"))]
|
||||
pub placeholder: String,
|
||||
#[serde(rename = "drawIcon")]
|
||||
pub draw_icon: bool,
|
||||
pub disabled: bool,
|
||||
|
||||
@@ -11,6 +11,7 @@ use graphene_std::animation::RealTimeMode;
|
||||
use graphene_std::blending::BlendMode;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::core_types::misc::format_f64;
|
||||
use graphene_std::generator::Generator;
|
||||
use graphene_std::gradient::Gradient;
|
||||
use graphene_std::list::{INTERNAL_ATTRIBUTE_PREFIX, Item, List, NodeIdPath};
|
||||
use graphene_std::math::float_noise::round_away_float_noise;
|
||||
@@ -32,7 +33,7 @@ use graphene_std::vector::style::{
|
||||
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin,
|
||||
};
|
||||
use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector};
|
||||
use graphene_std::{Appearance, Artboard, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Graphic};
|
||||
use graphene_std::{Appearance, Artboard, BevelDirection, BevelStyle, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource, Graphic};
|
||||
use kurbo::BezPath;
|
||||
use std::any::Any;
|
||||
use std::ops::Range;
|
||||
@@ -394,6 +395,7 @@ macro_rules! inspectable_types {
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<String>,
|
||||
List<f64>,
|
||||
List<i64>,
|
||||
@@ -450,6 +452,7 @@ macro_rules! inspectable_types {
|
||||
Item<Raster<GPU>>,
|
||||
Item<Color>,
|
||||
Item<Gradient>,
|
||||
Item<Generator>,
|
||||
Item<String>,
|
||||
Item<f64>,
|
||||
Item<i64>,
|
||||
@@ -618,7 +621,7 @@ impl<T: TableItemLayout> TableItemLayout for Item<T> {
|
||||
}
|
||||
}
|
||||
|
||||
let attribute_keys: Vec<String> = self.attributes().keys().map(str::to_string).collect();
|
||||
let attribute_keys: Vec<String> = self.attributes().keys().filter(|key| !key.starts_with(INTERNAL_ATTRIBUTE_PREFIX)).map(str::to_string).collect();
|
||||
|
||||
// A single element, so no leading ID column, unlike the `List` table
|
||||
let saved_gradient_settings = data.gradient_settings;
|
||||
@@ -792,6 +795,45 @@ impl TableItemLayout for Coverage {
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for Effects {
|
||||
fn type_name() -> &'static str {
|
||||
"Effects"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
"Effects".to_string()
|
||||
}
|
||||
// The wrapping `Item` already contributes the breadcrumb; the inner list supplies the next level
|
||||
fn layout_with_breadcrumb(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
self.value_page(data)
|
||||
}
|
||||
// Label the spreadsheet's element button with the inner list's identifier, like Appearance
|
||||
fn value_widgets(&self, target: PathStep, data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
self.0.value_widgets(target, data)
|
||||
}
|
||||
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
self.0.layout_with_breadcrumb(data)
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for Effect {
|
||||
fn type_name() -> &'static str {
|
||||
"Effect"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
"Effect".to_string()
|
||||
}
|
||||
// The wrapping row already contributes the breadcrumb; the inner item supplies the next level
|
||||
fn layout_with_breadcrumb(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
self.value_page(data)
|
||||
}
|
||||
fn value_widgets(&self, target: PathStep, data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
self.0.value_widgets(target, data)
|
||||
}
|
||||
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
self.0.layout_with_breadcrumb(data)
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for TransferCurve {
|
||||
fn type_name() -> &'static str {
|
||||
"TransferCurve"
|
||||
@@ -857,6 +899,7 @@ impl TableItemLayout for Graphic {
|
||||
Self::RasterGPU(item) => item.identifier(),
|
||||
Self::Color(item) => item.identifier(),
|
||||
Self::Gradient(item) => item.identifier(),
|
||||
Self::Generator(item) => item.identifier(),
|
||||
Self::Text(item) => item.identifier(),
|
||||
Self::NoneList(list) => list.identifier(),
|
||||
Self::GraphicList(list) => list.identifier(),
|
||||
@@ -865,6 +908,7 @@ impl TableItemLayout for Graphic {
|
||||
Self::RasterGPUList(list) => list.identifier(),
|
||||
Self::ColorList(list) => list.identifier(),
|
||||
Self::GradientList(list) => list.identifier(),
|
||||
Self::GeneratorList(list) => list.identifier(),
|
||||
Self::TextList(list) => list.identifier(),
|
||||
Self::StrokeList(list) => list.identifier(),
|
||||
}
|
||||
@@ -882,6 +926,7 @@ impl TableItemLayout for Graphic {
|
||||
Self::RasterGPU(item) => item.layout_with_breadcrumb(data),
|
||||
Self::Color(item) => item.layout_with_breadcrumb(data),
|
||||
Self::Gradient(item) => item.layout_with_breadcrumb(data),
|
||||
Self::Generator(item) => item.layout_with_breadcrumb(data),
|
||||
Self::Text(item) => item.layout_with_breadcrumb(data),
|
||||
Self::NoneList(list) => list.layout_with_breadcrumb(data),
|
||||
Self::GraphicList(list) => list.layout_with_breadcrumb(data),
|
||||
@@ -890,6 +935,7 @@ impl TableItemLayout for Graphic {
|
||||
Self::RasterGPUList(list) => list.layout_with_breadcrumb(data),
|
||||
Self::ColorList(list) => list.layout_with_breadcrumb(data),
|
||||
Self::GradientList(list) => list.layout_with_breadcrumb(data),
|
||||
Self::GeneratorList(list) => list.layout_with_breadcrumb(data),
|
||||
Self::TextList(list) => list.layout_with_breadcrumb(data),
|
||||
Self::StrokeList(list) => list.layout_with_breadcrumb(data),
|
||||
}
|
||||
@@ -1213,6 +1259,11 @@ macro_rules! impl_table_item_layout_for_choice_enum {
|
||||
impl_table_item_layout_for_choice_enum!(
|
||||
BlendMode,
|
||||
Cover,
|
||||
BevelDirection,
|
||||
BevelStyle,
|
||||
EffectKind,
|
||||
Generator,
|
||||
GlowSource,
|
||||
GradientForm,
|
||||
GradientSpread,
|
||||
GradientSpace,
|
||||
@@ -1359,9 +1410,11 @@ macro_rules! known_item_types {
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<String>,
|
||||
List<f64>,
|
||||
Gradient,
|
||||
Generator,
|
||||
Color,
|
||||
NodeId,
|
||||
DAffine2,
|
||||
@@ -1383,6 +1436,12 @@ macro_rules! known_item_types {
|
||||
Appearance,
|
||||
Coverage,
|
||||
Cover,
|
||||
Effects,
|
||||
Effect,
|
||||
EffectKind,
|
||||
GlowSource,
|
||||
BevelStyle,
|
||||
BevelDirection,
|
||||
DashPattern,
|
||||
BoxCorners,
|
||||
TransferCurve,
|
||||
|
||||
@@ -325,6 +325,9 @@ pub enum DocumentMessage {
|
||||
UpdateAppearanceAttributes {
|
||||
appearance_attributes: HashMap<NodeId, Arc<Appearance>>,
|
||||
},
|
||||
UpdateEffectsReach {
|
||||
effects_reach: HashMap<NodeId, f64>,
|
||||
},
|
||||
Undo,
|
||||
UngroupSelectedLayers,
|
||||
UngroupLayer {
|
||||
|
||||
@@ -1915,6 +1915,14 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
.collect();
|
||||
self.network_interface.update_appearance_attributes(layer_appearance_attributes);
|
||||
}
|
||||
DocumentMessage::UpdateEffectsReach { effects_reach } => {
|
||||
let layer_effects_reach = effects_reach
|
||||
.into_iter()
|
||||
.filter(|(node_id, _)| self.network_interface.document_network().nodes.contains_key(node_id) && self.network_interface.is_layer(node_id, &[]))
|
||||
.map(|(node_id, reach)| (LayerNodeIdentifier::new(node_id, &self.network_interface), reach))
|
||||
.collect();
|
||||
self.network_interface.update_effects_reach(layer_effects_reach);
|
||||
}
|
||||
DocumentMessage::Undo => {
|
||||
if self.network_interface.transaction_status() != TransactionStatus::Finished {
|
||||
return;
|
||||
@@ -5069,15 +5077,11 @@ mod document_message_handler_tests {
|
||||
assert!(!base_lengths.is_empty(), "Instrumentation should have recorded at least one stack base");
|
||||
assert!(base_lengths.iter().all(|&len| len == 0), "Every stack base should be empty, found lengths {base_lengths:?}");
|
||||
|
||||
let news: Vec<graphene_std::list::List<graphene_std::Graphic>> = instrumented
|
||||
.grab_all_input::<graphene_std::graphic::extend::NewInput, graphene_std::list::List<graphene_std::Graphic>>(&editor.runtime)
|
||||
let news: Vec<graphene_std::list::Item<graphene_std::Graphic>> = instrumented
|
||||
.grab_all_input::<graphene_std::graphic::extend::NewInput, graphene_std::list::Item<graphene_std::Graphic>>(&editor.runtime)
|
||||
.collect();
|
||||
assert!(!news.is_empty(), "Instrumentation should have recorded at least one stacked element list");
|
||||
let phantom_count = news
|
||||
.iter()
|
||||
.flat_map(|new| new.iter_element_values())
|
||||
.filter(|graphic| matches!(graphic, graphene_std::Graphic::None(_)))
|
||||
.count();
|
||||
assert!(!news.is_empty(), "Instrumentation should have recorded at least one stacked element");
|
||||
let phantom_count = news.iter().filter(|new| matches!(new.element(), graphene_std::Graphic::None(_))).count();
|
||||
assert_eq!(phantom_count, 0, "No stacked element should be a phantom None graphic");
|
||||
}
|
||||
|
||||
|
||||
@@ -761,20 +761,26 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
self.responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
|
||||
/// Write the Gradient Form to the last 'Gradient Form' node in the chain, inserting one only when the value differs
|
||||
/// Write the Gradient Form's curvatures to the last 'Gradient Curvature' node in the chain, inserting one only when the form differs
|
||||
/// from the default (`Linear`).
|
||||
pub fn gradient_form_set(&mut self, gradient_form: GradientForm) {
|
||||
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, IDENTIFIER, StartCurvatureInput};
|
||||
use graphene_std::renderer::dial_gradient::{LINEAR_DIALS, RADIAL_DIALS};
|
||||
|
||||
let Some(output_layer) = self.get_output_layer() else { return };
|
||||
|
||||
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
|
||||
let identifier = graphene_std::math_nodes::gradient_form::IDENTIFIER;
|
||||
let create_if_nonexistent = gradient_form != GradientForm::default();
|
||||
let Some(node_id) = self.existing_proto_node_id_at(&target_input, identifier, create_if_nonexistent) else {
|
||||
let Some(node_id) = self.existing_proto_node_id_at(&target_input, IDENTIFIER, create_if_nonexistent) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::gradient_form::GradientFormInput);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::GradientForm(gradient_form), false), false);
|
||||
let [start, end] = match gradient_form {
|
||||
GradientForm::Linear => LINEAR_DIALS,
|
||||
GradientForm::Radial => RADIAL_DIALS,
|
||||
};
|
||||
self.set_input_with_refresh(InputConnector::node(node_id, StartCurvatureInput), NodeInput::value(TaggedValue::Number(start), false), false);
|
||||
self.set_input_with_refresh(InputConnector::node(node_id, EndCurvatureInput), NodeInput::value(TaggedValue::Number(end), false), false);
|
||||
}
|
||||
|
||||
/// Set the spread on the chain's gradient value, which is where the ramp carries it.
|
||||
|
||||
@@ -175,44 +175,25 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
icon: Some("NodeMerge"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(4), 0)],
|
||||
exports: vec![NodeInput::node(NodeId(2), 0)],
|
||||
nodes: [
|
||||
// Primary (bottom) input type coercion
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::import(generic!(T), 0)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::as_graphic::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-14, -2)),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -2)),
|
||||
..Default::default()
|
||||
},
|
||||
// Secondary (left) input type coercion
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::import(generic!(T), 1)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::into_group::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-14, -1)),
|
||||
..Default::default()
|
||||
},
|
||||
// Derive the parent layer's NodeId from the document path
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::DocumentNodePath)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::path_of_subgraph::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-14, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// Stamp each item of the content with the parent layer's NodeId via the `editor:layer_path` attribute,
|
||||
// so editor tools (e.g. selection, click target routing) can trace data back to its owning layer.
|
||||
NodeTemplate {
|
||||
inputs: vec![
|
||||
NodeInput::node(NodeId(1), 0),
|
||||
NodeInput::value(TaggedValue::String(graphene_std::ATTR_EDITOR_LAYER_PATH.to_string()), false),
|
||||
NodeInput::node(NodeId(2), 0),
|
||||
],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::write_attribute::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -1)),
|
||||
..Default::default()
|
||||
},
|
||||
NodeTemplate {
|
||||
call_argument: generic!(T),
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::node(NodeId(3), 0)],
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::node(NodeId(1), 0)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::extend::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -2)),
|
||||
..Default::default()
|
||||
@@ -244,7 +225,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
icon: Some("NodeArtboard"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(3), 0)],
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [
|
||||
NodeTemplate {
|
||||
call_argument: generic!(T),
|
||||
@@ -256,32 +237,13 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
NodeInput::import(item!(TaggedValue), 4),
|
||||
NodeInput::import(item!(TaggedValue), 5),
|
||||
],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-14, -3)),
|
||||
..Default::default()
|
||||
},
|
||||
// Derive the parent layer's NodeId from the document path
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::DocumentNodePath)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::path_of_subgraph::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-14, 3)),
|
||||
..Default::default()
|
||||
},
|
||||
// Stamp each item of the content with the parent layer's NodeId via the `editor:layer_path` attribute,
|
||||
// so editor tools (e.g. selection, click target routing) can trace data back to its owning layer.
|
||||
NodeTemplate {
|
||||
inputs: vec![
|
||||
NodeInput::node(NodeId(0), 0),
|
||||
NodeInput::value(TaggedValue::String(graphene_std::ATTR_EDITOR_LAYER_PATH.to_string()), false),
|
||||
NodeInput::node(NodeId(1), 0),
|
||||
],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::write_attribute::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -3)),
|
||||
..Default::default()
|
||||
},
|
||||
NodeTemplate {
|
||||
inputs: vec![
|
||||
NodeInput::import(graphene_std::Type::Fn(Box::new(concrete!(Context)), Box::new(list!(Artboard))), 0),
|
||||
NodeInput::node(NodeId(2), 0),
|
||||
NodeInput::node(NodeId(0), 0),
|
||||
],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::extend::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -4)),
|
||||
@@ -798,6 +760,7 @@ fn static_node_inspector() -> NodeInspector {
|
||||
map.insert("exposure_inspector".to_string(), Box::new(node_inspector::exposure_inspector));
|
||||
map.insert("format_number_inspector".to_string(), Box::new(node_inspector::format_number_inspector));
|
||||
map.insert("string_capitalization_inspector".to_string(), Box::new(node_inspector::string_capitalization_inspector));
|
||||
map.insert("gradient_curvature_inspector".to_string(), Box::new(node_inspector::gradient_curvature_inspector));
|
||||
map.insert("rectangle_inspector".to_string(), Box::new(node_inspector::rectangle_inspector));
|
||||
map.insert("grid_inspector".to_string(), Box::new(node_inspector::grid_inspector));
|
||||
map.insert("spiral_inspector".to_string(), Box::new(node_inspector::spiral_inspector));
|
||||
|
||||
@@ -40,7 +40,7 @@ use graphene_std::vector::style::{
|
||||
build_transform_with_y_preservation,
|
||||
};
|
||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
|
||||
use graphene_std::{Artboard, Graphic, Vector};
|
||||
use graphene_std::{Artboard, BevelDirection, BevelStyle, GlowSource, Graphic, Vector};
|
||||
use graphene_std::{NodeParameter, ParameterRef};
|
||||
use math_parser::parser::{MessagePart, ParseError};
|
||||
use std::path::PathBuf;
|
||||
@@ -388,6 +388,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &mut extra_widgets),
|
||||
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
Some(x) if id_is::<Graphic>(x) => color_widget(default_info, ColorInput::default()),
|
||||
// ============
|
||||
// STRUCT TYPES
|
||||
// ============
|
||||
@@ -438,6 +439,9 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
Some(x) if id_is::<BooleanOperation>(x) => enum_choice::<BooleanOperation>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<CentroidType>(x) => enum_choice::<CentroidType>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<DesaturateMethod>(x) => enum_choice::<DesaturateMethod>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<GlowSource>(x) => enum_choice::<GlowSource>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<BevelStyle>(x) => enum_choice::<BevelStyle>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<BevelDirection>(x) => enum_choice::<BevelDirection>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<QRCodeErrorCorrectionLevel>(x) => enum_choice::<QRCodeErrorCorrectionLevel>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<ScaleType>(x) => enum_choice::<ScaleType>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<InterpolationDistribution>(x) => enum_choice::<InterpolationDistribution>().for_socket(default_info).inspector_row(),
|
||||
@@ -1001,7 +1005,12 @@ pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetI
|
||||
}
|
||||
}
|
||||
|
||||
let parameter_widgets_info = ParameterWidgetsInfo {
|
||||
blank_assist: false,
|
||||
..parameter_widgets_info
|
||||
};
|
||||
let ParameterWidgetsInfo {
|
||||
document_id,
|
||||
document_node,
|
||||
node_id,
|
||||
index,
|
||||
@@ -1025,8 +1034,27 @@ pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetI
|
||||
Some(TaggedValue::TypeDefault(_)) => Font::default(),
|
||||
_ => return (first_widgets, second_widgets),
|
||||
};
|
||||
|
||||
let filters = vec![TypeFilter::font()];
|
||||
let file_drop_action = IngestAction::resource_input(document_id, node_id, index, &filters);
|
||||
let load_button = IconButton::new("FileImport", 24)
|
||||
.tooltip_label("Load Font File")
|
||||
.tooltip_description("Use a font that isn't in the list by loading its .ttf or .otf file. The font is saved with the document.")
|
||||
.on_update(move |_| {
|
||||
IngestMessage::SetResourceInput {
|
||||
document_id,
|
||||
node_id,
|
||||
input_index: index,
|
||||
filters: filters.clone(),
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.widget_instance();
|
||||
|
||||
{
|
||||
first_widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
load_button,
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
DropdownInput::new(vec![
|
||||
fonts
|
||||
@@ -1050,7 +1078,15 @@ pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetI
|
||||
.collect::<Vec<_>>(),
|
||||
])
|
||||
.selected_index(fonts.font_catalog.iter().position(|family| family.name == font.font_family).map(|i| i as u32))
|
||||
.placeholder(font.font_family.clone())
|
||||
.virtual_scrolling(true)
|
||||
.on_file_drop(move |file| {
|
||||
IngestMessage::Ingest {
|
||||
content: DataTransferItem::from_file(PathBuf::from(&file.name), Some(file.mime_type.as_str()).filter(|mime| !mime.is_empty()), file.data.clone()).into(),
|
||||
action: file_drop_action.clone(),
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.widget_instance(),
|
||||
]);
|
||||
|
||||
@@ -1094,6 +1130,7 @@ pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetI
|
||||
})
|
||||
.map(|i| i as u32),
|
||||
)
|
||||
.placeholder(font.font_style.clone())
|
||||
.widget_instance(),
|
||||
]);
|
||||
second_widgets = Some(second_row);
|
||||
@@ -3013,6 +3050,79 @@ pub(crate) fn string_capitalization_inspector(node_id: NodeId, context: &mut Nod
|
||||
vec![capitalization, LayoutGroup::row(joiner_widgets), LayoutGroup::row(joiner_preset_buttons)]
|
||||
}
|
||||
|
||||
pub(crate) fn gradient_curvature_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||
use graphene_std::math_nodes::gradient_curvature::*;
|
||||
use graphene_std::renderer::dial_gradient::{LINEAR_DIALS, RADIAL_DIALS};
|
||||
|
||||
// The curvatures set in the panel, or `None` when either is fed from the graph, so it can't take a preset
|
||||
let curvatures = match get_document_node(node_id, context) {
|
||||
Ok(document_node) => {
|
||||
let curvature = |index: usize| match document_node.inputs.get(index).and_then(|input| input.as_non_exposed_value()) {
|
||||
Some(&TaggedValue::Number(value)) => Some(value),
|
||||
_ => None,
|
||||
};
|
||||
curvature(StartCurvatureInput::INDEX).zip(curvature(EndCurvatureInput::INDEX)).map(|(start, end)| [start, end])
|
||||
}
|
||||
Err(err) => {
|
||||
log::error!("Could not get document node in gradient_curvature_inspector: {err}");
|
||||
return Vec::new();
|
||||
}
|
||||
};
|
||||
|
||||
// Each form's button sets both curvatures to the form's own, and stands out while they're exactly those
|
||||
let mut form = vec![
|
||||
TextLabel::new("Form")
|
||||
.tooltip_label("Form")
|
||||
.tooltip_description("Sets both curvatures to those of a standard gradient form.")
|
||||
.widget_instance(),
|
||||
];
|
||||
add_blank_assist(&mut form);
|
||||
form.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
for (label, [start, end], tooltip) in [
|
||||
("Linear", LINEAR_DIALS, "Sets both curvatures to 0, making straight contours."),
|
||||
("Radial", RADIAL_DIALS, "Sets the start curvature to 1 and the end curvature to 0.5, making circles around the start."),
|
||||
] {
|
||||
form.push(
|
||||
TextButton::new(label)
|
||||
.tooltip_description(tooltip)
|
||||
.emphasized(curvatures == Some([start, end]))
|
||||
.disabled(curvatures.is_none())
|
||||
.on_update(move |_: &TextButton| Message::Batched {
|
||||
messages: Box::new([
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: StartCurvatureInput::INDEX,
|
||||
value: TaggedValue::Number(start).into(),
|
||||
}
|
||||
.into(),
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: EndCurvatureInput::INDEX,
|
||||
value: TaggedValue::Number(end).into(),
|
||||
}
|
||||
.into(),
|
||||
]),
|
||||
})
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
);
|
||||
}
|
||||
|
||||
// The same sliders the curvatures would get without this panel
|
||||
let options = ParameterOptions {
|
||||
soft_min: Some(-1.),
|
||||
soft_max: Some(1.),
|
||||
slider: true,
|
||||
..Default::default()
|
||||
};
|
||||
let mut curvature = |index: usize| inspector_row_from_type(node_id, index, &concrete!(f64), options, context).unwrap_or_else(|rows| rows);
|
||||
|
||||
let mut layout = vec![LayoutGroup::row(form)];
|
||||
layout.extend(curvature(StartCurvatureInput::INDEX));
|
||||
layout.extend(curvature(EndCurvatureInput::INDEX));
|
||||
layout
|
||||
}
|
||||
|
||||
pub(crate) fn rectangle_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||
use graphene_std::vector::generator_nodes::rectangle::*;
|
||||
|
||||
|
||||
@@ -34,6 +34,8 @@ impl FrontendGraphDataType {
|
||||
"Gradient" => Self::Gradient,
|
||||
"String" => Self::Typography,
|
||||
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
|
||||
// A generator draws pixels like an image, at whatever resolution is needed
|
||||
"Generator" => Self::Raster,
|
||||
raster if raster.starts_with("Raster") => Self::Raster,
|
||||
_ => Self::General,
|
||||
}
|
||||
|
||||
@@ -270,7 +270,7 @@ impl OverlayContext {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn take_scene(self) -> VelloSceneBuilder {
|
||||
pub fn take_scene(self) -> VelloSceneBuilder<'static> {
|
||||
let mut internal = self.internal.lock().expect("Failed to lock internal overlay context");
|
||||
let empty_scene = overlay_scene(&internal.viewport);
|
||||
std::mem::replace(&mut internal.scene, empty_scene)
|
||||
@@ -486,13 +486,13 @@ pub enum DrawHandles {
|
||||
}
|
||||
|
||||
pub(super) struct OverlayContextInternal {
|
||||
scene: VelloSceneBuilder,
|
||||
scene: VelloSceneBuilder<'static>,
|
||||
viewport: ViewportMessageHandler,
|
||||
visibility_settings: OverlaysVisibilitySettings,
|
||||
}
|
||||
|
||||
/// An empty scene covering the viewport's physical pixels, matching the resolution the viewport renders at.
|
||||
fn overlay_scene(viewport: &ViewportMessageHandler) -> VelloSceneBuilder {
|
||||
fn overlay_scene(viewport: &ViewportMessageHandler) -> VelloSceneBuilder<'static> {
|
||||
// The smallest texture size limit WebGL2 guarantees, which only matters for the overlays' tiny pattern images
|
||||
const MAX_TEXTURE_SIZE: u32 = 2048;
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ use std::sync::Arc;
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum ResourceMessage {
|
||||
StoreEmbedded { resource_id: ResourceId, data: Arc<[u8]> },
|
||||
StoreFont { resource_id: ResourceId, font: Font, data: Arc<[u8]> },
|
||||
AddFont { resource_id: ResourceId, font: Font },
|
||||
ResolveAll,
|
||||
Resolve { resource_id: ResourceId },
|
||||
|
||||
@@ -35,6 +35,20 @@ impl MessageHandler<ResourceMessage, ResourceMessageContext<'_>> for ResourceMes
|
||||
self.registry.resolve(&resource_id, hash);
|
||||
responses.add(ResourceStorageMessage::Store { data });
|
||||
}
|
||||
ResourceMessage::StoreFont { resource_id, font, data } => {
|
||||
let hash = ResourceHash::from(data.as_ref());
|
||||
self.registry.push_source_back(&resource_id, DataSource::Embedded);
|
||||
self.registry.push_source_back(
|
||||
&resource_id,
|
||||
DataSource::Font {
|
||||
family: font.font_family.clone(),
|
||||
style: Some(font.font_style.clone()),
|
||||
},
|
||||
);
|
||||
self.registry.resolve(&resource_id, hash);
|
||||
responses.add(ResourceStorageMessage::Store { data });
|
||||
responses.add(FontsMessage::ResourceResolved { font, hash });
|
||||
}
|
||||
ResourceMessage::AddFont { resource_id, font } => {
|
||||
let style = fonts.font_catalog.find_font_style_in_catalog(&font);
|
||||
let style_name = style.map(|style| style.to_named_style()).unwrap_or_else(|| font.font_style.clone());
|
||||
|
||||
@@ -51,6 +51,8 @@ pub struct DocumentMetadata {
|
||||
pub layer_vector_data: HashMap<LayerNodeIdentifier, Arc<Item<Vector>>>,
|
||||
/// Per-layer `ATTR_APPEARANCE` attribute, exposed so message handlers can read paint information that lives on the list.
|
||||
pub layer_appearance_attributes: HashMap<LayerNodeIdentifier, Arc<Appearance>>,
|
||||
/// How far each layer's effects paint past its content, in document pixels, for the layers with effects.
|
||||
pub layer_effects_reach: HashMap<LayerNodeIdentifier, f64>,
|
||||
/// Transform from document space to viewport space.
|
||||
pub document_to_viewport: DAffine2,
|
||||
/// The transform from document space to viewport space that the latest render was made with, which is the one `upstream_footprints` include.
|
||||
@@ -347,9 +349,9 @@ impl DocumentMetadata {
|
||||
}
|
||||
|
||||
/// Get the bounding box of the specified layer in document space, expanded to include the actual rendered
|
||||
/// stroke geometry when the layer is a vector with a stroke style. Only the first item of a layer's vector data
|
||||
/// is recorded, so the others count through the click-target-based bounds, without their strokes.
|
||||
pub fn bounding_box_document_with_stroke(&self, layer: LayerNodeIdentifier) -> Option<[DVec2; 2]> {
|
||||
/// stroke geometry when the layer is a vector with a stroke style, and how far its effects paint past it. Only the first item of a
|
||||
/// layer's vector data is recorded, so the others count through the click-target-based bounds, without their strokes.
|
||||
pub fn bounding_box_document_with_stroke_and_effects(&self, layer: LayerNodeIdentifier) -> Option<[DVec2; 2]> {
|
||||
let stroked = self.layer_vector_data.get(&layer).and_then(|item| {
|
||||
let stroke = self
|
||||
.layer_appearance_attributes
|
||||
@@ -359,8 +361,10 @@ impl DocumentMetadata {
|
||||
let paths = paths_from_item_attributes(item.as_ref()).unwrap_or_else(|| no_paths());
|
||||
item.element().stroke_inclusive_bounding_box_with_transform(paths, self.transform_to_document(layer), stroke.as_ref())
|
||||
});
|
||||
let [min, max] = [stroked, self.bounding_box_document(layer)].into_iter().flatten().reduce(Quad::combine_bounds)?;
|
||||
|
||||
[stroked, self.bounding_box_document(layer)].into_iter().flatten().reduce(Quad::combine_bounds)
|
||||
let reach = self.layer_effects_reach.get(&layer).copied().unwrap_or_default();
|
||||
Some([min - reach, max + reach])
|
||||
}
|
||||
|
||||
/// Get the bounding box of the click target of the specified layer in viewport space
|
||||
@@ -732,7 +736,7 @@ mod tests {
|
||||
let later_item = ClickTarget::new_with_path(line(100., 110.), 0.);
|
||||
metadata.click_targets.insert(layer, vec![Arc::new(later_item)]);
|
||||
|
||||
let [min, max] = metadata.bounding_box_document_with_stroke(layer).unwrap();
|
||||
let [min, max] = metadata.bounding_box_document_with_stroke_and_effects(layer).unwrap();
|
||||
assert_eq!((min.x, max.x), (0., 110.));
|
||||
}
|
||||
|
||||
|
||||
+13
-13
@@ -1216,9 +1216,9 @@ async fn the_empty_import_connectors_add_the_next_import_or_fill_the_empty_prima
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let merge = editor.create_node_by_name_at(merge_definition(), 0, 0).await;
|
||||
let path = vec![merge];
|
||||
editor.enter_editable_network(merge).await;
|
||||
let subgraph = editor.create_node_by_name_at(DefinitionIdentifier::Network("Origins to Polyline".into()), 0, 0).await;
|
||||
let path = vec![subgraph];
|
||||
editor.enter_editable_network(subgraph).await;
|
||||
let import_count = editor.active_document().network_interface.number_of_imports(&path);
|
||||
|
||||
// With a primary, the only one is past the last import
|
||||
@@ -1226,20 +1226,20 @@ async fn the_empty_import_connectors_add_the_next_import_or_fill_the_empty_prima
|
||||
let empty_connectors = network_interface.empty_import_export_connectors(true, &path);
|
||||
assert_eq!(empty_connectors.iter().map(|(index, _)| *index).collect::<Vec<_>>(), vec![import_count]);
|
||||
|
||||
// The attribute name given to Merge's interior Write Attribute node
|
||||
let write_attribute = network_interface
|
||||
// The closed setting given to the subgraph's interior Points to Polyline node
|
||||
let points_to_polyline = network_interface
|
||||
.nested_network(&path)
|
||||
.and_then(|network| {
|
||||
network
|
||||
.nodes
|
||||
.iter()
|
||||
.find(|(_, node)| node.implementation == DocumentNodeImplementation::ProtoNode(graphene_std::graphic::write_attribute::IDENTIFIER))
|
||||
.find(|(_, node)| node.implementation == DocumentNodeImplementation::ProtoNode(graphene_std::vector::points_to_polyline::IDENTIFIER))
|
||||
})
|
||||
.map(|(node_id, _)| *node_id)
|
||||
.expect("Merge should contain a Write Attribute node");
|
||||
let value_input = InputConnector::node_at_index(write_attribute, 1);
|
||||
.expect("Origins to Polyline should contain a Points to Polyline node");
|
||||
let value_input = InputConnector::node_at_index(points_to_polyline, 1);
|
||||
let Some(NodeInput::Value { tagged_value, .. }) = network_interface.input_from_connector(&value_input, &path) else {
|
||||
panic!("Merge's Write Attribute node should be given its attribute name as a value");
|
||||
panic!("The Points to Polyline node should be given its closed setting as a value");
|
||||
};
|
||||
let displaced_value = (**tagged_value).clone();
|
||||
|
||||
@@ -1257,7 +1257,7 @@ async fn the_empty_import_connectors_add_the_next_import_or_fill_the_empty_prima
|
||||
"the new import should be wired to the input"
|
||||
);
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
let new_input = network_interface.input_from_connector(&InputConnector::node_at_index(merge, import_count), &[]);
|
||||
let new_input = network_interface.input_from_connector(&InputConnector::node_at_index(subgraph, import_count), &[]);
|
||||
assert!(
|
||||
matches!(new_input, Some(NodeInput::Value { tagged_value, exposed: true }) if **tagged_value == displaced_value),
|
||||
"the new import should take over the value its wire displaced, found {new_input:?}"
|
||||
@@ -1273,11 +1273,11 @@ async fn the_empty_import_connectors_add_the_next_import_or_fill_the_empty_prima
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
assert!(network_interface.empty_import_export_connectors(true, &path).iter().any(|(index, _)| *index == 0));
|
||||
|
||||
// The content given to Merge's interior Write Attribute node by its Into Group node
|
||||
let wired_input = InputConnector::node_at_index(write_attribute, 0);
|
||||
// The points given to the subgraph's interior Points to Polyline node by its Combine Paths node
|
||||
let wired_input = InputConnector::node_at_index(points_to_polyline, 0);
|
||||
assert!(
|
||||
matches!(network_interface.input_from_connector(&wired_input, &path), Some(NodeInput::Node { .. })),
|
||||
"Merge's Write Attribute node should be wired its content from another node"
|
||||
"The Points to Polyline node should have its points wired from another node"
|
||||
);
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::AddImportAndConnect {
|
||||
|
||||
+14
-16
@@ -864,14 +864,15 @@ async fn reconciling_an_input_value_edit_reproduces_the_interface() {
|
||||
let group = only_group(editor);
|
||||
editor.active_document_mut().network_interface.make_editable(&[group]);
|
||||
let interface = &mut editor.active_document_mut().network_interface;
|
||||
let (inner, index) = interface
|
||||
let extend = graph_craft::document::DocumentNodeImplementation::ProtoNode(graphene_std::graphic::extend::IDENTIFIER);
|
||||
let inner = interface
|
||||
.nested_network(&[group])
|
||||
.expect("the group's network")
|
||||
.nodes
|
||||
.iter()
|
||||
.find_map(|(id, node)| Some((*id, node.inputs.iter().position(|input| input.as_value().is_some())?)))
|
||||
.expect("a node with a value input inside the group");
|
||||
interface.set_input(&InputConnector::node_at_index(inner, index), NodeInput::value(TaggedValue::Number(42.), false), &[group]);
|
||||
.find_map(|(id, node)| (node.implementation == extend).then_some(*id))
|
||||
.expect("an Extend node inside the group");
|
||||
interface.set_input(&InputConnector::node_at_index(inner, 0), NodeInput::value(TaggedValue::None, false), &[group]);
|
||||
})
|
||||
.await;
|
||||
}
|
||||
@@ -1064,13 +1065,14 @@ fn table_layer(editor: &EditorTestUtils) -> (NodeId, graph_craft::document::Netw
|
||||
.expect("a committed layer should name a table entry")
|
||||
}
|
||||
|
||||
/// A node inside the table entry `definition`, and the index of one of its value inputs.
|
||||
fn value_input_inside(editor: &EditorTestUtils, definition: graph_craft::document::NetworkId) -> (NodeId, usize) {
|
||||
/// The Extend node inside the layer's table entry `definition`, and the index of its base input.
|
||||
fn input_inside(editor: &EditorTestUtils, definition: graph_craft::document::NetworkId) -> (NodeId, usize) {
|
||||
let extend = graph_craft::document::DocumentNodeImplementation::ProtoNode(graphene_std::graphic::extend::IDENTIFIER);
|
||||
editor.active_document().network_interface.document_network().definitions[&definition]
|
||||
.nodes
|
||||
.iter()
|
||||
.find_map(|(id, node)| node.inputs.iter().position(|input| matches!(input, NodeInput::Value { .. })).map(|index| (*id, index)))
|
||||
.expect("the layer's network should have a node with a value input")
|
||||
.find_map(|(id, node)| (node.implementation == extend).then_some((*id, 0)))
|
||||
.expect("the layer's network should have an Extend node")
|
||||
}
|
||||
|
||||
/// The network location `deltas` recorded for a write to an input of `node_id`.
|
||||
@@ -1119,7 +1121,7 @@ async fn an_edit_inside_a_table_entry_constructs_the_diff() {
|
||||
let (layer, _) = table_layer(&editor);
|
||||
editor.active_document_mut().network_interface.make_editable(&[layer]);
|
||||
let (layer, definition) = table_layer(&editor);
|
||||
let (inner, input_index) = value_input_inside(&editor, definition);
|
||||
let (inner, input_index) = input_inside(&editor, definition);
|
||||
|
||||
let working = convert(&editor);
|
||||
editor.active_document_mut().network_interface.discard_deltas();
|
||||
@@ -1174,7 +1176,7 @@ async fn a_write_keeps_its_network_when_the_instance_changes_implementation() {
|
||||
let (layer, _) = table_layer(&editor);
|
||||
editor.active_document_mut().network_interface.make_editable(&[layer]);
|
||||
let (layer, definition) = table_layer(&editor);
|
||||
let (inner, input_index) = value_input_inside(&editor, definition);
|
||||
let (inner, input_index) = input_inside(&editor, definition);
|
||||
let interface = &mut editor.active_document_mut().network_interface;
|
||||
interface.discard_deltas();
|
||||
|
||||
@@ -1387,14 +1389,10 @@ async fn making_an_instance_unique_forks_its_network() {
|
||||
assert_ne!(forked, definition);
|
||||
assert!(!interface.is_shared(©, &[]) && !interface.is_shared(&layer, &[]));
|
||||
|
||||
let (inner, input_index) = value_input_inside(&editor, forked);
|
||||
let (inner, input_index) = input_inside(&editor, forked);
|
||||
let original = editor.active_document().network_interface.document_network().definitions[&definition].clone();
|
||||
let interface = &mut editor.active_document_mut().network_interface;
|
||||
let NodeInput::Value { tagged_value, exposed } = &interface.document_network().definitions[&forked].nodes[&inner].inputs[input_index] else {
|
||||
unreachable!("the input was found as a value")
|
||||
};
|
||||
let flipped = NodeInput::value((**tagged_value).clone(), !exposed);
|
||||
interface.set_input(&InputConnector::node_at_index(inner, input_index), flipped, &[copy]);
|
||||
interface.set_input(&InputConnector::node_at_index(inner, input_index), NodeInput::value(TaggedValue::None, false), &[copy]);
|
||||
|
||||
assert_ne!(interface.document_network().definitions[&forked], original, "the edit should change the copy's network");
|
||||
assert_eq!(interface.document_network().definitions[&definition], original, "the original's network should be untouched");
|
||||
|
||||
@@ -1063,11 +1063,11 @@ impl NodeNetworkInterface {
|
||||
Some(transformed.bounding_box())
|
||||
}
|
||||
|
||||
/// Calculates the document bounds in document space, expanding vector layer bounds to include the rendered
|
||||
/// stroke width. Used for export so the output canvas captures strokes that overflow the path geometry.
|
||||
pub fn document_bounds_document_space_with_stroke(&self, include_artboards: bool) -> Option<[DVec2; 2]> {
|
||||
/// Calculates the document bounds in document space, expanding layer bounds to include the rendered stroke width and
|
||||
/// effects. Used for export so the output canvas captures strokes and shadows that overflow the path geometry.
|
||||
pub fn document_bounds_document_space_with_stroke_and_effects(&self, include_artboards: bool) -> Option<[DVec2; 2]> {
|
||||
self.document_metadata.document_bounds(include_artboards, true, || {
|
||||
self.combined_document_bounds(include_artboards, |metadata, layer| metadata.bounding_box_document_with_stroke(layer))
|
||||
self.combined_document_bounds(include_artboards, |metadata, layer| metadata.bounding_box_document_with_stroke_and_effects(layer))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1084,17 +1084,17 @@ impl NodeNetworkInterface {
|
||||
.reduce(Quad::combine_bounds)
|
||||
}
|
||||
|
||||
/// Calculates the selected layer bounds in document space, expanding vector layer bounds to include the
|
||||
/// rendered stroke width. Used for export so the output canvas captures strokes that overflow the path geometry.
|
||||
pub fn selected_bounds_document_space_with_stroke(&self, include_artboards: bool, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
|
||||
/// Calculates the selected layer bounds in document space, expanding layer bounds to include the rendered stroke width
|
||||
/// and effects. Used for export so the output canvas captures strokes and shadows that overflow the path geometry.
|
||||
pub fn selected_bounds_document_space_with_stroke_and_effects(&self, include_artboards: bool, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
|
||||
let Some(selected_nodes) = self.selected_nodes_in_nested_network(network_path) else {
|
||||
log::error!("Could not get selected nodes in selected_bounds_document_space_with_stroke");
|
||||
log::error!("Could not get selected nodes in selected_bounds_document_space_with_stroke_and_effects");
|
||||
return None;
|
||||
};
|
||||
selected_nodes
|
||||
.selected_layers(&self.document_metadata)
|
||||
.filter(|&layer| include_artboards || !self.is_artboard(&layer.to_node(), &[]))
|
||||
.filter_map(|layer| self.document_metadata.bounding_box_document_with_stroke(layer))
|
||||
.filter_map(|layer| self.document_metadata.bounding_box_document_with_stroke_and_effects(layer))
|
||||
.reduce(Quad::combine_bounds)
|
||||
}
|
||||
|
||||
|
||||
@@ -200,4 +200,9 @@ impl NodeNetworkInterface {
|
||||
pub fn update_appearance_attributes(&mut self, new_layer_appearance_attributes: HashMap<LayerNodeIdentifier, Arc<Appearance>>) {
|
||||
self.document_metadata.layer_appearance_attributes = new_layer_appearance_attributes;
|
||||
}
|
||||
|
||||
/// Update how far each layer's effects paint past its content.
|
||||
pub fn update_effects_reach(&mut self, new_layer_effects_reach: HashMap<LayerNodeIdentifier, f64>) {
|
||||
self.document_metadata.layer_effects_reach = new_layer_effects_reach;
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,7 @@ use graphene_std::text::{TextAlign, TypesettingConfig};
|
||||
use graphene_std::transform::ScaleType;
|
||||
use graphene_std::uuid::NodeId;
|
||||
use graphene_std::vector::graphic_types;
|
||||
use graphene_std::vector::style::{GradientRamp, GradientSpread, PaintOrder, StrokeAlign};
|
||||
use graphene_std::vector::style::{GradientForm, GradientRamp, GradientSpread, PaintOrder, StrokeAlign};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::f64::consts::PI;
|
||||
use std::ops::Range;
|
||||
@@ -295,10 +295,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
node: graphene_std::math_nodes::footprint_value::IDENTIFIER,
|
||||
aliases: &["graphene_math_nodes::FootprintValueNode", "graphene_core::ops::FootprintValueNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::gradient_form::IDENTIFIER,
|
||||
aliases: &["math_nodes::GradientTypeNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::gradient_spread::IDENTIFIER,
|
||||
aliases: &["math_nodes::SpreadMethodNode"],
|
||||
@@ -512,8 +508,8 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::filter::blur::IDENTIFIER,
|
||||
aliases: &["graphene_raster_nodes::filter::BlurNode", "graphene_std::filter::BlurNode"],
|
||||
node: graphene_std::blending_nodes::effects::blur::IDENTIFIER,
|
||||
aliases: &["raster_nodes::filter::BlurNode", "graphene_raster_nodes::filter::BlurNode", "graphene_std::filter::BlurNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::adjustments::brightness_contrast::IDENTIFIER,
|
||||
@@ -533,8 +529,9 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_core::raster::ChannelMixerNode",
|
||||
],
|
||||
},
|
||||
// Color Overlay became Paint Overlay, whose paint input takes the old color input's value as a solid paint
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::blending_nodes::color_overlay::IDENTIFIER,
|
||||
node: graphene_std::blending_nodes::effects::paint_overlay::IDENTIFIER,
|
||||
aliases: &[
|
||||
"graphene_raster_nodes::adjustments::ColorOverlayNode",
|
||||
"graphene_raster_nodes::generate_curves::ColorOverlayNode",
|
||||
@@ -542,6 +539,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_core::raster::adjustments::ColorOverlayNode",
|
||||
"raster_nodes::generate_curves::ColorOverlayNode",
|
||||
"graphene_raster_nodes::blending_nodes::ColorOverlayNode",
|
||||
"raster_nodes::blending_nodes::ColorOverlayNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
@@ -1279,6 +1277,10 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
if *new == graphene_std::math_nodes::math_function::IDENTIFIER {
|
||||
reset_default_display_name(document, node_id, &network_path, "Math f(x)");
|
||||
}
|
||||
|
||||
if *new == graphene_std::blending_nodes::effects::paint_overlay::IDENTIFIER {
|
||||
reset_default_display_name(document, node_id, &network_path, "Color Overlay");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1397,9 +1399,9 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
}
|
||||
}
|
||||
|
||||
// The Merge and Artboard networks no longer pass their content through a Monitor node, since thumbnails are found from the layers themselves.
|
||||
// The Merge and Artboard networks no longer hold a Monitor node or write the layer's path onto their content, since the editor finds thumbnails and writes the paths itself.
|
||||
// Pre-pass for the same reason as the Brush, Transform, and Image migrations above: rebuilding the network orphans its child paths.
|
||||
let monitored_layers: Vec<(NodeId, Vec<NodeId>, DefinitionIdentifier)> = document
|
||||
let outdated_layers: Vec<(NodeId, Vec<NodeId>, DefinitionIdentifier)> = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
.recursive_nodes()
|
||||
@@ -1408,12 +1410,16 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
let reference = document.network_interface.reference(node_id, &path)?;
|
||||
let is_merge_or_artboard = [DefinitionIdentifier::Network("Merge".into()), DefinitionIdentifier::Network("Artboard".into())].contains(&reference);
|
||||
|
||||
let has_monitor = network.nodes.values().any(|inner_node| is_monitor(&inner_node.implementation));
|
||||
let path_of_subgraph = DocumentNodeImplementation::ProtoNode(graphene_std::graphic::path_of_subgraph::IDENTIFIER);
|
||||
let has_removed_node = network
|
||||
.nodes
|
||||
.values()
|
||||
.any(|inner_node| is_monitor(&inner_node.implementation) || inner_node.implementation == path_of_subgraph);
|
||||
|
||||
(is_merge_or_artboard && has_monitor).then_some((*node_id, path, reference))
|
||||
(is_merge_or_artboard && has_removed_node).then_some((*node_id, path, reference))
|
||||
})
|
||||
.collect();
|
||||
for (node_id, network_path, reference) in &monitored_layers {
|
||||
for (node_id, network_path, reference) in &outdated_layers {
|
||||
let Some(definition) = resolve_document_node_type(reference) else { continue };
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut definition.default_node_template());
|
||||
}
|
||||
@@ -1680,6 +1686,49 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
}
|
||||
}
|
||||
|
||||
// The "Gradient Form" node was replaced by "Gradient Curvature", whose two curvatures take the presets of the form it set
|
||||
const GRADIENT_FORM: [&str; 2] = ["math_nodes::GradientFormNode", "math_nodes::GradientTypeNode"];
|
||||
let gradient_form_nodes: Vec<(NodeId, Vec<NodeId>)> = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
.recursive_nodes()
|
||||
.filter_map(|(node_id, node, path)| {
|
||||
let DocumentNodeImplementation::ProtoNode(identifier) = &node.implementation else { return None };
|
||||
GRADIENT_FORM.contains(&identifier.as_str().split('<').next().unwrap_or_default()).then_some((*node_id, path))
|
||||
})
|
||||
.collect();
|
||||
for (node_id, network_path) in &gradient_form_nodes {
|
||||
let Some(definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER)) else {
|
||||
continue;
|
||||
};
|
||||
let mut node_template = definition.default_node_template();
|
||||
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
let Some(old_inputs) = document.network_interface.replace_inputs(node_id, network_path, &mut node_template) else {
|
||||
continue;
|
||||
};
|
||||
reset_default_display_name(document, node_id, network_path, "Gradient Form");
|
||||
|
||||
if let Some(input) = old_inputs.first() {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), input.clone(), network_path);
|
||||
}
|
||||
|
||||
let [start, end] = match old_inputs.get(1).and_then(|input| input.as_value()) {
|
||||
Some(TaggedValue::GradientForm(GradientForm::Radial)) => graphene_std::renderer::dial_gradient::RADIAL_DIALS,
|
||||
Some(TaggedValue::GradientForm(GradientForm::Linear)) => graphene_std::renderer::dial_gradient::LINEAR_DIALS,
|
||||
_ => {
|
||||
log::warn!("Old \"Gradient Form\" node {node_id} has no fixed form to migrate, so it becomes linear");
|
||||
graphene_std::renderer::dial_gradient::LINEAR_DIALS
|
||||
}
|
||||
};
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::Number(start), false), network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 2), NodeInput::value(TaggedValue::Number(end), false), network_path);
|
||||
}
|
||||
|
||||
// "Position on Path" and "Tangent on Path" were merged into the multi-output "Evaluate Path" node, with position at output 0 and tangent direction at output 1.
|
||||
// Tangent instances get an "Inverse Tangent" node inserted to turn that direction back into the angle their downstream wires expect.
|
||||
const POSITION_ON_PATH: &str = "graphene_core::vector::PositionOnPathNode";
|
||||
@@ -1858,6 +1907,52 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
}
|
||||
}
|
||||
|
||||
// Noise Pattern and Mandelbrot once drew images cut off at a square, 100 units for a clipped Noise Pattern and 1 for Mandelbrot, where their
|
||||
// patterns now fill the plane. An old Noise Pattern has a Clip toggle, after the primary input or first from before that input existed,
|
||||
// and an old Mandelbrot lacks the primary input. Each takes the current inputs, with a square filled by its pattern where it was cut off.
|
||||
let old_pattern_nodes = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
.recursive_nodes()
|
||||
.filter_map(|(node_id, node, path)| {
|
||||
let reference = document.network_interface.reference(node_id, &path)?;
|
||||
let clipped = |clip_index: usize| !matches!(node.inputs.get(clip_index).and_then(|input| input.as_value()), Some(TaggedValue::Bool(false)));
|
||||
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER) {
|
||||
let starts_with_clip = matches!(node.inputs.first().and_then(|input| input.as_value()), Some(TaggedValue::Bool(_)));
|
||||
let clip_index = match node.inputs.len() {
|
||||
16 => 1,
|
||||
15 if starts_with_clip => 0,
|
||||
_ => return None,
|
||||
};
|
||||
return Some((*node_id, path, reference, Some(clip_index), clipped(clip_index).then_some(100.)));
|
||||
}
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER) && node.inputs.is_empty() {
|
||||
return Some((*node_id, path, reference, None, Some(1.)));
|
||||
}
|
||||
None
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
for (node_id, network_path, reference, clip_index, clipped_size) in &old_pattern_nodes {
|
||||
let Some(definition) = resolve_document_node_type(reference) else { continue };
|
||||
let mut node_template = definition.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
let Some(old_inputs) = document.network_interface.replace_inputs(node_id, network_path, &mut node_template) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
// The noise settings follow the Clip toggle, in the same order as the current inputs after the primary one
|
||||
if let Some(clip_index) = clip_index {
|
||||
for (offset, input) in old_inputs.iter().skip(clip_index + 1).enumerate() {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1 + offset), input.clone(), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(size) = clipped_size {
|
||||
fill_square_with_pattern(document, node_id, network_path, *size);
|
||||
}
|
||||
}
|
||||
|
||||
// Parameters that historically accepted fractional numbers are now integers (the polygon and star "Sides", the index,
|
||||
// shift amount, and slice bound parameters of the list, string, and regex nodes, the "Path is Closed" index, and the
|
||||
// "Blend" count), so a stored F64 truncates as those slots' own casts and Floor node did, preserving what documents drew
|
||||
@@ -1917,6 +2012,76 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
document.require_whole_document_stage();
|
||||
}
|
||||
|
||||
/// Splices a rectangle filled with the pattern node's output onto the wires leaving it, 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.
|
||||
fn fill_square_with_pattern(document: &mut DocumentMessageHandler, pattern_node_id: &NodeId, network_path: &[NodeId], size: f64) -> Option<()> {
|
||||
let downstream_consumers: Vec<InputConnector> = document
|
||||
.network_interface
|
||||
.outward_wires(network_path)
|
||||
.and_then(|wires| wires.get(&OutputConnector::node(*pattern_node_id, 0)))
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let was_in_chain = document.network_interface.is_chain(pattern_node_id, network_path);
|
||||
|
||||
let template = |identifier| resolve_document_node_type(&DefinitionIdentifier::ProtoNode(identifier)).map(|definition| definition.default_node_template());
|
||||
let rectangle_template = template(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER)?;
|
||||
let fill_template = template(graphene_std::vector_nodes::fill::IDENTIFIER)?;
|
||||
let transform_template = template(graphene_std::transform_nodes::transform::IDENTIFIER)?;
|
||||
|
||||
let [rectangle_id, fill_id, paint_transform_id, placement_transform_id] = [(); 4].map(|_| NodeId::new());
|
||||
document.network_interface.insert_node(rectangle_id, rectangle_template, network_path);
|
||||
document.network_interface.insert_node(fill_id, fill_template, network_path);
|
||||
document.network_interface.insert_node(paint_transform_id, transform_template.clone(), network_path);
|
||||
document.network_interface.insert_node(placement_transform_id, transform_template, network_path);
|
||||
|
||||
let set_value = |document: &mut DocumentMessageHandler, node_id: NodeId, index: usize, value: TaggedValue| {
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(node_id, index), NodeInput::value(value, false), network_path);
|
||||
};
|
||||
let wire = |document: &mut DocumentMessageHandler, node_id: NodeId, index: usize, source: NodeId| {
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(node_id, index), NodeInput::node(source, 0), network_path);
|
||||
};
|
||||
|
||||
// The rectangle's width and height, and the half-square translations of the paint and the filled rectangle
|
||||
set_value(document, rectangle_id, 1, TaggedValue::Number(size));
|
||||
set_value(document, rectangle_id, 2, TaggedValue::Number(size));
|
||||
set_value(document, paint_transform_id, 1, TaggedValue::DVec2(DVec2::splat(-size / 2.)));
|
||||
set_value(document, placement_transform_id, 1, TaggedValue::DVec2(DVec2::splat(size / 2.)));
|
||||
|
||||
wire(document, paint_transform_id, 0, *pattern_node_id);
|
||||
wire(document, fill_id, 0, rectangle_id);
|
||||
wire(document, fill_id, 1, paint_transform_id);
|
||||
wire(document, placement_transform_id, 0, fill_id);
|
||||
for consumer in &downstream_consumers {
|
||||
document.network_interface.set_input(consumer, NodeInput::node(placement_transform_id, 0), network_path);
|
||||
}
|
||||
|
||||
// A pattern in a layer chain gives way to the filled rectangle there, moving below to paint it, and otherwise the new nodes sit beside it
|
||||
if was_in_chain {
|
||||
document.network_interface.force_set_upstream_to_chain(&placement_transform_id, network_path);
|
||||
|
||||
if let Some(fill_position) = document.network_interface.position(&fill_id, network_path) {
|
||||
document.network_interface.set_absolute_position(&paint_transform_id, fill_position + IVec2::new(-7, 3), network_path);
|
||||
document.network_interface.set_absolute_position(pattern_node_id, fill_position + IVec2::new(-14, 3), network_path);
|
||||
}
|
||||
} else if let Some(position) = document.network_interface.position(pattern_node_id, network_path) {
|
||||
let offsets = [
|
||||
(paint_transform_id, IVec2::new(7, 0)),
|
||||
(rectangle_id, IVec2::new(7, -3)),
|
||||
(fill_id, IVec2::new(14, 0)),
|
||||
(placement_transform_id, IVec2::new(21, 0)),
|
||||
];
|
||||
for (node_id, offset) in offsets {
|
||||
document.network_interface.shift_absolute_node_position(&node_id, position + offset, network_path);
|
||||
}
|
||||
}
|
||||
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Converts a legacy stroke dash input (a `List<f64>`, single `f64`, or comma/space separated `String`) to the `DashPattern` value type.
|
||||
fn migrate_dash_input(input: &NodeInput) -> Option<NodeInput> {
|
||||
let NodeInput::Value { tagged_value, exposed } = input else { return None };
|
||||
@@ -2448,7 +2613,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
(graphene_std::artboard::create_artboard::BackgroundInput.into(), Color::WHITE),
|
||||
(graphene_std::math_nodes::color_value::ColorInput.into(), Color::TRANSPARENT),
|
||||
(graphene_std::raster_nodes::adjustments::black_and_white::TintInput.into(), Color::BLACK),
|
||||
(graphene_std::raster_nodes::blending_nodes::color_overlay::ColorInput.into(), Color::BLACK),
|
||||
];
|
||||
for (parameter, fallback) in conversions {
|
||||
if reference != DefinitionIdentifier::ProtoNode(parameter.node_identifier.clone()) {
|
||||
@@ -2769,20 +2933,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
}
|
||||
}
|
||||
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER) && inputs_count == 15 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 0), NodeInput::value(TaggedValue::None, false), network_path);
|
||||
for (i, input) in old_inputs.iter().enumerate() {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, i + 1), input.clone(), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
// The Threshold node's luminance calculation input was retired
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::adjustments::threshold::IDENTIFIER) && inputs_count == 4 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
@@ -5101,6 +5251,54 @@ mod tests {
|
||||
assert!(matches!(migrated, NodeInput::Value { exposed: true, .. }), "the exposed flag should be kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_form_nodes_become_gradient_curvature_presets() {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
|
||||
use graphene_std::renderer::dial_gradient::{LINEAR_DIALS, RADIAL_DIALS};
|
||||
|
||||
let (source_id, form_id) = (NodeId(1), NodeId(2));
|
||||
for (identifier, form, dials) in [
|
||||
("math_nodes::GradientFormNode", GradientForm::Radial, RADIAL_DIALS),
|
||||
("math_nodes::GradientTypeNode", GradientForm::Linear, LINEAR_DIALS),
|
||||
] {
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
let placeholder = || NodeInput::value(TaggedValue::None, false);
|
||||
document.network_interface.insert_node(
|
||||
source_id,
|
||||
NodeTemplate {
|
||||
inputs: vec![placeholder()],
|
||||
..Default::default()
|
||||
},
|
||||
&[],
|
||||
);
|
||||
document.network_interface.insert_node(
|
||||
form_id,
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new(identifier)),
|
||||
inputs: vec![placeholder(); 2],
|
||||
..Default::default()
|
||||
},
|
||||
&[],
|
||||
);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(form_id, 0), NodeInput::node(source_id, 0), &[]);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(form_id, 1), NodeInput::value(TaggedValue::GradientForm(form), false), &[]);
|
||||
migrate(&mut document);
|
||||
|
||||
let node = &document.network_interface.document_network().nodes[&form_id];
|
||||
assert!(matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::math_nodes::gradient_curvature::IDENTIFIER));
|
||||
assert_eq!(node.inputs.first(), Some(&NodeInput::node(source_id, 0)), "the gradient feeding {identifier} should stay wired");
|
||||
|
||||
let curvature = |index: usize| node.inputs.get(index).and_then(|input| input.as_value()).cloned();
|
||||
assert_eq!(
|
||||
[curvature(1), curvature(2)],
|
||||
dials.map(|dial| Some(TaggedValue::Number(dial))),
|
||||
"{form:?} should become its curvature presets"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_no_duplicate_node_replacements() {
|
||||
let mut hashmap = HashMap::<ProtoNodeIdentifier, u32>::new();
|
||||
@@ -6050,4 +6248,79 @@ mod tests {
|
||||
assert!(converted > 0. && converted < 1., "bias {bias} became {converted}");
|
||||
}
|
||||
}
|
||||
|
||||
// Noise Pattern and Mandelbrot once drew a square of their patterns, which now fill the plane, so the square becomes a rectangle filled with the pattern
|
||||
#[tokio::test]
|
||||
async fn clipped_patterns_become_rectangles_filled_with_them() {
|
||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
|
||||
let proto = |identifier| DefinitionIdentifier::ProtoNode(identifier);
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let noise = editor.create_node_by_name(proto(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER)).await;
|
||||
let mandelbrot = editor.create_node_by_name(proto(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER)).await;
|
||||
let noise_reader = editor.create_node_by_name(proto(graphene_std::transform_nodes::transform::IDENTIFIER)).await;
|
||||
let mandelbrot_reader = editor.create_node_by_name(proto(graphene_std::transform_nodes::transform::IDENTIFIER)).await;
|
||||
|
||||
let document = editor.active_document_mut();
|
||||
for (reader, pattern) in [(noise_reader, noise), (mandelbrot_reader, mandelbrot)] {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(reader, 0), NodeInput::node(pattern, 0), &[]);
|
||||
}
|
||||
|
||||
// Save them as an older editor did, the Noise Pattern with its Clip toggle on and the Mandelbrot without a primary input
|
||||
let mut noise_inputs = document.network_interface.document_node(&noise, &[]).unwrap().inputs.clone();
|
||||
noise_inputs.insert(1, NodeInput::value(TaggedValue::Bool(true), false));
|
||||
noise_inputs[2] = NodeInput::value(TaggedValue::Integer(7), false);
|
||||
for (node_id, inputs) in [(noise, noise_inputs), (mandelbrot, Vec::new())] {
|
||||
let mut legacy = NodeTemplate { inputs, ..Default::default() };
|
||||
legacy.normalize_input_metadata();
|
||||
document.network_interface.replace_inputs(&node_id, &[], &mut legacy);
|
||||
}
|
||||
let serialized = document.serialize_document();
|
||||
|
||||
let opened = load_legacy_document(serialized, &HashMapResourceStorage::new(), false).expect("the document should open");
|
||||
let interface = &opened.network_interface;
|
||||
let input = |node_id: NodeId, index: usize| interface.document_node(&node_id, &[]).and_then(|node| node.inputs.get(index)).cloned();
|
||||
let upstream = |node_id: NodeId, index: usize| input(node_id, index).and_then(|input| input.as_node());
|
||||
let value = |node_id: NodeId, index: usize| input(node_id, index).and_then(|input| input.as_value().cloned());
|
||||
|
||||
// Each reader now reads a rectangle of the square's size, moved onto the square, filled with the pattern moved back by the same amount
|
||||
for (reader, pattern, size) in [(noise_reader, noise, 100.), (mandelbrot_reader, mandelbrot, 1.)] {
|
||||
let placement = upstream(reader, 0).expect("the reader should read the placement transform");
|
||||
assert_eq!(value(placement, 1), Some(TaggedValue::DVec2(DVec2::splat(size / 2.))));
|
||||
|
||||
let fill = upstream(placement, 0).expect("the placement should move the filled rectangle");
|
||||
let rectangle = upstream(fill, 0).expect("the fill should paint a rectangle");
|
||||
assert_eq!((value(rectangle, 1), value(rectangle, 2)), (Some(TaggedValue::Number(size)), Some(TaggedValue::Number(size))));
|
||||
|
||||
let paint = upstream(fill, 1).expect("the fill should paint with the moved pattern");
|
||||
assert_eq!(value(paint, 1), Some(TaggedValue::DVec2(DVec2::splat(-size / 2.))));
|
||||
assert_eq!(upstream(paint, 0), Some(pattern));
|
||||
}
|
||||
|
||||
// The noise settings shift down past the removed Clip toggle, and the Mandelbrot gains its primary input
|
||||
assert_eq!(interface.document_node(&noise, &[]).unwrap().inputs.len(), 15);
|
||||
assert_eq!(value(noise, 1), Some(TaggedValue::Integer(7)));
|
||||
assert_eq!(interface.document_node(&mandelbrot, &[]).unwrap().inputs.len(), 1);
|
||||
}
|
||||
|
||||
// The demo draws its patterns through layers and adjustments, which must all take the generators the patterns now are
|
||||
#[tokio::test]
|
||||
async fn marbled_mandelbrot_renders_after_migration() {
|
||||
use crate::messages::portfolio::ingest::utility_types::{DataTransferItem, IngestAction};
|
||||
use crate::messages::prelude::IngestMessage;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
let data = std::fs::read("../demo-artwork/marbled-mandelbrot.graphite").unwrap();
|
||||
editor.dispatch(IngestMessage::Ingest {
|
||||
content: DataTransferItem::from_file("marbled-mandelbrot.graphite".into(), None, data).into(),
|
||||
action: IngestAction::Open,
|
||||
});
|
||||
if let Err(error) = editor.eval_graph_until_finished().await {
|
||||
panic!("The migrated demo failed to render: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ use graph_craft::application_io::resource::ResourceId;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::raster::Image;
|
||||
use graphene_std::raster_nodes::color_lookup_table::{Lut, LutParseError};
|
||||
use graphene_std::text::Font;
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct IngestMessageContext {
|
||||
@@ -66,7 +67,7 @@ impl MessageHandler<IngestMessage, IngestMessageContext> for IngestMessageHandle
|
||||
let preferred = items.into_iter().min_by_key(|item| match item.data {
|
||||
TransferData::Svg(_) => 0,
|
||||
TransferData::Raster { .. } => 1,
|
||||
TransferData::Document(_) | TransferData::LegacyDocument(_) | TransferData::Lut(_) | TransferData::Other(_) => 2,
|
||||
TransferData::Document(_) | TransferData::LegacyDocument(_) | TransferData::Lut(_) | TransferData::Font(_) | TransferData::Other(_) => 2,
|
||||
TransferData::Text(_) => 3,
|
||||
TransferData::ApplicationData(_) => 4,
|
||||
});
|
||||
@@ -103,11 +104,17 @@ impl MessageHandler<IngestMessage, IngestMessageContext> for IngestMessageHandle
|
||||
return;
|
||||
}
|
||||
|
||||
// The file goes to the document that asked for it, which may no longer be active or open once the dialog closes
|
||||
let resource_id = ResourceId::new();
|
||||
|
||||
let font = if data_type == DataType::Font { Font::from_data(&data) } else { None };
|
||||
let resource_store_message = match font {
|
||||
Some(font) => ResourceMessage::StoreFont { resource_id, font, data: data.into() },
|
||||
None => ResourceMessage::StoreEmbedded { resource_id, data: data.into() },
|
||||
};
|
||||
|
||||
let messages = [
|
||||
DocumentMessage::AddTransaction,
|
||||
DocumentMessage::Resource(ResourceMessage::StoreEmbedded { resource_id, data: data.into() }),
|
||||
resource_store_message.into(),
|
||||
DocumentMessage::NodeGraph(NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: input_index as usize,
|
||||
@@ -172,7 +179,7 @@ impl MessageHandler<IngestMessage, IngestMessageContext> for IngestMessageHandle
|
||||
};
|
||||
(insert, None)
|
||||
}
|
||||
TransferData::Lut(_) | TransferData::Other(_) | TransferData::Text(_) | TransferData::ApplicationData(_) => return unsupported(responses),
|
||||
TransferData::Lut(_) | TransferData::Font(_) | TransferData::Other(_) | TransferData::Text(_) | TransferData::ApplicationData(_) => return unsupported(responses),
|
||||
};
|
||||
|
||||
if !place_at_origin {
|
||||
@@ -209,7 +216,7 @@ fn unsupported(responses: &mut VecDeque<Message>) {
|
||||
});
|
||||
}
|
||||
|
||||
/// The reason a node input refuses the file, or `None` if it accepts it. An input that lists its accepted types takes an image or LUT only if it fully parses.
|
||||
/// The reason a node input refuses the file, or `None` if it accepts it. An input that lists its accepted types takes an image, LUT, or font only if it parses.
|
||||
fn rejection(data: &[u8], data_type: DataType, accepted_types: &[DataType]) -> Option<&'static str> {
|
||||
const WRONG_TYPE: &str = "This input does not accept the format of the chosen file.";
|
||||
|
||||
@@ -233,6 +240,7 @@ fn rejection(data: &[u8], data_type: DataType, accepted_types: &[DataType]) -> O
|
||||
}
|
||||
LutParseError::Unreadable => "This file could not be read as a LUT. It may be corrupted or an unsupported format variant.",
|
||||
}),
|
||||
DataType::Font => Font::from_data(data).is_none().then_some("This file could not be read as a font."),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -442,6 +450,27 @@ mod tests {
|
||||
assert!(!stores(IDENTITY_CUBE, TypeFilter::raster()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_input_stores_a_font_file_under_the_name_it_carries() {
|
||||
let font_file: &[u8] = crate::messages::portfolio::fonts::FALLBACK_FONT_RESOURCE.as_ref();
|
||||
let stored_font = |data: &[u8]| {
|
||||
let responses = ingest_named(data, Some("custom.ttf"), resource_input(TypeFilter::font().types), true);
|
||||
responses.into_iter().find_map(|message| match message {
|
||||
Message::Portfolio(PortfolioMessage::DocumentPassMessage {
|
||||
document_id: REQUESTING_DOCUMENT,
|
||||
message: DocumentMessage::Resource(ResourceMessage::StoreFont { font, .. }),
|
||||
}) => Some(font),
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
|
||||
assert_eq!(stored_font(font_file), Some(Font::new("Source Sans Pro".to_string(), "Regular (400)".to_string())));
|
||||
|
||||
// A file cut off after its intact signature, and an image named as a font
|
||||
assert_eq!(stored_font(&font_file[..40]), None);
|
||||
assert_eq!(stored_font(&Image::new(8, 8, Color::WHITE).to_png()), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lookup_table_outside_a_node_input_only_shows_a_dialog() {
|
||||
let responses = ingest_named(IDENTITY_CUBE, Some("grade.cube"), IngestAction::Import, true);
|
||||
|
||||
@@ -23,6 +23,9 @@ const TEXT_MIME: &str = "text/plain";
|
||||
const GRAPHITE_PREFIX: &str = "graphite: ";
|
||||
const SNIFFED_TEXT_LENGTH: usize = 4096;
|
||||
|
||||
const FONT_FILE_EXTENSIONS: &[&str] = &["ttf", "otf"];
|
||||
const FONT_FILE_SIGNATURES: [&[u8]; 3] = [&[0, 1, 0, 0], b"OTTO", b"true"];
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
pub enum IngestAction {
|
||||
@@ -65,6 +68,7 @@ pub enum DataType {
|
||||
Gdd,
|
||||
Svg,
|
||||
Raster(ImageFormat),
|
||||
Font,
|
||||
Lut,
|
||||
Text,
|
||||
#[default]
|
||||
@@ -98,6 +102,7 @@ impl DataType {
|
||||
GDD_FILE_EXTENSION => Self::Gdd,
|
||||
"svg" => Self::Svg,
|
||||
extension if LUT_FILE_EXTENSIONS.contains(&extension) => Self::Lut,
|
||||
extension if FONT_FILE_EXTENSIONS.contains(&extension) => Self::Font,
|
||||
extension => ImageFormat::from_extension(extension).map_or(Self::Unknown, Self::Raster),
|
||||
}
|
||||
}
|
||||
@@ -113,6 +118,9 @@ impl DataType {
|
||||
if let Ok(format) = image::guess_format(data) {
|
||||
return Self::Raster(format);
|
||||
}
|
||||
if FONT_FILE_SIGNATURES.iter().any(|signature| data.starts_with(signature)) {
|
||||
return Self::Font;
|
||||
}
|
||||
|
||||
// Only the head is read as text, where a character split by the cut is the one invalid sequence tolerated
|
||||
let head = &data[..data.len().min(SNIFFED_TEXT_LENGTH)];
|
||||
@@ -139,8 +147,7 @@ impl DataType {
|
||||
Self::Svg => SVG_MIME,
|
||||
Self::Raster(format) => format.to_mime_type(),
|
||||
Self::Text => TEXT_MIME,
|
||||
// The LUT formats share no MIME type
|
||||
Self::Lut | Self::Unknown => return None,
|
||||
Self::Lut | Self::Font | Self::Unknown => return None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -151,6 +158,7 @@ impl DataType {
|
||||
Self::Svg => &["svg"],
|
||||
Self::Raster(format) => format.extensions_str(),
|
||||
Self::Lut => LUT_FILE_EXTENSIONS,
|
||||
Self::Font => FONT_FILE_EXTENSIONS,
|
||||
Self::Text | Self::Unknown => &[],
|
||||
}
|
||||
}
|
||||
@@ -189,6 +197,13 @@ impl TypeFilter {
|
||||
types: vec![DataType::Lut],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn font() -> Self {
|
||||
Self {
|
||||
name: "Font".into(),
|
||||
types: vec![DataType::Font],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<TypeFilter> for FileFilter {
|
||||
@@ -221,6 +236,7 @@ pub enum TransferData {
|
||||
Document(Vec<u8>),
|
||||
LegacyDocument(String),
|
||||
Lut(Vec<u8>),
|
||||
Font(Vec<u8>),
|
||||
Other(Vec<u8>),
|
||||
}
|
||||
|
||||
@@ -232,6 +248,7 @@ impl TransferData {
|
||||
Self::Document(_) => DataType::Gdd,
|
||||
Self::LegacyDocument(_) => DataType::GraphiteLegacy,
|
||||
Self::Lut(_) => DataType::Lut,
|
||||
Self::Font(_) => DataType::Font,
|
||||
Self::Text(_) | Self::ApplicationData(_) => DataType::Text,
|
||||
Self::Other(_) => DataType::Unknown,
|
||||
}
|
||||
@@ -240,7 +257,7 @@ impl TransferData {
|
||||
pub fn into_bytes(self) -> Vec<u8> {
|
||||
match self {
|
||||
Self::Text(text) | Self::Svg(text) | Self::LegacyDocument(text) => text.into_bytes(),
|
||||
Self::Raster { data, .. } | Self::Document(data) | Self::Lut(data) | Self::Other(data) => data,
|
||||
Self::Raster { data, .. } | Self::Document(data) | Self::Lut(data) | Self::Font(data) | Self::Other(data) => data,
|
||||
Self::ApplicationData(_) => DataTransferItem::from(self).into_raw().map(|(_, data)| data.into_bytes()).unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
@@ -295,6 +312,7 @@ impl DataTransferItem {
|
||||
DataType::Svg => text(data, TransferData::Svg),
|
||||
DataType::Raster(format) => TransferData::Raster { format, data },
|
||||
DataType::Lut => TransferData::Lut(data),
|
||||
DataType::Font => TransferData::Font(data),
|
||||
DataType::Text | DataType::Unknown => TransferData::Other(data),
|
||||
};
|
||||
Self { data, path: Some(path) }
|
||||
@@ -312,7 +330,7 @@ impl DataTransferItem {
|
||||
},
|
||||
TransferData::Svg(svg) => Some((DataType::Svg, RawData::Text(svg))),
|
||||
TransferData::Raster { format, data } => Some((DataType::Raster(format), RawData::Bytes(data))),
|
||||
TransferData::Document(_) | TransferData::LegacyDocument(_) | TransferData::Lut(_) | TransferData::Other(_) => None,
|
||||
TransferData::Document(_) | TransferData::LegacyDocument(_) | TransferData::Lut(_) | TransferData::Font(_) | TransferData::Other(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -404,6 +422,7 @@ mod tests {
|
||||
DataType::from_content("\u{feff}<?xml version=\"1.0\"?>\n<svg xmlns=\"http://www.w3.org/2000/svg\"/>".as_bytes()),
|
||||
DataType::Svg
|
||||
);
|
||||
assert_eq!(DataType::from_content(b"OTTO\0\x0c"), DataType::Font);
|
||||
assert_eq!(DataType::from_content(b"just text"), DataType::Unknown);
|
||||
assert_eq!(DataType::from_content(&[0xff, 0xfe, 0x00]), DataType::Unknown);
|
||||
}
|
||||
@@ -426,6 +445,7 @@ mod tests {
|
||||
assert_eq!(detect(Some("application/graphite+json"), ""), DataType::GraphiteLegacy);
|
||||
assert_eq!(detect(Some("image/png"), "document.gdd"), DataType::Raster(ImageFormat::Png));
|
||||
assert_eq!(detect(None, "grade.CUBE"), DataType::Lut);
|
||||
assert_eq!(detect(None, "Custom.TTF"), DataType::Font);
|
||||
assert_eq!(detect(Some("application/vnd.iccprofile"), "profile.icm"), DataType::Lut);
|
||||
assert_eq!(detect(Some("text/csv"), "table.csv"), DataType::Unknown);
|
||||
assert_eq!(DataType::detect(&[], None, None), DataType::Unknown);
|
||||
|
||||
@@ -346,7 +346,7 @@ pub fn replaceable_paint_chain(layer: LayerNodeIdentifier, network_interface: &N
|
||||
// A generator discards its primary input, so the chain ends at whichever one is reached
|
||||
let generators = [graphene_std::math_nodes::color_value::IDENTIFIER, graphene_std::math_nodes::gradient_value::IDENTIFIER];
|
||||
let setters = [
|
||||
graphene_std::math_nodes::gradient_form::IDENTIFIER,
|
||||
graphene_std::math_nodes::gradient_curvature::IDENTIFIER,
|
||||
graphene_std::math_nodes::gradient_spread::IDENTIFIER,
|
||||
graphene_std::math_nodes::gradient_positions::IDENTIFIER,
|
||||
graphene_std::math_nodes::gradient_midpoints::IDENTIFIER,
|
||||
|
||||
@@ -698,8 +698,7 @@ mod test_artboard {
|
||||
Err(e) => panic!("Failed to evaluate graph: {e}"),
|
||||
};
|
||||
instrumented
|
||||
.grab_all_input::<graphene_std::graphic::extend::NewInput, List<Artboard>>(&editor.runtime)
|
||||
.flatten()
|
||||
.grab_all_input::<graphene_std::graphic::extend::NewInput, graphene_std::list::Item<Artboard>>(&editor.runtime)
|
||||
.collect()
|
||||
}
|
||||
|
||||
|
||||
@@ -413,7 +413,7 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
|
||||
let walk_from = network_interface.upstream_output_connector(&target_input, &[]).and_then(|out| out.node_id()).unwrap_or(layer.to_node());
|
||||
|
||||
let transform_reference = DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER);
|
||||
let gradient_form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_form::IDENTIFIER);
|
||||
let gradient_curvature_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER);
|
||||
|
||||
let mut transforms_downstream_to_upstream: Vec<DAffine2> = Vec::new();
|
||||
let mut gradient_form: Option<GradientForm> = None;
|
||||
@@ -430,11 +430,14 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
|
||||
|
||||
if reference == transform_reference {
|
||||
transforms_downstream_to_upstream.push(read_transform_node_value(&document_node.inputs));
|
||||
} else if reference == gradient_form_reference
|
||||
&& gradient_form.is_none()
|
||||
&& let Some(TaggedValue::GradientForm(value)) = document_node.inputs.get(1).and_then(|input| input.as_value())
|
||||
{
|
||||
gradient_form = Some(*value);
|
||||
} else if reference == gradient_curvature_reference && gradient_form.is_none() {
|
||||
// Curvatures other than the radial form's are drawn with the linear form's controls
|
||||
let curvature = |index: usize| match document_node.inputs.get(index).and_then(|input| input.as_value()) {
|
||||
Some(&TaggedValue::Number(value)) => value,
|
||||
_ => 0.,
|
||||
};
|
||||
let is_radial = [curvature(1), curvature(2)] == graphene_std::renderer::dial_gradient::RADIAL_DIALS;
|
||||
gradient_form = Some(if is_radial { GradientForm::Radial } else { GradientForm::Linear });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3366,7 +3369,7 @@ mod test_gradient {
|
||||
.await;
|
||||
let feeder_position = editor.active_document_mut().network_interface.position(&gradient_value_id, &[]).expect("Gradient Value position");
|
||||
|
||||
// Set the gradient form through the tool, which splices a 'Gradient Form' node onto the Fill's fill input wire.
|
||||
// Set the gradient form through the tool, which splices a 'Gradient Curvature' node onto the Fill's fill input wire.
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
|
||||
editor.select_tool(ToolType::Gradient).await;
|
||||
editor
|
||||
@@ -3375,7 +3378,7 @@ mod test_gradient {
|
||||
})
|
||||
.await;
|
||||
|
||||
let form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_form::IDENTIFIER);
|
||||
let form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER);
|
||||
let form_node_id = {
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
network_interface
|
||||
@@ -3384,10 +3387,10 @@ mod test_gradient {
|
||||
.keys()
|
||||
.copied()
|
||||
.find(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&form_reference))
|
||||
.expect("Gradient Form node should have been inserted")
|
||||
.expect("Gradient Curvature node should have been inserted")
|
||||
};
|
||||
|
||||
let form_position = editor.active_document_mut().network_interface.position(&form_node_id, &[]).expect("Gradient Form position");
|
||||
let form_position = editor.active_document_mut().network_interface.position(&form_node_id, &[]).expect("Gradient Curvature position");
|
||||
let feeder_position_after = editor.active_document_mut().network_interface.position(&gradient_value_id, &[]).expect("Gradient Value position after");
|
||||
|
||||
assert_eq!(form_position, feeder_position, "the inserted node should occupy the feeder's former slot, not the graph origin");
|
||||
|
||||
@@ -448,11 +448,11 @@ impl NodeGraphExecutor {
|
||||
};
|
||||
|
||||
// Calculate the bounding box of the region to be exported (artboard bounds always contribute).
|
||||
// `AllArtwork` and `Selection` expand vector layer bounds by the rendered stroke width so strokes
|
||||
// drawn at render-time (without a `Solidify Stroke`) aren't clipped at the export canvas edge.
|
||||
// `AllArtwork` and `Selection` expand layer bounds by the rendered stroke width and effects reach so strokes
|
||||
// and shadows drawn at render-time (without a `Solidify Stroke`) aren't clipped at the export canvas edge.
|
||||
let bounds = match export_config.bounds {
|
||||
ExportBounds::AllArtwork => document.network_interface.document_bounds_document_space_with_stroke(true),
|
||||
ExportBounds::Selection => document.network_interface.selected_bounds_document_space_with_stroke(true, &[]),
|
||||
ExportBounds::AllArtwork => document.network_interface.document_bounds_document_space_with_stroke_and_effects(true),
|
||||
ExportBounds::Selection => document.network_interface.selected_bounds_document_space_with_stroke_and_effects(true, &[]),
|
||||
ExportBounds::Artboard(id) => document.metadata().bounding_box_document(id),
|
||||
}
|
||||
.ok_or_else(|| "No bounding box".to_string())?;
|
||||
@@ -1034,6 +1034,7 @@ impl NodeGraphExecutor {
|
||||
clip_targets,
|
||||
vector_data,
|
||||
appearance_attributes,
|
||||
effects_reach,
|
||||
backgrounds: _,
|
||||
} = render_output.metadata;
|
||||
|
||||
@@ -1050,6 +1051,7 @@ impl NodeGraphExecutor {
|
||||
responses.add(DocumentMessage::UpdateClipTargets { clip_targets });
|
||||
responses.add(DocumentMessage::UpdateVectorData { vector_data });
|
||||
responses.add(DocumentMessage::UpdateAppearanceAttributes { appearance_attributes });
|
||||
responses.add(DocumentMessage::UpdateEffectsReach { effects_reach });
|
||||
responses.add(DocumentMessage::RenderScrollbars);
|
||||
responses.add(DocumentMessage::RenderRulers);
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
|
||||
@@ -19,6 +19,7 @@ use graphene_std::runtime::AsyncRuntime;
|
||||
use graphene_std::vector::style::RenderMode;
|
||||
use graphene_std::{Context, NodeError, Poll};
|
||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, ResolvedDocumentNodeTypesDelta};
|
||||
use interpreted_executor::layer_paths::write_layer_paths;
|
||||
use interpreted_executor::util::wrap_network_in_scope;
|
||||
use observer::Observer;
|
||||
pub use observer::{InspectResult, InspectedContext, Observation, ObservedConnector, ObservedValue};
|
||||
@@ -27,6 +28,8 @@ use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc::{Receiver, Sender};
|
||||
use thumbnails::Thumbnails;
|
||||
|
||||
#[cfg(test)]
|
||||
mod layer_path_tests;
|
||||
mod observer;
|
||||
mod thumbnails;
|
||||
|
||||
@@ -212,6 +215,7 @@ impl NodeRuntime {
|
||||
};
|
||||
|
||||
apply_previews(&mut network, &previewed);
|
||||
write_layer_paths(&mut network, &layers);
|
||||
self.observer.replace_all(observations);
|
||||
self.resources = resources;
|
||||
|
||||
@@ -584,31 +588,48 @@ mod tests {
|
||||
editor.dispatch(Message::Wake).iter().any(|message| matches!(message, FrontendMessage::TriggerSaveFile { .. }))
|
||||
}
|
||||
|
||||
/// Fills the document's layer with a trace of noise, which an export has to wait on over several evaluations.
|
||||
fn vectorize_layer(editor: &mut EditorTestUtils) {
|
||||
/// Adds a layer tracing an image of noise, which an export has to wait on over several evaluations.
|
||||
async fn add_traced_noise_layer(editor: &mut EditorTestUtils) {
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
|
||||
use graphene_std::raster::Image;
|
||||
use graphene_std::raster::color::Color;
|
||||
|
||||
// Pseudo-random grays from an xorshift sequence, so the trace finds many small regions
|
||||
let mut noise = Image::new(64, 64, Color::BLACK);
|
||||
let mut state = 0x2545_f491_u32;
|
||||
for pixel in &mut noise.data {
|
||||
state ^= state << 13;
|
||||
state ^= state >> 17;
|
||||
state ^= state << 5;
|
||||
let gray = (state % 256) as f32 / 255.;
|
||||
*pixel = Color::from_rgbaf32_unchecked(gray, gray, gray, 1.);
|
||||
}
|
||||
editor.create_raster_image(noise, None).await;
|
||||
|
||||
// Trace the image between the layer and the nodes feeding it
|
||||
let layer = editor.active_document().metadata().all_layers().next().unwrap();
|
||||
let mut create = |node_type| {
|
||||
let node_id = NodeId::new();
|
||||
editor.dispatch(NodeGraphMessage::CreateNodeFromContextMenu {
|
||||
node_id: Some(node_id),
|
||||
node_type,
|
||||
xy: None,
|
||||
add_transaction: true,
|
||||
});
|
||||
node_id
|
||||
};
|
||||
let noise = create(DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER));
|
||||
let vectorize = create(DefinitionIdentifier::ProtoNode(graphene_std::vectorize_nodes::vectorize::IDENTIFIER));
|
||||
let content = InputConnector::node_at_index(layer.to_node(), 1);
|
||||
let image = editor
|
||||
.active_document()
|
||||
.network_interface
|
||||
.upstream_output_connector(&content, &[])
|
||||
.expect("the image layer has content");
|
||||
|
||||
let vectorize = NodeId::new();
|
||||
editor.dispatch(NodeGraphMessage::CreateNodeFromContextMenu {
|
||||
node_id: Some(vectorize),
|
||||
node_type: DefinitionIdentifier::ProtoNode(graphene_std::vectorize_nodes::vectorize::IDENTIFIER),
|
||||
xy: None,
|
||||
add_transaction: true,
|
||||
});
|
||||
editor.dispatch(NodeGraphMessage::CreateWire {
|
||||
output_connector: OutputConnector::primary_output(noise),
|
||||
output_connector: image,
|
||||
input_connector: InputConnector::node_at_index(vectorize, 0),
|
||||
});
|
||||
editor.dispatch(NodeGraphMessage::CreateWire {
|
||||
output_connector: OutputConnector::primary_output(vectorize),
|
||||
input_connector: InputConnector::node_at_index(layer.to_node(), 1),
|
||||
input_connector: content,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -655,8 +676,7 @@ mod tests {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.handle_message(DocumentMessage::SetRenderMode { render_mode: RenderMode::SvgPreview }).await;
|
||||
editor.draw_rect(0., 0., 512., 512.).await;
|
||||
vectorize_layer(&mut editor);
|
||||
add_traced_noise_layer(&mut editor).await;
|
||||
|
||||
send_export(&mut editor);
|
||||
editor.runtime.update();
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graphene_std::graphic::extend;
|
||||
|
||||
fn rectangle() -> DefinitionIdentifier {
|
||||
DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER)
|
||||
}
|
||||
|
||||
// A layer without an Extend node gets its path written onto its whole output
|
||||
#[tokio::test]
|
||||
async fn a_layer_gets_click_targets() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let rectangle = editor.create_node_by_name_at(rectangle(), 0, 0).await;
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::CreateWire {
|
||||
output_connector: OutputConnector::node(rectangle, 0),
|
||||
input_connector: InputConnector::Export(0),
|
||||
})
|
||||
.await;
|
||||
assert!(editor.active_document().metadata().click_targets.is_empty(), "A node not shown as a layer should have no click targets");
|
||||
|
||||
editor.handle_message(NodeGraphMessage::SetToNodeOrLayer { node_id: rectangle, is_layer: true }).await;
|
||||
|
||||
let document = editor.active_document();
|
||||
let layer = LayerNodeIdentifier::new(rectangle, &document.network_interface);
|
||||
let click_targets = document.metadata().click_targets(layer);
|
||||
assert!(
|
||||
click_targets.is_some_and(|click_targets| !click_targets.is_empty()),
|
||||
"A node shown as a layer should have click targets"
|
||||
);
|
||||
}
|
||||
|
||||
// A layer that is an Extend node gets its path written onto what it adds
|
||||
#[tokio::test]
|
||||
async fn an_extend_node_layer_gets_click_targets() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let extend = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(extend::IDENTIFIER), 0, 0).await;
|
||||
let (below, added) = (editor.create_node_by_name_at(rectangle(), -10, 0).await, editor.create_node_by_name_at(rectangle(), -10, 4).await);
|
||||
for (rectangle, input) in [(below, InputConnector::node(extend, extend::BaseInput)), (added, InputConnector::node(extend, extend::NewInput))] {
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::CreateWire {
|
||||
output_connector: OutputConnector::node(rectangle, 0),
|
||||
input_connector: input,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::CreateWire {
|
||||
output_connector: OutputConnector::node(extend, 0),
|
||||
input_connector: InputConnector::Export(0),
|
||||
})
|
||||
.await;
|
||||
|
||||
editor.handle_message(NodeGraphMessage::SetToNodeOrLayer { node_id: extend, is_layer: true }).await;
|
||||
|
||||
let document = editor.active_document();
|
||||
let layer = LayerNodeIdentifier::new(extend, &document.network_interface);
|
||||
let click_targets = document.metadata().click_targets(layer);
|
||||
assert!(
|
||||
click_targets.is_some_and(|click_targets| !click_targets.is_empty()),
|
||||
"An Extend node shown as a layer should have click targets for what it adds"
|
||||
);
|
||||
}
|
||||
@@ -4,12 +4,11 @@ use crate::messages::frontend::FrontendMessage;
|
||||
use atlas::ThumbnailAtlasLayout;
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
use graph_craft::application_io::PlatformEditorApi;
|
||||
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeNetwork};
|
||||
use graph_craft::document::{NodeId, NodeNetwork};
|
||||
#[cfg(feature = "gpu")]
|
||||
use graphene_std::application_io::{ApplicationIo, Texture};
|
||||
use graphene_std::bounds::RenderBoundingBox;
|
||||
use graphene_std::gradient::Gradient;
|
||||
use graphene_std::graphic::extend;
|
||||
use graphene_std::list::{Item, List};
|
||||
#[cfg(feature = "gpu")]
|
||||
use graphene_std::ops::ConvertAsync;
|
||||
@@ -19,8 +18,9 @@ use graphene_std::raster_types::{CPU, GPU, Raster};
|
||||
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
|
||||
use graphene_std::transform::{Footprint, RenderQuality};
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::{Artboard, Color, Context, ContextFeatures, Graphic, NodeParameter};
|
||||
use graphene_std::{Artboard, Color, Context, ContextFeatures, Graphic};
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
use interpreted_executor::layer_paths::layer_content;
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -399,20 +399,7 @@ pub fn layers_svg(layers: &[NodeId], network: &NodeNetwork, executor: &DynamicEx
|
||||
|
||||
/// The proto node giving the content a layer's thumbnail shows, which is only what the layer adds if it extends the stack below it.
|
||||
fn thumbnail_source(layer_path: &[NodeId], network: &NodeNetwork, executor: &DynamicExecutor) -> Option<NodeId> {
|
||||
let output = network.output_source(layer_path, 0)?;
|
||||
|
||||
// A hidden layer, or one passing through what's below it, has nothing of its own to show
|
||||
if !output.starts_with(layer_path) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let (node_id, network_path) = output.split_last()?;
|
||||
let node = network.nested_network(network_path)?.nodes.get(node_id)?;
|
||||
let source = if node.implementation == DocumentNodeImplementation::ProtoNode(extend::IDENTIFIER) {
|
||||
network.input_source(network_path, node.inputs.get(extend::NewInput::INDEX)?)?
|
||||
} else {
|
||||
output
|
||||
};
|
||||
let source = layer_content(layer_path, network)?.source(network)?;
|
||||
|
||||
executor.tree().source_map().get(source.as_slice()).map(|(id, _)| *id)
|
||||
}
|
||||
@@ -484,6 +471,7 @@ mod tests {
|
||||
use glam::UVec2;
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::application_io::TimingInformation;
|
||||
use interpreted_executor::layer_paths::layer_path_writer_id;
|
||||
|
||||
async fn compile_and_run(editor: &mut EditorTestUtils) {
|
||||
let portfolio = editor.portfolio_message_handler_mut();
|
||||
@@ -510,7 +498,7 @@ mod tests {
|
||||
let layer = editor.get_selected_layer().await.expect("The drawn rectangle should be selected").to_node();
|
||||
|
||||
compile_and_run(&mut editor).await;
|
||||
let merge_content = compiled_id(&editor, &[layer, shipped_node_id("Merge", NodeId(3))]);
|
||||
let merge_content = compiled_id(&editor, &[layer, layer_path_writer_id(shipped_node_id("Merge", NodeId(2)))]);
|
||||
assert!(merge_content.is_some(), "The Merge layer's content should be compiled");
|
||||
assert_eq!(
|
||||
editor.runtime.thumbnails.sources.get(&layer).copied(),
|
||||
|
||||
@@ -540,9 +540,10 @@
|
||||
margin-left: 8px;
|
||||
}
|
||||
|
||||
// A label alone in its row lines up with the parameter names that follow their expose buttons
|
||||
> .text-label:only-child {
|
||||
// A label with no expose button before it lines up with the parameter names that follow one
|
||||
> .text-label:first-child {
|
||||
margin-left: calc(20px + 8px + 8px);
|
||||
--wire-indent: 20px;
|
||||
}
|
||||
|
||||
> .separator.horizontal.unrelated {
|
||||
|
||||
@@ -8,27 +8,13 @@
|
||||
import { widgetSizingStyles } from "/src/utility-functions/widgets";
|
||||
import type { MenuListEntry, ActionShortcut, WidgetSizing } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
const DASH_ENTRY: MenuListEntry = {
|
||||
value: "",
|
||||
label: "-",
|
||||
icon: undefined,
|
||||
annotation: "",
|
||||
disabled: false,
|
||||
children: [],
|
||||
childrenHash: 0n,
|
||||
font: undefined,
|
||||
tooltipLabel: "",
|
||||
tooltipDescription: "",
|
||||
tooltipShortcut: undefined,
|
||||
tooltipCode: "",
|
||||
};
|
||||
|
||||
const dispatch = createEventDispatcher<{ selectedIndex: number; previewIndex: number; fileDrop: File }>();
|
||||
|
||||
let self: LayoutRow | undefined;
|
||||
|
||||
// Content
|
||||
export let selectedIndex: number | undefined = undefined; // When not provided, a dash is displayed
|
||||
export let selectedIndex: number | undefined = undefined; // When not provided, the placeholder is displayed
|
||||
export let placeholder = "-";
|
||||
export let drawIcon = false;
|
||||
export let disabled = false;
|
||||
// Children
|
||||
@@ -132,13 +118,13 @@
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function makeActiveEntry(): MenuListEntry {
|
||||
function makeActiveEntry(): MenuListEntry | undefined {
|
||||
const allEntries = entries.flat();
|
||||
|
||||
if (selectedIndex !== undefined && selectedIndex >= 0 && selectedIndex < allEntries.length) {
|
||||
return allEntries[selectedIndex];
|
||||
}
|
||||
return DASH_ENTRY;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function takesDraggedFile(e: DragEvent): boolean {
|
||||
@@ -187,10 +173,10 @@
|
||||
data-dropdown-input
|
||||
>
|
||||
<LayoutRow class="dropdown-box" classes={{ disabled, open }} {tooltipLabel} {tooltipDescription} {tooltipShortcut} on:click={() => !disabled && (open = true)} data-floating-menu-spawner>
|
||||
{#if activeEntry.icon}
|
||||
{#if activeEntry?.icon}
|
||||
<IconLabel class="dropdown-icon" icon={activeEntry.icon} />
|
||||
{/if}
|
||||
<TextLabel class="dropdown-label">{activeEntry.label}</TextLabel>
|
||||
<TextLabel class="dropdown-label">{activeEntry?.label ?? placeholder}</TextLabel>
|
||||
<IconLabel class="dropdown-arrow" icon="DropdownArrow" />
|
||||
</LayoutRow>
|
||||
<MenuList
|
||||
@@ -200,7 +186,7 @@
|
||||
on:activeEntry={({ detail }) => commitEntry(detail)}
|
||||
on:open={({ detail }) => (open = detail)}
|
||||
{open}
|
||||
activeEntry={activeEntry === DASH_ENTRY ? undefined : activeEntry}
|
||||
{activeEntry}
|
||||
{entries}
|
||||
entriesHash={entriesHash || 0n}
|
||||
{drawIcon}
|
||||
|
||||
@@ -577,6 +577,9 @@ tagged_value! {
|
||||
TonalRange(raster_nodes::adjustments::TonalRange),
|
||||
AdjustmentChannel(raster_nodes::adjustments::AdjustmentChannel),
|
||||
HueSaturationRange(raster_nodes::adjustments::HueSaturationRange),
|
||||
GlowSource(graphic_types::GlowSource),
|
||||
BevelStyle(graphic_types::BevelStyle),
|
||||
BevelDirection(graphic_types::BevelDirection),
|
||||
GridType(vector::misc::GridType),
|
||||
GridTopology(vector::misc::GridTopology),
|
||||
ArcType(vector::misc::ArcType),
|
||||
@@ -711,6 +714,25 @@ impl TaggedValue {
|
||||
None
|
||||
}
|
||||
|
||||
fn to_stroke_align(input: &str) -> Option<vector::style::StrokeAlign> {
|
||||
let mut choices = input.split("::");
|
||||
let (first, second) = (choices.next()?.trim(), choices.next()?.trim());
|
||||
if first == "StrokeAlign" {
|
||||
return Some(match second {
|
||||
"Center" => vector::style::StrokeAlign::Center,
|
||||
"Inside" => vector::style::StrokeAlign::Inside,
|
||||
"Outside" => vector::style::StrokeAlign::Outside,
|
||||
_ => {
|
||||
log::error!("Invalid StrokeAlign default type variant: {input}");
|
||||
return None;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
log::error!("Invalid StrokeAlign default type: {input}");
|
||||
None
|
||||
}
|
||||
|
||||
match ty {
|
||||
Type::Generic(_) => None,
|
||||
Type::Concrete(concrete_type) => {
|
||||
@@ -729,6 +751,7 @@ impl TaggedValue {
|
||||
() if ty == TypeId::of::<Graphic>() => to_color(string).map(TaggedValue::Color)?,
|
||||
() if ty == TypeId::of::<Gradient>() => to_gradient(string).map(|gradient| TaggedValue::GradientRamp(gradient.into()))?,
|
||||
() if ty == TypeId::of::<ReferencePoint>() => to_reference_point(string).map(TaggedValue::ReferencePoint)?,
|
||||
() if ty == TypeId::of::<vector::style::StrokeAlign>() => to_stroke_align(string).map(TaggedValue::StrokeAlign)?,
|
||||
() if ty == TypeId::of::<DashPattern>() => TaggedValue::DashPattern(core_types::misc::parse_f64_list(string)),
|
||||
() if ty == TypeId::of::<BoxCorners>() => TaggedValue::BoxCorners(core_types::misc::parse_f64_list(string)),
|
||||
_ => return None,
|
||||
|
||||
@@ -2,6 +2,7 @@ use graph_craft::ProtoNodeIdentifier;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeNetwork};
|
||||
use graph_craft::proto::{ConstructionArgs, ProtoNetwork, ProtoNode};
|
||||
use graphene_std::graphic::write_layer_path;
|
||||
use graphene_std::simplify_identifier_name;
|
||||
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
|
||||
use std::error::Error;
|
||||
@@ -57,6 +58,7 @@ enum Kind {
|
||||
Nullify,
|
||||
Expand,
|
||||
Scope,
|
||||
LayerPath,
|
||||
}
|
||||
|
||||
impl Kind {
|
||||
@@ -68,6 +70,7 @@ impl Kind {
|
||||
Kind::Nullify => "+nullify",
|
||||
Kind::Expand => "+expand",
|
||||
Kind::Scope => "+scope",
|
||||
Kind::LayerPath => "+layer-path",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -234,6 +237,7 @@ fn kind(proto: &ProtoNode, origin: &[NodeId], document: &Document) -> Kind {
|
||||
_ if appended && path.last() == Some(&NodeId(10)) => Kind::Nullify,
|
||||
_ if proto.original_location.auto_convert_index.is_some() => Kind::Convert,
|
||||
ConstructionArgs::Value(_) => Kind::Value,
|
||||
_ if proto.identifier == write_layer_path::IDENTIFIER => Kind::LayerPath,
|
||||
_ if origin.is_empty() => Kind::Scope,
|
||||
_ if document[origin].1.as_ref() == Some(&proto.identifier) => Kind::Document,
|
||||
_ => Kind::Expand,
|
||||
|
||||
@@ -13,6 +13,7 @@ use graph_craft::proto::ProtoNetwork;
|
||||
use graphene_std::application_io::ApplicationIo;
|
||||
use graphene_std::runtime::{AsyncRuntime, RuntimeHandle, Spawn, Task};
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
use interpreted_executor::layer_paths::write_layer_paths;
|
||||
use interpreted_executor::util::wrap_network_in_scope;
|
||||
use std::collections::HashMap;
|
||||
use std::error::Error;
|
||||
@@ -24,13 +25,15 @@ use std::sync::{Arc, Mutex};
|
||||
pub struct OpenedDocument {
|
||||
pub gdd: Option<GddV1>,
|
||||
pub network: NodeNetwork,
|
||||
/// The path of every layer in `network`.
|
||||
pub layers: Vec<Vec<NodeId>>,
|
||||
/// What `dump` shows for each node and network, when asked for.
|
||||
pub names: Option<HashMap<Vec<NodeId>, String>>,
|
||||
}
|
||||
|
||||
/// Open `path` with [`document_loader::open_document`]. `with_names` also collects its display names.
|
||||
pub async fn open_document(path: &Path, with_names: bool) -> Result<OpenedDocument, Box<dyn Error>> {
|
||||
let LoadedDocument { network, origin } = document_loader::open_document(path).await?;
|
||||
let LoadedDocument { network, layers, origin } = document_loader::open_document(path).await?;
|
||||
|
||||
let (gdd, names) = match origin {
|
||||
DocumentOrigin::Legacy(document_string) => (None, with_names.then(|| dump::legacy_names(&document_string))),
|
||||
@@ -43,7 +46,7 @@ pub async fn open_document(path: &Path, with_names: bool) -> Result<OpenedDocume
|
||||
(Some(*gdd), names)
|
||||
}
|
||||
};
|
||||
Ok(OpenedDocument { gdd, network, names })
|
||||
Ok(OpenedDocument { gdd, network, layers, names })
|
||||
}
|
||||
|
||||
/// The name of each node, keyed by the path the dump visits it at.
|
||||
@@ -89,7 +92,9 @@ pub async fn editor_api(gdd: Option<&GddV1>) -> (Arc<PlatformApplicationIo>, Arc
|
||||
(application_io, editor_api)
|
||||
}
|
||||
|
||||
pub fn compile_graph(network: NodeNetwork, editor_api: Arc<PlatformEditorApi>, gdd: Option<&GddV1>, runtime: RuntimeHandle) -> Result<ProtoNetwork, Box<dyn Error>> {
|
||||
/// Compile `network`, writing the path of each of its `layers` onto what that layer renders.
|
||||
pub fn compile_graph(mut network: NodeNetwork, layers: &[Vec<NodeId>], editor_api: Arc<PlatformEditorApi>, gdd: Option<&GddV1>, runtime: RuntimeHandle) -> Result<ProtoNetwork, Box<dyn Error>> {
|
||||
write_layer_paths(&mut network, layers);
|
||||
let mut network = wrap_network_in_scope(network, editor_api, runtime);
|
||||
|
||||
let preprocessor = preprocessor::Preprocessor::new();
|
||||
@@ -117,7 +122,7 @@ pub async fn compile_document(document: OpenedDocument) -> Result<CompiledDocume
|
||||
let (application_io, editor_api) = editor_api(document.gdd.as_ref()).await;
|
||||
let spawner = Arc::new(TokioSpawner::default());
|
||||
let runtime = AsyncRuntime::new(spawner.clone());
|
||||
let proto_network = compile_graph(document.network, editor_api, document.gdd.as_ref(), runtime.handle())?;
|
||||
let proto_network = compile_graph(document.network, &document.layers, editor_api, document.gdd.as_ref(), runtime.handle())?;
|
||||
|
||||
Ok(CompiledDocument {
|
||||
proto_network,
|
||||
|
||||
@@ -124,11 +124,11 @@ impl Viewer {
|
||||
}
|
||||
|
||||
fn recompile(&mut self) {
|
||||
let network = match self.runtime.block_on(self.live.network()) {
|
||||
Ok(network) => network,
|
||||
let (network, layers) = match self.runtime.block_on(self.live.network_with_layers()) {
|
||||
Ok(network_with_layers) => network_with_layers,
|
||||
Err(error) => return log::error!("Failed to build the runtime network: {error}"),
|
||||
};
|
||||
let proto = match compile_graph(network, self.editor_api.clone(), Some(self.live.document()), self.graph_runtime.handle()) {
|
||||
let proto = match compile_graph(network, &layers, self.editor_api.clone(), Some(self.live.document()), self.graph_runtime.handle()) {
|
||||
Ok(proto) => proto,
|
||||
Err(error) => return log::error!("Compile failed: {error}"),
|
||||
};
|
||||
|
||||
@@ -0,0 +1,316 @@
|
||||
//! Writes each layer's path onto what it renders, so what's rendered can be traced back to its layer.
|
||||
|
||||
use crate::node_registry::NODE_REGISTRY;
|
||||
use graph_craft::ProtoNodeIdentifier;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, DocumentNodeMetadata, NodeId, NodeInput, NodeNetwork};
|
||||
use graphene_std::NodeParameter;
|
||||
use graphene_std::graphic::{extend, write_layer_path};
|
||||
use graphene_std::list::NodeIdPath;
|
||||
use std::collections::HashMap;
|
||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
|
||||
/// What a layer adds to the document, which is what its thumbnail shows and what its path is written onto.
|
||||
pub enum LayerContent {
|
||||
/// What the Extend node the layer ends in is given to add, with the path of the network the node is in.
|
||||
Added { network_path: Vec<NodeId>, extend: NodeId },
|
||||
/// Everything the layer outputs, from the node at this path.
|
||||
Output(Vec<NodeId>),
|
||||
}
|
||||
|
||||
/// The content of the layer at this path, unless it's hidden or passes through what's below it and so has none of its own.
|
||||
pub fn layer_content(layer_path: &[NodeId], network: &NodeNetwork) -> Option<LayerContent> {
|
||||
let output = network.output_source(layer_path, 0)?;
|
||||
if !output.starts_with(layer_path) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let (node_id, network_path) = output.split_last()?;
|
||||
let node = network.nested_network(network_path)?.nodes.get(node_id)?;
|
||||
if node.implementation != DocumentNodeImplementation::ProtoNode(extend::IDENTIFIER) {
|
||||
return Some(LayerContent::Output(output));
|
||||
}
|
||||
|
||||
Some(LayerContent::Added {
|
||||
network_path: network_path.to_vec(),
|
||||
extend: *node_id,
|
||||
})
|
||||
}
|
||||
|
||||
impl LayerContent {
|
||||
/// The path of the node producing the content once compiled.
|
||||
pub fn source(&self, network: &NodeNetwork) -> Option<Vec<NodeId>> {
|
||||
match self {
|
||||
Self::Added { network_path, extend } => {
|
||||
let added = network.nested_network(network_path)?.nodes.get(extend)?.inputs.get(extend::NewInput::INDEX)?;
|
||||
network.input_source(network_path, added)
|
||||
}
|
||||
Self::Output(output) => Some(output.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Puts a node after each layer's content that writes the layer's path onto it.
|
||||
/// A layer has none if its content may be of a type that can't carry the path.
|
||||
pub fn write_layer_paths(network: &mut NodeNetwork, layer_paths: &[Vec<NodeId>]) {
|
||||
let mut carries_layer_path = HashMap::new();
|
||||
|
||||
// O(layers * depth)
|
||||
for layer_path in layer_paths {
|
||||
let Some((layer, parent_path)) = layer_path.split_last() else { continue };
|
||||
let Some(content) = layer_content(layer_path, network) else { continue };
|
||||
|
||||
// An Extend node nested deeper than the layer may be in a network that other layers share.
|
||||
// So the writer goes after the layer's output, and the Extend node only decides if the content can carry the path.
|
||||
let content = match content {
|
||||
LayerContent::Added { network_path, extend } if network_path.len() > layer_path.len() => LayerContent::Output([network_path.as_slice(), &[extend]].concat()),
|
||||
content => content,
|
||||
};
|
||||
|
||||
let Some(source) = content.source(network) else { continue };
|
||||
if !source_can_carry_layer_path(source, network, &mut carries_layer_path) {
|
||||
continue;
|
||||
}
|
||||
|
||||
match content {
|
||||
// The writer goes between the Extend node and what it's given to add, inside the layer or beside it if the layer is that node
|
||||
LayerContent::Added { network_path, extend } => {
|
||||
let writer = layer_path_writer_id(extend);
|
||||
let layer_beside = if network_path.len() == layer_path.len() { Vec::new() } else { vec![*layer] };
|
||||
let Some(holder) = network_mut(network, &network_path) else { continue };
|
||||
let Some(added) = holder.nodes.get_mut(&extend).and_then(|node| node.inputs.get_mut(extend::NewInput::INDEX)) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
// Every layer made from the same network shares the writer
|
||||
if *added == NodeInput::node(writer, 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let content = std::mem::replace(added, NodeInput::node(writer, 0));
|
||||
holder.nodes.insert(writer, layer_path_writer(content, layer_beside));
|
||||
}
|
||||
// The writer goes beside the layer, taking over everything its output feeds
|
||||
LayerContent::Output(_) => {
|
||||
let writer = layer_path_writer_id(*layer);
|
||||
let Some(holder) = network_mut(network, parent_path) else { continue };
|
||||
if holder.nodes.contains_key(&writer) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let (output, written) = (NodeInput::node(*layer, 0), NodeInput::node(writer, 0));
|
||||
let inputs = holder.nodes.values_mut().flat_map(|node| &mut node.inputs).chain(&mut holder.exports);
|
||||
inputs.filter(|input| **input == output).for_each(|input| *input = written.clone());
|
||||
|
||||
holder.nodes.insert(writer, layer_path_writer(output, vec![*layer]));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How the layer path writer fares with what a proto node outputs.
|
||||
#[derive(Clone, Copy)]
|
||||
enum CarriesLayerPath {
|
||||
Always,
|
||||
/// The node outputs the type its one input is given, so that decides it.
|
||||
AsItsInput,
|
||||
Never,
|
||||
}
|
||||
|
||||
/// Whether the layer path writer can take everything the proto node at this path may output.
|
||||
fn source_can_carry_layer_path(mut source: Vec<NodeId>, network: &NodeNetwork, carries_layer_path: &mut HashMap<ProtoNodeIdentifier, CarriesLayerPath>) -> bool {
|
||||
loop {
|
||||
let Some((node_id, network_path)) = source.split_last() else { return false };
|
||||
let Some(node) = network.nested_network(network_path).and_then(|network| network.nodes.get(node_id)) else {
|
||||
return false;
|
||||
};
|
||||
let DocumentNodeImplementation::ProtoNode(identifier) = &node.implementation else { return false };
|
||||
|
||||
match *carries_layer_path.entry(identifier.clone()).or_insert_with(|| output_can_carry_layer_path(identifier)) {
|
||||
CarriesLayerPath::Always => return true,
|
||||
CarriesLayerPath::Never => return false,
|
||||
CarriesLayerPath::AsItsInput => {
|
||||
let Some(input_source) = node.inputs.first().and_then(|input| network.input_source(network_path, input)) else {
|
||||
return false;
|
||||
};
|
||||
source = input_source;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn output_can_carry_layer_path(identifier: &ProtoNodeIdentifier) -> CarriesLayerPath {
|
||||
let (Some(outputs), Some(writers)) = (NODE_REGISTRY.get(identifier), NODE_REGISTRY.get(&write_layer_path::IDENTIFIER)) else {
|
||||
return CarriesLayerPath::Never;
|
||||
};
|
||||
|
||||
let writes_type = |output: &graph_craft::Type| {
|
||||
let content = |writer: &graphene_std::NodeIOTypes| writer.inputs.get(write_layer_path::ContentInput::INDEX).is_some_and(|content| content.nested_type() == output);
|
||||
writers.keys().any(content)
|
||||
};
|
||||
if outputs.keys().all(|output| writes_type(output.return_value.nested_type())) {
|
||||
return CarriesLayerPath::Always;
|
||||
}
|
||||
|
||||
let as_its_input = |output: &graphene_std::NodeIOTypes| matches!(output.inputs.as_slice(), [input] if input.nested_type() == output.return_value.nested_type());
|
||||
if outputs.keys().all(as_its_input) {
|
||||
CarriesLayerPath::AsItsInput
|
||||
} else {
|
||||
CarriesLayerPath::Never
|
||||
}
|
||||
}
|
||||
|
||||
/// The network at this path, which is either an entry of the definitions table or held by its node.
|
||||
fn network_mut<'a>(network: &'a mut NodeNetwork, path: &[NodeId]) -> Option<&'a mut NodeNetwork> {
|
||||
// The last table entry along the path, which holds any networks after it
|
||||
let mut table_entry = None;
|
||||
let mut current = &*network;
|
||||
for (index, node_id) in path.iter().enumerate() {
|
||||
current = match ¤t.nodes.get(node_id)?.implementation {
|
||||
DocumentNodeImplementation::Definition(id) => {
|
||||
table_entry = Some((*id, index + 1));
|
||||
network.definitions.get(id)?
|
||||
}
|
||||
DocumentNodeImplementation::Network(held) => held,
|
||||
_ => return None,
|
||||
};
|
||||
}
|
||||
|
||||
let (mut current, held_path) = match table_entry {
|
||||
Some((id, held_from)) => (network.definitions.get_mut(&id)?, &path[held_from..]),
|
||||
None => (network, path),
|
||||
};
|
||||
for node_id in held_path {
|
||||
let DocumentNodeImplementation::Network(held) = &mut current.nodes.get_mut(node_id)?.implementation else {
|
||||
return None;
|
||||
};
|
||||
current = held;
|
||||
}
|
||||
|
||||
Some(current)
|
||||
}
|
||||
|
||||
/// The ID of the node writing the layer path onto what the node with this ID outputs or is given, which stays the same between compilations.
|
||||
pub fn layer_path_writer_id(node_id: NodeId) -> NodeId {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
"layer path writer".hash(&mut hasher);
|
||||
node_id.hash(&mut hasher);
|
||||
NodeId(hasher.finish())
|
||||
}
|
||||
|
||||
fn layer_path_writer(content: NodeInput, layer_beside: Vec<NodeId>) -> DocumentNode {
|
||||
DocumentNode {
|
||||
inputs: vec![
|
||||
content,
|
||||
// The writer is directly inside the layer or beside it, so removing only its own ID gives the path
|
||||
NodeInput::value(TaggedValue::Integer(1), false),
|
||||
NodeInput::value(TaggedValue::NodeIdPath(NodeIdPath::from(layer_beside)), false),
|
||||
NodeInput::Reflection(DocumentNodeMetadata::DocumentNodePath),
|
||||
],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(write_layer_path::IDENTIFIER),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use graph_craft::document::NetworkId;
|
||||
|
||||
#[test]
|
||||
fn content_that_cannot_carry_a_layer_path_is_left_alone() {
|
||||
let path_node = DocumentNode {
|
||||
inputs: vec![NodeInput::Reflection(DocumentNodeMetadata::DocumentNodePath)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::graphic::path_of_subgraph::IDENTIFIER),
|
||||
..Default::default()
|
||||
};
|
||||
let mut network = NodeNetwork {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [(NodeId(1), path_node)].into_iter().collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let unchanged = network.clone();
|
||||
|
||||
write_layer_paths(&mut network, &[vec![NodeId(1)]]);
|
||||
|
||||
assert_eq!(network, unchanged);
|
||||
}
|
||||
|
||||
fn proto_node(identifier: ProtoNodeIdentifier, inputs: Vec<NodeInput>) -> DocumentNode {
|
||||
DocumentNode {
|
||||
inputs,
|
||||
implementation: DocumentNodeImplementation::ProtoNode(identifier),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn definition_node(id: NetworkId) -> DocumentNode {
|
||||
DocumentNode {
|
||||
implementation: DocumentNodeImplementation::Definition(id),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A network shaped like 'Merge', where an Extend node adds what the node beside it gives.
|
||||
fn merge_like(added: DocumentNode) -> NodeNetwork {
|
||||
let extend = proto_node(extend::IDENTIFIER, vec![NodeInput::value(TaggedValue::None, false), NodeInput::node(NodeId(2), 0)]);
|
||||
NodeNetwork {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [(NodeId(1), extend), (NodeId(2), added)].into_iter().collect(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
// One network is shared by a layer at the root and by a layer inside another layer, so the one writer inside it has to suit both
|
||||
#[test]
|
||||
fn a_network_shared_by_layers_at_different_depths_writes_each_layer_path() {
|
||||
let (merge, group) = (NetworkId(1), NetworkId(2));
|
||||
let rectangle = proto_node(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER, Vec::new());
|
||||
let group_network = NodeNetwork {
|
||||
exports: vec![NodeInput::node(NodeId(30), 0)],
|
||||
nodes: [(NodeId(30), definition_node(merge))].into_iter().collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let network = NodeNetwork {
|
||||
exports: vec![NodeInput::node(NodeId(10), 0)],
|
||||
nodes: [(NodeId(10), definition_node(merge)), (NodeId(20), definition_node(group))].into_iter().collect(),
|
||||
definitions: [(merge, merge_like(rectangle)), (group, group_network)].into_iter().collect(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// The outer layer comes first in one order and last in the other
|
||||
let orders = [
|
||||
[vec![NodeId(20)], vec![NodeId(10)], vec![NodeId(20), NodeId(30)]],
|
||||
[vec![NodeId(10)], vec![NodeId(20), NodeId(30)], vec![NodeId(20)]],
|
||||
];
|
||||
let written = orders.map(|layer_paths| {
|
||||
let mut network = network.clone();
|
||||
write_layer_paths(&mut network, &layer_paths);
|
||||
network
|
||||
});
|
||||
assert_eq!(written[0], written[1], "The order the layers are given in should not change what's written");
|
||||
|
||||
// The writer writes the path of the layer holding its network, whichever layer that is
|
||||
let writer = &written[0].definitions[&merge].nodes[&layer_path_writer_id(NodeId(1))];
|
||||
let (levels_up, layer_beside) = (writer.input(write_layer_path::LevelsUpInput), writer.input(write_layer_path::LayerBesideInput));
|
||||
assert_eq!(levels_up, Some(&NodeInput::value(TaggedValue::Integer(1), false)));
|
||||
assert_eq!(layer_beside, Some(&NodeInput::value(TaggedValue::NodeIdPath(NodeIdPath::from(Vec::new())), false)));
|
||||
}
|
||||
|
||||
// Content that already writes its own layer path, like the 'Merge' networks of older documents, gets no second writer
|
||||
#[test]
|
||||
fn a_network_writing_its_own_layer_path_is_left_alone() {
|
||||
let write_attribute = proto_node(graphene_std::graphic::write_attribute::IDENTIFIER, Vec::new());
|
||||
let mut network = NodeNetwork {
|
||||
exports: vec![NodeInput::node(NodeId(10), 0)],
|
||||
nodes: [(NodeId(10), definition_node(NetworkId(1)))].into_iter().collect(),
|
||||
definitions: [(NetworkId(1), merge_like(write_attribute))].into_iter().collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let unchanged = network.clone();
|
||||
|
||||
write_layer_paths(&mut network, &[vec![NodeId(10)]]);
|
||||
|
||||
assert_eq!(network, unchanged);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
#![recursion_limit = "256"]
|
||||
|
||||
pub mod dynamic_executor;
|
||||
pub mod layer_paths;
|
||||
pub mod node_registry;
|
||||
pub mod util;
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ use graphene_animation::AnimationCurve;
|
||||
use graphene_std::animation::RealTimeMode;
|
||||
use graphene_std::any::DynAnyNode;
|
||||
use graphene_std::brush::Stroke;
|
||||
use graphene_std::generator::Generator;
|
||||
use graphene_std::gradient::Gradient;
|
||||
use graphene_std::list::{AttributeValueDyn, Bundle, Item, List, ListDyn, NodeIdPath};
|
||||
#[cfg(feature = "gpu")]
|
||||
@@ -27,6 +28,7 @@ use graphene_std::vector::misc::{
|
||||
use graphene_std::vector::style::{DashPattern, GradientForm, GradientHueDirection, GradientInterpolation, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector, VectorModification};
|
||||
use graphene_std::{Artboard, Context, Graphic, NodeIO, NodeIOTypes, ProtoNodeIdentifier, concrete, fn_type};
|
||||
use graphene_std::{BevelDirection, BevelStyle, GlowSource};
|
||||
use node_registry_macros::async_node;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
@@ -56,6 +58,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Raster<CPU>>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Color>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Gradient>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Generator>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<String>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<NodeIdPath>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<f64>]),
|
||||
@@ -76,6 +79,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Raster<GPU>>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Color>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Gradient>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Generator>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<DashPattern>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<BoxCorners>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<TransferCurve>]),
|
||||
@@ -285,6 +289,9 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
TonalRange,
|
||||
AdjustmentChannel,
|
||||
HueSaturationRange,
|
||||
GlowSource,
|
||||
BevelStyle,
|
||||
BevelDirection,
|
||||
Stroke,
|
||||
ScaleType,
|
||||
ReferencePoint,
|
||||
@@ -318,6 +325,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
Graphic,
|
||||
Color,
|
||||
Gradient,
|
||||
Generator,
|
||||
String,
|
||||
f64,
|
||||
DVec2,
|
||||
@@ -350,6 +358,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
Raster<CPU>,
|
||||
Color,
|
||||
Gradient,
|
||||
Generator,
|
||||
f64,
|
||||
i64,
|
||||
bool,
|
||||
@@ -390,6 +399,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
String,
|
||||
Color,
|
||||
Gradient,
|
||||
Generator,
|
||||
Artboard,
|
||||
));
|
||||
#[cfg(feature = "gpu")]
|
||||
@@ -441,6 +451,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
// This is what lets a paint list zip element-wise against the content it paints.
|
||||
node_types.extend(embed_adapter_row!(from_element: Color, element: Graphic));
|
||||
node_types.extend(embed_adapter_row!(from_element: Gradient, element: Graphic));
|
||||
node_types.extend(embed_adapter_row!(from_element: Generator, element: Graphic));
|
||||
node_types.extend(embed_adapter_row!(from_element: String, element: Graphic));
|
||||
node_types.extend(embed_adapter_row!(from_element: Vector, element: Graphic));
|
||||
node_types.extend(embed_adapter_row!(from_element: Raster<CPU>, element: Graphic));
|
||||
@@ -498,6 +509,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
attribute_value_node!(List<String>),
|
||||
attribute_value_node!(List<Color>),
|
||||
attribute_value_node!(List<Gradient>),
|
||||
attribute_value_node!(List<Generator>),
|
||||
attribute_value_node!(List<Vector>),
|
||||
attribute_value_node!(List<Raster<CPU>>),
|
||||
#[cfg(feature = "gpu")]
|
||||
@@ -526,6 +538,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
transform_list_node!(element: Raster<GPU>),
|
||||
transform_list_node!(element: Color),
|
||||
transform_list_node!(element: Gradient),
|
||||
transform_list_node!(element: Generator),
|
||||
];
|
||||
node_types.extend(transform_list_rows);
|
||||
let mut map: HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeConstructor>> = HashMap::new();
|
||||
|
||||
@@ -32,9 +32,10 @@ pub use glam_ext::FallibleVec2Operations;
|
||||
pub use graphene_hash;
|
||||
pub use graphene_hash::CacheHash;
|
||||
pub use list::{
|
||||
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME, ATTR_END,
|
||||
ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_FORM, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_LETTER_SPACING,
|
||||
ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM, ATTR_TYPE,
|
||||
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME,
|
||||
ATTR_EFFECTS, ATTR_END, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_FORM, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION,
|
||||
ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_GRADIENT_START_CURVATURE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME,
|
||||
ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM, ATTR_TYPE,
|
||||
};
|
||||
pub use memo::MemoHash;
|
||||
pub use num_traits;
|
||||
|
||||
@@ -61,6 +61,11 @@ pub const ATTR_CLIP: &str = "clip";
|
||||
pub const ATTR_GRADIENT_SPREAD: &str = "gradient_spread";
|
||||
/// Gradient's `GradientForm` (`Linear` or `Radial`).
|
||||
pub const ATTR_GRADIENT_FORM: &str = "gradient_form";
|
||||
/// Gradient's `f64` curvature dial for the contour through its start, from -1 to 1: 0 is a line, ±1 is the start point
|
||||
/// itself, and between is a circle bowing toward (positive) or away from (negative) the end. Absent, the form decides it.
|
||||
pub const ATTR_GRADIENT_START_CURVATURE: &str = "gradient_start_curvature";
|
||||
/// Gradient's `f64` curvature dial for the contour through its end, like `gradient_start_curvature` with the ends swapped.
|
||||
pub const ATTR_GRADIENT_END_CURVATURE: &str = "gradient_end_curvature";
|
||||
/// Gradient's `GradientSpace`, the color space its stops interpolate in.
|
||||
pub const ATTR_GRADIENT_SPACE: &str = "gradient_space";
|
||||
/// Gradient's `GradientHueDirection` (`Shorter`, `Longer`, `Increasing`, or `Decreasing`), which way around the
|
||||
@@ -80,6 +85,9 @@ pub const ATTR_POSITION: &str = "position";
|
||||
pub const ATTR_MIDPOINT: &str = "midpoint";
|
||||
/// Item's ordered list of paint passes, of type `Appearance`. Earlier coverages paint first, compositing below later ones.
|
||||
pub const ATTR_APPEARANCE: &str = "appearance";
|
||||
/// Item's ordered list of effects, of type `Effects`, which the renderer applies in turn to the pixels the item renders to.
|
||||
/// Unlike the appearance, it doesn't cascade to descendants.
|
||||
pub const ATTR_EFFECTS: &str = "effects";
|
||||
// TODO: Add a "fill_rule" attribute as a sibling of "paint" on the coverage list (uniform across covers) once a FillRule type ships
|
||||
/// Coverage's `Graphic` paint (implicit default `Graphic::None`, painting nothing), on the
|
||||
/// `List<Coverage>` inside an `Appearance`.
|
||||
|
||||
@@ -21,6 +21,7 @@ wasm = [
|
||||
"core-types/wasm",
|
||||
"vector-types/wasm",
|
||||
"raster-types/wasm",
|
||||
"tsify",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
@@ -28,6 +29,7 @@ wasm = [
|
||||
# Local dependencies
|
||||
core-types = { workspace = true }
|
||||
graphene-hash = { workspace = true }
|
||||
graphene-resource = { workspace = true }
|
||||
brush-types = { workspace = true }
|
||||
raster-types = { workspace = true, features = ["wgpu"] }
|
||||
vector-types = { workspace = true }
|
||||
@@ -40,4 +42,5 @@ serde_json = { workspace = true }
|
||||
|
||||
# Optional workspace dependencies
|
||||
serde = { workspace = true, optional = true }
|
||||
tsify = { workspace = true, optional = true }
|
||||
wasm-bindgen = { workspace = true, optional = true }
|
||||
@@ -0,0 +1,533 @@
|
||||
//! Color adjustments as plain data holding their nodes' settings in the nodes' own units, decoded from effect rows, carried out by the kernels of the `raster-kernels` crate.
|
||||
|
||||
use crate::Graphic;
|
||||
use crate::effects::EffectKind;
|
||||
use crate::parameters::ParameterVisitor;
|
||||
use core_types::Color;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::Item;
|
||||
use core_types::transfer_curve::TransferCurve;
|
||||
use dyn_any::DynAny;
|
||||
use graphene_resource::Resource;
|
||||
use vector_types::Gradient;
|
||||
|
||||
/// A color adjustment applied to each color on its own, with no regard for its neighbors.
|
||||
#[derive(Clone, Debug, PartialEq, CacheHash)]
|
||||
pub enum Adjustment {
|
||||
Desaturate {
|
||||
method: DesaturateMethod,
|
||||
},
|
||||
GammaCorrection {
|
||||
gamma: f64,
|
||||
inverse: bool,
|
||||
},
|
||||
MakeOpaque,
|
||||
BrightnessContrast {
|
||||
/// Percent.
|
||||
brightness: f64,
|
||||
/// Percent.
|
||||
contrast: f64,
|
||||
use_classic: bool,
|
||||
/// On a scale of 0 to 255.
|
||||
classic_pivot: f64,
|
||||
},
|
||||
Levels(Box<LevelsSettings>),
|
||||
Curves(Box<CurvesSettings>),
|
||||
BlackAndWhite(BlackAndWhiteSettings),
|
||||
HueSaturation(Box<HueSaturationSettings>),
|
||||
Invert,
|
||||
Threshold {
|
||||
/// Percent.
|
||||
min_luminance: f64,
|
||||
/// Percent.
|
||||
max_luminance: f64,
|
||||
},
|
||||
GradientMap {
|
||||
/// The gradient, with its whole-ramp settings as its attributes.
|
||||
gradient: Item<Gradient>,
|
||||
reverse: bool,
|
||||
},
|
||||
Vibrance {
|
||||
/// Percent.
|
||||
vibrance: f64,
|
||||
/// Percent.
|
||||
saturation: f64,
|
||||
},
|
||||
ChannelMixer(Box<ChannelMixerSettings>),
|
||||
SelectiveColor(Box<SelectiveColorSettings>),
|
||||
Posterize {
|
||||
levels: i64,
|
||||
},
|
||||
Exposure {
|
||||
exposure: f64,
|
||||
offset: f64,
|
||||
gamma_correction: f64,
|
||||
},
|
||||
ColorBalance(ColorBalanceSettings),
|
||||
PhotoFilter {
|
||||
color: Color,
|
||||
/// Percent.
|
||||
density: f64,
|
||||
preserve_luminosity: bool,
|
||||
},
|
||||
ColorLookup {
|
||||
/// The file the lookup table is read from.
|
||||
lut_file: Resource,
|
||||
},
|
||||
ColorOverlay {
|
||||
color: Color,
|
||||
blend_mode: BlendMode,
|
||||
/// Percent.
|
||||
opacity: f64,
|
||||
},
|
||||
}
|
||||
|
||||
impl Adjustment {
|
||||
pub fn kind(&self) -> EffectKind {
|
||||
match self {
|
||||
Self::Desaturate { .. } => EffectKind::Desaturate,
|
||||
Self::GammaCorrection { .. } => EffectKind::GammaCorrection,
|
||||
Self::MakeOpaque => EffectKind::MakeOpaque,
|
||||
Self::BrightnessContrast { .. } => EffectKind::BrightnessContrast,
|
||||
Self::Levels(_) => EffectKind::Levels,
|
||||
Self::Curves(_) => EffectKind::Curves,
|
||||
Self::BlackAndWhite(_) => EffectKind::BlackAndWhite,
|
||||
Self::HueSaturation(_) => EffectKind::HueSaturation,
|
||||
Self::Invert => EffectKind::Invert,
|
||||
Self::Threshold { .. } => EffectKind::Threshold,
|
||||
Self::GradientMap { .. } => EffectKind::GradientMap,
|
||||
Self::Vibrance { .. } => EffectKind::Vibrance,
|
||||
Self::ChannelMixer(_) => EffectKind::ChannelMixer,
|
||||
Self::SelectiveColor(_) => EffectKind::SelectiveColor,
|
||||
Self::Posterize { .. } => EffectKind::Posterize,
|
||||
Self::Exposure { .. } => EffectKind::Exposure,
|
||||
Self::ColorBalance(_) => EffectKind::ColorBalance,
|
||||
Self::PhotoFilter { .. } => EffectKind::PhotoFilter,
|
||||
Self::ColorLookup { .. } => EffectKind::ColorLookup,
|
||||
Self::ColorOverlay { .. } => EffectKind::PaintOverlay,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether each channel of the result depends only on the same channel of the color, making the adjustment four curves.
|
||||
pub fn is_per_channel(&self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::GammaCorrection { .. }
|
||||
| Self::MakeOpaque
|
||||
| Self::BrightnessContrast { .. }
|
||||
| Self::Levels(_)
|
||||
| Self::Curves(_)
|
||||
| Self::Invert
|
||||
| Self::Posterize { .. }
|
||||
| Self::Exposure { .. }
|
||||
| Self::ColorBalance(_)
|
||||
)
|
||||
}
|
||||
|
||||
/// Visits each parameter with the attribute it rides, named after the node's parameter, and its implicit default, which is the node's.
|
||||
pub(crate) fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor) {
|
||||
match self {
|
||||
Self::Desaturate { method } => visitor.parameter("method", method, DesaturateMethod::default()),
|
||||
Self::GammaCorrection { gamma, inverse } => {
|
||||
visitor.parameter("gamma", gamma, 2.2);
|
||||
visitor.parameter("inverse", inverse, false);
|
||||
}
|
||||
Self::MakeOpaque | Self::Invert => {}
|
||||
Self::BrightnessContrast {
|
||||
brightness,
|
||||
contrast,
|
||||
use_classic,
|
||||
classic_pivot,
|
||||
} => {
|
||||
visitor.parameter("brightness", brightness, 0.);
|
||||
visitor.parameter("contrast", contrast, 0.);
|
||||
visitor.parameter("use_classic", use_classic, false);
|
||||
visitor.parameter("classic_pivot", classic_pivot, 127.);
|
||||
}
|
||||
Self::Levels(settings) => {
|
||||
let LevelsSettings { composite, red, green, blue, alpha } = settings.as_mut();
|
||||
composite.visit_parameters(visitor, "");
|
||||
red.visit_parameters(visitor, "red");
|
||||
green.visit_parameters(visitor, "green");
|
||||
blue.visit_parameters(visitor, "blue");
|
||||
alpha.visit_parameters(visitor, "alpha");
|
||||
}
|
||||
Self::Curves(settings) => {
|
||||
let CurvesSettings { composite, red, green, blue, alpha } = settings.as_mut();
|
||||
visitor.parameter("curve", composite, TransferCurve::default());
|
||||
visitor.parameter("red_curve", red, TransferCurve::default());
|
||||
visitor.parameter("green_curve", green, TransferCurve::default());
|
||||
visitor.parameter("blue_curve", blue, TransferCurve::default());
|
||||
visitor.parameter("alpha_curve", alpha, TransferCurve::default());
|
||||
}
|
||||
Self::BlackAndWhite(settings) => {
|
||||
visitor.parameter("use_tint", &mut settings.use_tint, false);
|
||||
visitor.parameter("tint", &mut settings.tint, Color::from(SRGBA8::new(0xe1, 0xd3, 0xb3, 0xff)));
|
||||
visitor.parameter("reds", &mut settings.reds, 40.);
|
||||
visitor.parameter("yellows", &mut settings.yellows, 60.);
|
||||
visitor.parameter("greens", &mut settings.greens, 40.);
|
||||
visitor.parameter("cyans", &mut settings.cyans, 60.);
|
||||
visitor.parameter("blues", &mut settings.blues, 20.);
|
||||
visitor.parameter("magentas", &mut settings.magentas, 80.);
|
||||
}
|
||||
Self::HueSaturation(settings) => {
|
||||
let HueSaturationSettings {
|
||||
master,
|
||||
colorize,
|
||||
colorize_sliders,
|
||||
reds,
|
||||
yellows,
|
||||
greens,
|
||||
cyans,
|
||||
blues,
|
||||
magentas,
|
||||
} = settings.as_mut();
|
||||
|
||||
master.visit_parameters(visitor, "", [0., 0., 0.]);
|
||||
visitor.parameter("colorize", colorize, false);
|
||||
colorize_sliders.visit_parameters(visitor, "colorize", [24., 25., 0.]);
|
||||
|
||||
reds.visit_parameters(visitor, "reds", [315., 345., 15., 45.]);
|
||||
yellows.visit_parameters(visitor, "yellows", [15., 45., 75., 105.]);
|
||||
greens.visit_parameters(visitor, "greens", [75., 105., 135., 165.]);
|
||||
cyans.visit_parameters(visitor, "cyans", [135., 165., 195., 225.]);
|
||||
blues.visit_parameters(visitor, "blues", [195., 225., 255., 285.]);
|
||||
magentas.visit_parameters(visitor, "magentas", [255., 285., 315., 345.]);
|
||||
}
|
||||
Self::Threshold { min_luminance, max_luminance } => {
|
||||
visitor.parameter("min_luminance", min_luminance, 50.);
|
||||
visitor.parameter("max_luminance", max_luminance, 100.);
|
||||
}
|
||||
Self::GradientMap { gradient, reverse } => {
|
||||
visitor.parameter("gradient", gradient, Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE])));
|
||||
visitor.parameter("reverse", reverse, false);
|
||||
}
|
||||
Self::Vibrance { vibrance, saturation } => {
|
||||
visitor.parameter("vibrance", vibrance, 0.);
|
||||
visitor.parameter("saturation", saturation, 0.);
|
||||
}
|
||||
Self::ChannelMixer(settings) => {
|
||||
let ChannelMixerSettings {
|
||||
monochrome,
|
||||
monochrome_mix,
|
||||
red,
|
||||
green,
|
||||
blue,
|
||||
} = settings.as_mut();
|
||||
|
||||
visitor.parameter("monochrome", monochrome, false);
|
||||
monochrome_mix.visit_parameters(visitor, "monochrome", [40., 40., 20., 0.]);
|
||||
red.visit_parameters(visitor, "red", [100., 0., 0., 0.]);
|
||||
green.visit_parameters(visitor, "green", [0., 100., 0., 0.]);
|
||||
blue.visit_parameters(visitor, "blue", [0., 0., 100., 0.]);
|
||||
}
|
||||
Self::SelectiveColor(settings) => {
|
||||
let SelectiveColorSettings {
|
||||
mode,
|
||||
reds,
|
||||
yellows,
|
||||
greens,
|
||||
cyans,
|
||||
blues,
|
||||
magentas,
|
||||
whites,
|
||||
neutrals,
|
||||
blacks,
|
||||
} = settings.as_mut();
|
||||
|
||||
visitor.parameter("mode", mode, RelativeAbsolute::default());
|
||||
let groups = [
|
||||
("reds", reds),
|
||||
("yellows", yellows),
|
||||
("greens", greens),
|
||||
("cyans", cyans),
|
||||
("blues", blues),
|
||||
("magentas", magentas),
|
||||
("whites", whites),
|
||||
("neutrals", neutrals),
|
||||
("blacks", blacks),
|
||||
];
|
||||
for (name, inks) in groups {
|
||||
inks.visit_parameters(visitor, name);
|
||||
}
|
||||
}
|
||||
Self::Posterize { levels } => visitor.parameter("levels", levels, 4),
|
||||
Self::Exposure { exposure, offset, gamma_correction } => {
|
||||
visitor.parameter("exposure", exposure, 0.);
|
||||
visitor.parameter("offset", offset, 0.);
|
||||
visitor.parameter("gamma_correction", gamma_correction, 1.);
|
||||
}
|
||||
Self::ColorBalance(settings) => {
|
||||
settings.shadows.visit_parameters(visitor, "shadows");
|
||||
settings.midtones.visit_parameters(visitor, "midtones");
|
||||
settings.highlights.visit_parameters(visitor, "highlights");
|
||||
visitor.parameter("preserve_luminosity", &mut settings.preserve_luminosity, true);
|
||||
}
|
||||
Self::PhotoFilter { color, density, preserve_luminosity } => {
|
||||
visitor.parameter("color", color, Color::from(SRGBA8::new(0xec, 0x8a, 0x00, 0xff)));
|
||||
visitor.parameter("density", density, 25.);
|
||||
visitor.parameter("preserve_luminosity", preserve_luminosity, true);
|
||||
}
|
||||
Self::ColorLookup { lut_file } => visitor.parameter("lut_file", lut_file, Resource::default()),
|
||||
Self::ColorOverlay { color, blend_mode, opacity } => {
|
||||
// Rides the row as the paint of the Paint Overlay node, which stamps it
|
||||
let mut paint = Graphic::from(*color);
|
||||
visitor.parameter("paint", &mut paint, Graphic::from(Color::BLACK));
|
||||
if let Graphic::Color(paint) = paint {
|
||||
*color = *paint.element();
|
||||
}
|
||||
visitor.parameter("blend_mode", blend_mode, BlendMode::default());
|
||||
visitor.parameter("opacity", opacity, 100.);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Conversion from a color to grayscale.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
#[widget(Dropdown)]
|
||||
pub enum DesaturateMethod {
|
||||
/// Light level of the color, the Y (luminance) of Rec. 709, which weights the linear-light RGB channels by `0.2126, 0.7152, 0.0722`.
|
||||
///
|
||||
/// Accessibility contrast ratios and SVG luminance masks use this.
|
||||
#[default]
|
||||
#[label("Luminance (Rec. 709)")]
|
||||
#[cfg_attr(feature = "serde", serde(alias = "SRGB"))]
|
||||
LuminanceRec709,
|
||||
/// Light level approximation for the color, the Y′ (luma) of Rec. 709, which weights the gamma-encoded RGB channels by `0.2126, 0.7152, 0.0722`.
|
||||
///
|
||||
/// CSS filter functions such as `grayscale()` use this.
|
||||
#[label("Luma (Rec. 709)")]
|
||||
LumaRec709,
|
||||
/// Light level approximation for the color, the Y′ (luma) of Rec. 601, which weights the gamma-encoded RGB channels by `0.299, 0.587, 0.114`.
|
||||
///
|
||||
/// The Luminosity family of blend modes uses this, rounded to `0.3, 0.59, 0.11`.
|
||||
#[label("Luma (Rec. 601)")]
|
||||
LumaRec601,
|
||||
/// Perceptually uniform scale from black to white, the L (lightness) of OkLab.
|
||||
#[label("Lightness (OkLab)")]
|
||||
#[cfg_attr(feature = "serde", serde(alias = "Perceptual"))]
|
||||
LightnessOkLab,
|
||||
/// Mean of the three linear-light RGB channels.
|
||||
#[menu_separator]
|
||||
#[cfg_attr(feature = "serde", serde(alias = "AverageChannels"))]
|
||||
ChannelsAverage,
|
||||
/// Smallest of the three linear-light RGB channels.
|
||||
#[cfg_attr(feature = "serde", serde(alias = "MinimumChannels"))]
|
||||
ChannelsMinimum,
|
||||
/// Largest of the three linear-light RGB channels, the V (value) of HSV.
|
||||
#[cfg_attr(feature = "serde", serde(alias = "MaximumChannels"))]
|
||||
ChannelsMaximum,
|
||||
/// Midpoint of the largest and smallest gamma-encoded RGB channels, the L (lightness) of HSL.
|
||||
///
|
||||
/// The classic "Desaturate" command of many image editors uses this.
|
||||
#[label("Lightness (HSL)")]
|
||||
LightnessHsl,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
#[widget(Radio)]
|
||||
pub enum RelativeAbsolute {
|
||||
#[default]
|
||||
Relative,
|
||||
Absolute,
|
||||
}
|
||||
|
||||
/// One channel's Levels record: percentage input and output points and the midtones gamma.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct LevelsRecord {
|
||||
pub shadows: f64,
|
||||
pub midtones: f64,
|
||||
pub highlights: f64,
|
||||
pub output_minimums: f64,
|
||||
pub output_maximums: f64,
|
||||
}
|
||||
|
||||
/// The composite record that the three color channels pass through after their own, and the alpha record that stands apart.
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct LevelsSettings {
|
||||
pub composite: LevelsRecord,
|
||||
pub red: LevelsRecord,
|
||||
pub green: LevelsRecord,
|
||||
pub blue: LevelsRecord,
|
||||
pub alpha: LevelsRecord,
|
||||
}
|
||||
|
||||
/// The composite curve that the three color channels pass through after their own, and the alpha curve that stands apart.
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct CurvesSettings {
|
||||
pub composite: TransferCurve,
|
||||
pub red: TransferCurve,
|
||||
pub green: TransferCurve,
|
||||
pub blue: TransferCurve,
|
||||
pub alpha: TransferCurve,
|
||||
}
|
||||
|
||||
/// The percentage each hue contributes to the gray, and the color tinting it when `use_tint` is set.
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct BlackAndWhiteSettings {
|
||||
pub use_tint: bool,
|
||||
pub tint: Color,
|
||||
pub reds: f64,
|
||||
pub yellows: f64,
|
||||
pub greens: f64,
|
||||
pub cyans: f64,
|
||||
pub blues: f64,
|
||||
pub magentas: f64,
|
||||
}
|
||||
|
||||
/// One set of Hue/Saturation sliders: a hue in degrees and saturation and lightness percentages.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct HueSaturationSliders {
|
||||
pub hue: f64,
|
||||
pub saturation: f64,
|
||||
pub lightness: f64,
|
||||
}
|
||||
|
||||
/// The sliders for one range of hues, which apply fully from the range start to its end, fading out at the falloff ends. Edges are in degrees.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct HueRangeSettings {
|
||||
pub sliders: HueSaturationSliders,
|
||||
pub falloff_start: f64,
|
||||
pub range_start: f64,
|
||||
pub range_end: f64,
|
||||
pub falloff_end: f64,
|
||||
}
|
||||
|
||||
/// The master sliders shift every color, each hue range adds its own, and colorizing replaces them all with an absolute hue and saturation.
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct HueSaturationSettings {
|
||||
pub master: HueSaturationSliders,
|
||||
pub colorize: bool,
|
||||
pub colorize_sliders: HueSaturationSliders,
|
||||
pub reds: HueRangeSettings,
|
||||
pub yellows: HueRangeSettings,
|
||||
pub greens: HueRangeSettings,
|
||||
pub cyans: HueRangeSettings,
|
||||
pub blues: HueRangeSettings,
|
||||
pub magentas: HueRangeSettings,
|
||||
}
|
||||
|
||||
/// The percentages of each source channel, plus a constant, that sum to one output channel.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct ChannelMixerRow {
|
||||
pub red: f64,
|
||||
pub green: f64,
|
||||
pub blue: f64,
|
||||
pub constant: f64,
|
||||
}
|
||||
|
||||
/// A row for each output channel, or for the single gray channel when monochrome.
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct ChannelMixerSettings {
|
||||
pub monochrome: bool,
|
||||
pub monochrome_mix: ChannelMixerRow,
|
||||
pub red: ChannelMixerRow,
|
||||
pub green: ChannelMixerRow,
|
||||
pub blue: ChannelMixerRow,
|
||||
}
|
||||
|
||||
/// Percentage offsets to the cyan, magenta, yellow, and black inks of one group of colors.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct SelectiveColorInks {
|
||||
pub cyan: f64,
|
||||
pub magenta: f64,
|
||||
pub yellow: f64,
|
||||
pub black: f64,
|
||||
}
|
||||
|
||||
/// The ink offsets of each group of colors, and whether they are relative to the inks already present.
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct SelectiveColorSettings {
|
||||
pub mode: RelativeAbsolute,
|
||||
pub reds: SelectiveColorInks,
|
||||
pub yellows: SelectiveColorInks,
|
||||
pub greens: SelectiveColorInks,
|
||||
pub cyans: SelectiveColorInks,
|
||||
pub blues: SelectiveColorInks,
|
||||
pub magentas: SelectiveColorInks,
|
||||
pub whites: SelectiveColorInks,
|
||||
pub neutrals: SelectiveColorInks,
|
||||
pub blacks: SelectiveColorInks,
|
||||
}
|
||||
|
||||
/// Percentage shifts along the three opponent color axes for one tonal range.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct ColorBalanceShifts {
|
||||
pub cyan_red: f64,
|
||||
pub magenta_green: f64,
|
||||
pub yellow_blue: f64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct ColorBalanceSettings {
|
||||
pub shadows: ColorBalanceShifts,
|
||||
pub midtones: ColorBalanceShifts,
|
||||
pub highlights: ColorBalanceShifts,
|
||||
pub preserve_luminosity: bool,
|
||||
}
|
||||
|
||||
/// The attribute key of a parameter in one of a node's groups of parameters, which the node names with the group's prefix.
|
||||
fn grouped_key(group: &str, parameter: &str) -> String {
|
||||
if group.is_empty() { parameter.to_string() } else { format!("{group}_{parameter}") }
|
||||
}
|
||||
|
||||
impl LevelsRecord {
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str) {
|
||||
visitor.parameter(&grouped_key(group, "shadows"), &mut self.shadows, 0.);
|
||||
visitor.parameter(&grouped_key(group, "midtones"), &mut self.midtones, 1.);
|
||||
visitor.parameter(&grouped_key(group, "highlights"), &mut self.highlights, 100.);
|
||||
visitor.parameter(&grouped_key(group, "output_minimums"), &mut self.output_minimums, 0.);
|
||||
visitor.parameter(&grouped_key(group, "output_maximums"), &mut self.output_maximums, 100.);
|
||||
}
|
||||
}
|
||||
|
||||
impl HueSaturationSliders {
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str, [hue, saturation, lightness]: [f64; 3]) {
|
||||
visitor.parameter(&grouped_key(group, "hue"), &mut self.hue, hue);
|
||||
visitor.parameter(&grouped_key(group, "saturation"), &mut self.saturation, saturation);
|
||||
visitor.parameter(&grouped_key(group, "lightness"), &mut self.lightness, lightness);
|
||||
}
|
||||
}
|
||||
|
||||
impl HueRangeSettings {
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str, [falloff_start, range_start, range_end, falloff_end]: [f64; 4]) {
|
||||
self.sliders.visit_parameters(visitor, group, [0.; 3]);
|
||||
visitor.parameter(&grouped_key(group, "falloff_start"), &mut self.falloff_start, falloff_start);
|
||||
visitor.parameter(&grouped_key(group, "range_start"), &mut self.range_start, range_start);
|
||||
visitor.parameter(&grouped_key(group, "range_end"), &mut self.range_end, range_end);
|
||||
visitor.parameter(&grouped_key(group, "falloff_end"), &mut self.falloff_end, falloff_end);
|
||||
}
|
||||
}
|
||||
|
||||
impl ChannelMixerRow {
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str, [red, green, blue, constant]: [f64; 4]) {
|
||||
visitor.parameter(&grouped_key(group, "red"), &mut self.red, red);
|
||||
visitor.parameter(&grouped_key(group, "green"), &mut self.green, green);
|
||||
visitor.parameter(&grouped_key(group, "blue"), &mut self.blue, blue);
|
||||
visitor.parameter(&grouped_key(group, "constant"), &mut self.constant, constant);
|
||||
}
|
||||
}
|
||||
|
||||
impl SelectiveColorInks {
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str) {
|
||||
visitor.parameter(&grouped_key(group, "cyan"), &mut self.cyan, 0.);
|
||||
visitor.parameter(&grouped_key(group, "magenta"), &mut self.magenta, 0.);
|
||||
visitor.parameter(&grouped_key(group, "yellow"), &mut self.yellow, 0.);
|
||||
visitor.parameter(&grouped_key(group, "black"), &mut self.black, 0.);
|
||||
}
|
||||
}
|
||||
|
||||
impl ColorBalanceShifts {
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str) {
|
||||
visitor.parameter(&grouped_key(group, "cyan_red"), &mut self.cyan_red, 0.);
|
||||
visitor.parameter(&grouped_key(group, "magenta_green"), &mut self.magenta_green, 0.);
|
||||
visitor.parameter(&grouped_key(group, "yellow_blue"), &mut self.yellow_blue, 0.);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,684 @@
|
||||
//! An item's effects: an ordered list of image operations on the pixels the item renders to, stored in the `ATTR_EFFECTS` attribute.
|
||||
//! Each row is an [`EffectKind`] whose parameters ride its item as attributes, read as their defaults when absent.
|
||||
//! Each renderer decodes the rows into [`EffectOperation`]s and carries them out its own way, at the resolution of each render.
|
||||
|
||||
use crate::Graphic;
|
||||
use crate::adjustment::Adjustment;
|
||||
use crate::parameters::{ParameterVisitor, ReadParameters, WriteParameters};
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
use core_types::Color;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::{ATTR_EFFECTS, Item, List};
|
||||
use dyn_any::DynAny;
|
||||
use glam::{DAffine2, DMat2, DVec2, DVec3};
|
||||
use std::fmt::Debug;
|
||||
use vector_types::vector::style::StrokeAlign;
|
||||
|
||||
/// The image operation an [`Effect`] carries out.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, CacheHash)]
|
||||
pub enum EffectKind {
|
||||
/// Softens the content by blurring it.
|
||||
#[default]
|
||||
Blur,
|
||||
/// Casts the content's silhouette as a soft shadow beneath it.
|
||||
DropShadow,
|
||||
/// Casts a soft shadow inward from the content's edges, as if it were cut out of the surface.
|
||||
InnerShadow,
|
||||
/// Surrounds the content with a soft glow of its silhouette.
|
||||
OuterGlow,
|
||||
/// Glows inward from the content's edges, or outward from its center.
|
||||
InnerGlow,
|
||||
/// Shades the content's interior with soft bands from its silhouette cast two ways.
|
||||
Satin,
|
||||
/// Draws a band of color along the content's silhouette.
|
||||
Outline,
|
||||
/// Lights the content as if raised from the surface or pressed into it, with highlights and shadows along its edges.
|
||||
BevelAndEmboss,
|
||||
/// Paints over the content within its silhouette, mixing with its colors by a blend mode. A solid color paint is the color overlay adjustment.
|
||||
PaintOverlay,
|
||||
// The adjustments, which change each color of the content on its own, as their nodes of the same names do
|
||||
Desaturate,
|
||||
GammaCorrection,
|
||||
MakeOpaque,
|
||||
BrightnessContrast,
|
||||
Levels,
|
||||
Curves,
|
||||
BlackAndWhite,
|
||||
HueSaturation,
|
||||
Invert,
|
||||
Threshold,
|
||||
GradientMap,
|
||||
Vibrance,
|
||||
ChannelMixer,
|
||||
SelectiveColor,
|
||||
Posterize,
|
||||
Exposure,
|
||||
ColorBalance,
|
||||
PhotoFilter,
|
||||
ColorLookup,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for EffectKind {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::Blur => "Blur",
|
||||
Self::DropShadow => "Drop Shadow",
|
||||
Self::InnerShadow => "Inner Shadow",
|
||||
Self::OuterGlow => "Outer Glow",
|
||||
Self::InnerGlow => "Inner Glow",
|
||||
Self::Satin => "Satin",
|
||||
Self::Outline => "Outline",
|
||||
Self::BevelAndEmboss => "Bevel & Emboss",
|
||||
Self::PaintOverlay => "Paint Overlay",
|
||||
Self::Desaturate => "Desaturate",
|
||||
Self::GammaCorrection => "Gamma Correction",
|
||||
Self::MakeOpaque => "Make Opaque",
|
||||
Self::BrightnessContrast => "Brightness/Contrast",
|
||||
Self::Levels => "Levels",
|
||||
Self::Curves => "Curves",
|
||||
Self::BlackAndWhite => "Black & White",
|
||||
Self::HueSaturation => "Hue/Saturation",
|
||||
Self::Invert => "Invert",
|
||||
Self::Threshold => "Threshold",
|
||||
Self::GradientMap => "Gradient Map",
|
||||
Self::Vibrance => "Vibrance",
|
||||
Self::ChannelMixer => "Channel Mixer",
|
||||
Self::SelectiveColor => "Selective Color",
|
||||
Self::Posterize => "Posterize",
|
||||
Self::Exposure => "Exposure",
|
||||
Self::ColorBalance => "Color Balance",
|
||||
Self::PhotoFilter => "Photo Filter",
|
||||
Self::ColorLookup => "Color Lookup",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Where an inner glow starts from.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
#[widget(Radio)]
|
||||
pub enum GlowSource {
|
||||
/// Glows inward from the edges.
|
||||
#[default]
|
||||
Edge,
|
||||
/// Glows outward from the center.
|
||||
Center,
|
||||
}
|
||||
|
||||
/// Which slopes a bevel shapes from the content's edges.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
#[widget(Dropdown)]
|
||||
pub enum BevelStyle {
|
||||
/// Slopes up from the edges into the content.
|
||||
#[default]
|
||||
InnerBevel,
|
||||
/// Slopes down from the edges away from the content.
|
||||
OuterBevel,
|
||||
/// Slopes across the edges, half inside the content and half outside.
|
||||
Emboss,
|
||||
/// Slopes away from the edges both ways, as if pressed into the surface along them.
|
||||
PillowEmboss,
|
||||
}
|
||||
|
||||
/// Whether a bevel rises from the surface or sinks into it.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
#[widget(Radio)]
|
||||
pub enum BevelDirection {
|
||||
/// Raised from the surface.
|
||||
#[default]
|
||||
Up,
|
||||
/// Pressed into the surface.
|
||||
Down,
|
||||
}
|
||||
|
||||
/// The deviation of the blur that rounds a bevel's slopes of `size`, in the same units.
|
||||
pub fn bevel_smoothing(size: f64) -> f64 {
|
||||
size.max(0.) / 4.
|
||||
}
|
||||
|
||||
/// The unit vector toward a bevel's light from its `angle` and `altitude` in degrees, with `lengths_to_target` mapping document directions into the y-down space it's lit in.
|
||||
pub fn bevel_light(angle: f64, altitude: f64, lengths_to_target: DMat2) -> DVec3 {
|
||||
let (angle, altitude) = (angle.to_radians(), altitude.clamp(0., 90.).to_radians());
|
||||
let across = (lengths_to_target * DVec2::new(angle.cos(), -angle.sin())).try_normalize().unwrap_or(DVec2::X);
|
||||
(across * altitude.cos()).extend(altitude.sin())
|
||||
}
|
||||
|
||||
/// An overlay's paint with its unit square fitted to `content_bounds`, the content's extent in the space it's drawn in, if it's a gradient or image without its own placement.
|
||||
pub fn fitted_paint(paint: &Graphic, content_bounds: [DVec2; 2]) -> Option<Graphic> {
|
||||
let unplaced = match paint {
|
||||
Graphic::Gradient(item) => item.attribute::<DAffine2>(ATTR_TRANSFORM).is_none(),
|
||||
Graphic::RasterCPU(item) => item.attribute::<DAffine2>(ATTR_TRANSFORM).is_none(),
|
||||
Graphic::RasterGPU(item) => item.attribute::<DAffine2>(ATTR_TRANSFORM).is_none(),
|
||||
_ => false,
|
||||
};
|
||||
if !unplaced {
|
||||
return None;
|
||||
}
|
||||
|
||||
let fit = DAffine2::from_translation(content_bounds[0]) * DAffine2::from_scale(content_bounds[1] - content_bounds[0]);
|
||||
let mut paint = paint.clone();
|
||||
match &mut paint {
|
||||
Graphic::Gradient(item) => item.set_attribute(ATTR_TRANSFORM, fit),
|
||||
Graphic::RasterCPU(item) => item.set_attribute(ATTR_TRANSFORM, fit),
|
||||
Graphic::RasterGPU(item) => item.set_attribute(ATTR_TRANSFORM, fit),
|
||||
_ => {}
|
||||
}
|
||||
Some(paint)
|
||||
}
|
||||
|
||||
/// One image operation of an [`Effects`] list: an [`EffectKind`] plus its parameters, carried as attributes on the inner item.
|
||||
/// Each parameter's attribute is named after the input of the node that stamps the kind. Attributes the kind doesn't take are ignored.
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct Effect(pub Item<EffectKind>);
|
||||
|
||||
impl Effect {
|
||||
/// Creates an effect row carrying out the given operation, stamping only the parameters that differ from their implicit defaults.
|
||||
pub fn new(operation: &EffectOperation) -> Self {
|
||||
let mut item = Item::new_from_element(operation.kind());
|
||||
operation.clone().visit_parameters(&mut WriteParameters(&mut item));
|
||||
Self(item)
|
||||
}
|
||||
|
||||
/// This effect's kind.
|
||||
pub fn kind(&self) -> EffectKind {
|
||||
*self.0.element()
|
||||
}
|
||||
|
||||
/// Decodes the parameters into an [`EffectOperation`], falling back to the default for any absent attribute.
|
||||
pub fn operation(&self) -> EffectOperation {
|
||||
let mut operation = EffectOperation::placeholder(self.kind());
|
||||
operation.visit_parameters(&mut ReadParameters(&|key| self.0.attributes().get_any(key)));
|
||||
|
||||
// A solid paint mixes the same into every pixel, so the renderers carry it out with the other adjustments
|
||||
match operation {
|
||||
EffectOperation::PaintOverlay {
|
||||
paint: Graphic::Color(color),
|
||||
blend_mode,
|
||||
opacity,
|
||||
} => EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||||
color: *color.element(),
|
||||
blend_mode,
|
||||
opacity,
|
||||
}),
|
||||
operation => operation,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An item's ordered list of effects. A blur acts on the result of those before it, while shadows and glows are cast from the content and stack in order beneath it (or within it, for an inner shadow).
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct Effects(pub List<Effect>);
|
||||
|
||||
impl Effects {
|
||||
/// Creates the list of rows carrying out the given operations in order.
|
||||
pub fn from_operations(operations: impl IntoIterator<Item = EffectOperation>) -> Self {
|
||||
let mut effects = Self::default();
|
||||
for operation in operations {
|
||||
effects.0.push(Item::new_from_element(Effect::new(&operation)));
|
||||
}
|
||||
effects
|
||||
}
|
||||
|
||||
/// The effects in the order they're carried out.
|
||||
pub fn effects(&self) -> impl Iterator<Item = &Effect> {
|
||||
self.0.iter_element_values()
|
||||
}
|
||||
|
||||
/// The effects after the first `count`.
|
||||
pub fn after(&self, count: usize) -> Self {
|
||||
let mut remaining = Self::default();
|
||||
for effect in self.effects().skip(count) {
|
||||
remaining.0.push(Item::new_from_element(effect.clone()));
|
||||
}
|
||||
remaining
|
||||
}
|
||||
|
||||
/// The effects decoded into the operations renderers carry out, in order.
|
||||
pub fn operations(&self) -> impl Iterator<Item = EffectOperation> + '_ {
|
||||
self.effects().map(Effect::operation)
|
||||
}
|
||||
|
||||
/// How far past the content the effects together can paint, in document pixels.
|
||||
pub fn reach(&self) -> f64 {
|
||||
self.operations().map(|operation| operation.reach()).sum()
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.0.len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.0.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// How far an outline of `weight` reaches outside the silhouette's edge and inside it, by where it's aligned.
|
||||
pub fn outline_extents(weight: f64, align: StrokeAlign) -> (f64, f64) {
|
||||
match align {
|
||||
StrokeAlign::Outside => (weight, 0.),
|
||||
StrokeAlign::Inside => (0., weight),
|
||||
StrokeAlign::Center => (weight / 2., weight / 2.),
|
||||
}
|
||||
}
|
||||
|
||||
/// Appends an effect to the item's list, after those already applied to it.
|
||||
pub fn stamp_effect<T>(item: &mut Item<T>, effect: Effect) {
|
||||
item.attribute_mut_or_insert_default::<Effects>(ATTR_EFFECTS).0.push(Item::new_from_element(effect));
|
||||
}
|
||||
|
||||
/// An effect's parameters decoded from its row, the form that renderers carry it out from. Lengths are in document pixels.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum EffectOperation {
|
||||
Blur {
|
||||
/// The standard deviation of the Gaussian, or the half width of the box.
|
||||
radius: f64,
|
||||
/// Whether to average a box of pixels rather than weighting them by a Gaussian.
|
||||
box_blur: bool,
|
||||
/// Whether to blend the colors with their gamma encoding rather than in linear light.
|
||||
gamma: bool,
|
||||
},
|
||||
DropShadow {
|
||||
color: Color,
|
||||
offset: DVec2,
|
||||
blur: f64,
|
||||
spread: f64,
|
||||
},
|
||||
InnerShadow {
|
||||
color: Color,
|
||||
offset: DVec2,
|
||||
blur: f64,
|
||||
spread: f64,
|
||||
},
|
||||
OuterGlow {
|
||||
color: Color,
|
||||
blur: f64,
|
||||
spread: f64,
|
||||
},
|
||||
InnerGlow {
|
||||
color: Color,
|
||||
blur: f64,
|
||||
/// How far the glow grows into the content before it softens.
|
||||
choke: f64,
|
||||
source: GlowSource,
|
||||
},
|
||||
Satin {
|
||||
color: Color,
|
||||
/// How far each of the two casts of the silhouette is moved, in opposite directions.
|
||||
offset: DVec2,
|
||||
blur: f64,
|
||||
invert: bool,
|
||||
},
|
||||
Outline {
|
||||
color: Color,
|
||||
weight: f64,
|
||||
align: StrokeAlign,
|
||||
},
|
||||
BevelAndEmboss {
|
||||
style: BevelStyle,
|
||||
/// How steep the slopes are, as a percentage.
|
||||
depth: f64,
|
||||
direction: BevelDirection,
|
||||
/// How wide the slopes are.
|
||||
size: f64,
|
||||
/// How much the highlights and shadows are blurred.
|
||||
soften: f64,
|
||||
/// The direction the light comes from, in degrees counterclockwise from the right.
|
||||
angle: f64,
|
||||
/// How high the light is above the surface, in degrees from flat to straight overhead.
|
||||
altitude: f64,
|
||||
highlight_color: Color,
|
||||
shadow_color: Color,
|
||||
},
|
||||
/// Paints over the content with a paint other than a solid color, since a solid one decodes into the color overlay adjustment instead.
|
||||
PaintOverlay {
|
||||
/// Placed in the space the content's item is, or fitted to the content's bounds if it's a gradient or image without its own placement.
|
||||
paint: Graphic,
|
||||
blend_mode: BlendMode,
|
||||
/// Percent.
|
||||
opacity: f64,
|
||||
},
|
||||
Adjustment(Adjustment),
|
||||
}
|
||||
|
||||
impl EffectOperation {
|
||||
/// The operation an effect of this kind carries out when its row gives none of its parameters, matching the defaults of the node that stamps it.
|
||||
pub fn default_for(kind: EffectKind) -> Self {
|
||||
Effect(Item::new_from_element(kind)).operation()
|
||||
}
|
||||
|
||||
pub fn kind(&self) -> EffectKind {
|
||||
match self {
|
||||
Self::Blur { .. } => EffectKind::Blur,
|
||||
Self::DropShadow { .. } => EffectKind::DropShadow,
|
||||
Self::InnerShadow { .. } => EffectKind::InnerShadow,
|
||||
Self::OuterGlow { .. } => EffectKind::OuterGlow,
|
||||
Self::InnerGlow { .. } => EffectKind::InnerGlow,
|
||||
Self::Satin { .. } => EffectKind::Satin,
|
||||
Self::Outline { .. } => EffectKind::Outline,
|
||||
Self::BevelAndEmboss { .. } => EffectKind::BevelAndEmboss,
|
||||
Self::PaintOverlay { .. } => EffectKind::PaintOverlay,
|
||||
Self::Adjustment(adjustment) => adjustment.kind(),
|
||||
}
|
||||
}
|
||||
|
||||
/// How far past the content this operation can paint, or reads from, in document pixels.
|
||||
pub fn reach(&self) -> f64 {
|
||||
// A Gaussian is negligible past three standard deviations
|
||||
match self {
|
||||
Self::Blur { radius, .. } => 3. * radius.max(0.),
|
||||
Self::DropShadow { offset, blur, spread, .. } => offset.length() + spread.max(0.) + 3. * blur.max(0.),
|
||||
Self::InnerShadow { offset, blur, .. } => offset.length() + 3. * blur.max(0.),
|
||||
Self::OuterGlow { blur, spread, .. } => spread.max(0.) + 3. * blur.max(0.),
|
||||
Self::InnerGlow { blur, choke, .. } => choke.max(0.) + 3. * blur.max(0.),
|
||||
Self::Satin { offset, blur, .. } => offset.length() + 3. * blur.max(0.),
|
||||
Self::Outline { weight, .. } => weight.max(0.),
|
||||
Self::BevelAndEmboss { size, soften, .. } => size.max(0.) + 3. * (soften.max(0.) + bevel_smoothing(*size)),
|
||||
Self::PaintOverlay { .. } | Self::Adjustment(_) => 0.,
|
||||
}
|
||||
}
|
||||
|
||||
/// An operation of this kind with arbitrary parameters, for a visitor to fill in.
|
||||
fn placeholder(kind: EffectKind) -> Self {
|
||||
match kind {
|
||||
EffectKind::Blur => Self::Blur {
|
||||
radius: 0.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
},
|
||||
EffectKind::DropShadow => Self::DropShadow {
|
||||
color: Color::TRANSPARENT,
|
||||
offset: DVec2::ZERO,
|
||||
blur: 0.,
|
||||
spread: 0.,
|
||||
},
|
||||
EffectKind::InnerShadow => Self::InnerShadow {
|
||||
color: Color::TRANSPARENT,
|
||||
offset: DVec2::ZERO,
|
||||
blur: 0.,
|
||||
spread: 0.,
|
||||
},
|
||||
EffectKind::OuterGlow => Self::OuterGlow {
|
||||
color: Color::TRANSPARENT,
|
||||
blur: 0.,
|
||||
spread: 0.,
|
||||
},
|
||||
EffectKind::InnerGlow => Self::InnerGlow {
|
||||
color: Color::TRANSPARENT,
|
||||
blur: 0.,
|
||||
choke: 0.,
|
||||
source: GlowSource::default(),
|
||||
},
|
||||
EffectKind::Satin => Self::Satin {
|
||||
color: Color::TRANSPARENT,
|
||||
offset: DVec2::ZERO,
|
||||
blur: 0.,
|
||||
invert: false,
|
||||
},
|
||||
EffectKind::Outline => Self::Outline {
|
||||
color: Color::TRANSPARENT,
|
||||
weight: 0.,
|
||||
align: StrokeAlign::default(),
|
||||
},
|
||||
EffectKind::BevelAndEmboss => Self::BevelAndEmboss {
|
||||
style: BevelStyle::default(),
|
||||
depth: 0.,
|
||||
direction: BevelDirection::default(),
|
||||
size: 0.,
|
||||
soften: 0.,
|
||||
angle: 0.,
|
||||
altitude: 0.,
|
||||
highlight_color: Color::TRANSPARENT,
|
||||
shadow_color: Color::TRANSPARENT,
|
||||
},
|
||||
EffectKind::PaintOverlay => Self::PaintOverlay {
|
||||
paint: Graphic::default(),
|
||||
blend_mode: BlendMode::default(),
|
||||
opacity: 0.,
|
||||
},
|
||||
EffectKind::Desaturate => Self::Adjustment(Adjustment::Desaturate { method: Default::default() }),
|
||||
EffectKind::GammaCorrection => Self::Adjustment(Adjustment::GammaCorrection { gamma: 0., inverse: false }),
|
||||
EffectKind::MakeOpaque => Self::Adjustment(Adjustment::MakeOpaque),
|
||||
EffectKind::BrightnessContrast => Self::Adjustment(Adjustment::BrightnessContrast {
|
||||
brightness: 0.,
|
||||
contrast: 0.,
|
||||
use_classic: false,
|
||||
classic_pivot: 0.,
|
||||
}),
|
||||
EffectKind::Levels => Self::Adjustment(Adjustment::Levels(Default::default())),
|
||||
EffectKind::Curves => Self::Adjustment(Adjustment::Curves(Default::default())),
|
||||
EffectKind::BlackAndWhite => Self::Adjustment(Adjustment::BlackAndWhite(Default::default())),
|
||||
EffectKind::HueSaturation => Self::Adjustment(Adjustment::HueSaturation(Default::default())),
|
||||
EffectKind::Invert => Self::Adjustment(Adjustment::Invert),
|
||||
EffectKind::Threshold => Self::Adjustment(Adjustment::Threshold { min_luminance: 0., max_luminance: 0. }),
|
||||
EffectKind::GradientMap => Self::Adjustment(Adjustment::GradientMap {
|
||||
gradient: Default::default(),
|
||||
reverse: false,
|
||||
}),
|
||||
EffectKind::Vibrance => Self::Adjustment(Adjustment::Vibrance { vibrance: 0., saturation: 0. }),
|
||||
EffectKind::ChannelMixer => Self::Adjustment(Adjustment::ChannelMixer(Default::default())),
|
||||
EffectKind::SelectiveColor => Self::Adjustment(Adjustment::SelectiveColor(Default::default())),
|
||||
EffectKind::Posterize => Self::Adjustment(Adjustment::Posterize { levels: 0 }),
|
||||
EffectKind::Exposure => Self::Adjustment(Adjustment::Exposure {
|
||||
exposure: 0.,
|
||||
offset: 0.,
|
||||
gamma_correction: 0.,
|
||||
}),
|
||||
EffectKind::ColorBalance => Self::Adjustment(Adjustment::ColorBalance(Default::default())),
|
||||
EffectKind::PhotoFilter => Self::Adjustment(Adjustment::PhotoFilter {
|
||||
color: Color::TRANSPARENT,
|
||||
density: 0.,
|
||||
preserve_luminosity: false,
|
||||
}),
|
||||
EffectKind::ColorLookup => Self::Adjustment(Adjustment::ColorLookup { lut_file: Default::default() }),
|
||||
}
|
||||
}
|
||||
|
||||
/// Visits each parameter with the attribute it rides and its implicit default, the one listing that writing and reading rows share.
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor) {
|
||||
match self {
|
||||
Self::Blur { radius, box_blur, gamma } => {
|
||||
visitor.parameter("radius", radius, 0.);
|
||||
visitor.parameter("box_blur", box_blur, false);
|
||||
visitor.parameter("gamma", gamma, false);
|
||||
}
|
||||
Self::DropShadow { color, offset, blur, spread } | Self::InnerShadow { color, offset, blur, spread } => {
|
||||
visitor.parameter("color", color, Color::from(SRGBA8::new(0, 0, 0, 0x80)));
|
||||
visitor.parameter("offset", offset, DVec2::splat(4.));
|
||||
visitor.parameter("blur", blur, 4.);
|
||||
visitor.parameter("spread", spread, 0.);
|
||||
}
|
||||
Self::OuterGlow { color, blur, spread } => {
|
||||
visitor.parameter("color", color, Color::from(SRGBA8::new(0xff, 0xff, 0xbe, 0xbf)));
|
||||
visitor.parameter("blur", blur, 8.);
|
||||
visitor.parameter("spread", spread, 0.);
|
||||
}
|
||||
Self::InnerGlow { color, blur, choke, source } => {
|
||||
visitor.parameter("color", color, Color::from(SRGBA8::new(0xff, 0xff, 0xbe, 0xbf)));
|
||||
visitor.parameter("blur", blur, 8.);
|
||||
visitor.parameter("choke", choke, 0.);
|
||||
visitor.parameter("source", source, GlowSource::default());
|
||||
}
|
||||
Self::Satin { color, offset, blur, invert } => {
|
||||
visitor.parameter("color", color, Color::from(SRGBA8::new(0, 0, 0, 0x80)));
|
||||
visitor.parameter("offset", offset, DVec2::new(10., 4.));
|
||||
visitor.parameter("blur", blur, 14.);
|
||||
visitor.parameter("invert", invert, true);
|
||||
}
|
||||
Self::Outline { color, weight, align } => {
|
||||
visitor.parameter("color", color, Color::BLACK);
|
||||
visitor.parameter("weight", weight, 3.);
|
||||
visitor.parameter("align", align, StrokeAlign::Outside);
|
||||
}
|
||||
Self::BevelAndEmboss {
|
||||
style,
|
||||
depth,
|
||||
direction,
|
||||
size,
|
||||
soften,
|
||||
angle,
|
||||
altitude,
|
||||
highlight_color,
|
||||
shadow_color,
|
||||
} => {
|
||||
visitor.parameter("style", style, BevelStyle::default());
|
||||
visitor.parameter("depth", depth, 100.);
|
||||
visitor.parameter("direction", direction, BevelDirection::default());
|
||||
visitor.parameter("size", size, 5.);
|
||||
visitor.parameter("soften", soften, 0.);
|
||||
visitor.parameter("angle", angle, 120.);
|
||||
visitor.parameter("altitude", altitude, 30.);
|
||||
visitor.parameter("highlight_color", highlight_color, Color::from(SRGBA8::new(0xff, 0xff, 0xff, 0xbf)));
|
||||
visitor.parameter("shadow_color", shadow_color, Color::from(SRGBA8::new(0, 0, 0, 0xbf)));
|
||||
}
|
||||
Self::PaintOverlay { paint, blend_mode, opacity } => {
|
||||
visitor.parameter("paint", paint, Graphic::from(Color::BLACK));
|
||||
visitor.parameter("blend_mode", blend_mode, BlendMode::default());
|
||||
visitor.parameter("opacity", opacity, 100.);
|
||||
}
|
||||
Self::Adjustment(adjustment) => adjustment.visit_parameters(visitor),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vector_types::{Gradient, GradientStop};
|
||||
|
||||
#[test]
|
||||
fn rows_round_trip_their_operations_eliding_defaults() {
|
||||
let operations = [
|
||||
EffectOperation::Blur {
|
||||
radius: 6.,
|
||||
box_blur: true,
|
||||
gamma: false,
|
||||
},
|
||||
EffectOperation::default_for(EffectKind::DropShadow),
|
||||
EffectOperation::InnerShadow {
|
||||
color: Color::RED,
|
||||
offset: DVec2::new(-2., 3.),
|
||||
blur: 1.,
|
||||
spread: 5.,
|
||||
},
|
||||
EffectOperation::OuterGlow {
|
||||
color: Color::BLUE,
|
||||
blur: 8.,
|
||||
spread: 2.,
|
||||
},
|
||||
EffectOperation::InnerGlow {
|
||||
color: Color::GREEN,
|
||||
blur: 3.,
|
||||
choke: 1.,
|
||||
source: GlowSource::Center,
|
||||
},
|
||||
EffectOperation::Satin {
|
||||
color: Color::BLACK,
|
||||
offset: DVec2::new(5., -6.),
|
||||
blur: 2.,
|
||||
invert: false,
|
||||
},
|
||||
EffectOperation::Outline {
|
||||
color: Color::RED,
|
||||
weight: 7.,
|
||||
align: StrokeAlign::Center,
|
||||
},
|
||||
EffectOperation::BevelAndEmboss {
|
||||
style: BevelStyle::PillowEmboss,
|
||||
depth: 250.,
|
||||
direction: BevelDirection::Down,
|
||||
size: 12.,
|
||||
soften: 2.,
|
||||
angle: -45.,
|
||||
altitude: 60.,
|
||||
highlight_color: Color::YELLOW,
|
||||
shadow_color: Color::BLUE,
|
||||
},
|
||||
EffectOperation::PaintOverlay {
|
||||
paint: Graphic::from(Gradient::new([0., 1.].map(|position| GradientStop {
|
||||
position,
|
||||
midpoint: 0.5,
|
||||
color: Color::from_rgbaf32_unchecked(position as f32, 0., 1., 1.),
|
||||
}))),
|
||||
blend_mode: BlendMode::Multiply,
|
||||
opacity: 60.,
|
||||
},
|
||||
EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||||
color: Color::GREEN,
|
||||
blend_mode: BlendMode::Screen,
|
||||
opacity: 100.,
|
||||
}),
|
||||
];
|
||||
|
||||
for operation in operations {
|
||||
assert_eq!(Effect::new(&operation).operation(), operation);
|
||||
}
|
||||
|
||||
// A solid paint decodes into the color overlay adjustment, which the Paint Overlay row also carries
|
||||
let solid = EffectOperation::PaintOverlay {
|
||||
paint: Graphic::from(Color::RED),
|
||||
blend_mode: BlendMode::Normal,
|
||||
opacity: 50.,
|
||||
};
|
||||
let solid_row = Effect::new(&solid);
|
||||
assert_eq!(solid_row.kind(), EffectKind::PaintOverlay);
|
||||
assert_eq!(
|
||||
solid_row.operation(),
|
||||
EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||||
color: Color::RED,
|
||||
blend_mode: BlendMode::Normal,
|
||||
opacity: 50.,
|
||||
})
|
||||
);
|
||||
|
||||
let default_row = Effect::new(&EffectOperation::default_for(EffectKind::DropShadow));
|
||||
assert_eq!(default_row.0.attributes().iter_any().count(), 0, "a default operation stamps no parameters");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adjustment_rows_elide_their_defaults_and_name_grouped_parameters() {
|
||||
use EffectKind::*;
|
||||
let kinds = [
|
||||
Desaturate,
|
||||
GammaCorrection,
|
||||
MakeOpaque,
|
||||
BrightnessContrast,
|
||||
Levels,
|
||||
Curves,
|
||||
BlackAndWhite,
|
||||
HueSaturation,
|
||||
Invert,
|
||||
Threshold,
|
||||
GradientMap,
|
||||
Vibrance,
|
||||
ChannelMixer,
|
||||
SelectiveColor,
|
||||
Posterize,
|
||||
Exposure,
|
||||
ColorBalance,
|
||||
PhotoFilter,
|
||||
ColorLookup,
|
||||
PaintOverlay,
|
||||
];
|
||||
for kind in kinds {
|
||||
let operation = EffectOperation::default_for(kind);
|
||||
assert_eq!(operation.kind(), kind);
|
||||
assert_eq!(Effect::new(&operation).0.attributes().iter_any().count(), 0, "{kind} stamps no defaults");
|
||||
}
|
||||
|
||||
// A parameter in one of the node's groups rides the attribute named with the group's prefix
|
||||
let mut levels = EffectOperation::default_for(Levels);
|
||||
if let EffectOperation::Adjustment(Adjustment::Levels(settings)) = &mut levels {
|
||||
settings.blue.midtones = 1.5;
|
||||
}
|
||||
let row = Effect::new(&levels);
|
||||
assert_eq!(row.0.attribute::<f64>("blue_midtones"), Some(&1.5));
|
||||
assert_eq!(row.operation(), levels);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
//! Procedural patterns described by their settings, rendered at whatever resolution is needed of whatever part is seen by the kernels of the `raster-kernels` crate.
|
||||
|
||||
use crate::parameters::{ParameterVisitor, ReadParameters, StampParameters};
|
||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::Item;
|
||||
use dyn_any::DynAny;
|
||||
use glam::DAffine2;
|
||||
use std::any::Any;
|
||||
|
||||
/// Style of noise pattern.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
#[widget(Dropdown)]
|
||||
pub enum NoiseType {
|
||||
#[default]
|
||||
Perlin,
|
||||
#[label("OpenSimplex2")]
|
||||
OpenSimplex2,
|
||||
#[label("OpenSimplex2S")]
|
||||
OpenSimplex2S,
|
||||
Cellular,
|
||||
ValueCubic,
|
||||
Value,
|
||||
WhiteNoise,
|
||||
}
|
||||
|
||||
/// Style of layered levels of the noise pattern.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
pub enum FractalType {
|
||||
#[default]
|
||||
None,
|
||||
#[label("Fractional Brownian Motion")]
|
||||
FBm,
|
||||
Ridged,
|
||||
PingPong,
|
||||
#[label("Progressive (Domain Warp Only)")]
|
||||
DomainWarpProgressive,
|
||||
#[label("Independent (Domain Warp Only)")]
|
||||
DomainWarpIndependent,
|
||||
}
|
||||
|
||||
/// Distance function used by the cellular noise.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
pub enum CellularDistanceFunction {
|
||||
#[default]
|
||||
Euclidean,
|
||||
#[label("Euclidean Squared (Faster)")]
|
||||
EuclideanSq,
|
||||
Manhattan,
|
||||
Hybrid,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
pub enum CellularReturnType {
|
||||
CellValue,
|
||||
#[default]
|
||||
#[label("Nearest (F1)")]
|
||||
Nearest,
|
||||
#[label("Next Nearest (F2)")]
|
||||
NextNearest,
|
||||
#[label("Average (F1 / 2 + F2 / 2)")]
|
||||
Average,
|
||||
#[label("Difference (F2 - F1)")]
|
||||
Difference,
|
||||
#[label("Product (F2 * F1 / 2)")]
|
||||
Product,
|
||||
#[label("Division (F1 / F2)")]
|
||||
Division,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
#[widget(Dropdown)]
|
||||
pub enum DomainWarpType {
|
||||
#[default]
|
||||
None,
|
||||
#[label("OpenSimplex2")]
|
||||
OpenSimplex2,
|
||||
#[label("OpenSimplex2 Reduced")]
|
||||
OpenSimplex2Reduced,
|
||||
BasicGrid,
|
||||
}
|
||||
|
||||
/// The settings of a noise pattern, with lengths measured in the document units of the space it's sampled in.
|
||||
#[derive(Debug, Clone, Default, PartialEq, CacheHash)]
|
||||
pub struct NoiseSettings {
|
||||
pub seed: i64,
|
||||
pub scale: f64,
|
||||
pub noise_type: NoiseType,
|
||||
pub domain_warp_type: DomainWarpType,
|
||||
pub domain_warp_amplitude: f64,
|
||||
pub fractal_type: FractalType,
|
||||
pub fractal_octaves: i64,
|
||||
pub fractal_lacunarity: f64,
|
||||
pub fractal_gain: f64,
|
||||
pub fractal_weighted_strength: f64,
|
||||
pub fractal_ping_pong_strength: f64,
|
||||
pub cellular_distance_function: CellularDistanceFunction,
|
||||
pub cellular_return_type: CellularReturnType,
|
||||
pub cellular_jitter: f64,
|
||||
}
|
||||
|
||||
/// A procedural pattern, a function of position in its own space that renders across any area at any resolution.
|
||||
#[derive(Debug, Clone, PartialEq, CacheHash)]
|
||||
pub enum GeneratorPattern {
|
||||
Noise(NoiseSettings),
|
||||
/// The Mandelbrot set, with the unit square spanning -2 to 1 along the real axis and -1.5 to 1.5 along the imaginary axis.
|
||||
Mandelbrot,
|
||||
}
|
||||
|
||||
/// A procedural pattern filling the whole plane, which renderers draw at whatever resolution they need across whatever part they see.
|
||||
/// The item's transform places the pattern's own space, and a noise pattern's settings ride the item as attributes named after the Noise Pattern node's parameters.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny)]
|
||||
pub enum Generator {
|
||||
#[default]
|
||||
Noise,
|
||||
/// The Mandelbrot set, with the unit square spanning -2 to 1 along the real axis and -1.5 to 1.5 along the imaginary axis.
|
||||
Mandelbrot,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Generator {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::Noise => "Noise",
|
||||
Self::Mandelbrot => "Mandelbrot",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl BoundingBox for Generator {
|
||||
fn bounding_box(&self, transform: DAffine2, _include_stroke: bool) -> RenderBoundingBox {
|
||||
match transform.matrix2.determinant() == 0. {
|
||||
true => RenderBoundingBox::None,
|
||||
false => RenderBoundingBox::Infinite,
|
||||
}
|
||||
}
|
||||
|
||||
fn thumbnail_bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
|
||||
self.bounding_box(transform, include_stroke)
|
||||
}
|
||||
}
|
||||
|
||||
impl NoiseSettings {
|
||||
/// Stamps every setting onto the generator's item, whatever its value, so which attributes the item carries doesn't depend on them.
|
||||
pub fn stamp(&self, item: &mut Item<Generator>) {
|
||||
self.clone().visit_parameters(&mut StampParameters(item));
|
||||
}
|
||||
|
||||
/// Visits each setting with the attribute it rides, named after the Noise Pattern node's parameter, and its default, which is the node's.
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor) {
|
||||
visitor.parameter("seed", &mut self.seed, 0);
|
||||
visitor.parameter("scale", &mut self.scale, 10.);
|
||||
visitor.parameter("noise_type", &mut self.noise_type, NoiseType::default());
|
||||
visitor.parameter("domain_warp_type", &mut self.domain_warp_type, DomainWarpType::default());
|
||||
visitor.parameter("domain_warp_amplitude", &mut self.domain_warp_amplitude, 100.);
|
||||
visitor.parameter("fractal_type", &mut self.fractal_type, FractalType::default());
|
||||
visitor.parameter("fractal_octaves", &mut self.fractal_octaves, 3);
|
||||
visitor.parameter("fractal_lacunarity", &mut self.fractal_lacunarity, 2.);
|
||||
visitor.parameter("fractal_gain", &mut self.fractal_gain, 0.5);
|
||||
visitor.parameter("fractal_weighted_strength", &mut self.fractal_weighted_strength, 0.);
|
||||
visitor.parameter("fractal_ping_pong_strength", &mut self.fractal_ping_pong_strength, 2.);
|
||||
visitor.parameter("cellular_distance_function", &mut self.cellular_distance_function, CellularDistanceFunction::default());
|
||||
visitor.parameter("cellular_return_type", &mut self.cellular_return_type, CellularReturnType::default());
|
||||
visitor.parameter("cellular_jitter", &mut self.cellular_jitter, 1.);
|
||||
}
|
||||
}
|
||||
|
||||
impl GeneratorPattern {
|
||||
/// The pattern a generator draws, reading a noise pattern's settings with `attribute`, which looks one of the item's attributes up by key.
|
||||
/// Each setting the item lacks takes its default.
|
||||
pub fn decode<'a>(generator: Generator, attribute: &'a dyn Fn(&str) -> Option<&'a dyn Any>) -> Self {
|
||||
match generator {
|
||||
Generator::Noise => {
|
||||
let mut settings = NoiseSettings::default();
|
||||
settings.visit_parameters(&mut ReadParameters(attribute));
|
||||
Self::Noise(settings)
|
||||
}
|
||||
Generator::Mandelbrot => Self::Mandelbrot,
|
||||
}
|
||||
}
|
||||
|
||||
/// The pattern a generator item draws.
|
||||
pub fn of_item(item: &Item<Generator>) -> Self {
|
||||
Self::decode(*item.element(), &|key| item.attributes().get_any(key))
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
use crate::appearance::{Appearance, Cover, Coverage};
|
||||
use crate::generator::Generator;
|
||||
use brush_types::Stroke;
|
||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
@@ -26,6 +27,7 @@ pub enum Graphic {
|
||||
RasterGPU(Item<Raster<GPU>>),
|
||||
Color(Item<Color>),
|
||||
Gradient(Item<Gradient>),
|
||||
Generator(Item<Generator>),
|
||||
Text(Item<String>),
|
||||
NoneList(List<none::None>),
|
||||
GraphicList(List<Graphic>),
|
||||
@@ -34,6 +36,7 @@ pub enum Graphic {
|
||||
RasterGPUList(List<Raster<GPU>>),
|
||||
ColorList(List<Color>),
|
||||
GradientList(List<Gradient>),
|
||||
GeneratorList(List<Generator>),
|
||||
TextList(List<String>),
|
||||
StrokeList(List<Stroke>),
|
||||
}
|
||||
@@ -137,6 +140,23 @@ impl From<List<Gradient>> for Graphic {
|
||||
}
|
||||
}
|
||||
|
||||
// Generator
|
||||
impl From<Generator> for Graphic {
|
||||
fn from(generator: Generator) -> Self {
|
||||
Graphic::Generator(Item::new_from_element(generator))
|
||||
}
|
||||
}
|
||||
impl From<Item<Generator>> for Graphic {
|
||||
fn from(generator: Item<Generator>) -> Self {
|
||||
Graphic::Generator(generator)
|
||||
}
|
||||
}
|
||||
impl From<List<Generator>> for Graphic {
|
||||
fn from(generator: List<Generator>) -> Self {
|
||||
Graphic::GeneratorList(generator)
|
||||
}
|
||||
}
|
||||
|
||||
// Stroke
|
||||
impl From<Stroke> for Graphic {
|
||||
fn from(stroke: Stroke) -> Self {
|
||||
@@ -312,12 +332,14 @@ pub fn bake_paint_transforms(attributes: &mut ItemAttributeValues, transform: DA
|
||||
Graphic::RasterCPU(item) => bake_item_transform(item, transform),
|
||||
Graphic::RasterGPU(item) => bake_item_transform(item, transform),
|
||||
Graphic::Gradient(item) => bake_item_transform(item, transform),
|
||||
Graphic::Generator(item) => bake_item_transform(item, transform),
|
||||
Graphic::Text(item) => bake_item_transform(item, transform),
|
||||
Graphic::GraphicList(list) => bake_list_transform(list, transform),
|
||||
Graphic::VectorList(list) => bake_list_transform(list, transform),
|
||||
Graphic::RasterCPUList(list) => bake_list_transform(list, transform),
|
||||
Graphic::RasterGPUList(list) => bake_list_transform(list, transform),
|
||||
Graphic::GradientList(list) => bake_list_transform(list, transform),
|
||||
Graphic::GeneratorList(list) => bake_list_transform(list, transform),
|
||||
Graphic::TextList(list) => bake_list_transform(list, transform),
|
||||
Graphic::StrokeList(list) => bake_list_transform(list, transform),
|
||||
// A color has no spatial extent, so there is no placement for a transform to move
|
||||
@@ -380,6 +402,16 @@ impl TryFromGraphic for Gradient {
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFromGraphic for Generator {
|
||||
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
|
||||
match graphic {
|
||||
Graphic::Generator(item) => Some(List::new_from_item(item)),
|
||||
Graphic::GeneratorList(list) => Some(list),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFromGraphic for String {
|
||||
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
|
||||
match graphic {
|
||||
@@ -418,7 +450,7 @@ impl IntoGraphicList for List<Graphic> {
|
||||
impl IntoGraphicList for List<Vector> {
|
||||
fn into_graphic_list(self) -> List<Graphic> {
|
||||
// A synthetic container, not a real group layer, so it carries no `editor:layer_path` that would
|
||||
// overwrite the inner items' own stamps when flattened back out
|
||||
// overwrite the inner items' own layer paths when flattened back out
|
||||
List::new_from_element(Graphic::VectorList(self))
|
||||
}
|
||||
}
|
||||
@@ -447,6 +479,12 @@ impl IntoGraphicList for List<Gradient> {
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoGraphicList for List<Generator> {
|
||||
fn into_graphic_list(self) -> List<Graphic> {
|
||||
List::new_from_element(Graphic::GeneratorList(self))
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoGraphicList for List<Stroke> {
|
||||
fn into_graphic_list(self) -> List<Graphic> {
|
||||
let layer_path: NodeIdPath = self.attribute_cloned_or_default(ATTR_EDITOR_LAYER_PATH, 0);
|
||||
@@ -560,6 +598,7 @@ impl Graphic {
|
||||
Graphic::RasterGPU(item) => item_clipped(item),
|
||||
Graphic::Color(item) => item_clipped(item),
|
||||
Graphic::Gradient(item) => item_clipped(item),
|
||||
Graphic::Generator(item) => item_clipped(item),
|
||||
Graphic::Text(item) => item_clipped(item),
|
||||
Graphic::NoneList(list) => all_clipped(list),
|
||||
Graphic::VectorList(list) => all_clipped(list),
|
||||
@@ -568,6 +607,7 @@ impl Graphic {
|
||||
Graphic::RasterGPUList(list) => all_clipped(list),
|
||||
Graphic::ColorList(list) => all_clipped(list),
|
||||
Graphic::GradientList(list) => all_clipped(list),
|
||||
Graphic::GeneratorList(list) => all_clipped(list),
|
||||
Graphic::TextList(list) => all_clipped(list),
|
||||
Graphic::StrokeList(list) => all_clipped(list),
|
||||
}
|
||||
@@ -606,6 +646,7 @@ impl Graphic {
|
||||
}
|
||||
Graphic::RasterCPU(_) | Graphic::RasterCPUList(_) => false,
|
||||
Graphic::RasterGPU(_) | Graphic::RasterGPUList(_) => false,
|
||||
Graphic::Generator(_) | Graphic::GeneratorList(_) => false,
|
||||
Graphic::Color(item) => item_opacity_is_full(item) && item.element().is_opaque(),
|
||||
Graphic::ColorList(list) => !list.is_empty() && every_item_has_full_opacity(list) && list.iter_element_values().all(|color| color.is_opaque()),
|
||||
// A `Clear` spread cuts off to transparency past the ends, leaving the rest of the region unpainted
|
||||
@@ -652,9 +693,11 @@ impl Graphic {
|
||||
// Their content is never inspected, so zeroed opacity is the only invisibility these can report
|
||||
Graphic::RasterCPU(item) => item_opacity_is_zero(item),
|
||||
Graphic::RasterGPU(item) => item_opacity_is_zero(item),
|
||||
Graphic::Generator(item) => item_opacity_is_zero(item),
|
||||
Graphic::Text(item) => item_opacity_is_zero(item),
|
||||
Graphic::RasterCPUList(list) => every_item_has_zero_opacity(list),
|
||||
Graphic::RasterGPUList(list) => every_item_has_zero_opacity(list),
|
||||
Graphic::GeneratorList(list) => every_item_has_zero_opacity(list),
|
||||
Graphic::TextList(list) => every_item_has_zero_opacity(list),
|
||||
Graphic::StrokeList(list) => every_item_has_zero_opacity(list),
|
||||
}
|
||||
@@ -670,11 +713,12 @@ impl Graphic {
|
||||
match self {
|
||||
// A leaf always holds exactly one element, so only the none-typed content is truly empty
|
||||
Graphic::None(_) | Graphic::NoneList(_) => true,
|
||||
Graphic::Graphic(_) | Graphic::Vector(_) | Graphic::RasterCPU(_) | Graphic::RasterGPU(_) | Graphic::Color(_) | Graphic::Gradient(_) | Graphic::Text(_) => false,
|
||||
Graphic::Graphic(_) | Graphic::Vector(_) | Graphic::RasterCPU(_) | Graphic::RasterGPU(_) | Graphic::Color(_) | Graphic::Gradient(_) | Graphic::Generator(_) | Graphic::Text(_) => false,
|
||||
Graphic::GraphicList(list) => list.is_empty(),
|
||||
Graphic::VectorList(list) => list.is_empty(),
|
||||
Graphic::ColorList(list) => list.is_empty(),
|
||||
Graphic::GradientList(list) => list.is_empty(),
|
||||
Graphic::GeneratorList(list) => list.is_empty(),
|
||||
Graphic::RasterCPUList(list) => list.is_empty(),
|
||||
Graphic::RasterGPUList(list) => list.is_empty(),
|
||||
Graphic::TextList(list) => list.is_empty(),
|
||||
@@ -831,6 +875,7 @@ impl BoundingBox for Graphic {
|
||||
Graphic::RasterGPU(item) => item.bounding_box(transform, include_stroke),
|
||||
Graphic::Color(item) => item.bounding_box(transform, include_stroke),
|
||||
Graphic::Gradient(item) => item.bounding_box(transform, include_stroke),
|
||||
Graphic::Generator(item) => item.bounding_box(transform, include_stroke),
|
||||
Graphic::Text(item) => item.bounding_box(transform, include_stroke),
|
||||
Graphic::VectorList(list) => vector_list_bounding_box(list, transform, include_stroke),
|
||||
Graphic::RasterCPUList(list) => list.bounding_box(transform, include_stroke),
|
||||
@@ -838,6 +883,7 @@ impl BoundingBox for Graphic {
|
||||
Graphic::GraphicList(list) => list.bounding_box(transform, include_stroke),
|
||||
Graphic::ColorList(list) => list.bounding_box(transform, include_stroke),
|
||||
Graphic::GradientList(list) => list.bounding_box(transform, include_stroke),
|
||||
Graphic::GeneratorList(list) => list.bounding_box(transform, include_stroke),
|
||||
Graphic::TextList(list) => list.bounding_box(transform, include_stroke),
|
||||
Graphic::StrokeList(list) => list.bounding_box(transform, include_stroke),
|
||||
}
|
||||
@@ -852,6 +898,7 @@ impl BoundingBox for Graphic {
|
||||
Graphic::RasterGPU(item) => item.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::Color(item) => item.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::Gradient(item) => item.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::Generator(item) => item.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::Text(item) => item.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::VectorList(vector) => vector_list_bounding_box(vector, transform, include_stroke),
|
||||
Graphic::RasterCPUList(raster) => raster.thumbnail_bounding_box(transform, include_stroke),
|
||||
@@ -859,6 +906,7 @@ impl BoundingBox for Graphic {
|
||||
Graphic::GraphicList(list) => list.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::ColorList(color) => color.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::GradientList(gradient) => gradient.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::GeneratorList(generator) => generator.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::TextList(list) => list.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::StrokeList(list) => list.thumbnail_bounding_box(transform, include_stroke),
|
||||
}
|
||||
@@ -946,7 +994,7 @@ mod tests {
|
||||
Graphic::VectorList(List::new_from_element(Vector::default()))
|
||||
}
|
||||
|
||||
fn vector_list_stamped_with_layers(layers: [u64; 2]) -> List<Vector> {
|
||||
fn vector_list_with_layer_paths(layers: [u64; 2]) -> List<Vector> {
|
||||
let mut list = List::new();
|
||||
|
||||
for layer in layers {
|
||||
@@ -961,13 +1009,13 @@ mod tests {
|
||||
// The wrapper minted for a typed list is a container rather than a layer, so it must never claim a layer path
|
||||
#[test]
|
||||
fn wrapping_a_typed_list_leaves_the_wrapper_anonymous() {
|
||||
let graphic_list = vector_list_stamped_with_layers([7, 9]).into_graphic_list();
|
||||
let graphic_list = vector_list_with_layer_paths([7, 9]).into_graphic_list();
|
||||
|
||||
assert_eq!(graphic_list.len(), 1);
|
||||
assert!(!graphic_list.attribute_keys().any(|key| key == ATTR_EDITOR_LAYER_PATH));
|
||||
}
|
||||
|
||||
fn layer_stamps(flattened: &List<Vector>) -> Vec<Option<NodeId>> {
|
||||
fn item_layers(flattened: &List<Vector>) -> Vec<Option<NodeId>> {
|
||||
(0..flattened.len())
|
||||
.map(|index| {
|
||||
flattened
|
||||
@@ -980,22 +1028,22 @@ mod tests {
|
||||
.collect()
|
||||
}
|
||||
|
||||
// Round-tripping through that wrapper must not collapse the items' distinct stamps onto item 0's
|
||||
// Round-tripping through that wrapper must not collapse the items' distinct layer paths onto item 0's
|
||||
#[test]
|
||||
fn round_trip_through_the_wrapper_preserves_per_item_layer_paths() {
|
||||
let flattened: List<Vector> = vector_list_stamped_with_layers([7, 9]).into_flattened_list();
|
||||
let flattened: List<Vector> = vector_list_with_layer_paths([7, 9]).into_flattened_list();
|
||||
|
||||
assert_eq!(layer_stamps(&flattened), [Some(NodeId(7)), Some(NodeId(9))]);
|
||||
assert_eq!(item_layers(&flattened), [Some(NodeId(7)), Some(NodeId(9))]);
|
||||
}
|
||||
|
||||
// The embedding adapter reaches the same flattened stamps as the wrapper, each item carrying its own inside its variant
|
||||
// The embedding adapter reaches the same flattened layer paths as the wrapper, each item carrying its own inside its variant
|
||||
#[test]
|
||||
fn embedding_each_item_preserves_per_item_layer_paths() {
|
||||
let embedded: List<Graphic> = vector_list_stamped_with_layers([7, 9]).into_iter().map(|item| Item::new_from_element(Graphic::from(item))).collect();
|
||||
let embedded: List<Graphic> = vector_list_with_layer_paths([7, 9]).into_iter().map(|item| Item::new_from_element(Graphic::from(item))).collect();
|
||||
|
||||
let flattened: List<Vector> = embedded.into_flattened_list();
|
||||
|
||||
assert_eq!(layer_stamps(&flattened), [Some(NodeId(7)), Some(NodeId(9))]);
|
||||
assert_eq!(item_layers(&flattened), [Some(NodeId(7)), Some(NodeId(9))]);
|
||||
}
|
||||
|
||||
// Flattening must not invent attributes that neither the parent graphic nor the child carried
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
pub mod adjustment;
|
||||
pub mod appearance;
|
||||
pub mod artboard;
|
||||
pub mod effects;
|
||||
pub mod generator;
|
||||
pub mod graphic;
|
||||
pub(crate) mod parameters;
|
||||
|
||||
// Re-export all transitive dependencies so downstream crates only need to depend on graphic-types
|
||||
pub use core_types;
|
||||
@@ -8,8 +12,11 @@ pub use raster_types;
|
||||
pub use vector_types;
|
||||
|
||||
// Re-export commonly used types at the crate root
|
||||
pub use adjustment::Adjustment;
|
||||
pub use appearance::{Appearance, Cover, CoverPlacement, Coverage, FillAndStroke, stamp_coverage};
|
||||
pub use artboard::Artboard;
|
||||
pub use effects::{BevelDirection, BevelStyle, Effect, EffectKind, EffectOperation, Effects, GlowSource, fitted_paint, stamp_effect};
|
||||
pub use generator::Generator;
|
||||
pub use graphic::{Graphic, IntoGraphicList, TryFromGraphic, Vector};
|
||||
|
||||
pub mod migrations {
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
//! Parameters riding an item as attributes, each read as its default when absent, which one listing per operation both writes and reads.
|
||||
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::Item;
|
||||
use std::any::Any;
|
||||
use std::fmt::Debug;
|
||||
|
||||
/// What a value needs to ride an attribute.
|
||||
pub(crate) trait ParameterValue: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static {}
|
||||
impl<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static> ParameterValue for T {}
|
||||
|
||||
/// Handles each parameter of an operation, given the attribute key it rides and its default.
|
||||
pub(crate) trait ParameterVisitor {
|
||||
fn parameter<T: ParameterValue>(&mut self, key: &str, value: &mut T, default: T);
|
||||
}
|
||||
|
||||
/// Stamps each parameter that differs from its default onto an item, for rows whose attributes are part of their value.
|
||||
pub(crate) struct WriteParameters<'a, T>(pub &'a mut Item<T>);
|
||||
|
||||
impl<T> ParameterVisitor for WriteParameters<'_, T> {
|
||||
fn parameter<U: ParameterValue>(&mut self, key: &str, value: &mut U, default: U) {
|
||||
if *value != default {
|
||||
self.0.set_attribute(key, value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Stamps every parameter onto an item, for an item on a wire, whose attributes mustn't come and go with their values.
|
||||
pub(crate) struct StampParameters<'a, T>(pub &'a mut Item<T>);
|
||||
|
||||
impl<T> ParameterVisitor for StampParameters<'_, T> {
|
||||
fn parameter<U: ParameterValue>(&mut self, key: &str, value: &mut U, _default: U) {
|
||||
self.0.set_attribute(key, value.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads each parameter from the attribute that the lookup finds by key, or its default where there's none.
|
||||
pub(crate) struct ReadParameters<'a>(pub &'a dyn Fn(&str) -> Option<&'a dyn Any>);
|
||||
|
||||
impl ParameterVisitor for ReadParameters<'_> {
|
||||
fn parameter<T: ParameterValue>(&mut self, key: &str, value: &mut T, default: T) {
|
||||
*value = (self.0)(key).and_then(|value| value.downcast_ref::<T>()).cloned().unwrap_or(default);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
[package]
|
||||
name = "raster-kernels"
|
||||
description = "The kernels carrying out Graphene's raster operations, such as each color adjustment"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
readme.workspace = true
|
||||
homepage.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
# Local dependencies
|
||||
core-types = { workspace = true }
|
||||
graphene-resource = { workspace = true }
|
||||
graphic-types = { workspace = true }
|
||||
raster-types = { workspace = true }
|
||||
vector-types = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
fastnoise-lite = { workspace = true }
|
||||
glam = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
@@ -0,0 +1,126 @@
|
||||
//! Bakes runs of adjustments into the lookup tables the GPU carries them out with, sampling the CPU kernels so the two agree by construction.
|
||||
|
||||
use crate::adjustments::adjust_colors;
|
||||
use core_types::Color;
|
||||
use graphic_types::adjustment::Adjustment;
|
||||
|
||||
/// Entries in a one-dimensional table, enough that interpolating between them strays less than a level from even a steep curve.
|
||||
pub const CURVE_TABLE_SIZE: usize = 4096;
|
||||
|
||||
/// Grid points along each axis of a color cube, enough that interpolating within its tetrahedra stays within a few levels of the smooth kernels.
|
||||
pub const CUBE_SIZE: usize = 65;
|
||||
|
||||
/// Grid points along each axis of a draft color cube, an eighth the work of [`CUBE_SIZE`] for settings changing every frame, at about three times its error.
|
||||
pub const DRAFT_CUBE_SIZE: usize = 33;
|
||||
|
||||
/// One pass of the GPU's adjustment shader, with the tables it looks colors up in. Values are gamma-encoded.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum AdjustmentPass {
|
||||
/// The red, green, blue, and alpha channels each through their own curve, sampled at [`CURVE_TABLE_SIZE`] values from 0 to 1.
|
||||
Curves(Vec<[f32; 4]>),
|
||||
/// Colors through a cube of `size` samples along each of red, green, and blue, with red varying fastest and blue slowest.
|
||||
/// Alpha passes through its own curve of [`CURVE_TABLE_SIZE`] samples.
|
||||
Cube { size: usize, colors: Vec<[f32; 3]>, alpha: Vec<f32> },
|
||||
/// Each color replaced by the entry of [`CURVE_TABLE_SIZE`] its luma (the weighted sum of its channels) picks, keeping its alpha.
|
||||
Luma { weights: [f32; 3], colors: Vec<[f32; 3]> },
|
||||
/// Vibrance, whose steep toe near black no table captures, computed directly from its amounts in -1..1 and its saturation scale.
|
||||
Vibrance { vibrance: f32, saturation_scale: f32 },
|
||||
}
|
||||
|
||||
impl AdjustmentPass {
|
||||
/// The passes that carry out `adjustments` in order, merging each run of those a table can capture into one pass, with cubes of `cube_size` along each side.
|
||||
pub fn plan(adjustments: &[Adjustment], cube_size: usize) -> Vec<Self> {
|
||||
let mut passes = Vec::new();
|
||||
let mut run: Vec<&Adjustment> = Vec::new();
|
||||
|
||||
for adjustment in adjustments {
|
||||
let own_pass = match adjustment {
|
||||
Adjustment::Vibrance { vibrance, saturation } => Some(Self::Vibrance {
|
||||
vibrance: (vibrance / 100.) as f32,
|
||||
saturation_scale: (1. + saturation / 100.) as f32,
|
||||
}),
|
||||
// A step in luma, which a table of luma keeps sharp where a cube would blur it
|
||||
Adjustment::Threshold { .. } => Some(Self::Luma {
|
||||
weights: [4915., 9667., 1802.].map(|weight| weight / 16384.),
|
||||
colors: luma_table(adjustment, [4915., 9667., 1802.].map(|weight| weight / 16384.)),
|
||||
}),
|
||||
// A gradient's hard stops are steps too
|
||||
Adjustment::GradientMap { .. } => Some(Self::Luma {
|
||||
weights: [0.3, 0.59, 0.11],
|
||||
colors: luma_table(adjustment, [0.3, 0.59, 0.11]),
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
match own_pass {
|
||||
Some(pass) => {
|
||||
passes.extend(Self::from_run(&run, cube_size));
|
||||
run.clear();
|
||||
passes.push(pass);
|
||||
}
|
||||
None => run.push(adjustment),
|
||||
}
|
||||
}
|
||||
passes.extend(Self::from_run(&run, cube_size));
|
||||
|
||||
passes
|
||||
}
|
||||
|
||||
/// Whether any of the passes looks colors up in a cube, the only table whose size varies.
|
||||
pub fn any_cube(passes: &[Self]) -> bool {
|
||||
passes.iter().any(|pass| matches!(pass, Self::Cube { .. }))
|
||||
}
|
||||
|
||||
/// One pass carrying out a run of adjustments in order, as four curves if each acts on the channels separately, or else as a cube.
|
||||
fn from_run(run: &[&Adjustment], cube_size: usize) -> Option<Self> {
|
||||
if run.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let apply_run = |colors: &mut [Color]| run.iter().for_each(|adjustment| adjust_colors(adjustment, colors));
|
||||
|
||||
// The color channels never read alpha, and alpha depends on alpha alone, so one ramp feeds every channel at once
|
||||
let mut ramp: Vec<Color> = (0..CURVE_TABLE_SIZE)
|
||||
.map(|index| {
|
||||
let value = index as f32 / (CURVE_TABLE_SIZE - 1) as f32;
|
||||
Color::from_gamma_srgb_channels(value, value, value, value)
|
||||
})
|
||||
.collect();
|
||||
apply_run(&mut ramp);
|
||||
let ramp: Vec<[f32; 4]> = ramp.iter().map(Color::to_gamma_srgb_channels).collect();
|
||||
|
||||
if run.iter().all(|adjustment| adjustment.is_per_channel()) {
|
||||
return Some(Self::Curves(ramp));
|
||||
}
|
||||
|
||||
let step = |index: usize| index as f32 / (cube_size - 1) as f32;
|
||||
let mut cube = Vec::with_capacity(cube_size.pow(3));
|
||||
for blue in 0..cube_size {
|
||||
for green in 0..cube_size {
|
||||
for red in 0..cube_size {
|
||||
cube.push(Color::from_gamma_srgb_channels(step(red), step(green), step(blue), 1.));
|
||||
}
|
||||
}
|
||||
}
|
||||
apply_run(&mut cube);
|
||||
|
||||
Some(Self::Cube {
|
||||
size: cube_size,
|
||||
colors: cube.iter().map(|color| color.to_gamma_srgb_channels()).map(|[red, green, blue, _]| [red, green, blue]).collect(),
|
||||
alpha: ramp.iter().map(|channels| channels[3]).collect(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The adjustment's results for grays of each luma, which stand for every color of that luma when the adjustment reads only its luma.
|
||||
fn luma_table(adjustment: &Adjustment, weights: [f32; 3]) -> Vec<[f32; 3]> {
|
||||
let total: f32 = weights.iter().sum();
|
||||
let mut grays: Vec<Color> = (0..CURVE_TABLE_SIZE)
|
||||
.map(|index| {
|
||||
let value = index as f32 / (CURVE_TABLE_SIZE - 1) as f32 / total;
|
||||
Color::from_gamma_srgb_channels(value, value, value, 1.)
|
||||
})
|
||||
.collect();
|
||||
adjust_colors(adjustment, &mut grays);
|
||||
|
||||
grays.iter().map(|color| color.to_gamma_srgb_channels()).map(|[red, green, blue, _]| [red, green, blue]).collect()
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,26 @@
|
||||
//! The kernels blending one color with another.
|
||||
|
||||
use crate::MapColor;
|
||||
use core_types::Color;
|
||||
use core_types::blending::{BlendMode, apply_blend_mode};
|
||||
|
||||
pub(crate) struct ColorOverlay {
|
||||
pub(crate) color: Color,
|
||||
pub(crate) blend_mode: BlendMode,
|
||||
pub(crate) opacity: f32,
|
||||
}
|
||||
|
||||
impl MapColor for ColorOverlay {
|
||||
fn map_cpu(&self, pixel: Color) -> Color {
|
||||
overlay_paint(pixel, self.color, self.blend_mode, self.opacity)
|
||||
}
|
||||
}
|
||||
|
||||
/// The color with `paint` mixed over it by the blend mode, as much as the paint's alpha times `opacity` (from 0 to 1), keeping the color's own alpha.
|
||||
pub fn overlay_paint(color: Color, paint: Color, blend_mode: BlendMode, opacity: f32) -> Color {
|
||||
let overlay = apply_blend_mode(paint, color, blend_mode);
|
||||
let amount = opacity * paint.a();
|
||||
let mix = |under: f32, over: f32| under + (over - under) * amount;
|
||||
|
||||
Color::from_rgbaf32_unchecked(mix(color.r(), overlay.r()), mix(color.g(), overlay.g()), mix(color.b(), overlay.b()), color.a())
|
||||
}
|
||||
+56
-29
@@ -8,35 +8,60 @@ mod format_look;
|
||||
|
||||
use crate::adjustments::{SRGB_TO_XYZ_D50, WHITE_XYZ_D50, XYZ_D50_TO_SRGB, multiply_matrix};
|
||||
use core_types::color::{linear_to_srgb, srgb_to_linear};
|
||||
use graphene_resource::{Resource, ResourceHash};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use graphene_resource::{Resource, ResourceHash, WeakResource};
|
||||
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
|
||||
|
||||
pub const LUT_FILE_EXTENSIONS: &[&str] = &["cube", "3dl", "look", "csp", "icc", "icm"];
|
||||
|
||||
/// A file's parse result, in the form the cache shares out.
|
||||
type ParsedLut = Result<Arc<Lut>, LutParseError>;
|
||||
|
||||
/// The last file a node parsed, kept as the node's own data so the file is not parsed anew each time the node runs again.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct LutCache(Arc<Mutex<Option<(ResourceHash, ParsedLut)>>>);
|
||||
/// A parse result, kept while the file it came from is still loaded somewhere.
|
||||
struct ParsedFile {
|
||||
hash: ResourceHash,
|
||||
file: WeakResource,
|
||||
parsed: ParsedLut,
|
||||
}
|
||||
|
||||
impl LutCache {
|
||||
/// [`Lut::parse`] for a resource, reusing the last result while the file's content hash stays the same.
|
||||
pub fn parse(&self, resource: &Resource) -> ParsedLut {
|
||||
// A lock poisoned by a panic elsewhere still guards a usable cache
|
||||
let mut cached = self.0.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
/// The parse results of the files that are still loaded, shared by every adjustment that reads a lookup table.
|
||||
static PARSED_FILES: Mutex<Vec<ParsedFile>> = Mutex::new(Vec::new());
|
||||
|
||||
let hash = resource.hash();
|
||||
if let Some((cached_hash, result)) = cached.as_ref()
|
||||
&& *cached_hash == hash
|
||||
{
|
||||
return result.clone();
|
||||
fn parsed_files() -> MutexGuard<'static, Vec<ParsedFile>> {
|
||||
// A lock poisoned by a panic elsewhere still guards a usable cache
|
||||
PARSED_FILES.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// [`Lut::parse`] for a resource, reusing the result for as long as a file with the same content hash stays loaded. O(n) in the loaded files.
|
||||
pub fn parse_cached(resource: &Resource) -> ParsedLut {
|
||||
let hash = resource.hash();
|
||||
|
||||
{
|
||||
let mut parsed_files = parsed_files();
|
||||
|
||||
// Follows the copy in hand before pruning, in case another copy of the same content is the one that went away
|
||||
let cached = parsed_files.iter_mut().find(|entry| entry.hash == hash).map(|entry| {
|
||||
entry.file = resource.downgrade();
|
||||
entry.parsed.clone()
|
||||
});
|
||||
parsed_files.retain(|entry| entry.file.is_alive());
|
||||
|
||||
if let Some(parsed) = cached {
|
||||
return parsed;
|
||||
}
|
||||
|
||||
let result = Lut::parse(resource).map(Arc::new);
|
||||
*cached = Some((hash, result.clone()));
|
||||
result
|
||||
}
|
||||
|
||||
// Parsed outside the lock, so a large file doesn't hold up the adjustments reading other files
|
||||
let parsed = Lut::parse(resource).map(Arc::new);
|
||||
|
||||
let mut parsed_files = parsed_files();
|
||||
if !parsed_files.iter().any(|entry| entry.hash == hash) {
|
||||
parsed_files.push(ParsedFile {
|
||||
hash,
|
||||
file: resource.downgrade(),
|
||||
parsed: parsed.clone(),
|
||||
});
|
||||
}
|
||||
parsed
|
||||
}
|
||||
|
||||
/// Why a file could not be read as a lookup table.
|
||||
@@ -423,18 +448,20 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cache_parses_a_file_once_until_the_file_changes() {
|
||||
let file = Resource::new(b"LUT_1D_SIZE 2\n0 0 0\n1 1 1\n".to_vec());
|
||||
let cache = LutCache::default();
|
||||
let first = cache.parse(&file).unwrap();
|
||||
assert!(Arc::ptr_eq(&first, &cache.parse(&file).unwrap()));
|
||||
fn the_cache_parses_a_file_once_while_it_stays_loaded() {
|
||||
let file = Resource::new(b"LUT_1D_SIZE 2\n0 0 0\n0.5 1 1\n".to_vec());
|
||||
let first = parse_cached(&file).unwrap();
|
||||
|
||||
// A cloned node shares its cache
|
||||
assert!(Arc::ptr_eq(&first, &cache.clone().parse(&file).unwrap()));
|
||||
// Any number of other files, failed ones included, leave it in place
|
||||
let others: Vec<Resource> = (0..20).map(|index| Resource::new(format!("not a table {index}").into_bytes())).collect();
|
||||
others.iter().for_each(|other| assert!(parse_cached(other).is_err()));
|
||||
assert!(Arc::ptr_eq(&first, &parse_cached(&file).unwrap()));
|
||||
|
||||
// Another file takes its place, a failed one included
|
||||
assert!(cache.parse(&Resource::new(b"hello world".to_vec())).is_err());
|
||||
assert!(!Arc::ptr_eq(&first, &cache.parse(&file).unwrap()));
|
||||
// Once no copy of it is loaded, parsing another file clears it out
|
||||
let content = file.to_vec();
|
||||
drop(file);
|
||||
assert!(parse_cached(&Resource::new(b"not a table either".to_vec())).is_err());
|
||||
assert!(!Arc::ptr_eq(&first, &parse_cached(&Resource::new(content)).unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,423 @@
|
||||
//! The image operations that effects are built from, on the CPU: blurring, growing shapes, and shifting.
|
||||
//! They mirror the renderer's GPU passes, so a raster's effects read the same in a node that needs its pixels as on the canvas.
|
||||
|
||||
use raster_types::parallel_rows::fill_rows;
|
||||
|
||||
/// Blurs and spreads shorter than this, in pixels, leave no visible trace.
|
||||
pub const NEGLIGIBLE_LENGTH: f64 = 0.01;
|
||||
|
||||
/// The largest Gaussian standard deviation, in pixels, convolved on the image itself rather than a halved copy.
|
||||
pub const MAX_DIRECT_GAUSSIAN_SIGMA: f64 = 8.;
|
||||
|
||||
/// The largest box half width, in pixels, convolved on the image itself rather than a halved copy.
|
||||
pub const MAX_DIRECT_BOX_RADIUS: f64 = 24.;
|
||||
|
||||
/// The farthest texel from the center a kernel weighs, which fits both direct limits.
|
||||
pub const MAX_KERNEL_REACH: usize = 24;
|
||||
|
||||
/// The most times an image is halved for a blur, by which point it is one pixel across.
|
||||
const MAX_LEVELS: u32 = 16;
|
||||
|
||||
/// A blur's kernel along one axis, sized in pixels.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum BlurKernel {
|
||||
Gaussian { sigma: f64 },
|
||||
Box { radius: f64 },
|
||||
}
|
||||
|
||||
impl BlurKernel {
|
||||
/// How many times the image is halved before the kernel runs, so the kernel stays within [`MAX_KERNEL_REACH`].
|
||||
pub fn levels(self) -> u32 {
|
||||
let (length, direct_limit) = match self {
|
||||
Self::Gaussian { sigma } => (sigma, MAX_DIRECT_GAUSSIAN_SIGMA),
|
||||
Self::Box { radius } => (radius, MAX_DIRECT_BOX_RADIUS),
|
||||
};
|
||||
|
||||
(length / direct_limit).log2().ceil().clamp(0., MAX_LEVELS as f64) as u32
|
||||
}
|
||||
|
||||
/// The weights of the texels from the center outward for an image halved `levels` times, normalized so the symmetric kernel sums to 1.
|
||||
pub fn weights(self, levels: u32) -> Vec<f64> {
|
||||
let level_scale = (1 << levels) as f64;
|
||||
|
||||
let weights: Vec<f64> = match self {
|
||||
Self::Gaussian { sigma } => {
|
||||
// Halving the image and doubling it back blur it too, so the kernel makes up only the rest of the variance
|
||||
let pyramid_variance = (4_f64.powi(levels as i32) - 1.) / 3.;
|
||||
let sigma = (sigma * sigma - pyramid_variance).max(0.).sqrt() / level_scale;
|
||||
if sigma < NEGLIGIBLE_LENGTH {
|
||||
return vec![1.];
|
||||
}
|
||||
|
||||
let reach = ((3. * sigma).ceil() as usize).min(MAX_KERNEL_REACH);
|
||||
(0..=reach).map(|i| (-((i * i) as f64) / (2. * sigma * sigma)).exp()).collect()
|
||||
}
|
||||
// The texels at the ends weigh only the fraction of them the box covers, so the blur grows smoothly with its radius
|
||||
Self::Box { radius } => {
|
||||
let radius = radius / level_scale;
|
||||
let reach = (radius.ceil() as usize).min(MAX_KERNEL_REACH);
|
||||
(0..=reach).map(|i| (radius + 1. - i as f64).clamp(0., 1.)).collect()
|
||||
}
|
||||
};
|
||||
|
||||
let total = weights[0] + 2. * weights[1..].iter().sum::<f64>();
|
||||
weights.into_iter().map(|weight| weight / total).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// A pixel value the operations can weigh, sum, and compare: one coverage channel, or premultiplied color channels.
|
||||
pub trait Sample: Copy + Default + Send + Sync {
|
||||
fn scaled(self, factor: f32) -> Self;
|
||||
fn plus(self, other: Self) -> Self;
|
||||
fn max(self, other: Self) -> Self;
|
||||
}
|
||||
|
||||
impl Sample for f32 {
|
||||
fn scaled(self, factor: f32) -> Self {
|
||||
self * factor
|
||||
}
|
||||
fn plus(self, other: Self) -> Self {
|
||||
self + other
|
||||
}
|
||||
fn max(self, other: Self) -> Self {
|
||||
f32::max(self, other)
|
||||
}
|
||||
}
|
||||
|
||||
impl Sample for [f32; 4] {
|
||||
fn scaled(self, factor: f32) -> Self {
|
||||
self.map(|channel| channel * factor)
|
||||
}
|
||||
fn plus(self, other: Self) -> Self {
|
||||
std::array::from_fn(|channel| self[channel] + other[channel])
|
||||
}
|
||||
fn max(self, other: Self) -> Self {
|
||||
std::array::from_fn(|channel| self[channel].max(other[channel]))
|
||||
}
|
||||
}
|
||||
|
||||
/// An image of [`Sample`]s in rows, which the operations read and write.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Plane<T> {
|
||||
pub width: usize,
|
||||
pub height: usize,
|
||||
pub data: Vec<T>,
|
||||
}
|
||||
|
||||
impl<T: Sample> Plane<T> {
|
||||
pub fn new(width: usize, height: usize) -> Self {
|
||||
Self {
|
||||
width,
|
||||
height,
|
||||
data: vec![T::default(); width * height],
|
||||
}
|
||||
}
|
||||
|
||||
/// A plane of the same size whose pixels are `map` of this one's.
|
||||
pub fn map<U: Sample>(&self, map: impl Fn(T) -> U + Sync) -> Plane<U> {
|
||||
let mut mapped = Plane::new(self.width, self.height);
|
||||
fill_rows(&mut mapped.data, self.width, |y, row| {
|
||||
let source = &self.data[y * self.width..(y + 1) * self.width];
|
||||
row.iter_mut().zip(source).for_each(|(target, &value)| *target = map(value));
|
||||
});
|
||||
mapped
|
||||
}
|
||||
|
||||
/// Combines this plane with `other`, of the same size, pixel by pixel.
|
||||
pub fn zip<U: Sample, V: Sample>(&self, other: &Plane<U>, combine: impl Fn(T, U) -> V + Sync) -> Plane<V> {
|
||||
let mut combined = Plane::new(self.width, self.height);
|
||||
fill_rows(&mut combined.data, self.width, |y, row| {
|
||||
let range = y * self.width..(y + 1) * self.width;
|
||||
let pairs = self.data[range.clone()].iter().zip(&other.data[range]);
|
||||
row.iter_mut().zip(pairs).for_each(|(target, (&a, &b))| *target = combine(a, b));
|
||||
});
|
||||
combined
|
||||
}
|
||||
|
||||
/// The plane with its rows and columns swapped, so a horizontal operation can work vertically. O(width × height).
|
||||
fn transposed(&self) -> Self {
|
||||
let mut transposed = Self::new(self.height, self.width);
|
||||
fill_rows(&mut transposed.data, self.height, |x, row| {
|
||||
row.iter_mut().enumerate().for_each(|(y, target)| *target = self.data[y * self.width + x]);
|
||||
});
|
||||
transposed
|
||||
}
|
||||
|
||||
/// Runs `operation` on each row, which it reads in full and writes as a new row of `width` pixels.
|
||||
fn map_rows(&self, width: usize, operation: impl Fn(&[T], &mut [T]) + Sync) -> Self {
|
||||
let mut result = Self::new(width, self.height);
|
||||
fill_rows(&mut result.data, width, |y, row| operation(&self.data[y * self.width..(y + 1) * self.width], row));
|
||||
result
|
||||
}
|
||||
|
||||
/// Runs `along_rows` on the plane's rows, then on its columns by way of one transpose there and back.
|
||||
fn along_both_axes<P>(self, horizontal: P, vertical: P, along_rows: impl Fn(Self, P) -> Self) -> Self {
|
||||
let plane = along_rows(self, horizontal);
|
||||
along_rows(plane.transposed(), vertical).transposed()
|
||||
}
|
||||
|
||||
/// Blurs the plane by a kernel along each axis. Kernels too wide to convolve directly run on a copy halved along their axis enough times
|
||||
/// for them to fit, then doubled back. O(width × height) per pass, with a pass for each halving and doubling.
|
||||
pub fn blurred(self, horizontal: BlurKernel, vertical: BlurKernel) -> Self {
|
||||
self.along_both_axes(horizontal, vertical, |mut plane, kernel| {
|
||||
let levels = kernel.levels();
|
||||
let length = plane.width;
|
||||
let level_length = |level: u32| length.div_ceil(1 << level);
|
||||
|
||||
for level in 1..=levels {
|
||||
plane = plane.map_rows(level_length(level), halve_row);
|
||||
}
|
||||
|
||||
let weights = kernel.weights(levels);
|
||||
plane = plane.map_rows(level_length(levels), |source, target| convolve_row(source, target, &weights));
|
||||
|
||||
for level in (0..levels).rev() {
|
||||
plane = plane.map_rows(level_length(level), double_row);
|
||||
}
|
||||
plane
|
||||
})
|
||||
}
|
||||
|
||||
/// Grows the shapes by a distance in pixels along each axis, in a square like SVG's `feMorphology`.
|
||||
pub fn dilated(self, horizontal: f64, vertical: f64) -> Self {
|
||||
self.along_both_axes(horizontal, vertical, |mut plane, distance| {
|
||||
let length = plane.width;
|
||||
|
||||
// Steps that double, then the remainder, so each step grows the shapes by up to as much as all the steps before it
|
||||
let (mut covered, mut step) = (0., 1.);
|
||||
while covered + step <= distance {
|
||||
plane = plane.map_rows(length, |source, target| dilate_row(source, target, step));
|
||||
covered += step;
|
||||
step *= 2.;
|
||||
}
|
||||
if distance - covered >= NEGLIGIBLE_LENGTH {
|
||||
plane = plane.map_rows(length, |source, target| dilate_row(source, target, distance - covered));
|
||||
}
|
||||
plane
|
||||
})
|
||||
}
|
||||
|
||||
/// Moves the image by a fractional offset in pixels, interpolating between pixels and leaving transparency where it uncovers the edges.
|
||||
pub fn shifted(self, offset_x: f64, offset_y: f64) -> Self {
|
||||
self.along_both_axes(offset_x, offset_y, |plane, offset| plane.map_rows(plane.width, |source, target| shift_row(source, target, offset)))
|
||||
}
|
||||
}
|
||||
|
||||
impl Plane<f32> {
|
||||
/// The coverage of the band reaching `width` pixels from the silhouette's edge, outward or (if `inward`) inward, measured in straight lines so it rounds corners.
|
||||
pub fn edge_band(&self, width: f64, inward: bool) -> Self {
|
||||
// The edge lies about half a pixel short of the nearest pixel across it, and the band fades out over one pixel
|
||||
let distances = self.distances_across_edge(width, inward);
|
||||
let width = width as f32;
|
||||
distances.map(|distance| (width + 1. - distance).clamp(0., 1.))
|
||||
}
|
||||
|
||||
/// Each pixel's distance to the nearest pixel across the silhouette's edge: outside it if `inward`, or inside it otherwise, with those pixels at zero.
|
||||
/// Jump flooding finds them in a pass for each halving of a step that starts past `reach`, so farther pixels may find none and lie at infinity. O(width × height × log(reach)).
|
||||
pub fn distances_across_edge(&self, reach: f64, inward: bool) -> Self {
|
||||
// The side of the edge that distances are measured from, whose pixels are their own nearest
|
||||
let is_seed = |coverage: f32| (coverage >= 0.5) != inward;
|
||||
let mut nearest: Vec<Option<[i32; 2]>> = self.data.iter().map(|&coverage| is_seed(coverage).then_some([0, 0])).collect();
|
||||
|
||||
let (columns, rows) = (self.width as i32, self.height as i32);
|
||||
let length_squared = |[x, y]: [i32; 2]| x * x + y * y;
|
||||
let mut step = (reach.max(0.).ceil() as u32 + 1).next_power_of_two();
|
||||
while step >= 1 {
|
||||
let previous = nearest.clone();
|
||||
let step_length = step as i32;
|
||||
|
||||
// Each pixel keeps the nearest of the seeds that it and its eight neighbors a step away have found so far
|
||||
fill_rows(&mut nearest, self.width, |y, row| {
|
||||
for (x, best) in row.iter_mut().enumerate() {
|
||||
for neighbor_y in -1..=1 {
|
||||
for neighbor_x in -1..=1 {
|
||||
let (x, y) = (x as i32 + neighbor_x * step_length, y as i32 + neighbor_y * step_length);
|
||||
if x < 0 || y < 0 || x >= columns || y >= rows {
|
||||
continue;
|
||||
}
|
||||
let Some([offset_x, offset_y]) = previous[(y * columns + x) as usize] else { continue };
|
||||
|
||||
let candidate = [offset_x + neighbor_x * step_length, offset_y + neighbor_y * step_length];
|
||||
if best.is_none_or(|best| length_squared(candidate) < length_squared(best)) {
|
||||
*best = Some(candidate);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
step /= 2;
|
||||
}
|
||||
|
||||
let data = nearest
|
||||
.into_iter()
|
||||
.map(|offset| offset.map_or(f32::INFINITY, |offset| (length_squared(offset) as f32).sqrt()))
|
||||
.collect();
|
||||
Self {
|
||||
width: self.width,
|
||||
height: self.height,
|
||||
data,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The row's value at a position measured in pixels from the first pixel's center, interpolating linearly and holding the end pixels beyond the ends.
|
||||
fn sample_row<T: Sample>(row: &[T], position: f64) -> T {
|
||||
let last = row.len() as f64 - 1.;
|
||||
let position = position.clamp(0., last.max(0.));
|
||||
let index = position.floor() as usize;
|
||||
let fraction = (position - index as f64) as f32;
|
||||
|
||||
match row.get(index + 1) {
|
||||
Some(&next) if fraction > 0. => row[index].scaled(1. - fraction).plus(next.scaled(fraction)),
|
||||
_ => row[index],
|
||||
}
|
||||
}
|
||||
|
||||
/// Halves the row by averaging each pair of pixels, the last pixel of an odd row pairing with itself.
|
||||
fn halve_row<T: Sample>(source: &[T], target: &mut [T]) {
|
||||
for (index, value) in target.iter_mut().enumerate() {
|
||||
let first = source[2 * index];
|
||||
let second = source.get(2 * index + 1).copied().unwrap_or(first);
|
||||
*value = first.plus(second).scaled(0.5);
|
||||
}
|
||||
}
|
||||
|
||||
/// Doubles a halved row back to its length, interpolating at each pixel's center within the pair it was averaged into.
|
||||
fn double_row<T: Sample>(source: &[T], target: &mut [T]) {
|
||||
for (index, value) in target.iter_mut().enumerate() {
|
||||
*value = sample_row(source, index as f64 / 2. - 0.25);
|
||||
}
|
||||
}
|
||||
|
||||
/// Weighs each pixel's neighbors by the symmetric kernel `weights`, from the center outward, holding the end pixels beyond the ends.
|
||||
fn convolve_row<T: Sample>(source: &[T], target: &mut [T], weights: &[f64]) {
|
||||
let last = source.len() as isize - 1;
|
||||
let at = |index: isize| source[index.clamp(0, last) as usize];
|
||||
|
||||
for (index, value) in target.iter_mut().enumerate() {
|
||||
let index = index as isize;
|
||||
let mut sum = at(index).scaled(weights[0] as f32);
|
||||
for (distance, &weight) in weights.iter().enumerate().skip(1) {
|
||||
let pair = at(index - distance as isize).plus(at(index + distance as isize));
|
||||
sum = sum.plus(pair.scaled(weight as f32));
|
||||
}
|
||||
*value = sum;
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes each pixel's maximum with the row's values `step` pixels to either side.
|
||||
fn dilate_row<T: Sample>(source: &[T], target: &mut [T], step: f64) {
|
||||
for (index, value) in target.iter_mut().enumerate() {
|
||||
let position = index as f64;
|
||||
*value = source[index].max(sample_row(source, position - step)).max(sample_row(source, position + step));
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves the row by `offset` pixels, with nothing beyond its ends.
|
||||
fn shift_row<T: Sample>(source: &[T], target: &mut [T], offset: f64) {
|
||||
let length = source.len() as f64;
|
||||
for (index, value) in target.iter_mut().enumerate() {
|
||||
let position = index as f64 - offset;
|
||||
let floor = position.floor();
|
||||
let fraction = (position - floor) as f32;
|
||||
|
||||
let at = |index: f64| if index >= 0. && index < length { source[index as usize] } else { T::default() };
|
||||
*value = at(floor).scaled(1. - fraction).plus(at(floor + 1.).scaled(fraction));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn kernel_weights_sum_to_one() {
|
||||
for kernel in [
|
||||
BlurKernel::Gaussian { sigma: 3. },
|
||||
BlurKernel::Gaussian { sigma: 40. },
|
||||
BlurKernel::Box { radius: 5.5 },
|
||||
BlurKernel::Box { radius: 100. },
|
||||
] {
|
||||
let levels = kernel.levels();
|
||||
let weights = kernel.weights(levels);
|
||||
let total = weights[0] + 2. * weights[1..].iter().sum::<f64>();
|
||||
|
||||
assert!((total - 1.).abs() < 1e-9, "{kernel:?} weights sum to {total}");
|
||||
assert!(weights.len() <= MAX_KERNEL_REACH + 1, "{kernel:?} reaches {} texels", weights.len());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn small_kernels_run_without_halving() {
|
||||
assert_eq!(BlurKernel::Gaussian { sigma: MAX_DIRECT_GAUSSIAN_SIGMA }.levels(), 0);
|
||||
assert_eq!(
|
||||
BlurKernel::Gaussian {
|
||||
sigma: MAX_DIRECT_GAUSSIAN_SIGMA * 1.01
|
||||
}
|
||||
.levels(),
|
||||
1
|
||||
);
|
||||
assert_eq!(BlurKernel::Box { radius: 1. }.levels(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gaussian_blur_spreads_a_point_with_the_requested_deviation() {
|
||||
// A single bright pixel blurs into the Gaussian itself, whose variance the pyramid must preserve at every level count
|
||||
for sigma in [2., 20.] {
|
||||
let size = 401;
|
||||
let mut plane = Plane::<f32>::new(size, 1);
|
||||
plane.data[size / 2] = 1.;
|
||||
|
||||
let blurred = plane.blurred(BlurKernel::Gaussian { sigma }, BlurKernel::Gaussian { sigma: 0. });
|
||||
let total: f32 = blurred.data.iter().sum();
|
||||
let variance: f64 = blurred.data.iter().enumerate().map(|(x, &value)| value as f64 * (x as f64 - (size / 2) as f64).powi(2)).sum::<f64>() / total as f64;
|
||||
|
||||
assert!((total - 1.).abs() < 1e-3, "sigma {sigma} keeps the total at {total}");
|
||||
assert!((variance.sqrt() - sigma).abs() / sigma < 0.05, "sigma {sigma} spreads to a deviation of {}", variance.sqrt());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dilation_grows_shapes_by_the_distance() {
|
||||
let mut plane = Plane::<f32>::new(21, 21);
|
||||
plane.data[10 * 21 + 10] = 1.;
|
||||
|
||||
let dilated = plane.dilated(3., 3.);
|
||||
let covered = dilated.data.iter().filter(|&&value| value >= 0.999).count();
|
||||
|
||||
assert_eq!(covered, 7 * 7, "a point grows into a 7 by 7 square");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edge_bands_round_the_corners_they_grow_around() {
|
||||
// A single pixel grows into a disk the band's width across, rather than a square
|
||||
let mut point = Plane::<f32>::new(21, 21);
|
||||
point.data[10 * 21 + 10] = 1.;
|
||||
let outward = point.edge_band(5., false);
|
||||
let at = |plane: &Plane<f32>, x: usize, y: usize| plane.data[y * 21 + x];
|
||||
|
||||
assert_eq!(at(&outward, 15, 10), 1., "the full width along an axis");
|
||||
assert_eq!(at(&outward, 17, 10), 0., "past the width");
|
||||
assert_eq!(at(&outward, 15, 14), 0., "past the width diagonally, where a square would still reach");
|
||||
|
||||
// Inward, only the pixels near the edge are covered
|
||||
let mut square = Plane::<f32>::new(21, 21);
|
||||
for y in 2..19 {
|
||||
square.data[y * 21 + 2..y * 21 + 19].fill(1.);
|
||||
}
|
||||
let inward = square.edge_band(3., true);
|
||||
|
||||
assert_eq!(at(&inward, 2, 10), 1., "at the edge");
|
||||
assert_eq!(at(&inward, 10, 10), 0., "deep inside");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shifting_moves_by_fractions_of_a_pixel() {
|
||||
let mut plane = Plane::<f32>::new(4, 1);
|
||||
plane.data[1] = 1.;
|
||||
|
||||
let shifted = plane.shifted(0.25, 0.);
|
||||
|
||||
assert_eq!(shifted.data, vec![0., 0.75, 0.25, 0.]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
//! The kernels rendering each [`GeneratorPattern`] across any area of its space at any resolution.
|
||||
|
||||
use core_types::Color;
|
||||
use glam::{DVec2, IVec2, Vec2};
|
||||
use graphic_types::generator::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, GeneratorPattern, NoiseSettings, NoiseType};
|
||||
use raster_types::parallel_rows::fill_rows;
|
||||
use raster_types::{Image, ImageError};
|
||||
|
||||
/// The most iterations a point is tested for escaping the Mandelbrot set, beyond which it counts as inside.
|
||||
const MANDELBROT_ITERATIONS: u32 = 255;
|
||||
|
||||
/// The pattern across `area` of its own space, from its minimum to its maximum corner, sampled at the centers of a `width` by `height` grid of pixels.
|
||||
/// Fails where an image of that size can't be allocated.
|
||||
/// The rows are rendered in parallel on native targets.
|
||||
pub fn render_pattern(pattern: &GeneratorPattern, area: [DVec2; 2], width: u32, height: u32) -> Result<Image<Color>, ImageError> {
|
||||
let mut image = Image::try_new(width, height, Color::TRANSPARENT)?;
|
||||
let pixel_size = (area[1] - area[0]) / DVec2::new(width as f64, height as f64);
|
||||
let pixel_center = |x: usize, y: usize| area[0] + (DVec2::new(x as f64, y as f64) + 0.5) * pixel_size;
|
||||
|
||||
let sample = pattern_sampler(pattern);
|
||||
fill_rows(&mut image.data, width as usize, |y, row| {
|
||||
row.iter_mut().enumerate().for_each(|(x, pixel)| *pixel = sample(pixel_center(x, y)));
|
||||
});
|
||||
|
||||
Ok(image)
|
||||
}
|
||||
|
||||
/// Samples the pattern's color at points in its own space, after the setup shared by every sample.
|
||||
pub fn pattern_sampler(pattern: &GeneratorPattern) -> impl Fn(DVec2) -> Color + Sync + use<> {
|
||||
let noise = match pattern {
|
||||
GeneratorPattern::Noise(settings) => Some(NoiseSampler::new(settings)),
|
||||
GeneratorPattern::Mandelbrot => None,
|
||||
};
|
||||
|
||||
move |point| match &noise {
|
||||
Some(noise) => Color::from_luminance(noise.sample(point)),
|
||||
None => {
|
||||
let value = mandelbrot_escape_iterations(point * 3. - DVec2::new(2., 1.5)) as f32 / MANDELBROT_ITERATIONS as f32;
|
||||
Color::from_rgbaf32_unchecked(value, value, value, 1.)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Samples a noise pattern's luminance, from 0 to 1, at positions in its space.
|
||||
struct NoiseSampler {
|
||||
noise: fastnoise_lite::FastNoiseLite,
|
||||
white_noise_seed: Option<i32>,
|
||||
domain_warp: bool,
|
||||
}
|
||||
|
||||
impl NoiseSampler {
|
||||
fn new(settings: &NoiseSettings) -> Self {
|
||||
let mut noise = fastnoise_lite::FastNoiseLite::with_seed(settings.seed as i32);
|
||||
noise.set_frequency(Some(1. / (settings.scale as f32).max(f32::EPSILON)));
|
||||
|
||||
// Domain warp
|
||||
let domain_warp_type = match settings.domain_warp_type {
|
||||
DomainWarpType::None => None,
|
||||
DomainWarpType::OpenSimplex2 => Some(fastnoise_lite::DomainWarpType::OpenSimplex2),
|
||||
DomainWarpType::OpenSimplex2Reduced => Some(fastnoise_lite::DomainWarpType::OpenSimplex2Reduced),
|
||||
DomainWarpType::BasicGrid => Some(fastnoise_lite::DomainWarpType::BasicGrid),
|
||||
};
|
||||
let domain_warp = domain_warp_type.is_some() && settings.domain_warp_amplitude > 0.;
|
||||
noise.set_domain_warp_type(domain_warp_type);
|
||||
noise.set_domain_warp_amp(Some(settings.domain_warp_amplitude as f32));
|
||||
|
||||
// Noise and fractal
|
||||
let noise_type = match settings.noise_type {
|
||||
NoiseType::Perlin => fastnoise_lite::NoiseType::Perlin,
|
||||
NoiseType::OpenSimplex2 => fastnoise_lite::NoiseType::OpenSimplex2,
|
||||
NoiseType::OpenSimplex2S => fastnoise_lite::NoiseType::OpenSimplex2S,
|
||||
NoiseType::Cellular => fastnoise_lite::NoiseType::Cellular,
|
||||
NoiseType::ValueCubic => fastnoise_lite::NoiseType::ValueCubic,
|
||||
NoiseType::Value => fastnoise_lite::NoiseType::Value,
|
||||
NoiseType::WhiteNoise => {
|
||||
return Self {
|
||||
noise,
|
||||
white_noise_seed: Some(settings.seed as i32),
|
||||
domain_warp: false,
|
||||
};
|
||||
}
|
||||
};
|
||||
noise.set_noise_type(Some(noise_type));
|
||||
let fractal_type = match settings.fractal_type {
|
||||
FractalType::None => fastnoise_lite::FractalType::None,
|
||||
FractalType::FBm => fastnoise_lite::FractalType::FBm,
|
||||
FractalType::Ridged => fastnoise_lite::FractalType::Ridged,
|
||||
FractalType::PingPong => fastnoise_lite::FractalType::PingPong,
|
||||
FractalType::DomainWarpProgressive => fastnoise_lite::FractalType::DomainWarpProgressive,
|
||||
FractalType::DomainWarpIndependent => fastnoise_lite::FractalType::DomainWarpIndependent,
|
||||
};
|
||||
noise.set_fractal_type(Some(fractal_type));
|
||||
noise.set_fractal_octaves(Some(settings.fractal_octaves as i32));
|
||||
noise.set_fractal_lacunarity(Some(settings.fractal_lacunarity as f32));
|
||||
noise.set_fractal_gain(Some(settings.fractal_gain as f32));
|
||||
noise.set_fractal_weighted_strength(Some(settings.fractal_weighted_strength as f32));
|
||||
noise.set_fractal_ping_pong_strength(Some(settings.fractal_ping_pong_strength as f32));
|
||||
|
||||
// Cellular
|
||||
let cellular_distance_function = match settings.cellular_distance_function {
|
||||
CellularDistanceFunction::Euclidean => fastnoise_lite::CellularDistanceFunction::Euclidean,
|
||||
CellularDistanceFunction::EuclideanSq => fastnoise_lite::CellularDistanceFunction::EuclideanSq,
|
||||
CellularDistanceFunction::Manhattan => fastnoise_lite::CellularDistanceFunction::Manhattan,
|
||||
CellularDistanceFunction::Hybrid => fastnoise_lite::CellularDistanceFunction::Hybrid,
|
||||
};
|
||||
let cellular_return_type = match settings.cellular_return_type {
|
||||
CellularReturnType::CellValue => fastnoise_lite::CellularReturnType::CellValue,
|
||||
CellularReturnType::Nearest => fastnoise_lite::CellularReturnType::Distance,
|
||||
CellularReturnType::NextNearest => fastnoise_lite::CellularReturnType::Distance2,
|
||||
CellularReturnType::Average => fastnoise_lite::CellularReturnType::Distance2Add,
|
||||
CellularReturnType::Difference => fastnoise_lite::CellularReturnType::Distance2Sub,
|
||||
CellularReturnType::Product => fastnoise_lite::CellularReturnType::Distance2Mul,
|
||||
CellularReturnType::Division => fastnoise_lite::CellularReturnType::Distance2Div,
|
||||
};
|
||||
noise.set_cellular_distance_function(Some(cellular_distance_function));
|
||||
noise.set_cellular_return_type(Some(cellular_return_type));
|
||||
noise.set_cellular_jitter(Some(settings.cellular_jitter as f32));
|
||||
|
||||
Self {
|
||||
noise,
|
||||
white_noise_seed: None,
|
||||
domain_warp,
|
||||
}
|
||||
}
|
||||
|
||||
fn sample(&self, position: DVec2) -> f32 {
|
||||
// White noise gives each square of one document unit its own random value
|
||||
if let Some(seed) = self.white_noise_seed {
|
||||
return white_noise(seed, position.floor().as_ivec2());
|
||||
}
|
||||
|
||||
let (mut x, mut y) = (position.x as f32, position.y as f32);
|
||||
if self.domain_warp {
|
||||
(x, y) = self.noise.domain_warp_2d(x, y);
|
||||
}
|
||||
(self.noise.get_noise_2d(x, y) + 1.) * 0.5
|
||||
}
|
||||
}
|
||||
|
||||
/// A random value from 0 to 1 for each cell of a grid, the same for the same seed and cell. In 32-bit math, which a GPU can match.
|
||||
fn white_noise(seed: i32, cell: IVec2) -> f32 {
|
||||
let [hash, _, _] = pcg3d([cell.x as u32, cell.y as u32, seed as u32]);
|
||||
|
||||
// The top 24 bits, which an f32 holds exactly
|
||||
(hash >> 8) as f32 / (1_u32 << 24) as f32
|
||||
}
|
||||
|
||||
/// PCG3D from Jarzynski and Olano's "Hash Functions for GPU Rendering", which spreads every input bit across the result.
|
||||
fn pcg3d(input: [u32; 3]) -> [u32; 3] {
|
||||
let mix = |[x, y, z]: [u32; 3]| {
|
||||
let x = x.wrapping_add(y.wrapping_mul(z));
|
||||
let y = y.wrapping_add(z.wrapping_mul(x));
|
||||
let z = z.wrapping_add(x.wrapping_mul(y));
|
||||
[x, y, z]
|
||||
};
|
||||
|
||||
let v = mix(input.map(|value| value.wrapping_mul(1_664_525).wrapping_add(1_013_904_223)));
|
||||
mix(v.map(|value| value ^ (value >> 16)))
|
||||
}
|
||||
|
||||
/// How many iterations `c` takes to escape the Mandelbrot set, or the iteration limit if it doesn't. In f32, which a GPU can match near the boundary.
|
||||
fn mandelbrot_escape_iterations(c: DVec2) -> u32 {
|
||||
let c = c.as_vec2();
|
||||
let mut z = Vec2::ZERO;
|
||||
for iteration in 0..MANDELBROT_ITERATIONS {
|
||||
z = Vec2::new(z.x * z.x - z.y * z.y, 2. * z.x * z.y) + c;
|
||||
if z.length_squared() > 4. {
|
||||
return iteration;
|
||||
}
|
||||
}
|
||||
MANDELBROT_ITERATIONS
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn renders_of_overlapping_areas_agree_where_they_overlap() {
|
||||
let noise = GeneratorPattern::Noise(NoiseSettings {
|
||||
seed: 7,
|
||||
scale: 10.,
|
||||
noise_type: NoiseType::OpenSimplex2,
|
||||
domain_warp_type: DomainWarpType::None,
|
||||
domain_warp_amplitude: 0.,
|
||||
fractal_type: FractalType::FBm,
|
||||
fractal_octaves: 3,
|
||||
fractal_lacunarity: 2.,
|
||||
fractal_gain: 0.5,
|
||||
fractal_weighted_strength: 0.,
|
||||
fractal_ping_pong_strength: 2.,
|
||||
cellular_distance_function: CellularDistanceFunction::Euclidean,
|
||||
cellular_return_type: CellularReturnType::Nearest,
|
||||
cellular_jitter: 1.,
|
||||
});
|
||||
|
||||
// One pixel per unit across 0 to 32, and again across 16 to 48, as two neighboring tiles of a render would sample it
|
||||
let whole = render_pattern(&noise, [DVec2::ZERO, DVec2::splat(32.)], 32, 32).unwrap();
|
||||
let shifted = render_pattern(&noise, [DVec2::splat(16.), DVec2::splat(48.)], 32, 32).unwrap();
|
||||
for y in 0..16 {
|
||||
for x in 0..16 {
|
||||
assert_eq!(whole.data[(y + 16) * 32 + x + 16], shifted.data[y * 32 + x]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn white_noise_is_the_same_wherever_and_however_finely_it_is_sampled() {
|
||||
let white_noise = |seed| {
|
||||
GeneratorPattern::Noise(NoiseSettings {
|
||||
seed,
|
||||
scale: 10.,
|
||||
noise_type: NoiseType::WhiteNoise,
|
||||
domain_warp_type: DomainWarpType::None,
|
||||
domain_warp_amplitude: 0.,
|
||||
fractal_type: FractalType::None,
|
||||
fractal_octaves: 1,
|
||||
fractal_lacunarity: 2.,
|
||||
fractal_gain: 0.5,
|
||||
fractal_weighted_strength: 0.,
|
||||
fractal_ping_pong_strength: 2.,
|
||||
cellular_distance_function: CellularDistanceFunction::Euclidean,
|
||||
cellular_return_type: CellularReturnType::Nearest,
|
||||
cellular_jitter: 1.,
|
||||
})
|
||||
};
|
||||
|
||||
// Each unit cell keeps its value when sampled four times as finely
|
||||
let coarse = render_pattern(&white_noise(3), [DVec2::ZERO, DVec2::splat(4.)], 4, 4).unwrap();
|
||||
let fine = render_pattern(&white_noise(3), [DVec2::ZERO, DVec2::splat(4.)], 16, 16).unwrap();
|
||||
for y in 0..16 {
|
||||
for x in 0..16 {
|
||||
assert_eq!(fine.data[y * 16 + x], coarse.data[(y / 4) * 4 + x / 4]);
|
||||
}
|
||||
}
|
||||
|
||||
// The values spread across the whole range, and another seed gives others
|
||||
let luminances: Vec<f32> = coarse.data.iter().map(|color| color.r()).collect();
|
||||
assert!(luminances.iter().any(|&value| value < 0.5) && luminances.iter().any(|&value| value > 0.5));
|
||||
assert_ne!(render_pattern(&white_noise(4), [DVec2::ZERO, DVec2::splat(4.)], 4, 4).unwrap().data, coarse.data);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
use core_types::Color;
|
||||
|
||||
/// A per-pixel color mapping, run by `map_cpu` on the CPU.
|
||||
pub trait MapColor: Sync + 'static {
|
||||
fn map_cpu(&self, color: Color) -> Color;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
//! The kernels carrying out raster operations, such as color adjustments and procedural patterns, each worked out once from its settings.
|
||||
|
||||
pub mod adjustment_tables;
|
||||
pub mod adjustments;
|
||||
mod blending;
|
||||
pub mod color_lookup_table;
|
||||
pub mod effect_kernels;
|
||||
pub mod generators;
|
||||
mod kernel;
|
||||
pub mod raster_effects;
|
||||
pub mod value_effects;
|
||||
|
||||
pub use kernel::*;
|
||||
pub use raster_effects::evaluate_raster_effects;
|
||||
pub use value_effects::{evaluate_color_effects, evaluate_gradient_effects};
|
||||
@@ -0,0 +1,486 @@
|
||||
//! Carries out a raster's effects on the CPU at the raster's own resolution, for the nodes that read its pixels.
|
||||
//! Each step mirrors the renderer's GPU passes, working on premultiplied gamma-encoded channels as they do.
|
||||
|
||||
use crate::adjustments::adjust_colors;
|
||||
use crate::blending::overlay_paint;
|
||||
use crate::effect_kernels::{BlurKernel, NEGLIGIBLE_LENGTH, Plane};
|
||||
use crate::generators::pattern_sampler;
|
||||
use core_types::FallibleVec2Operations;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::color::{linear_to_srgb, srgb_to_linear};
|
||||
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_FORM, ATTR_GRADIENT_START_CURVATURE, Item};
|
||||
use core_types::{ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color};
|
||||
use glam::{DAffine2, DMat2, DVec2, DVec3};
|
||||
use graphic_types::Graphic;
|
||||
use graphic_types::adjustment::Adjustment;
|
||||
use graphic_types::effects::{BevelDirection, BevelStyle, EffectOperation, Effects, GlowSource, bevel_light, bevel_smoothing, fitted_paint, outline_extents};
|
||||
use graphic_types::generator::GeneratorPattern;
|
||||
use raster_types::parallel_rows::fill_rows;
|
||||
use raster_types::{CPU, Image, Raster};
|
||||
use vector_types::gradient::{Gradient, GradientForm, GradientSettings, LINEAR_DIALS, RADIAL_DIALS, wrapped_dial};
|
||||
|
||||
/// The most pixels an image may grow to with the margin its effects cast into, beyond which the margin is cut short.
|
||||
const MAX_PIXELS_WITH_MARGIN: f64 = (1 << 24) as f64;
|
||||
|
||||
/// The raster with its effects carried out into its pixels, grown to hold what they cast past its edges, and with the effects and the fill opacity they used removed.
|
||||
/// A raster without the effects attribute is returned as it is.
|
||||
pub fn evaluate_raster_effects(item: Item<Raster<CPU>>) -> Item<Raster<CPU>> {
|
||||
let Some(operations) = item.attribute::<Effects>(ATTR_EFFECTS).map(|effects| effects.operations().collect::<Vec<_>>()) else {
|
||||
return item;
|
||||
};
|
||||
let transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let fill = item.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, 1.) as f32;
|
||||
|
||||
let (raster, attributes) = item.into_parts();
|
||||
let (raster, transform) = match evaluate(&raster, transform, &operations, fill) {
|
||||
Some((image, grown_transform)) => (Raster::new_cpu(image), grown_transform),
|
||||
None => (raster, transform),
|
||||
};
|
||||
|
||||
// Which attributes come out depends only on whether the effects attribute came in, not on what it holds
|
||||
let mut item = Item::from_parts(raster, attributes);
|
||||
item.remove_attribute::<Effects>(ATTR_EFFECTS);
|
||||
item.remove_attribute::<f64>(ATTR_OPACITY_FILL);
|
||||
item.set_attribute(ATTR_TRANSFORM, transform);
|
||||
item
|
||||
}
|
||||
|
||||
/// The raster with `adjustments` carried out on its colors, even those of transparent pixels, as for the adjustments leading its effects.
|
||||
/// The result is kept with the raster's pixels, so adjusting them the same way again reuses it, ID and all.
|
||||
pub fn adjusted_raster(raster: &Raster<CPU>, adjustments: &[Adjustment]) -> Raster<CPU> {
|
||||
let mut hasher = std::hash::DefaultHasher::new();
|
||||
adjustments.iter().for_each(|adjustment| core_types::graphene_hash::CacheHash::cache_hash(adjustment, &mut hasher));
|
||||
let key = std::hash::Hasher::finish(&hasher);
|
||||
|
||||
raster.derived(key, |raster| {
|
||||
let mut image = raster.data().clone();
|
||||
adjustments.iter().for_each(|adjustment| adjust_colors(adjustment, &mut image.data));
|
||||
Raster::new_cpu(image)
|
||||
})
|
||||
}
|
||||
|
||||
/// The image of the effects carried out on `raster`, which `transform` places in the document, with the transform placing that larger image.
|
||||
/// `None` when there's nothing to carry out, or the image is empty or its transform can't be inverted.
|
||||
fn evaluate(raster: &Raster<CPU>, transform: DAffine2, operations: &[EffectOperation], fill: f32) -> Option<(Image<Color>, DAffine2)> {
|
||||
let (width, height) = (raster.width as usize, raster.height as usize);
|
||||
if (operations.is_empty() && fill >= 1.) || width == 0 || height == 0 || transform.matrix2.determinant() == 0. {
|
||||
return None;
|
||||
}
|
||||
let size = DVec2::new(width as f64, height as f64);
|
||||
|
||||
// Unless a fill fades them first, leading adjustments change the image's own colors, keeping even transparent pixels' colors
|
||||
let leading_adjustments = operations.iter().take_while(|_| fill == 1.).map_while(|operation| match operation {
|
||||
EffectOperation::Adjustment(adjustment) => Some(adjustment),
|
||||
_ => None,
|
||||
});
|
||||
let mut colors = std::borrow::Cow::Borrowed(raster.data.as_slice());
|
||||
let mut remaining = operations;
|
||||
for adjustment in leading_adjustments {
|
||||
adjust_colors(adjustment, colors.to_mut());
|
||||
remaining = &remaining[1..];
|
||||
}
|
||||
if remaining.is_empty() {
|
||||
let data = colors.iter().map(|color| color.with_alpha(color.a() * fill)).collect();
|
||||
return Some((
|
||||
Image {
|
||||
width: raster.width,
|
||||
height: raster.height,
|
||||
data,
|
||||
},
|
||||
transform,
|
||||
));
|
||||
}
|
||||
let operations = remaining;
|
||||
|
||||
// Document lengths become pixels along each of the image's axes, and offsets map through the inverse of its pixel placement
|
||||
let pixels_to_document = transform.matrix2 * DMat2::from_diagonal(size.recip());
|
||||
let document_to_pixels = pixels_to_document.inverse();
|
||||
let pixels_per_length = DVec2::new(pixels_to_document.x_axis.length(), pixels_to_document.y_axis.length()).recip();
|
||||
|
||||
// A margin around the image to hold the blur and shadows cast past its edges, cut short for an image that would grow too large
|
||||
let reach: f64 = operations.iter().map(EffectOperation::reach).sum();
|
||||
let mut margin = (reach * pixels_per_length).ceil();
|
||||
let grown_size = size + 2. * margin;
|
||||
if grown_size.x * grown_size.y > MAX_PIXELS_WITH_MARGIN {
|
||||
let shrunk_size = grown_size * (MAX_PIXELS_WITH_MARGIN / (grown_size.x * grown_size.y)).sqrt();
|
||||
margin = ((shrunk_size - size) / 2.).max(DVec2::ZERO).floor();
|
||||
}
|
||||
let (margin_x, margin_y) = (margin.x as usize, margin.y as usize);
|
||||
|
||||
// The content at full strength, which casts every silhouette, and the content faded by the fill, which shows in the result
|
||||
let mut full = Plane::<[f32; 4]>::new(width + 2 * margin_x, height + 2 * margin_y);
|
||||
for (y, row) in colors.chunks_exact(width).enumerate() {
|
||||
let start = (y + margin_y) * full.width + margin_x;
|
||||
full.data[start..start + width]
|
||||
.iter_mut()
|
||||
.zip(row)
|
||||
.for_each(|(target, &color)| *target = premultiplied_gamma_channels(color));
|
||||
}
|
||||
let mut filled = (fill < 1.).then(|| full.map(|pixel| pixel.map(|channel| channel * fill)));
|
||||
// The shadows and glows stacked beneath the content
|
||||
let mut beneath: Option<Plane<[f32; 4]>> = None;
|
||||
|
||||
for operation in operations {
|
||||
match *operation {
|
||||
EffectOperation::Blur { radius, box_blur, gamma } => {
|
||||
let radius = radius * pixels_per_length;
|
||||
if radius.max_element() < NEGLIGIBLE_LENGTH {
|
||||
continue;
|
||||
}
|
||||
|
||||
// What lies beneath blurs together with the content
|
||||
if let Some(beneath) = beneath.take() {
|
||||
filled = filled.map(|filled| composite_beneath(&filled, &beneath, &full));
|
||||
full = composite_beneath(&full, &beneath, &full);
|
||||
}
|
||||
|
||||
let kernels = match box_blur {
|
||||
true => (BlurKernel::Box { radius: radius.x }, BlurKernel::Box { radius: radius.y }),
|
||||
false => (BlurKernel::Gaussian { sigma: radius.x }, BlurKernel::Gaussian { sigma: radius.y }),
|
||||
};
|
||||
full = blur(full, kernels, !gamma);
|
||||
filled = filled.map(|filled| blur(filled, kernels, !gamma));
|
||||
}
|
||||
EffectOperation::DropShadow { color, offset, blur, spread } => {
|
||||
let coverage = cast(&full, document_to_pixels * offset, blur * pixels_per_length, spread * pixels_per_length, false);
|
||||
beneath = Some(accumulate(beneath, &coverage, color));
|
||||
}
|
||||
EffectOperation::OuterGlow { color, blur, spread } => {
|
||||
let coverage = cast(&full, DVec2::ZERO, blur * pixels_per_length, spread * pixels_per_length, false);
|
||||
beneath = Some(accumulate(beneath, &coverage, color));
|
||||
}
|
||||
EffectOperation::InnerShadow { color, offset, blur, spread } => {
|
||||
let coverage = cast(&full, document_to_pixels * offset, blur * pixels_per_length, spread * pixels_per_length, true);
|
||||
filled = filled.map(|filled| composite_within(&filled, &coverage, &full, color));
|
||||
full = composite_within(&full, &coverage, &full, color);
|
||||
}
|
||||
EffectOperation::InnerGlow { color, blur, choke, source } => {
|
||||
let mut coverage = cast(&full, DVec2::ZERO, blur * pixels_per_length, choke * pixels_per_length, true);
|
||||
if source == GlowSource::Center {
|
||||
coverage = coverage.map(|coverage| 1. - coverage);
|
||||
}
|
||||
filled = filled.map(|filled| composite_within(&filled, &coverage, &full, color));
|
||||
full = composite_within(&full, &coverage, &full, color);
|
||||
}
|
||||
EffectOperation::Satin { color, offset, blur, invert } => {
|
||||
let offset = document_to_pixels * offset;
|
||||
let forward = cast(&full, offset, blur * pixels_per_length, DVec2::ZERO, false);
|
||||
let backward = cast(&full, -offset, blur * pixels_per_length, DVec2::ZERO, false);
|
||||
let coverage = forward.zip(&backward, |forward, backward| satin_coverage(forward, backward, invert));
|
||||
|
||||
filled = filled.map(|filled| composite_within(&filled, &coverage, &full, color));
|
||||
full = composite_within(&full, &coverage, &full, color);
|
||||
}
|
||||
EffectOperation::Outline { color, weight, align } => {
|
||||
// Straight-line distances can't stretch along one axis, so an image scaled unevenly takes the mean of its two scales
|
||||
let pixels_per_length = (pixels_per_length.x * pixels_per_length.y).sqrt();
|
||||
let (outside, inside) = outline_extents(weight * pixels_per_length, align);
|
||||
let silhouette = full.map(|[_, _, _, alpha]| alpha);
|
||||
|
||||
if outside >= NEGLIGIBLE_LENGTH {
|
||||
beneath = Some(accumulate(beneath, &silhouette.edge_band(outside, false), color));
|
||||
}
|
||||
if inside >= NEGLIGIBLE_LENGTH {
|
||||
let coverage = silhouette.edge_band(inside, true);
|
||||
filled = filled.map(|filled| composite_within(&filled, &coverage, &full, color));
|
||||
full = composite_within(&full, &coverage, &full, color);
|
||||
}
|
||||
}
|
||||
EffectOperation::BevelAndEmboss {
|
||||
style,
|
||||
depth,
|
||||
direction,
|
||||
size,
|
||||
soften,
|
||||
angle,
|
||||
altitude,
|
||||
highlight_color,
|
||||
shadow_color,
|
||||
} => {
|
||||
let pixels_per_length = (pixels_per_length.x * pixels_per_length.y).sqrt();
|
||||
let (size, soften) = (size * pixels_per_length, soften * pixels_per_length);
|
||||
if size < NEGLIGIBLE_LENGTH {
|
||||
continue;
|
||||
}
|
||||
|
||||
// The surface's height, rounded by a blur, lit from the light's direction into its highlights and shadows
|
||||
let height = soften_by(bevel_height(&full.map(|[_, _, _, alpha]| alpha), size, style), bevel_smoothing(size));
|
||||
let slope = depth / 100. * size * if direction == BevelDirection::Down { -1. } else { 1. };
|
||||
let light = bevel_light(angle, altitude, document_to_pixels);
|
||||
|
||||
// Their parts outside the content lie beneath it, and those inside are placed over it
|
||||
for (shadow, color) in [(false, highlight_color), (true, shadow_color)] {
|
||||
let coverage = soften_by(bevel_shading(&height, slope, light, shadow), soften);
|
||||
beneath = Some(accumulate(beneath, &coverage, color));
|
||||
filled = filled.map(|filled| composite_within(&filled, &coverage, &full, color));
|
||||
full = composite_within(&full, &coverage, &full, color);
|
||||
}
|
||||
}
|
||||
EffectOperation::PaintOverlay { ref paint, blend_mode, opacity } => {
|
||||
let corners = [DVec2::ZERO, DVec2::X, DVec2::Y, DVec2::ONE].map(|corner| transform.transform_point2(corner));
|
||||
let content_bounds = [corners.into_iter().reduce(DVec2::min).unwrap(), corners.into_iter().reduce(DVec2::max).unwrap()];
|
||||
let fitted = fitted_paint(paint, content_bounds);
|
||||
let Some(sample_paint) = paint_sampler(fitted.as_ref().unwrap_or(paint)) else { continue };
|
||||
|
||||
// The paint at each pixel's center, in the space the image is placed in
|
||||
let pixels_to_placement = transform * DAffine2::from_scale(size.recip()) * DAffine2::from_translation(-DVec2::new(margin_x as f64, margin_y as f64));
|
||||
let mut paint_colors = vec![Color::TRANSPARENT; full.data.len()];
|
||||
fill_rows(&mut paint_colors, full.width, |y, row| {
|
||||
for (x, color) in row.iter_mut().enumerate() {
|
||||
*color = sample_paint(pixels_to_placement.transform_point2(DVec2::new(x as f64 + 0.5, y as f64 + 0.5)));
|
||||
}
|
||||
});
|
||||
|
||||
let opacity = (opacity / 100.) as f32;
|
||||
filled = filled.map(|filled| overlay(&filled, &paint_colors, blend_mode, opacity));
|
||||
full = overlay(&full, &paint_colors, blend_mode, opacity);
|
||||
}
|
||||
EffectOperation::Adjustment(ref adjustment) => {
|
||||
full = adjust(&full, adjustment);
|
||||
filled = filled.map(|filled| adjust(&filled, adjustment));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let result = match (filled, beneath) {
|
||||
(filled, Some(beneath)) => composite_beneath(filled.as_ref().unwrap_or(&full), &beneath, &full),
|
||||
(Some(filled), None) => filled,
|
||||
(None, None) => full,
|
||||
};
|
||||
let image = Image {
|
||||
width: result.width as u32,
|
||||
height: result.height as u32,
|
||||
data: result.data.into_iter().map(straight_linear_color).collect(),
|
||||
};
|
||||
|
||||
// The grown image spans the margin on each side of the original's unit square
|
||||
let unit_margin = DVec2::new(margin_x as f64, margin_y as f64) / size;
|
||||
let grown_transform = transform * DAffine2::from_translation(-unit_margin) * DAffine2::from_scale(DVec2::ONE + 2. * unit_margin);
|
||||
|
||||
Some((image, grown_transform))
|
||||
}
|
||||
|
||||
/// A color as the premultiplied, gamma-encoded channels the effects work with.
|
||||
fn premultiplied_gamma_channels(color: Color) -> [f32; 4] {
|
||||
let [red, green, blue, alpha] = color.to_gamma_srgb_channels();
|
||||
[red * alpha, green * alpha, blue * alpha, alpha]
|
||||
}
|
||||
|
||||
/// Premultiplied, gamma-encoded channels back as a color.
|
||||
fn straight_linear_color([red, green, blue, alpha]: [f32; 4]) -> Color {
|
||||
if alpha <= 0. {
|
||||
return Color::TRANSPARENT;
|
||||
}
|
||||
Color::from_gamma_srgb_channels(red / alpha, green / alpha, blue / alpha, alpha.min(1.))
|
||||
}
|
||||
|
||||
/// Adjusts premultiplied gamma-encoded pixels by way of their straight colors, leaving fully transparent pixels empty since they keep no color to adjust.
|
||||
fn adjust(plane: &Plane<[f32; 4]>, adjustment: &Adjustment) -> Plane<[f32; 4]> {
|
||||
let mut colors: Vec<Color> = plane.data.iter().copied().map(straight_linear_color).collect();
|
||||
adjust_colors(adjustment, &mut colors);
|
||||
|
||||
let data = plane
|
||||
.data
|
||||
.iter()
|
||||
.zip(colors)
|
||||
.map(|(pixel, color)| if pixel[3] <= 0. { [0.; 4] } else { premultiplied_gamma_channels(color) })
|
||||
.collect();
|
||||
Plane {
|
||||
width: plane.width,
|
||||
height: plane.height,
|
||||
data,
|
||||
}
|
||||
}
|
||||
|
||||
/// Premultiplied channels with `transfer` applied to their straight color.
|
||||
fn transferred(transfer: fn(f32) -> f32) -> impl Fn([f32; 4]) -> [f32; 4] + Sync {
|
||||
move |[red, green, blue, alpha]| {
|
||||
if alpha <= 0. {
|
||||
return [0.; 4];
|
||||
}
|
||||
let channel = |value: f32| transfer((value / alpha).max(0.)) * alpha;
|
||||
[channel(red), channel(green), channel(blue), alpha]
|
||||
}
|
||||
}
|
||||
|
||||
/// Blurs premultiplied gamma-encoded pixels by a kernel along each axis, in linear light if `linear`.
|
||||
fn blur(plane: Plane<[f32; 4]>, (horizontal, vertical): (BlurKernel, BlurKernel), linear: bool) -> Plane<[f32; 4]> {
|
||||
match linear {
|
||||
true => plane.map(transferred(srgb_to_linear)).blurred(horizontal, vertical).map(transferred(linear_to_srgb)),
|
||||
false => plane.blurred(horizontal, vertical),
|
||||
}
|
||||
}
|
||||
|
||||
/// The coverage of the content's silhouette (or of the area outside it, if `inverse`), cast by `offset`, grown by `spread` and softened by a Gaussian of deviation `blur`, all in pixels along each axis.
|
||||
fn cast(content: &Plane<[f32; 4]>, offset: DVec2, blur: DVec2, spread: DVec2, inverse: bool) -> Plane<f32> {
|
||||
let mut coverage = content.map(|[_, _, _, alpha]| alpha).shifted(offset.x, offset.y);
|
||||
if inverse {
|
||||
coverage = coverage.map(|alpha| 1. - alpha);
|
||||
}
|
||||
|
||||
if spread.max_element() >= NEGLIGIBLE_LENGTH {
|
||||
coverage = coverage.dilated(spread.x, spread.y);
|
||||
}
|
||||
if blur.max_element() >= NEGLIGIBLE_LENGTH {
|
||||
coverage = coverage.blurred(BlurKernel::Gaussian { sigma: blur.x }, BlurKernel::Gaussian { sigma: blur.y });
|
||||
}
|
||||
coverage
|
||||
}
|
||||
|
||||
/// Stacks a silhouette's coverage, tinted `color`, over what lies `beneath` the content so far.
|
||||
fn accumulate(beneath: Option<Plane<[f32; 4]>>, coverage: &Plane<f32>, color: Color) -> Plane<[f32; 4]> {
|
||||
let color = premultiplied_gamma_channels(color);
|
||||
let tinted = coverage.map(|coverage| color.map(|channel| channel * coverage));
|
||||
|
||||
match beneath {
|
||||
Some(beneath) => tinted.zip(&beneath, |tinted, beneath| std::array::from_fn(|channel| tinted[channel] + beneath[channel] * (1. - tinted[3]))),
|
||||
None => tinted,
|
||||
}
|
||||
}
|
||||
|
||||
/// The image with a silhouette's coverage, tinted `color`, placed over it within the full-strength content.
|
||||
fn composite_within(image: &Plane<[f32; 4]>, coverage: &Plane<f32>, full_content: &Plane<[f32; 4]>, color: Color) -> Plane<[f32; 4]> {
|
||||
let color = premultiplied_gamma_channels(color);
|
||||
let coverages = coverage.zip(full_content, |coverage, content| [coverage, content[3], 0., 0.]);
|
||||
|
||||
image.zip(&coverages, |image, [coverage, content_alpha, _, _]| {
|
||||
let tinted = color.map(|channel| channel * coverage);
|
||||
std::array::from_fn(|channel| tinted[channel] * content_alpha + image[channel] * (1. - tinted[3]))
|
||||
})
|
||||
}
|
||||
|
||||
/// The image with the shadows and glows `beneath` placed under it, knocked out by the full-strength content.
|
||||
fn composite_beneath(image: &Plane<[f32; 4]>, beneath: &Plane<[f32; 4]>, full_content: &Plane<[f32; 4]>) -> Plane<[f32; 4]> {
|
||||
let knocked_out = beneath.zip(full_content, |beneath, content| beneath.map(|channel| channel * (1. - content[3])));
|
||||
image.zip(&knocked_out, |image, beneath| std::array::from_fn(|channel| image[channel] + beneath[channel]))
|
||||
}
|
||||
|
||||
/// Satin's shading where the two casts of the silhouette cover `forward` and `backward`: how much one covers without the other, or how much they agree if `invert`.
|
||||
fn satin_coverage(forward: f32, backward: f32, invert: bool) -> f32 {
|
||||
let difference = (forward - backward).abs();
|
||||
if invert { 1. - difference } else { difference }
|
||||
}
|
||||
|
||||
/// The plane blurred by a Gaussian of deviation `sigma` pixels, or left as it is for one too small to see.
|
||||
fn soften_by(plane: Plane<f32>, sigma: f64) -> Plane<f32> {
|
||||
match sigma >= NEGLIGIBLE_LENGTH {
|
||||
true => plane.blurred(BlurKernel::Gaussian { sigma }, BlurKernel::Gaussian { sigma }),
|
||||
false => plane,
|
||||
}
|
||||
}
|
||||
|
||||
/// A bevel's height from 0 to 1, from each pixel's signed distance to the silhouette's edge (positive inside), shaped by the `style` over `size` pixels.
|
||||
fn bevel_height(silhouette: &Plane<f32>, size: f64, style: BevelStyle) -> Plane<f32> {
|
||||
let to_inside = silhouette.distances_across_edge(size, false);
|
||||
let to_outside = silhouette.distances_across_edge(size, true);
|
||||
|
||||
// The pixels inside the silhouette are those at no distance from it, and the edge lies about half a pixel short of the nearest pixel across it
|
||||
to_inside.zip(&to_outside, |to_inside, to_outside| {
|
||||
let signed_distance = if to_inside == 0. { to_outside - 0.5 } else { 0.5 - to_inside };
|
||||
bevel_profile(signed_distance, size as f32, style)
|
||||
})
|
||||
}
|
||||
|
||||
/// The height from 0 to 1 at a signed distance from the edge (positive inside), rising smoothly across the `style`'s slope `size` pixels wide.
|
||||
fn bevel_profile(signed_distance: f32, size: f32, style: BevelStyle) -> f32 {
|
||||
let progress = match style {
|
||||
BevelStyle::InnerBevel => signed_distance / size,
|
||||
BevelStyle::OuterBevel => (signed_distance + size) / size,
|
||||
BevelStyle::Emboss => (signed_distance + size / 2.) / size,
|
||||
BevelStyle::PillowEmboss => signed_distance.abs() / (size / 2.),
|
||||
};
|
||||
let progress = progress.clamp(0., 1.);
|
||||
progress * progress * (3. - 2. * progress)
|
||||
}
|
||||
|
||||
/// How far the `light` brightens the bevel's surface past a flat surface's brightness, or if `shadow`, how far it falls short, from 0 to 1.
|
||||
/// `slope` scales the height's gradient into the surface's steepness, and is negative for a bevel pressed into the surface. O(width × height).
|
||||
fn bevel_shading(height: &Plane<f32>, slope: f64, light: DVec3, shadow: bool) -> Plane<f32> {
|
||||
let (width, rows) = (height.width as isize, height.height as isize);
|
||||
let at = |x: isize, y: isize| height.data[(y.clamp(0, rows - 1) * width + x.clamp(0, width - 1)) as usize];
|
||||
let (slope, light) = (slope as f32, light.as_vec3());
|
||||
|
||||
let mut shading = Plane::new(height.width, height.height);
|
||||
fill_rows(&mut shading.data, height.width, |y, row| {
|
||||
for (x, value) in row.iter_mut().enumerate() {
|
||||
let (x, y) = (x as isize, y as isize);
|
||||
let gradient = glam::Vec2::new(at(x + 1, y) - at(x - 1, y), at(x, y + 1) - at(x, y - 1)) / 2.;
|
||||
let shade = (-slope * gradient).extend(1.).normalize().dot(light);
|
||||
|
||||
*value = match shadow {
|
||||
true => (light.z - shade) / light.z.max(1e-4),
|
||||
false => (shade - light.z) / (1. - light.z).max(1e-4),
|
||||
}
|
||||
.clamp(0., 1.);
|
||||
}
|
||||
});
|
||||
shading
|
||||
}
|
||||
|
||||
/// Mixes the paint's color at each premultiplied gamma-encoded pixel over it by the blend mode, keeping the pixel's alpha.
|
||||
fn overlay(plane: &Plane<[f32; 4]>, paint: &[Color], blend_mode: BlendMode, opacity: f32) -> Plane<[f32; 4]> {
|
||||
let data = plane
|
||||
.data
|
||||
.iter()
|
||||
.zip(paint)
|
||||
.map(|(&pixel, &paint)| match pixel[3] > 0. {
|
||||
true => premultiplied_gamma_channels(overlay_paint(straight_linear_color(pixel), paint, blend_mode, opacity)),
|
||||
false => [0.; 4],
|
||||
})
|
||||
.collect();
|
||||
Plane {
|
||||
width: plane.width,
|
||||
height: plane.height,
|
||||
data,
|
||||
}
|
||||
}
|
||||
|
||||
/// Samples the paint's color at points in the space its placement maps into, for the paints the CPU can draw: colors, images, generators, and linear or radial gradients.
|
||||
fn paint_sampler(paint: &Graphic) -> Option<Box<dyn Fn(DVec2) -> Color + Sync + '_>> {
|
||||
let inverse = |placement: DAffine2| (placement.matrix2.determinant() != 0.).then(|| placement.inverse());
|
||||
|
||||
match paint {
|
||||
Graphic::Color(color) => {
|
||||
let color = *color.element();
|
||||
Some(Box::new(move |_| color))
|
||||
}
|
||||
Graphic::RasterCPU(item) => {
|
||||
let image = item.element();
|
||||
let to_pixels = DAffine2::from_scale(DVec2::new(image.width as f64, image.height as f64)) * inverse(item.attribute_cloned_or_default(ATTR_TRANSFORM))?;
|
||||
Some(Box::new(move |point| image.sample_bilinear(to_pixels.transform_point2(point))))
|
||||
}
|
||||
Graphic::Generator(item) => {
|
||||
let to_pattern = inverse(item.attribute_cloned_or_default(ATTR_TRANSFORM))?;
|
||||
let sample = pattern_sampler(&GeneratorPattern::of_item(item));
|
||||
Some(Box::new(move |point| sample(to_pattern.transform_point2(point))))
|
||||
}
|
||||
Graphic::Gradient(item) => {
|
||||
let position = gradient_position(item)?;
|
||||
let evaluator = item.element().evaluator(GradientSettings::from_item_attributes(item));
|
||||
Some(Box::new(move |point| evaluator.evaluate(position(point))))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// How far along a linear or radial gradient each point lies, or `None` for the other shapes its curvature dials make, which only the renderers draw.
|
||||
fn gradient_position(item: &Item<Gradient>) -> Option<Box<dyn Fn(DVec2) -> f64 + Sync>> {
|
||||
let placement: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let preset = item.attribute_cloned_or_default::<GradientForm>(ATTR_GRADIENT_FORM).dials();
|
||||
let dial = |key: &str, preset: f64| wrapped_dial(item.attribute_cloned_or(key, preset), preset);
|
||||
|
||||
match [dial(ATTR_GRADIENT_START_CURVATURE, preset[0]), dial(ATTR_GRADIENT_END_CURVATURE, preset[1])] {
|
||||
// Measured along the line across the bands, which stay parallel to the placement's sheared y axis as the renderers draw them
|
||||
LINEAR_DIALS => {
|
||||
let axis = placement.matrix2.x_axis;
|
||||
let line = axis.try_project_onto(placement.matrix2.y_axis.perp()).unwrap_or(axis);
|
||||
let origin = placement.translation;
|
||||
(line.length_squared() > 0.).then(|| Box::new(move |point: DVec2| (point - origin).dot(line) / line.length_squared()) as Box<dyn Fn(DVec2) -> f64 + Sync>)
|
||||
}
|
||||
RADIAL_DIALS => {
|
||||
let to_unit = (placement.matrix2.determinant() != 0.).then(|| placement.inverse())?;
|
||||
Some(Box::new(move |point| to_unit.transform_point2(point).length()))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
//! Carries out the adjustments among a color's or gradient's effects, for the nodes and paints that read the value rather than render it.
|
||||
//! A value read on its own has no pixels for the image operations among the effects (like blurs and shadows) to act on, so those are skipped.
|
||||
|
||||
use crate::adjustments::{PreparedAdjustment, adjust_color};
|
||||
use core_types::Color;
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, Item};
|
||||
use graphic_types::adjustment::Adjustment;
|
||||
use graphic_types::effects::{EffectOperation, Effects};
|
||||
use std::hash::{DefaultHasher, Hasher};
|
||||
use std::sync::{Mutex, PoisonError};
|
||||
use vector_types::{Gradient, GradientInterpolation, GradientSettings, GradientSpace};
|
||||
|
||||
/// How many adjusted gradients stay cached after the renders that used them, since paints read the same ones every render.
|
||||
const MAX_CACHED_GRADIENTS: usize = 32;
|
||||
|
||||
/// The gradients adjusted most recently, least recent first, keyed by the hash of what they were adjusted from.
|
||||
static ADJUSTED_GRADIENTS: Mutex<Vec<(u64, Gradient, GradientSettings)>> = Mutex::new(Vec::new());
|
||||
|
||||
/// The adjustments among the effects, in order.
|
||||
pub fn adjustments(effects: &Effects) -> Vec<Adjustment> {
|
||||
effects
|
||||
.operations()
|
||||
.filter_map(|operation| match operation {
|
||||
EffectOperation::Adjustment(adjustment) => Some(adjustment),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The color with `adjustments` carried out on it in order.
|
||||
pub fn adjusted_color(color: Color, adjustments: &[Adjustment]) -> Color {
|
||||
adjustments.iter().fold(color, |color, adjustment| adjust_color(adjustment, color))
|
||||
}
|
||||
|
||||
/// Carries out `adjustments` in order on any number of colors, with each one's kernel prepared once.
|
||||
fn prepared(adjustments: &[Adjustment]) -> impl Fn(Color) -> Color {
|
||||
let adjustments: Vec<PreparedAdjustment> = adjustments.iter().map(PreparedAdjustment::new).collect();
|
||||
move |color| adjustments.iter().fold(color, |color, adjustment| adjustment.adjust(color))
|
||||
}
|
||||
|
||||
/// The gradient with `adjustments` carried out along its ramp, with the settings to read the result with, or `None` if there are no adjustments.
|
||||
/// A stepped ramp holds each stop's color, so adjusting the stops is exact. Elsewhere an adjustment can bend the ramp between stops,
|
||||
/// so the adjusted ramp is resampled into stops that interpolate linearly in gamma.
|
||||
pub fn adjusted_gradient(gradient: &Gradient, settings: GradientSettings, adjustments: &[Adjustment]) -> Option<(Gradient, GradientSettings)> {
|
||||
if adjustments.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if settings.interpolation == GradientInterpolation::Stepped {
|
||||
let adjust = prepared(adjustments);
|
||||
return Some((gradient.map_colors(|color| adjust(*color)), settings));
|
||||
}
|
||||
|
||||
// Resampling takes thousands of evaluations for a steep adjustment, so recent results are reused
|
||||
let mut hasher = DefaultHasher::new();
|
||||
gradient.cache_hash(&mut hasher);
|
||||
settings.cache_hash(&mut hasher);
|
||||
adjustments.iter().for_each(|adjustment| adjustment.cache_hash(&mut hasher));
|
||||
let key = hasher.finish();
|
||||
|
||||
// A lock poisoned by a panic elsewhere still guards a usable cache
|
||||
let mut cached = ADJUSTED_GRADIENTS.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(index) = cached.iter().position(|(cached_key, ..)| *cached_key == key) {
|
||||
let entry = cached.remove(index);
|
||||
let result = (entry.1.clone(), entry.2);
|
||||
cached.push(entry);
|
||||
return Some(result);
|
||||
}
|
||||
|
||||
let resampled = gradient.map_ramp(settings, prepared(adjustments));
|
||||
let resampled_settings = GradientSettings {
|
||||
space: GradientSpace::RgbGamma,
|
||||
interpolation: GradientInterpolation::Linear,
|
||||
hue_direction: Default::default(),
|
||||
..settings
|
||||
};
|
||||
|
||||
cached.push((key, resampled.clone(), resampled_settings));
|
||||
let excess = cached.len().saturating_sub(MAX_CACHED_GRADIENTS);
|
||||
cached.drain(..excess);
|
||||
|
||||
Some((resampled, resampled_settings))
|
||||
}
|
||||
|
||||
/// The color with the adjustments among its effects carried out and the effects consumed, for nodes that read the color.
|
||||
/// A color without the effects attribute is returned as it is.
|
||||
pub fn evaluate_color_effects(item: Item<Color>) -> Item<Color> {
|
||||
let Some(adjustments) = item.attribute::<Effects>(ATTR_EFFECTS).map(adjustments) else {
|
||||
return item;
|
||||
};
|
||||
|
||||
let mut item = item;
|
||||
*item.element_mut() = adjusted_color(*item.element(), &adjustments);
|
||||
item.remove_attribute::<Effects>(ATTR_EFFECTS);
|
||||
item
|
||||
}
|
||||
|
||||
/// The gradient with the adjustments among its effects carried out along its ramp and the effects consumed, for nodes that read its colors.
|
||||
/// A gradient without the effects attribute is returned as it is.
|
||||
pub fn evaluate_gradient_effects(item: Item<Gradient>) -> Item<Gradient> {
|
||||
let Some(adjustments) = item.attribute::<Effects>(ATTR_EFFECTS).map(adjustments) else {
|
||||
return item;
|
||||
};
|
||||
let settings = GradientSettings::from_item_attributes(&item);
|
||||
|
||||
let mut item = item;
|
||||
let settings = match adjusted_gradient(item.element(), settings, &adjustments) {
|
||||
Some((gradient, adjusted_settings)) => {
|
||||
*item.element_mut() = gradient;
|
||||
adjusted_settings
|
||||
}
|
||||
None => settings,
|
||||
};
|
||||
|
||||
// Which attributes come out depends only on whether the effects attribute came in, not on what it holds
|
||||
item.remove_attribute::<Effects>(ATTR_EFFECTS);
|
||||
item.set_attribute(ATTR_GRADIENT_SPACE, settings.space);
|
||||
item.set_attribute(ATTR_GRADIENT_INTERPOLATION, settings.interpolation);
|
||||
item.set_attribute(ATTR_GRADIENT_HUE_DIRECTION, settings.hue_direction);
|
||||
item
|
||||
}
|
||||
Loaded 100 of 153 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user