Compare commits

..
106 changed files with 1162 additions and 9309 deletions

No files matched your search

+2 -5
View File
@@ -29,8 +29,6 @@ const DAILY_LIMIT_PER_CONTRIBUTOR = 40;
const MAX_RUN_PAGES = 10;
// The workflow step that fails only when a run reached a verdict against its title, by the end of its name
const VERDICT_STEP_NAME = "Fail for the title's verdict";
// The workflow step that passes a run whose title changed while it ran, without a verdict, by the end of its name
const SUPERSEDED_STEP_NAME = "Pass for a newer run's review";
const MAX_VERDICT_LOOKUPS = 5;
// How much of the PR's changes accompany the title, which keeps the message under about 20,000 tokens
@@ -177,15 +175,14 @@ async function listBranchRuns(workflowId: number, before?: number): Promise<Work
return newestFirst(runs);
}
// The newest finished run that reached a verdict on its title, skipping those that didn't (as when a service was unreachable or the title changed mid-run)
// The newest of the finished runs that reached a verdict on its title, skipping failures that didn't (such as when GitHub or the review service couldn't be reached)
async function latestVerdictRun(finishedRunsNewestFirst: WorkflowRun[]): Promise<WorkflowRun | undefined> {
for (let i = 0; i < Math.min(finishedRunsNewestFirst.length, MAX_VERDICT_LOOKUPS); i++) {
const run = finishedRunsNewestFirst[i];
if (run.conclusion === "success") return run;
const { jobs } = await github<{ jobs: { steps?: { name: string; conclusion: string | null }[] }[] }>("GET", `/repos/${repository}/actions/runs/${run.id}/jobs`);
const steps = jobs.flatMap((job) => job.steps || []);
if (steps.some((step) => step.name.endsWith(SUPERSEDED_STEP_NAME) && step.conclusion === "success")) continue;
if (run.conclusion === "success") return run;
if (steps.some((step) => step.name.endsWith(VERDICT_STEP_NAME) && step.conclusion === "failure")) return run;
}
+3 -4
View File
@@ -37,7 +37,6 @@ const pullRequestNumber = readEvent().pull_request.number;
const decision = readDecision();
const retried = RETRIED_OUTCOMES.includes(decision.outcome);
const passed = PASSING_OUTCOMES.includes(decision.outcome);
const superseded = decision.outcome === "superseded";
// New feedback replaces earlier comments so the latest is at the bottom of the conversation, while carried-over and retried outcomes leave them be
if (decision.outcome !== "unchanged" && decision.outcome !== "still_approved" && !retried) {
@@ -48,10 +47,10 @@ if (decision.outcome !== "unchanged" && decision.outcome !== "still_approved" &&
}
}
console.log(`::${passed || superseded ? "notice" : "error"}::${ANNOTATIONS[decision.outcome]}`);
console.log(`::${passed ? "notice" : "error"}::${ANNOTATIONS[decision.outcome]}`);
// Later runs tell verdicts, retries, and superseded runs apart by which of the workflow's last steps each one ran
const result = passed ? "approved" : superseded ? "superseded" : retried ? "retry" : "verdict";
// The workflow fails a different step for a verdict against the title than for an outcome to retry, which later runs read back to tell them apart
const result = passed ? "approved" : retried ? "retry" : "verdict";
fs.appendFileSync(requireEnvironment("GITHUB_OUTPUT"), `result=${result}\n`);
function readDecision(): Decision {
+1 -6
View File
@@ -64,12 +64,7 @@ jobs:
if: ${{ !cancelled() && steps.report.outputs.result == 'verdict' }}
run: exit 1
# A run whose title changed mid-run passes and leaves the check to the newer run, which skips it by this name (see `SUPERSEDED_STEP_NAME` in `gather.ts`)
- name: ⏭️ Pass for a newer run's review
if: ${{ !cancelled() && steps.report.outputs.result == 'superseded' }}
run: echo "A newer run reviews the changed title"
# Later runs review the title again after this failure, as they do when a step above fails unexpectedly
- name: 🔁 Fail without a verdict
if: ${{ !cancelled() && steps.report.outputs.result != 'verdict' && steps.report.outputs.result != 'approved' && steps.report.outputs.result != 'superseded' }}
if: ${{ !cancelled() && steps.report.outputs.result != 'verdict' && steps.report.outputs.result != 'approved' }}
run: exit 1
Generated
+15 -15
View File
@@ -2746,8 +2746,9 @@ dependencies = [
"fd-lock",
"futures",
"glam",
"graphite-desktop-ui",
"graphite-desktop-ui-cef",
"graphite-desktop-wrapper",
"graphite-wasm-wrapper",
"interprocess",
"lzma-rust2",
"muda",
@@ -2778,13 +2779,6 @@ dependencies = [
"serde",
]
[[package]]
name = "graphite-desktop-embedded-resources"
version = "0.0.0"
dependencies = [
"include_dir",
]
[[package]]
name = "graphite-desktop-platform-linux"
version = "0.0.0"
@@ -2797,7 +2791,7 @@ name = "graphite-desktop-platform-mac"
version = "0.0.0"
dependencies = [
"graphite-desktop",
"graphite-desktop-ui",
"graphite-desktop-ui-cef",
]
[[package]]
@@ -2809,14 +2803,14 @@ dependencies = [
]
[[package]]
name = "graphite-desktop-ui"
name = "graphite-desktop-ui-cef"
version = "0.0.0"
dependencies = [
"ash",
"bytemuck",
"cef",
"dirs",
"graphite-desktop-embedded-resources",
"graphite-desktop-ui-cef-embedded-resources",
"ipc-channel",
"libc",
"mach2",
@@ -2836,6 +2830,13 @@ dependencies = [
"winit",
]
[[package]]
name = "graphite-desktop-ui-cef-embedded-resources"
version = "0.0.0"
dependencies = [
"include_dir",
]
[[package]]
name = "graphite-desktop-wrapper"
version = "0.0.0"
@@ -2843,7 +2844,6 @@ dependencies = [
"base64 0.23.1",
"graph-craft",
"graphite-editor",
"graphite-wasm-wrapper",
"image",
"keyboard-types",
"serde",
@@ -8084,7 +8084,7 @@ dependencies = [
[[package]]
name = "vello_common"
version = "0.3.0"
source = "git+https://github.com/Keavon/vello.git?rev=a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c#a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c"
source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07"
dependencies = [
"bytemuck",
"fearless_simd",
@@ -8099,7 +8099,7 @@ dependencies = [
[[package]]
name = "vello_gpu"
version = "0.3.0"
source = "git+https://github.com/Keavon/vello.git?rev=a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c#a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c"
source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07"
dependencies = [
"bytemuck",
"hashbrown 0.17.1",
@@ -8113,7 +8113,7 @@ dependencies = [
[[package]]
name = "vello_gpu_shaders"
version = "0.3.0"
source = "git+https://github.com/Keavon/vello.git?rev=a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c#a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c"
source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07"
dependencies = [
"naga",
"wesl",
+4 -4
View File
@@ -3,7 +3,7 @@ members = [
"desktop",
"desktop/wrapper",
"desktop/ui",
"desktop/embedded-resources",
"desktop/ui/embedded-resources",
"desktop/bundle",
"desktop/platform/linux",
"desktop/platform/mac",
@@ -315,6 +315,6 @@ debug = true
rfd = { git = "https://github.com/timon-schelling/rfd.git", branch = "graphite" } # TODO: Remove this once https://github.com/PolyMeilex/rfd/pull/317 is merged and released
fastnoise-lite = { git = "https://github.com/Keavon/FastNoiseLite.git", rev = "26c1ac62e124d68ff970c2423dcda2ef24344060" } # TODO: Remove this once the WGSL port is upstreamed and released in version 1.2
# TODO: Remove these once the fork's fixes are upstreamed and released
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" }
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" }
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" }
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
+4 -3
View File
@@ -21,13 +21,14 @@ path = "src/main.rs"
[features]
default = ["recommended", "embedded_resources"]
recommended = ["accelerated_paint"]
embedded_resources = ["graphite-desktop-ui/embedded_resources"]
accelerated_paint = ["graphite-desktop-ui/accelerated_paint"]
embedded_resources = ["graphite-desktop-ui-cef/embedded_resources"]
accelerated_paint = ["graphite-desktop-ui-cef/accelerated_paint"]
[dependencies]
# Local dependencies
graphite-desktop-wrapper = { path = "wrapper" }
graphite-desktop-ui = { path = "ui" }
graphite-desktop-ui-cef = { path = "ui" }
graphite-wasm-wrapper = { path = "../frontend/wrapper", default-features = false, features = ["editor"] }
wgpu = { workspace = true }
winit = { workspace = true, features = [
+2 -2
View File
@@ -16,7 +16,7 @@ workspace = true
[features]
main = ["dep:graphite-desktop"]
helper = ["dep:graphite-desktop-ui"]
helper = ["dep:graphite-desktop-ui-cef"]
[[bin]]
name = "graphite"
@@ -30,4 +30,4 @@ required-features = ["helper"]
[dependencies]
graphite-desktop = { path = "../..", optional = true }
graphite-desktop-ui = { path = "../../ui", optional = true }
graphite-desktop-ui-cef = { path = "../../ui", optional = true }
+1 -1
View File
@@ -1,3 +1,3 @@
fn main() -> std::process::ExitCode {
graphite_desktop_ui::run_helper()
graphite_desktop_ui_cef::run_helper()
}
+11 -18
View File
@@ -20,13 +20,13 @@ use crate::dirs;
use crate::event::{AppEvent, AppEventScheduler};
use crate::input::InputState;
use crate::persist;
use crate::preferences;
use crate::preferences::{self, Acceleration};
use crate::render::{RenderError, RenderState};
use crate::spawner::TokioSpawner;
use crate::ui::{Acceleration, InputEvent, UiCommand, UiConfig, UiInstance};
use crate::ui::{InputEvent, Ui, UiBackend, UiCommand};
use crate::window::Window;
use crate::wrapper::messages::{DataTransfer, DesktopFrontendMessage, DesktopWrapperMessage, IngestAction};
use crate::wrapper::{DesktopWrapper, FolderStore, MmapResourceStorage, WgpuContext, WgpuExecutor, serialize_frontend_messages};
use crate::wrapper::messages::{DataTransfer, DesktopFrontendMessage, DesktopWrapperMessage, FrontendMessage, IngestAction};
use crate::wrapper::{DesktopWrapper, FolderStore, MmapResourceStorage, WgpuContext, WgpuExecutor};
pub(crate) struct App {
render_state: Option<RenderState>,
@@ -43,10 +43,10 @@ pub(crate) struct App {
app_event_scheduler: AppEventScheduler,
desktop_wrapper: DesktopWrapper,
runtime_command_sender: Sender<RuntimeCommand>,
ui: UiInstance,
ui: Ui,
ui_initialized: Option<Instant>,
ui_frame_received: bool,
ui_startup_buffer: Vec<Vec<u8>>,
ui_startup_buffer: Vec<Vec<FrontendMessage>>,
preferences: preferences::DesktopPreferences,
launch_documents: Option<Vec<PathBuf>>,
exiting: bool,
@@ -59,7 +59,7 @@ impl App {
}
pub(crate) fn new(
ui: UiInstance,
ui: Ui,
wgpu_context: WgpuContext,
app_event_receiver: Receiver<AppEvent>,
app_event_scheduler: AppEventScheduler,
@@ -181,8 +181,7 @@ impl App {
}
fn restart_ui(&mut self) {
let acceleration = self.preferences.acceleration;
if let Err(error) = self.ui.restart(UiConfig { acceleration }) {
if let Err(error) = self.ui.restart(&self.preferences) {
tracing::error!("Failed to restart the UI: {error}");
self.exit(Some(ExitReason::Shutdown));
return;
@@ -248,13 +247,7 @@ impl App {
fn handle_desktop_frontend_message(&mut self, message: DesktopFrontendMessage, responses: &mut Vec<DesktopWrapperMessage>) {
match message {
DesktopFrontendMessage::ToWeb(messages) => {
let Some(bytes) = serialize_frontend_messages(messages) else {
tracing::error!("Failed to serialize frontend messages");
return;
};
self.send_or_queue_web_message(bytes);
}
DesktopFrontendMessage::ToUi(messages) => self.send_or_queue_ui_message(messages),
DesktopFrontendMessage::OpenFileDialog { title, options, action } => {
let app_event_scheduler = self.app_event_scheduler.clone();
let _ = thread::spawn(move || {
@@ -465,7 +458,7 @@ impl App {
self.handle_desktop_frontend_messages(responses);
}
fn send_or_queue_web_message(&mut self, message: Vec<u8>) {
fn send_or_queue_ui_message(&mut self, message: Vec<FrontendMessage>) {
if self.ui_initialized.is_some() {
self.ui.send(UiCommand::Message(message));
} else {
@@ -475,7 +468,7 @@ impl App {
fn user_event(&mut self, event_loop: &dyn ActiveEventLoop, event: AppEvent) {
match event {
AppEvent::WebCommunicationInitialized => {
AppEvent::UiInitialized => {
self.ui_initialized = Some(Instant::now());
self.ui_frame_received = false;
for message in self.ui_startup_buffer.drain(..) {
-19
View File
@@ -9,25 +9,6 @@ pub(crate) fn ensure_dir_exists(path: &PathBuf) {
}
}
pub(crate) fn clear_dir(path: &PathBuf) {
let Ok(entries) = fs::read_dir(path) else {
tracing::error!("Failed to read directory at {path:?}");
return;
};
for entry in entries.flatten() {
let entry_path = entry.path();
if entry_path.is_dir() {
if let Err(e) = fs::remove_dir_all(&entry_path) {
tracing::error!("Failed to remove directory at {:?}: {}", entry_path, e);
}
} else if entry_path.is_file()
&& let Err(e) = fs::remove_file(&entry_path)
{
tracing::error!("Failed to remove file at {:?}: {}", entry_path, e);
}
}
}
pub(crate) fn app_data_dir() -> PathBuf {
let path = dirs::data_dir().expect("Failed to get data directory").join(APP_DIRECTORY_NAME);
ensure_dir_exists(&path);
+1 -1
View File
@@ -5,7 +5,7 @@ use crate::wrapper::messages::{DataTransfer, DesktopWrapperMessage};
pub(crate) enum AppEvent {
UiUpdate(wgpu::Texture),
CursorChange(Cursor),
WebCommunicationInitialized,
UiInitialized,
DesktopWrapperMessage(DesktopWrapperMessage),
ViewportTexture(Option<Texture>),
ClipboardRead,
+9 -29
View File
@@ -3,13 +3,13 @@ use crate::cli::Cli;
use crate::consts::APP_LOCK_FILE_NAME;
use crate::event::{AppEvent, CreateAppEventSchedulerEventLoopExt};
use clap::Parser;
use preferences::Acceleration;
use std::io::Write;
use std::process::ExitCode;
use tracing_subscriber::EnvFilter;
use ui::{Acceleration, UiConfig, UiContext, UiEvent, UiSetupResult};
use ui::{Ui, UiBackend, UiEvent};
use winit::event_loop::EventLoop;
pub(crate) use graphite_desktop_ui as ui;
pub(crate) use graphite_desktop_wrapper as wrapper;
mod app;
@@ -24,6 +24,7 @@ mod preferences;
mod render;
mod socket;
mod spawner;
mod ui;
mod window;
pub(crate) mod consts;
@@ -31,14 +32,9 @@ pub(crate) mod consts;
pub fn start() -> ExitCode {
tracing_subscriber::fmt().with_env_filter(EnvFilter::from_default_env()).init();
let ui_context = match UiContext::setup() {
UiSetupResult::Ready(context) => context,
UiSetupResult::Helper(code) => return code,
UiSetupResult::Failed => {
tracing::error!("Failed to set up the UI runtime");
return ExitCode::FAILURE;
}
};
if let Some(code) = ui::setup() {
return code;
}
let cli = Cli::parse();
@@ -73,8 +69,6 @@ pub fn start() -> ExitCode {
}
};
dirs::clear_dir(&ui::temp_dir_root());
// Must be called before event loop initialization or native window integrations will break
App::init();
@@ -98,14 +92,7 @@ pub fn start() -> ExitCode {
println!("UI acceleration is disabled");
}
let ui_context = match ui_context.start(UiConfig { acceleration: prefs.acceleration }) {
Ok(context) => context,
Err(error) => {
tracing::error!("Failed to start the UI runtime: {error}");
return ExitCode::FAILURE;
}
};
let ui = match ui_context.instance(&wgpu_context.device, &wgpu_context.queue) {
let ui = match Ui::start(&prefs, &wgpu_context) {
Ok(ui) => ui,
Err(error) => {
tracing::error!("Failed to start the UI: {error}");
@@ -120,17 +107,10 @@ pub fn start() -> ExitCode {
let spawned = std::thread::Builder::new().name("ui-events".to_string()).spawn(move || {
while let Some(event) = ui.recv() {
match event {
UiEvent::Ready => scheduler.schedule(AppEvent::WebCommunicationInitialized),
UiEvent::Ready => scheduler.schedule(AppEvent::UiInitialized),
UiEvent::Frame(texture) => scheduler.schedule(AppEvent::UiUpdate(texture)),
UiEvent::Cursor(cursor) => scheduler.schedule(AppEvent::CursorChange(cursor)),
UiEvent::Message(message) => match wrapper::deserialize_editor_message(&message) {
Some(message) => scheduler.schedule(AppEvent::DesktopWrapperMessage(message)),
None => tracing::error!("Failed to deserialize web message"),
},
UiEvent::Failure(error) => {
tracing::error!("UI failure: {error}");
scheduler.schedule(AppEvent::UiCrashed);
}
UiEvent::Message(message) => scheduler.schedule(AppEvent::DesktopWrapperMessage(message)),
UiEvent::Crashed => scheduler.schedule(AppEvent::UiCrashed),
}
}
+5 -1
View File
@@ -1,7 +1,11 @@
use graphite_desktop_wrapper::messages::Preferences;
use wgpu::PresentMode;
use crate::ui::Acceleration;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Acceleration {
Auto,
Disabled,
}
#[derive(Clone, PartialEq)]
pub(crate) struct DesktopPreferences {
+32
View File
@@ -0,0 +1,32 @@
use crate::preferences::DesktopPreferences;
use crate::wrapper::WgpuContext;
use crate::wrapper::messages::{DesktopWrapperMessage, FrontendMessage};
mod cef;
pub(crate) use cef::*;
pub(crate) trait UiBackend: Sized {
fn start(preferences: &DesktopPreferences, wgpu_context: &WgpuContext) -> Result<Self, UiError>;
fn send(&self, command: UiCommand);
fn recv(&self) -> Option<UiEvent>;
fn restart(&self, preferences: &DesktopPreferences) -> Result<(), UiError>;
fn shutdown(&self);
}
pub(crate) type UiError = Box<dyn std::error::Error + Send + Sync>;
pub(crate) enum UiCommand {
Input(InputEvent),
Resized { width: u32, height: u32 },
ScaleChanged(f64),
Refresh,
Message(Vec<FrontendMessage>),
}
pub(crate) enum UiEvent {
Ready,
Frame(wgpu::Texture),
Cursor(Cursor),
Message(DesktopWrapperMessage),
Crashed,
}
+120
View File
@@ -0,0 +1,120 @@
use super::{UiBackend, UiCommand, UiError, UiEvent};
use crate::preferences::{Acceleration, DesktopPreferences};
use crate::wrapper::WgpuContext;
use crate::wrapper::messages::DesktopWrapperMessage;
use graphite_desktop_ui_cef as cef;
use graphite_wasm_wrapper::native_communication::{decode_editor_command, encode_frontend_messages};
use std::fs;
use std::path::PathBuf;
use std::process::ExitCode;
use std::sync::Mutex;
pub(crate) use cef::{Cursor, InputEvent, InputEventBuilder, MULTICLICK_ALLOWED_TRAVEL, MULTICLICK_TIMEOUT, PINCH_ZOOM_SPEED, SCROLL_LINE_HEIGHT, SCROLL_LINE_WIDTH, SCROLL_SPEED_X, SCROLL_SPEED_Y};
#[derive(Clone)]
pub(crate) struct Ui {
instance: cef::UiInstance,
}
static SETUP: Mutex<Option<cef::UiContext<cef::Setup>>> = Mutex::new(None);
pub(crate) fn setup() -> Option<ExitCode> {
match cef::UiContext::setup() {
cef::UiSetupResult::Ready(context) => {
*SETUP.lock().unwrap() = Some(context);
None
}
cef::UiSetupResult::Failed => {
tracing::error!("Failed to set up the UI runtime");
Some(ExitCode::FAILURE)
}
cef::UiSetupResult::Helper(code) => Some(code),
}
}
impl UiBackend for Ui {
fn start(preferences: &DesktopPreferences, wgpu_context: &WgpuContext) -> Result<Self, UiError> {
let setup = SETUP.lock().unwrap().take().ok_or("The UI was started before it was set up")?;
clear_dir(&cef::temp_dir_root());
let context = setup.start(config(preferences))?;
let instance = context.instance(&wgpu_context.device, &wgpu_context.queue)?;
Ok(Self { instance })
}
fn send(&self, command: UiCommand) {
let command = match command {
UiCommand::Input(event) => cef::UiCommand::Input(event),
UiCommand::Resized { width, height } => cef::UiCommand::Resized { width, height },
UiCommand::ScaleChanged(scale) => cef::UiCommand::ScaleChanged(scale),
UiCommand::Refresh => cef::UiCommand::Refresh,
UiCommand::Message(messages) => {
let Some(bytes) = encode_frontend_messages(messages) else {
tracing::error!("Failed to serialize frontend messages");
return;
};
cef::UiCommand::Message(bytes)
}
};
self.instance.send(command);
}
fn recv(&self) -> Option<UiEvent> {
loop {
let event = match self.instance.recv()? {
cef::UiEvent::Ready => UiEvent::Ready,
cef::UiEvent::Frame(texture) => UiEvent::Frame(texture),
cef::UiEvent::Cursor(cursor) => UiEvent::Cursor(cursor),
cef::UiEvent::Message(bytes) => {
let Some(message) = decode_editor_command(&bytes) else {
tracing::error!("Failed to deserialize web message");
continue;
};
UiEvent::Message(DesktopWrapperMessage::FromUi(message.into()))
}
cef::UiEvent::Failure(error) => {
tracing::error!("UI failure: {error}");
UiEvent::Crashed
}
cef::UiEvent::Crashed => UiEvent::Crashed,
};
return Some(event);
}
}
fn restart(&self, preferences: &DesktopPreferences) -> Result<(), UiError> {
Ok(self.instance.restart(config(preferences))?)
}
fn shutdown(&self) {
self.instance.shutdown();
}
}
fn config(preferences: &DesktopPreferences) -> cef::UiConfig {
let acceleration = match preferences.acceleration {
Acceleration::Auto => cef::Acceleration::Auto,
Acceleration::Disabled => cef::Acceleration::Disabled,
};
cef::UiConfig { acceleration }
}
fn clear_dir(path: &PathBuf) {
let Ok(entries) = fs::read_dir(path) else {
tracing::error!("Failed to read directory at {path:?}");
return;
};
for entry in entries.flatten() {
let entry_path = entry.path();
if entry_path.is_dir() {
if let Err(e) = fs::remove_dir_all(&entry_path) {
tracing::error!("Failed to remove directory at {:?}: {}", entry_path, e);
}
} else if entry_path.is_file()
&& let Err(e) = fs::remove_file(&entry_path)
{
tracing::error!("Failed to remove file at {:?}: {}", entry_path, e);
}
}
}
+3 -3
View File
@@ -1,5 +1,5 @@
[package]
name = "graphite-desktop-ui"
name = "graphite-desktop-ui-cef"
description = "Renders the Graphite editor frontend UI into wgpu textures"
version.workspace = true
license.workspace = true
@@ -16,12 +16,12 @@ workspace = true
[features]
default = []
embedded_resources = ["dep:graphite-desktop-embedded-resources"]
embedded_resources = ["dep:graphite-desktop-ui-cef-embedded-resources"]
accelerated_paint = ["dep:ash", "dep:bytemuck", "dep:objc2-io-surface", "dep:objc2-metal", "dep:mach2"]
[dependencies]
# Local dependencies
graphite-desktop-embedded-resources = { path = "../embedded-resources", optional = true }
graphite-desktop-ui-cef-embedded-resources = { path = "embedded-resources", optional = true }
wgpu = { workspace = true }
wgpu-sync = { workspace = true }
@@ -1,5 +1,5 @@
[package]
name = "graphite-desktop-embedded-resources"
name = "graphite-desktop-ui-cef-embedded-resources"
description = "Graphite Desktop Embedded Resources"
version.workspace = true
license.workspace = true
@@ -1,5 +1,5 @@
const EMBEDDED_RESOURCES_ENV: &str = "EMBEDDED_RESOURCES";
const DEFAULT_RESOURCES_DIR: &str = "../../frontend/dist";
const DEFAULT_RESOURCES_DIR: &str = "../../../frontend/dist";
fn main() {
let mut embedded_resources: Option<String> = None;
+1 -1
View File
@@ -78,7 +78,7 @@ pub(crate) fn load(path: PathBuf) -> Option<Resource> {
WebResources::Embedded => {
#[cfg(feature = "embedded_resources")]
{
if let Some(resources) = &graphite_desktop_embedded_resources::EMBEDDED_RESOURCES
if let Some(resources) = &graphite_desktop_ui_cef_embedded_resources::EMBEDDED_RESOURCES
&& let Some(file) = resources.get_file(&path)
{
return Some(Resource {
-1
View File
@@ -17,7 +17,6 @@ workspace = true
[dependencies]
# Local dependencies
graphite-editor = { workspace = true }
graphite-wasm-wrapper = { path = "../../frontend/wrapper", default-features = false, features = ["editor"] }
graph-craft = { workspace = true }
wgpu-executor = { workspace = true }
@@ -5,7 +5,7 @@ use super::messages::{DesktopFrontendMessage, DesktopWrapperMessage, EditorMessa
pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMessageDispatcher, message: DesktopWrapperMessage) {
match message {
DesktopWrapperMessage::FromWeb(message) => {
DesktopWrapperMessage::FromUi(message) => {
dispatcher.queue_editor_message(*message);
}
DesktopWrapperMessage::Wake => {
-10
View File
@@ -2,7 +2,6 @@ use graph_craft::application_io::PlatformApplicationIo;
use graph_craft::application_io::resource::ResourceStorage;
use graphite_editor::application::{Editor, Environment, Host, Platform};
use graphite_editor::builder::{Builder, EditorBuilder, RuntimeBuilder};
use graphite_editor::messages::frontend::FrontendMessage;
use graphite_editor::node_graph_executor::NodeRuntime;
use message_dispatcher::DesktopWrapperMessageDispatcher;
@@ -80,12 +79,3 @@ impl DesktopWrapper {
executor.execute()
}
}
pub fn deserialize_editor_message(data: &[u8]) -> Option<DesktopWrapperMessage> {
let message = graphite_wasm_wrapper::native_communication::decode_editor_command(data)?;
Some(DesktopWrapperMessage::FromWeb(message.into()))
}
pub fn serialize_frontend_messages(messages: Vec<FrontendMessage>) -> Option<Vec<u8>> {
graphite_wasm_wrapper::native_communication::encode_frontend_messages(messages)
}
+1 -1
View File
@@ -60,7 +60,7 @@ impl<'a> DesktopWrapperMessageDispatcher<'a> {
}
if !frontend_messages.is_empty() {
self.respond(DesktopFrontendMessage::ToWeb(frontend_messages));
self.respond(DesktopFrontendMessage::ToUi(frontend_messages));
}
}
}
+3 -3
View File
@@ -1,4 +1,4 @@
use graphite_editor::messages::prelude::FrontendMessage;
pub use graphite_editor::messages::prelude::FrontendMessage;
use std::path::PathBuf;
pub(crate) use graphite_editor::messages::prelude::Message as EditorMessage;
@@ -12,7 +12,7 @@ pub use graphite_editor::messages::prelude::InputPreprocessorMessage as InputMes
pub use graphite_editor::messages::prelude::PreferencesMessageHandler as Preferences;
pub enum DesktopFrontendMessage {
ToWeb(Vec<FrontendMessage>),
ToUi(Vec<FrontendMessage>),
OpenLaunchDocuments,
OpenFileDialog {
title: String,
@@ -69,7 +69,7 @@ pub enum DesktopFrontendMessage {
}
pub enum DesktopWrapperMessage {
FromWeb(Box<EditorMessage>),
FromUi(Box<EditorMessage>),
Wake,
Input(InputMessage),
Ingest { content: DataTransfer, action: IngestAction },
@@ -3,4 +3,3 @@
use migration_core::rename;
rename!("raster_nodes::filter::BlurNode"@1 => "blending_nodes::effects::BlurNode"@2);
rename!("blending_nodes::filters::AddNoiseNode"@1 => "blending_nodes::filters::SpeckleNode"@2);
@@ -1,111 +0,0 @@
use migration_core::{Inputs, MigrationError, Node, NodeInput, encode, literal_of, migration};
use serde::{Deserialize, Serialize};
const GRADIENT_FORM: u32 = 4;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
Number(f64),
#[serde(alias = "GradientType")]
GradientForm(GradientForm),
}
#[derive(Serialize, Deserialize)]
enum GradientForm {
Linear,
Radial,
}
/// 'Fill' gives the gradient it paints the curvatures of a form, rather than the form: 0 and 0 for linear, and -1 and 0.5 for radial.
/// A wired form becomes linear, and the curvatures stay shown in the graph where the form was.
#[migration("graphene_core::vector::FillNode"@1 => @2)]
pub fn fill_v1(node: &Node, inputs: &mut Inputs) -> Result<(), MigrationError> {
let Some(form) = node.inputs().get(GRADIENT_FORM as usize) else {
return Err(MigrationError::invariant("Fill has a gradient form input"));
};
let [start, end] = match literal_of::<Tagged>(&form.input) {
Some(Tagged::GradientForm(GradientForm::Radial)) => [-1., 0.5],
_ => [0., 0.],
};
let exposed = match form.input {
NodeInput::Value { exposed, .. } => exposed,
_ => true,
};
let curvature = |curvature: f64| NodeInput::Value {
value: encode(&Tagged::Number(curvature)),
exposed,
};
inputs.set(GRADIENT_FORM, curvature(start));
inputs.insert(GRADIENT_FORM + 1, curvature(end));
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::{decl, literal};
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
const FORM_SLOT: usize = GRADIENT_FORM as usize;
/// A form stored under its name from before 'Gradient Type' became 'Gradient Form'.
#[derive(Serialize)]
enum LegacyTagged {
GradientType(GradientForm),
}
fn form(form: GradientForm) -> NodeInput {
literal(Tagged::GradientForm(form))
}
fn contract() -> SourceContract {
SourceContract::new(7, |random, slot| match slot {
FORM_SLOT if random.below(2) == 0 => form(GradientForm::Radial),
FORM_SLOT => form(GradientForm::Linear),
_ => literal(Tagged::Number(random.below(10) as f64)),
})
}
#[test]
fn rewrites_history() {
check_commutation(&FillV1, &contract());
check_undo(&FillV1, &contract());
}
#[test]
fn forms_become_their_curvature_presets() {
let other_inputs: Vec<NodeInput> = (0..7).map(|index| literal(Tagged::Number(index as f64))).collect();
let shown_radial = NodeInput::Value {
value: encode(&Tagged::GradientForm(GradientForm::Radial)),
exposed: true,
};
let curvature = |curvature: f64, exposed: bool| NodeInput::Value {
value: encode(&Tagged::Number(curvature)),
exposed,
};
// The curvatures stay shown in the graph where an exposed or wired form was, and the inputs after them keep their values
for (old_form, [start, end], exposed) in [
(form(GradientForm::Linear), [0., 0.], false),
(form(GradientForm::Radial), [-1., 0.5], false),
(literal(LegacyTagged::GradientType(GradientForm::Radial)), [-1., 0.5], false),
(shown_radial, [-1., 0.5], true),
(NodeInput::Import { index: 0 }, [0., 0.], true),
] {
let mut old_inputs = other_inputs.clone();
old_inputs[FORM_SLOT] = old_form;
let mut fixture = Fixture::new(&FillV1);
let fill = fixture.add(decl!("graphene_core::vector::FillNode"@1), old_inputs);
let migrated = fixture.migrate(&FillV1).unwrap();
let mut expected = other_inputs.clone();
expected.splice(FORM_SLOT..=FORM_SLOT, [curvature(start, exposed), curvature(end, exposed)]);
assert_eq!(fixture.declaration_of(&migrated, fill), Some(decl!("graphene_core::vector::FillNode"@2)));
assert_eq!(fixture.inputs(&migrated, fill), expected);
}
}
}
@@ -1,7 +1,5 @@
//! Migrations of the nodes in `graphene_core`.
mod fill_v1;
mod passthrough_from_read_attribute_gradient_form_node;
mod passthrough_from_upload_texture_node;
mod renames;
mod vary_colors_from_assign_colors;
@@ -1,36 +0,0 @@
use migration_core::{Inputs, migration};
/// 'Read Attribute Gradient Form' is gone since no node writes that attribute anymore, so it passes its content on and drops the attribute name.
#[migration("graphic_nodes::graphic::ReadAttributeGradientFormNode"@1 => "graphene_core::ops::PassthroughNode"@2)]
pub fn passthrough_from_read_attribute_gradient_form_node(inputs: &mut Inputs) {
inputs.truncate(1);
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::{decl, literal};
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&PassthroughFromReadAttributeGradientFormNode, &contract());
check_undo(&PassthroughFromReadAttributeGradientFormNode, &contract());
}
#[test]
fn keeps_the_content_and_drops_the_name() {
let (content, name) = (literal(1.), literal("gradient_form".to_string()));
let mut fixture = Fixture::new(&PassthroughFromReadAttributeGradientFormNode);
let read_attribute = fixture.add(decl!("graphic_nodes::graphic::ReadAttributeGradientFormNode"@1), vec![content.clone(), name]);
let migrated = fixture.migrate(&PassthroughFromReadAttributeGradientFormNode).unwrap();
assert_eq!(fixture.declaration_of(&migrated, read_attribute), Some(decl!("graphene_core::ops::PassthroughNode"@2)));
assert_eq!(fixture.inputs(&migrated, read_attribute), [content]);
}
}
@@ -1,127 +0,0 @@
use migration_core::attr::node::ui::DISPLAY_NAME;
use migration_core::{Attributes, Inputs, MigrationError, Node, NodeInput, encode, literal_of, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants this migration uses.
#[derive(Serialize, Deserialize)]
enum Tagged {
Number(f64),
#[serde(alias = "GradientType")]
GradientForm(GradientForm),
}
#[derive(Serialize, Deserialize)]
enum GradientForm {
Linear,
Radial,
}
const FORM: u32 = 1;
/// 'Gradient Form' became 'Gradient Curvature', with start and end curvatures taking the presets of the form it set: 0 and 0 for linear, -1 and 0.5 for
/// radial. A wired form becomes linear, the curvatures stay shown in the graph where the form was, 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.],
};
let exposed = match form.input {
NodeInput::Value { exposed, .. } => exposed,
_ => true,
};
let curvature = |curvature: f64| NodeInput::Value {
value: encode(&Tagged::Number(curvature)),
exposed,
};
inputs.set(FORM, curvature(start));
inputs.push(curvature(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::{decl, literal};
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());
}
/// A form stored under its name from before 'Gradient Type' became 'Gradient Form'.
#[derive(Serialize)]
enum LegacyTagged {
GradientType(GradientForm),
}
#[test]
fn forms_become_their_curvature_presets() {
let gradient = literal(Tagged::Number(0.));
let shown_radial = NodeInput::Value {
value: encode(&Tagged::GradientForm(GradientForm::Radial)),
exposed: true,
};
let curvature = |curvature: f64, exposed: bool| NodeInput::Value {
value: encode(&Tagged::Number(curvature)),
exposed,
};
// Curvatures stay shown in the graph where an exposed or wired form was
for (old_form, [start, end], exposed) in [
(form(GradientForm::Linear), [0., 0.], false),
(form(GradientForm::Radial), [-1., 0.5], false),
(literal(LegacyTagged::GradientType(GradientForm::Radial)), [-1., 0.5], false),
(shown_radial, [-1., 0.5], true),
(NodeInput::Import { index: 0 }, [0., 0.], true),
] {
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(), curvature(start, exposed), curvature(end, exposed)]);
}
}
#[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,5 +1,4 @@
//! Migrations of the nodes in `math_nodes`.
mod gradient_curvature_from_gradient_form;
mod math_formula_from_math_f;
mod renames;
-14
View File
@@ -148,24 +148,10 @@ pub const CURVATURE_COMB_MAX_TEETH_PER_SEGMENT: f64 = 128.;
pub const CURVATURE_COMB_MAX_TOOTH_LENGTH: f64 = 2000.;
// GRADIENT TOOL
pub const GRADIENT_LINE_WIDTH: f64 = 2.;
// Half the height of a midpoint diamond across the gradient line
pub const GRADIENT_MIDPOINT_DIAMOND_HALF_HEIGHT: f64 = 5.;
// Half the width of a midpoint diamond along the gradient line
pub const GRADIENT_MIDPOINT_DIAMOND_HALF_WIDTH: f64 = 3.;
// The radius of the circle approximating a midpoint diamond, which a press is measured against
pub const GRADIENT_MIDPOINT_DIAMOND_RADIUS: f64 = 4.;
// The radius of a color stop dot at its regular size, which a press is measured against
pub const GRADIENT_STOP_RADIUS: f64 = MANIPULATOR_GROUP_MARKER_SIZE / 1.5 + 1.;
pub const GRADIENT_MIDPOINT_MIN: f64 = 0.01;
pub const GRADIENT_MIDPOINT_MAX: f64 = 0.99;
pub const GRADIENT_STOP_MIN_VIEWPORT_GAP: f64 = 10.;
// In viewport pixels from a contour's dashed rim, within which a press takes hold of it
pub const GRADIENT_CONTOUR_RIM_GRAB_DISTANCE: f64 = 5.;
// In viewport pixels, within which a dragged contour handle snaps onto making its contour a line or a point
pub const GRADIENT_CONTOUR_SNAP_DISTANCE: f64 = 4.;
// In viewport pixels, the shortest an end circle's semi-minor axis lines are drawn, below which they have no aspect handles at their tips
pub const GRADIENT_SEMI_MINOR_AXIS_MIN_LENGTH: f64 = 20.;
// PEN TOOL
pub const CREATE_CURVE_THRESHOLD: f64 = 5.;
@@ -5,14 +5,10 @@ use crate::test_utils::gpu_executor;
use crate::test_utils::test_prelude::*;
use glam::{DAffine2, UVec2};
use graph_craft::document::value::TaggedValue;
use graphene_std::application_io::Texture;
use graphene_std::blending_nodes::effects::{blur, drop_shadow};
use graphene_std::graphic::{IntoGraphicList, extend};
use graphene_std::list::{Item, List};
use graphene_std::math_nodes::{color_value, gradient_value};
use graphene_std::raster_nodes::std_nodes::noise_pattern;
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
use graphene_std::vector::style::RenderMode;
use graphene_std::{Graphic, NodeParameter, ProtoNodeIdentifier, Vector};
#[derive(Clone, Copy, Debug)]
@@ -140,111 +136,6 @@ fn assert_clip(name: &str, graphic: &Graphic, blurred: bool) {
assert_eq!(pixel(170, 90)[3], 0, "{name}: the red is clipped away well past the base");
}
/// Endless content a layer can hold, which fills the whole canvas unless something clips it.
#[derive(Clone, Copy, Debug)]
enum Endless {
Color,
Gradient,
NoisePattern,
}
/// A document viewed in the `render_mode` with a blue rectangle filling (50, 50) to (130, 130).
async fn document_with_a_rectangle(render_mode: RenderMode) -> EditorTestUtils {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.handle_message(DocumentMessage::SetRenderMode { render_mode }).await;
let blue = Color::from_rgbaf32_unchecked(0., 0., 1., 1.);
editor.select_primary_color(blue).await;
editor.select_secondary_color(blue).await;
editor.draw_rect(50., 50., 130., 130.).await;
editor
}
/// Adds a new layer of `endless` content above the selected layer, clipped to it as by an Alt-click between them.
async fn add_clipped_endless_layer(editor: &mut EditorTestUtils, endless: Endless) {
editor.handle_message(DocumentMessage::CreateEmptyFolder).await;
let layer = editor.get_selected_layer().await.expect("the new layer is selected");
let node = match endless {
Endless::Color => color_value::IDENTIFIER,
Endless::Gradient => gradient_value::IDENTIFIER,
Endless::NoisePattern => noise_pattern::IDENTIFIER,
};
let node_type = DefinitionIdentifier::ProtoNode(node);
editor.handle_message(NodeGraphMessage::CreateNodeInLayerWithTransaction { node_type, layer }).await;
editor.handle_message(DocumentMessage::ClipLayer { id: layer.to_node() }).await;
}
/// Evaluates the document for a viewport of `size` as the app does, returning what the frontend is sent and the frame the runtime presents.
async fn evaluate_viewport(editor: &mut EditorTestUtils, size: UVec2) -> (Vec<FrontendMessage>, Option<Texture>) {
let portfolio = editor.portfolio_message_handler_mut();
let document_id = portfolio.active_document_id.expect("a document is open");
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
let document = documents.get_mut(&document_id).expect("the active document exists");
let submitted = executor
.submit_node_graph_evaluation(document, document_id, size, 1., Default::default(), Vec::new(), true, DVec2::ZERO)
.expect("the evaluation is submitted");
let mut messages = editor.dispatch(submitted);
editor.runtime.update();
let frame = editor.runtime.run().await;
messages.extend(editor.dispatch(Message::Wake));
(messages, frame)
}
#[tokio::test]
async fn endless_layers_clip_to_the_shape_beneath_them() {
let size = UVec2::new(256, 256);
let frame_pixels = async |editor: &mut EditorTestUtils| {
let (_, frame) = evaluate_viewport(editor, size).await;
let frame = frame.expect("the viewport presents a frame");
gpu_executor().read_texture_pixels(&frame).expect("the frame reads back")
};
let pixel = |pixels: &[u8], x: u32, y: u32| {
let index = (y * size.x + x) as usize * 4;
[pixels[index], pixels[index + 1], pixels[index + 2], pixels[index + 3]]
};
for endless in [Endless::Color, Endless::Gradient, Endless::NoisePattern] {
// In the viewport's Vello render, the endless content covers the rectangle but leaves the canvas past it as the rectangle alone left it
let mut editor = document_with_a_rectangle(RenderMode::Normal).await;
let rectangle_alone = frame_pixels(&mut editor).await;
add_clipped_endless_layer(&mut editor, endless).await;
let clipped = frame_pixels(&mut editor).await;
assert_ne!(pixel(&clipped, 90, 90), pixel(&rectangle_alone, 90, 90), "{endless:?}: the content shows within the rectangle");
for (x, y) in [(20, 20), (200, 90), (90, 200), (230, 230)] {
assert_eq!(
pixel(&clipped, x, y),
pixel(&rectangle_alone, x, y),
"{endless:?}: the content is clipped away at ({x}, {y}), past the rectangle"
);
}
// In SVG Preview, the endless content is drawn only within the rectangle's mask
let mut editor = document_with_a_rectangle(RenderMode::SvgPreview).await;
add_clipped_endless_layer(&mut editor, endless).await;
let (messages, _) = evaluate_viewport(&mut editor, size).await;
let svg = messages
.into_iter()
.find_map(|message| match message {
FrontendMessage::UpdateDocumentArtwork { svg } => Some(svg),
_ => None,
})
.expect("the viewport's artwork is sent as SVG");
let (unmasked, masked) = svg.split_once(r#"mask="url(#mask-"#).unwrap_or_else(|| panic!("{endless:?}: the content is masked: {svg}"));
let draws_endless_content = |markup: &str| ["<polyline", "<foreignObject"].iter().any(|tag| markup.contains(tag));
assert!(
!draws_endless_content(unmasked) && draws_endless_content(masked),
"{endless:?}: the content is drawn within the mask: {svg}"
);
}
}
#[tokio::test]
async fn clipping_bases_clip_by_their_filters_but_not_the_shadows_they_cast() {
for (effect_name, effect, blurred) in [("Blur", blur::IDENTIFIER, true), ("Drop Shadow", drop_shadow::IDENTIFIER, false)] {
@@ -31,8 +31,7 @@ use graphene_std::vector::misc::{
WeldMethod,
};
use graphene_std::vector::style::{
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap,
StrokeJoin,
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::{
@@ -409,6 +408,7 @@ macro_rules! inspectable_types {
List<DVec2>,
List<DAffine2>,
List<BlendMode>,
List<GradientForm>,
List<GradientSpread>,
List<GradientSpace>,
List<GradientHueDirection>,
@@ -469,7 +469,6 @@ macro_rules! inspectable_types {
Item<DAffine2>,
Item<BlendMode>,
Item<GradientForm>,
Item<GradientModel>,
Item<GradientSpread>,
Item<GradientSpace>,
Item<GradientHueDirection>,
@@ -1285,7 +1284,6 @@ impl_table_item_layout_for_choice_enum!(
MaskMode,
MinimumMaximumMode,
GradientForm,
GradientModel,
GradientSpread,
GradientSpace,
GradientHueDirection,
@@ -1481,7 +1479,6 @@ macro_rules! known_item_types {
TransferCurve,
BlendMode,
GradientForm,
GradientModel,
GradientSpread,
GradientSpace,
GradientHueDirection,
@@ -4138,7 +4138,7 @@ impl DocumentMessageHandler {
})
.unwrap_or((None, None, None));
let blend_mode_menu_entries = BlendMode::list()
let blend_mode_menu_entries = BlendMode::list_svg_subset()
.iter()
.map(|modes| {
modes
@@ -4155,7 +4155,7 @@ impl DocumentMessageHandler {
let widgets = vec![
DropdownInput::new(blend_mode_menu_entries)
.selected_index(blend_mode.and_then(|blend_mode| blend_mode.index_in_list()).map(|index| index as u32))
.selected_index(blend_mode.and_then(|blend_mode| blend_mode.index_in_list_svg_subset()).map(|index| index as u32))
.disabled(disabled)
.draw_icon(false)
.sizing(WidgetSizing::default().grow(false))
@@ -26,8 +26,7 @@ pub enum GraphOperationMessage {
layer: LayerNodeIdentifier,
#[serde(skip)]
gradient: Gradient,
/// The form whose curvatures the Fill takes, or `None` to keep its own.
gradient_form: Option<GradientForm>,
gradient_form: GradientForm,
gradient_settings: GradientSettings,
/// `None` lets the gradient cover the layer's bounding box, following it as the layer changes.
transform: Option<DAffine2>,
@@ -57,11 +56,6 @@ pub enum GraphOperationMessage {
layer: LayerNodeIdentifier,
gradient_form: GradientForm,
},
GradientCurvatureSet {
layer: LayerNodeIdentifier,
/// The start and end curvatures.
curvatures: [f64; 2],
},
GradientSpreadSet {
layer: LayerNodeIdentifier,
gradient_spread: GradientSpread,
@@ -86,11 +86,6 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
modify_inputs.gradient_form_set(gradient_form);
}
}
GraphOperationMessage::GradientCurvatureSet { layer, curvatures } => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.gradient_curvature_set(curvatures);
}
}
GraphOperationMessage::GradientSpreadSet { layer, gradient_spread } => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.gradient_spread_set(gradient_spread);
@@ -1039,7 +1034,7 @@ fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, g
space: gradient_info.spaces.get(linear.id()).copied().unwrap_or(GradientSpace::RgbGamma),
..Default::default()
};
modify_inputs.fill_gradient_set(gradient, Some(gradient_form), settings, Some(transform));
modify_inputs.fill_gradient_set(gradient, gradient_form, settings, Some(transform));
}
usvg::Paint::RadialGradient(radial) => {
let gradient_transform = usvg_transform(radial.transform());
@@ -1067,7 +1062,7 @@ fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, g
space: gradient_info.spaces.get(radial.id()).copied().unwrap_or(GradientSpace::RgbGamma),
..Default::default()
};
modify_inputs.fill_gradient_set(gradient, Some(gradient_form), settings, Some(transform));
modify_inputs.fill_gradient_set(gradient, gradient_form, settings, Some(transform));
}
usvg::Paint::Pattern(_) => warn!("SVG patterns are not currently supported"),
};
@@ -6,8 +6,7 @@ use crate::messages::portfolio::document::utility_types::document_metadata::Laye
use crate::messages::portfolio::document::utility_types::network_interface::{self, FlowType, InputConnector, NodeNetworkInterface, OutputConnector};
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::graph_modification_utils::{
ReplaceablePaintChain, fill_node_curvatures, get_fill_input_node_id, get_fill_node_id_with_direct_fill_input, get_upstream_gradient_value_node_id, gradient_chain_target_input,
gradient_curvature_values, replaceable_paint_chain,
ReplaceablePaintChain, get_fill_input_node_id, get_upstream_gradient_value_node_id, gradient_chain_target_input, replaceable_paint_chain,
};
use glam::{DAffine2, DVec2, IVec2};
use graph_craft::application_io::resource::ResourceId;
@@ -451,8 +450,7 @@ impl<'a> ModifyInputsContext<'a> {
}
}
/// Paints the layer's Fill with `gradient`, giving its curvatures those of `gradient_form` if that's given, unless the graph feeds them.
pub fn fill_gradient_set(&mut self, gradient: Gradient, gradient_form: Option<GradientForm>, settings: GradientSettings, transform: Option<DAffine2>) {
pub fn fill_gradient_set(&mut self, gradient: Gradient, gradient_form: GradientForm, settings: GradientSettings, transform: Option<DAffine2>) {
let existing_fill_node_id = self.existing_chain_hosted_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, false);
let Some(fill_node_id) = existing_fill_node_id.or_else(|| self.existing_chain_hosted_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, true)) else {
return;
@@ -492,31 +490,17 @@ impl<'a> ModifyInputsContext<'a> {
}
}
// Only a chosen form sets the curvatures, leaving any the graph feeds or that already make it
if let Some(gradient_form) = gradient_form {
self.write_fill_curvatures(fill_node_id, gradient_form.curvatures(), |current| GradientForm::from_curvatures(current) == Some(gradient_form));
}
self.responses.add(NodeGraphMessage::RunDocumentGraph);
self.set_input_with_refresh(
InputConnector::node(fill_node_id, graphene_std::vector::fill::GradientFormInput),
NodeInput::value(TaggedValue::GradientForm(gradient_form), false),
false,
);
if existing_fill_node_id.is_none() {
self.restore_default_stroke_order();
}
}
/// Write both curvatures to a Fill node's hidden curvature inputs unless the graph feeds them or its current ones are `already_written`, for the caller to then run the graph.
fn write_fill_curvatures(&mut self, fill_node_id: NodeId, curvatures: [f64; 2], already_written: impl Fn([f64; 2]) -> bool) {
use graphene_std::vector::fill::{EndCurvatureInput, StartCurvatureInput};
let current = self.network_interface.document_network().nodes.get(&fill_node_id).and_then(fill_node_curvatures);
if current.is_none_or(already_written) {
return;
}
let [start, end] = curvatures;
self.set_input_with_refresh(InputConnector::node(fill_node_id, StartCurvatureInput), NodeInput::value(TaggedValue::Number(start), false), true);
self.set_input_with_refresh(InputConnector::node(fill_node_id, EndCurvatureInput), NodeInput::value(TaggedValue::Number(end), false), true);
}
/// A freshly created Fill node lands at the chain start, downstream of any Stroke node, where it would
/// paint over the stroke. This hops the stroke back downstream so it keeps painting above by default.
fn restore_default_stroke_order(&mut self) {
@@ -777,47 +761,20 @@ impl<'a> ModifyInputsContext<'a> {
self.responses.add(NodeGraphMessage::RunDocumentGraph);
}
/// 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`). Curvatures fed from the graph (procedural authorship) or already making the form are left untouched.
/// Write the Gradient Form to the last 'Gradient Form' node in the chain, inserting one only when the value differs
/// from the default (`Linear`).
pub fn gradient_form_set(&mut self, gradient_form: GradientForm) {
self.write_gradient_curvatures(gradient_form.curvatures(), |current| GradientForm::from_curvatures(current) == Some(gradient_form));
}
/// Write both curvatures to the layer's gradient: a Fill node holding it, or else the last 'Gradient Curvature' node in its chain, inserting
/// one only when they differ from the default form's (`Linear`). Curvatures fed from the graph (procedural authorship) are left untouched.
pub fn gradient_curvature_set(&mut self, curvatures: [f64; 2]) {
if let Some(output_layer) = self.get_output_layer()
&& let Some(fill_node_id) = get_fill_node_id_with_direct_fill_input(output_layer, self.network_interface)
{
self.write_fill_curvatures(fill_node_id, curvatures, |current| current == curvatures);
self.responses.add(NodeGraphMessage::RunDocumentGraph);
return;
}
self.write_gradient_curvatures(curvatures, |current| current == curvatures);
}
/// Write these curvatures to the last 'Gradient Curvature' node in the chain unless its current ones are `already_written`.
fn write_gradient_curvatures(&mut self, curvatures: [f64; 2], already_written: impl Fn([f64; 2]) -> bool) {
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, IDENTIFIER, StartCurvatureInput};
let Some(output_layer) = self.get_output_layer() else { return };
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
let create_if_nonexistent = curvatures != GradientForm::default().curvatures();
let Some(node_id) = self.existing_proto_node_id_at(&target_input, IDENTIFIER, create_if_nonexistent) else {
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 {
return;
};
let Some(node) = self.network_interface.document_network().nodes.get(&node_id) else { return };
let Some(current) = gradient_curvature_values(node) else { return };
if already_written(current) {
return;
}
let [start, end] = curvatures;
self.set_input_with_refresh(InputConnector::node(node_id, StartCurvatureInput), NodeInput::value(TaggedValue::Number(start), false), true);
self.set_input_with_refresh(InputConnector::node(node_id, EndCurvatureInput), NodeInput::value(TaggedValue::Number(end), false), false);
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);
}
/// Set the spread on the chain's gradient value, which is where the ramp carries it.
@@ -1,11 +1,11 @@
use crate::application::Environment;
use crate::consts::{
DOUBLE_CLICK_ALLOWED_TRAVEL, VIEWPORT_ROTATE_SNAP_INTERVAL, VIEWPORT_SCROLL_RATE, VIEWPORT_ZOOM_LEVELS, VIEWPORT_ZOOM_MIN_FRACTION_COVER, VIEWPORT_ZOOM_MOUSE_RATE, VIEWPORT_ZOOM_SCALE_MAX,
VIEWPORT_ZOOM_SCALE_MIN, VIEWPORT_ZOOM_TO_FIT_PADDING_SCALE_FACTOR,
VIEWPORT_ROTATE_SNAP_INTERVAL, VIEWPORT_SCROLL_RATE, VIEWPORT_ZOOM_LEVELS, VIEWPORT_ZOOM_MIN_FRACTION_COVER, VIEWPORT_ZOOM_MOUSE_RATE, VIEWPORT_ZOOM_SCALE_MAX, VIEWPORT_ZOOM_SCALE_MIN,
VIEWPORT_ZOOM_TO_FIT_PADDING_SCALE_FACTOR,
};
use crate::messages::frontend::utility_types::MouseCursorIcon;
use crate::messages::input_mapper::utility_types::keyboard::{Key, MouseMotion};
use crate::messages::input_mapper::utility_types::pointer::{MouseKeys, ViewportPosition};
use crate::messages::input_mapper::utility_types::pointer::ViewportPosition;
use crate::messages::portfolio::document::navigation::utility_types::NavigationOperation;
use crate::messages::portfolio::document::utility_types::misc::PTZ;
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
@@ -34,8 +34,6 @@ pub struct NavigationMessageHandler {
abortable_pan_start: Option<f64>,
/// Whether the current drag navigates the artwork behind the open node graph, rather than the graph itself.
artwork_behind_graph: bool,
/// Where a middle press began panning the open node graph, kept until the pointer travels too far for its release to still be a click.
graph_middle_click_start: Option<ViewportPosition>,
}
#[message_handler_data]
@@ -101,10 +99,6 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
return;
};
self.navigation_operation = NavigationOperation::Pan { pan_original_for_abort: ptz.pan };
// Released before traveling far, a middle press that pans the open graph is instead a click on the node under it
let middle_press_in_graph = graph_view_overlay_open && ipp.mouse.mouse_keys == MouseKeys::MIDDLE;
self.graph_middle_click_start = middle_press_in_graph.then_some(ipp.mouse.position);
}
NavigationMessage::BeginCanvasTilt { was_dispatched_from_menu } => {
let Some(ptz) = get_ptz(document_ptz, network_interface, graph_view_overlay_open, breadcrumb_network_path) else {
@@ -347,13 +341,6 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
responses.add(ToolMessage::UpdateCursor);
responses.add(ToolMessage::UpdateHints);
responses.add(NavigateToolMessage::End);
// Not a pan after all, but a middle click in the graph
let middle_click_start = self.graph_middle_click_start.take();
let middle_released = !ipp.mouse.mouse_keys.contains(MouseKeys::MIDDLE);
if !abort_transform && middle_released && middle_click_start.is_some_and(|start| start.distance(ipp.mouse.position) <= DOUBLE_CLICK_ALLOWED_TRAVEL) {
responses.add(NodeGraphMessage::MiddleClick);
}
}
NavigationMessage::EndCanvasPTZWithClick { commit_key } => {
self.finish_operation_with_click = false;
@@ -430,10 +417,6 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
}
}
NavigationMessage::PointerMove { snap } => {
if self.graph_middle_click_start.is_some_and(|start| start.distance(ipp.mouse.position) > DOUBLE_CLICK_ALLOWED_TRAVEL) {
self.graph_middle_click_start = None;
}
match self.navigation_operation {
NavigationOperation::None => {}
NavigationOperation::Pan { .. } => {
@@ -686,7 +686,6 @@ 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));
@@ -170,8 +170,6 @@ pub enum NodeGraphMessage {
PointerOutsideViewport {
shift: Key,
},
/// Sent when the middle button is released where it was pressed in the graph, rather than having panned it.
MiddleClick,
/// Sent every frame while a dragged wire hovers a node, to expand it once the hover delay passes.
WireHoverTick,
/// Sends where everything gliding into place is drawn, along with the wires that follow it.
@@ -439,7 +437,6 @@ impl NodeGraphMessage {
| Self::PointerMove { .. }
| Self::PointerUp
| Self::PointerOutsideViewport { .. }
| Self::MiddleClick
| Self::WireHoverTick
| Self::SendGlide
| Self::GlideTick
@@ -1752,20 +1752,6 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
self.auto_panning.stop(&messages, responses);
}
}
// Middle-clicking a node toggles its visibility
NodeGraphMessage::MiddleClick => {
if !graph_view_overlay_open || network_interface.is_read_only(breadcrumb_network_path) {
return;
}
let Some(node_id) = network_interface.node_from_click(ipp.mouse.position, breadcrumb_network_path) else {
return;
};
responses.add(NodeGraphMessage::ToggleVisibility {
node_id,
network_path: breadcrumb_network_path.to_vec(),
});
}
NodeGraphMessage::WireHoverTick => {
self.expand_wire_hovered_node_after_delay(ipp.time, ipp.mouse.position, network_interface, selection_network_path, responses);
}
@@ -37,8 +37,8 @@ use graphene_std::vector::misc::{
ArcType, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod, WeldMethod,
};
use graphene_std::vector::style::{
FillChoice, Gradient, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStops, StrokeAlign,
StrokeCap, StrokeJoin, build_transform_with_y_preservation,
FillChoice, Gradient, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStops, StrokeAlign, StrokeCap, StrokeJoin,
build_transform_with_y_preservation,
};
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution, Vector};
@@ -254,23 +254,6 @@ pub(crate) struct ParameterOptions {
pub step: Option<f64>,
}
impl From<&graphene_std::registry::FieldMetadata> for ParameterOptions {
fn from(field: &graphene_std::registry::FieldMetadata) -> Self {
Self {
soft_min: field.number_soft_min,
soft_max: field.number_soft_max,
hard_min: field.number_hard_min,
hard_max: field.number_hard_max,
slider: field.number_mode_range,
multiline: field.multiline,
progression: field.progression,
unit: field.unit,
display_decimal_places: field.number_display_decimal_places,
step: field.number_step,
}
}
}
/// The values a range slider's two ends map to linearly and the one its double-click restores, if known.
#[derive(Clone, Copy)]
pub struct SliderRange {
@@ -434,7 +417,6 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
// AUTO-GENERATED ENUM TYPES
// =========================
Some(x) if id_is::<GradientForm>(x) => enum_choice::<GradientForm>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<GradientModel>(x) => enum_choice::<GradientModel>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<GradientSpread>(x) => enum_choice::<GradientSpread>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<GradientSpace>(x) => enum_choice::<GradientSpace>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<GradientHueDirection>(x) => enum_choice::<GradientHueDirection>().for_socket(default_info).inspector_row(),
@@ -1355,7 +1337,7 @@ pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Layout
return LayoutGroup::row(vec![]);
};
if let Some(&TaggedValue::BlendMode(blend_mode)) = input.as_non_exposed_value() {
let entries = BlendMode::list()
let entries = BlendMode::list_svg_subset()
.iter()
.map(|category| {
category
@@ -1372,7 +1354,9 @@ pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Layout
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
DropdownInput::new(entries).selected_index(blend_mode.index_in_list().map(|index| index as u32)).widget_instance(),
DropdownInput::new(entries)
.selected_index(blend_mode.index_in_list_svg_subset().map(|index| index as u32))
.widget_instance(),
]);
}
LayoutGroup::row(widgets).with_tooltip_description("Formula used for blending.")
@@ -3304,80 +3288,6 @@ 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::*;
// 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) => graph_modification_utils::gradient_curvature_values(document_node),
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 make that form
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, gradient_form, tooltip) in [
("Linear", GradientForm::Linear, "Sets both curvatures to 0, making straight contours."),
(
"Radial",
GradientForm::Radial,
"Sets the start curvature to -1 and the end curvature to 0.5, making circles around the start.",
),
] {
let [start, end] = gradient_form.curvatures();
form.push(
TextButton::new(label)
.tooltip_description(tooltip)
.emphasized(curvatures.and_then(GradientForm::from_curvatures) == Some(gradient_form))
.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 parameters would get without this panel
let options = |index: usize| {
let registry = graphene_std::registry::NODE_METADATA.lock().ok();
let field = registry.as_ref().and_then(|registry| registry.get(&IDENTIFIER)).and_then(|metadata| metadata.fields.get(index));
field.map(ParameterOptions::from).unwrap_or_default()
};
let mut row = |index: usize, ty: Type| {
context
.call_widget_override(&node_id, index)
.unwrap_or_else(|| inspector_row_from_type(node_id, index, &ty, options(index), context).unwrap_or_else(|rows| rows))
};
let mut layout = vec![LayoutGroup::row(form)];
layout.extend(row(StartCurvatureInput::INDEX, concrete!(f64)));
layout.extend(row(EndCurvatureInput::INDEX, concrete!(f64)));
layout
}
pub(crate) fn rectangle_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
use graphene_std::vector::generator_nodes::rectangle::*;
@@ -3535,7 +3445,18 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
.get(&proto_node_identifier)
.and_then(|metadata| metadata.fields.get(input_index))
{
options = ParameterOptions::from(field);
options = ParameterOptions {
soft_min: field.number_soft_min,
soft_max: field.number_soft_max,
hard_min: field.number_hard_min,
hard_max: field.number_hard_max,
slider: field.number_mode_range,
multiline: field.multiline,
progression: field.progression,
unit: field.unit,
display_decimal_places: field.number_display_decimal_places,
step: field.number_step,
};
default_type = field.default_type.clone();
}
@@ -3924,25 +3845,9 @@ pub(crate) fn fill_inspector(node_id: NodeId, context: &mut NodeInspectorContext
let entries = [GradientForm::Linear, GradientForm::Radial]
.iter()
.map(|&gradient_form| {
let [start, end] = gradient_form.curvatures();
RadioEntryData::new(format!("{:?}", gradient_form))
.label(gradient_form.to_string())
.on_update(move |_| 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_update(update_value(move |_| TaggedValue::GradientForm(gradient_form), node_id, GradientFormInput))
.on_commit(commit_value)
})
.collect();
@@ -1,8 +1,8 @@
use crate::consts::{
ARC_SWEEP_GIZMO_RADIUS, COLOR_OVERLAY_BLACK, COLOR_OVERLAY_BLUE, COLOR_OVERLAY_BLUE_50, COLOR_OVERLAY_GREEN, COLOR_OVERLAY_RED, COLOR_OVERLAY_WHITE, COLOR_OVERLAY_WHITE_05, COLOR_OVERLAY_YELLOW,
COLOR_OVERLAY_YELLOW_DULL, COMPASS_ROSE_ARROW_SIZE, COMPASS_ROSE_HOVER_RING_DIAMETER, COMPASS_ROSE_MAIN_RING_DIAMETER, COMPASS_ROSE_RING_INNER_DIAMETER, CURVATURE_COMB_DEFAULT_SCALE,
DOWEL_PIN_RADIUS, GRADIENT_LINE_WIDTH, GRADIENT_MIDPOINT_DIAMOND_HALF_HEIGHT, GRADIENT_MIDPOINT_DIAMOND_HALF_WIDTH, GRADIENT_STOP_RADIUS, MANIPULATOR_GROUP_MARKER_SIZE, PIVOT_CROSSHAIR_LENGTH,
PIVOT_CROSSHAIR_THICKNESS, PIVOT_DIAMETER, RESIZE_HANDLE_SIZE, SKEW_TRIANGLE_OFFSET, SKEW_TRIANGLE_SIZE,
DOWEL_PIN_RADIUS, GRADIENT_MIDPOINT_DIAMOND_RADIUS, MANIPULATOR_GROUP_MARKER_SIZE, PIVOT_CROSSHAIR_LENGTH, PIVOT_CROSSHAIR_THICKNESS, PIVOT_DIAMETER, RESIZE_HANDLE_SIZE, SKEW_TRIANGLE_OFFSET,
SKEW_TRIANGLE_SIZE,
};
use crate::messages::portfolio::document::overlays::utility_functions::hex_to_rgba_u8;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
@@ -24,7 +24,7 @@ use graphene_std::text::{TextAlign, TextContext, TypesettingConfig};
use graphene_std::vector::click_target::{ClickTarget, ClickTargetType};
use graphene_std::vector::misc::point_to_dvec2;
use graphene_std::vector::{PointId, SegmentId, Vector, VectorGeometry, no_paths, path, paths_from_list_row_attributes};
use graphene_std::{ATTR_TRANSFORM, Color, NodeParameter};
use graphene_std::{ATTR_TRANSFORM, NodeParameter};
use kurbo::{self, BezPath, ParamCurve};
use kurbo::{Affine, PathSeg};
use std::borrow::Cow;
@@ -404,12 +404,6 @@ impl OverlayContext {
self.record(move |overlays| overlays.dashed_polygon(&polygon, stroke_color.as_deref(), color_fill.as_deref(), dash_width, dash_gap_width, dash_offset));
}
/// Strokes the open path through these points, unlike [`Self::dashed_polygon`], which closes it.
pub fn dashed_polyline(&mut self, points: &[DVec2], color: Option<&str>, dash_width: Option<f64>, dash_gap_width: Option<f64>, dash_offset: Option<f64>) {
let (points, color) = (points.to_vec(), owned(color));
self.record(move |overlays| overlays.dashed_polyline(&points, color.as_deref(), dash_width, dash_gap_width, dash_offset));
}
pub fn line(&mut self, start: DVec2, end: DVec2, color: Option<&str>, thickness: Option<f64>) {
let color = owned(color);
self.record(move |overlays| overlays.line(start, end, color.as_deref(), thickness));
@@ -434,12 +428,6 @@ impl OverlayContext {
self.record(move |overlays| overlays.manipulator_handle(position, selected, color.as_deref()));
}
/// Draws a handle like [`Self::manipulator_handle`] outlined in `color`, and filled with it too where `selected`.
pub fn colored_manipulator_handle(&mut self, position: DVec2, selected: bool, color: &str) {
let color = color.to_owned();
self.record(move |overlays| overlays.filled_manipulator_handle(position, if selected { &color } else { COLOR_OVERLAY_WHITE }, &color));
}
pub fn manipulator_anchor(&mut self, position: DVec2, selected: bool, color: Option<&str>) {
let color = owned(color);
self.record(move |overlays| overlays.manipulator_anchor(position, selected, color.as_deref()));
@@ -450,15 +438,8 @@ impl OverlayContext {
self.record(move |overlays| overlays.gradient_color_stop(position, emphasis, &color, small));
}
/// Draws a gradient midpoint's diamond filled with `color`, taller across the gradient line at `angle` than it is wide, bordered like a color stop's dot.
pub fn gradient_midpoint(&mut self, position: DVec2, emphasis: GizmoEmphasis, color: &str, angle: f64) {
let color = color.to_owned();
self.record(move |overlays| overlays.gradient_midpoint(position, emphasis, &color, angle));
}
/// Draws a line in a gradient's own colors, from its color `stops` at fractions of the way from `start` to `end`, outlined in white and then black like its color stops.
pub fn gradient_line(&mut self, start: DVec2, end: DVec2, stops: Vec<(f64, Color)>) {
self.record(move |overlays| overlays.gradient_line(start, end, &stops));
pub fn gradient_midpoint(&mut self, position: DVec2, emphasis: GizmoEmphasis, angle: f64) {
self.record(move |overlays| overlays.gradient_midpoint(position, emphasis, angle));
}
pub fn resize_handle(&mut self, position: DVec2, rotation: f64) {
@@ -804,24 +785,6 @@ impl OverlayContextInternal {
self.stroke_in_view(&stroke, Self::parse_color(stroke_color), &path);
}
fn dashed_polyline(&mut self, points: &[DVec2], color: Option<&str>, dash_width: Option<f64>, dash_gap_width: Option<f64>, dash_offset: Option<f64>) {
let mut points = points.iter().map(|&point| self.snap_to_physical_pixel_center(point));
let Some(first) = points.next() else { return };
let mut path = BezPath::new();
path.move_to(kurbo::Point::new(first.x, first.y));
for point in points {
path.line_to(kurbo::Point::new(point.x, point.y));
}
let mut stroke = kurbo::Stroke::new(1.);
if let Some(dash_width) = dash_width {
stroke = stroke.with_dashes(dash_offset.unwrap_or(0.), [dash_width, dash_gap_width.unwrap_or(1.)]);
}
self.stroke_in_view(&stroke, Self::parse_color(color.unwrap_or(COLOR_OVERLAY_BLUE)), &path);
}
fn line(&mut self, start: DVec2, end: DVec2, color: Option<&str>, thickness: Option<f64>) {
self.dashed_line(start, end, color, thickness, None, None, None)
}
@@ -846,17 +809,16 @@ impl OverlayContextInternal {
}
fn manipulator_handle(&mut self, position: DVec2, selected: bool, color: Option<&str>) {
let fill = if selected { COLOR_OVERLAY_BLUE } else { COLOR_OVERLAY_WHITE };
self.filled_manipulator_handle(position, fill, color.unwrap_or(COLOR_OVERLAY_BLUE));
}
fn filled_manipulator_handle(&mut self, position: DVec2, fill: &str, stroke: &str) {
let transform = self.get_transform();
let position = self.snap_to_physical_pixel_center(position);
let circle = kurbo::Circle::new((position.x, position.y), MANIPULATOR_GROUP_MARKER_SIZE / 2.);
let fill = if selected { COLOR_OVERLAY_BLUE } else { COLOR_OVERLAY_WHITE };
self.scene.fill(peniko::Fill::NonZero, transform, Self::parse_color(fill), None, &circle);
self.scene.stroke(&kurbo::Stroke::new(1.), transform, Self::parse_color(stroke), None, &circle);
self.scene
.stroke(&kurbo::Stroke::new(1.), transform, Self::parse_color(color.unwrap_or(COLOR_OVERLAY_BLUE)), None, &circle);
}
fn hover_manipulator_handle(&mut self, position: DVec2, selected: bool) {
@@ -898,7 +860,7 @@ impl OverlayContextInternal {
GizmoEmphasis::Active => 1.,
};
let stroke_width = radius_offset * 2. + 1.;
let radius = (GRADIENT_STOP_RADIUS + radius_offset) * if small { 0.5 } else { 1. };
let radius = (MANIPULATOR_GROUP_MARKER_SIZE / 1.5 + 1. + radius_offset) * if small { 0.5 } else { 1. };
let mut draw_circle = |radius: f64, width: Option<f64>, color: &str| {
let circle = kurbo::Circle::new((position.x, position.y), radius);
@@ -916,59 +878,33 @@ impl OverlayContextInternal {
draw_circle(radius, Some(stroke_width), COLOR_OVERLAY_WHITE);
}
fn gradient_midpoint(&mut self, position: DVec2, emphasis: GizmoEmphasis, color: &str, angle: f64) {
let position = position.round() - DVec2::splat(0.5);
let transform = self.get_transform() * kurbo::Affine::translate((position.x, position.y)) * kurbo::Affine::rotate(angle);
// Grown for emphasis with a thicker white border, as a color stop's dot is
let radius_offset = match emphasis {
GizmoEmphasis::Regular => 0.,
GizmoEmphasis::Hovered => 0.5,
GizmoEmphasis::Active => 1.,
};
let stroke_width = radius_offset * 2. + 1.;
// Taller across the gradient line than it is wide along it
let (half_width, half_height) = (GRADIENT_MIDPOINT_DIAMOND_HALF_WIDTH + radius_offset, GRADIENT_MIDPOINT_DIAMOND_HALF_HEIGHT + radius_offset);
let mut diamond = BezPath::new();
diamond.move_to((half_width, 0.));
diamond.line_to((0., half_height));
diamond.line_to((-half_width, 0.));
diamond.line_to((0., -half_height));
diamond.close_path();
// The black border shows half a pixel past the white one, as around a color stop's dot
self.scene
.stroke(&kurbo::Stroke::new(stroke_width + 1.), transform, Self::parse_color(COLOR_OVERLAY_BLACK), None, &diamond);
self.scene.fill(peniko::Fill::NonZero, transform, Self::parse_color(color), None, &diamond);
self.scene.stroke(&kurbo::Stroke::new(stroke_width), transform, Self::parse_color(COLOR_OVERLAY_WHITE), None, &diamond);
}
fn gradient_line(&mut self, start: DVec2, end: DVec2, stops: &[(f64, Color)]) {
fn gradient_midpoint(&mut self, position: DVec2, emphasis: GizmoEmphasis, angle: f64) {
let transform = self.get_transform();
let position = position.round() - DVec2::splat(0.5);
// Centered on whole pixels, the even widths have crisp edges
let [start, end] = [start, end].map(|point| self.snap_to_physical_pixel(point));
let line = kurbo::Line::new((start.x, start.y), (end.x, end.y));
// Rotate diamond points by the gradient line angle
let (sin, cos) = angle.sin_cos();
let rotate = |dx: f64, dy: f64| DVec2::new(dx * cos - dy * sin, dx * sin + dy * cos);
// Bordered like a color stop's dot, by a pixel of white and then half a pixel of black
self.scene
.stroke(&kurbo::Stroke::new(GRADIENT_LINE_WIDTH + 3.), transform, Self::parse_color(COLOR_OVERLAY_BLACK), None, &line);
self.scene
.stroke(&kurbo::Stroke::new(GRADIENT_LINE_WIDTH + 2.), transform, Self::parse_color(COLOR_OVERLAY_WHITE), None, &line);
let top = rotate(0., -GRADIENT_MIDPOINT_DIAMOND_RADIUS);
let right = rotate(GRADIENT_MIDPOINT_DIAMOND_RADIUS, 0.);
let bottom = rotate(0., GRADIENT_MIDPOINT_DIAMOND_RADIUS);
let left = rotate(-GRADIENT_MIDPOINT_DIAMOND_RADIUS, 0.);
// Opaque like the stops' dots
let stops = stops.iter().map(|&(offset, color)| {
let [red, green, blue, _] = color.to_gamma_srgb_channels();
peniko::ColorStop {
offset: offset as f32,
color: peniko::color::DynamicColor::from_alpha_color(peniko::Color::new([red, green, blue, 1.])),
}
});
let mut gradient = peniko::Gradient::new_linear((start.x, start.y), (end.x, end.y));
gradient.stops = peniko::ColorStops(stops.collect());
let mut path = BezPath::new();
path.move_to(kurbo::Point::new(position.x + top.x, position.y + top.y));
path.line_to(kurbo::Point::new(position.x + right.x, position.y + right.y));
path.line_to(kurbo::Point::new(position.x + bottom.x, position.y + bottom.y));
path.line_to(kurbo::Point::new(position.x + left.x, position.y + left.y));
path.close_path();
self.scene.stroke(&kurbo::Stroke::new(GRADIENT_LINE_WIDTH), transform, &gradient, None, &line);
let (fill, stroke_width) = match emphasis {
GizmoEmphasis::Regular => (COLOR_OVERLAY_WHITE, 1.),
GizmoEmphasis::Hovered => (COLOR_OVERLAY_WHITE, 2.),
GizmoEmphasis::Active => (COLOR_OVERLAY_BLUE, 1.),
};
self.scene.fill(peniko::Fill::NonZero, transform, Self::parse_color(fill), None, &path);
self.scene.stroke(&kurbo::Stroke::new(stroke_width), transform, Self::parse_color(COLOR_OVERLAY_BLUE), None, &path);
}
fn resize_handle(&mut self, position: DVec2, rotation: f64) {
@@ -975,7 +975,7 @@ async fn legacy_four_input_fill_migrates_to_the_split_transform_shape() {
let network = document.network_interface.nested_network(&network_path).expect("the found network path should resolve");
let fill_node = &network.nodes[&node_id];
assert_eq!(fill_node.inputs.len(), 8, "the legacy Fill should upgrade to the 8-input shape");
assert_eq!(fill_node.inputs.len(), 7, "the legacy Fill should upgrade to the 7-input shape");
let paint = fill_node.input(graphene_std::vector::fill::PaintInput);
assert!(
matches!(paint, Some(graph_craft::document::NodeInput::Node { .. })),
@@ -1033,13 +1033,7 @@ async fn eight_input_fill_migrates_the_spread_input_into_the_ramp() {
let network = document.network_interface.nested_network(&network_path).expect("the found network path should resolve");
let fill_node = &network.nodes[&node_id];
assert_eq!(fill_node.inputs.len(), 8, "the eight-input Fill should come out in the modern shape, which also has eight inputs");
let curvatures = [graphene_std::vector::fill::StartCurvatureInput::INDEX, graphene_std::vector::fill::EndCurvatureInput::INDEX].map(|index| fill_node.inputs[index].as_value().cloned());
assert_eq!(
curvatures,
[0., 0.].map(|curvature| Some(TaggedValue::Number(curvature))),
"the linear form should become its curvatures"
);
assert_eq!(fill_node.inputs.len(), 7, "the eight-input Fill should fold down to the 7-input shape");
let paint = fill_node.input_value(graphene_std::vector::fill::PaintInput);
let Some(TaggedValue::GradientRamp(ramp)) = paint else {
@@ -3399,63 +3399,6 @@ async fn visibility_and_lock_toggles_made_in_an_open_transaction_undo_together()
);
}
#[tokio::test]
async fn middle_clicking_a_node_in_the_graph_toggles_its_visibility_but_middle_dragging_only_pans() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
let layer = editor.get_selected_layer().await.expect("the drawn rectangle should be selected").to_node();
editor.handle_message(DocumentMessage::GraphViewOverlay { open: true }).await;
let is_visible = |editor: &EditorTestUtils| editor.active_document().network_interface.is_visible(&layer, &[]);
let graph_pan = |editor: &EditorTestUtils| {
editor
.active_document()
.network_interface
.network_metadata(&[])
.unwrap()
.persistent_metadata
.navigation_metadata
.node_graph_ptz
.pan
};
let layer_in_viewport = |editor: &EditorTestUtils| {
let network_interface = &editor.active_document().network_interface;
let [min, max] = network_interface.node_bounding_box(&layer, &[]).expect("the layer should have bounds");
let node_graph_to_viewport = network_interface.network_metadata(&[]).unwrap().persistent_metadata.navigation_metadata.node_graph_to_viewport;
(0..=(max.x - min.x) as i32)
.map(|x| node_graph_to_viewport.transform_point2(DVec2::new(min.x + x as f64, (min.y + max.y) / 2.)))
.find(|&point| network_interface.node_from_click(point, &[]) == Some(layer))
.expect("the layer should be pressable")
};
let pointer_state = |position: DVec2, mouse_keys: MouseKeys| EditorPointerState {
editor_position: position,
mouse_keys,
..Default::default()
};
// Pressed and released with a wobble too small to count as a drag
let start = layer_in_viewport(&editor);
editor.mousedown(pointer_state(start, MouseKeys::MIDDLE), ModifierKeys::empty()).await;
assert!(is_visible(&editor), "pressing the middle button shouldn't toggle the layer yet");
editor.mouseup(pointer_state(start + DVec2::new(2., 0.), MouseKeys::empty()), ModifierKeys::empty()).await;
assert!(!is_visible(&editor), "a middle click on the layer should hide it");
// Dragged away and back before the release
let start = layer_in_viewport(&editor);
let pan_before = graph_pan(&editor);
editor.mousedown(pointer_state(start, MouseKeys::MIDDLE), ModifierKeys::empty()).await;
editor.move_mouse(start.x + 40., start.y, ModifierKeys::empty(), MouseKeys::MIDDLE).await;
assert_ne!(graph_pan(&editor), pan_before, "a middle drag should pan the graph");
editor.move_mouse(start.x, start.y, ModifierKeys::empty(), MouseKeys::MIDDLE).await;
editor.mouseup(pointer_state(start, MouseKeys::empty()), ModifierKeys::empty()).await;
assert!(!is_visible(&editor), "a middle drag shouldn't toggle the layer, even if released where it was pressed");
editor.handle_message(DocumentMessage::Undo).await;
assert!(is_visible(&editor), "one undo should revert the middle click");
}
#[tokio::test]
async fn shift_clicking_a_selected_node_in_the_graph_ends_its_press() {
let mut editor = EditorTestUtils::create();
@@ -21,7 +21,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::{GradientForm, GradientRamp, GradientSpread, PaintOrder, StrokeAlign};
use graphene_std::vector::style::{GradientRamp, GradientSpread, PaintOrder, StrokeAlign};
use std::collections::{HashMap, HashSet};
use std::f64::consts::PI;
use std::ops::Range;
@@ -181,6 +181,10 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
"graphic_nodes::graphic::ExtractElementNode",
],
},
NodeReplacement {
node: graphene_std::graphic::read_attribute_gradient_form::IDENTIFIER,
aliases: &["graphic_nodes::graphic::ReadAttributeGradientTypeNode"],
},
NodeReplacement {
node: graphene_std::graphic::read_attribute_gradient_spread::IDENTIFIER,
aliases: &["graphic_nodes::graphic::ReadAttributeSpreadMethodNode"],
@@ -297,6 +301,10 @@ 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"],
@@ -1681,52 +1689,6 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
}
}
// The "Gradient Form" node was replaced by "Gradient Curvature", with its two curvatures taking 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)) => GradientForm::Radial.curvatures(),
Some(TaggedValue::GradientForm(GradientForm::Linear)) => GradientForm::Linear.curvatures(),
_ => {
log::warn!("Old \"Gradient Form\" node {node_id} has no fixed form to migrate, so it becomes linear");
GradientForm::Linear.curvatures()
}
};
// The curvatures stay shown in the graph where an exposed or wired form was
let exposed = old_inputs.get(1).is_some_and(NodeInput::is_exposed);
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::Number(start), exposed), network_path);
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 2), NodeInput::value(TaggedValue::Number(end), exposed), 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";
@@ -2532,18 +2494,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
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)?;
// The 7-input shape's own gradient metadata defaults, which the steps after this one read until the legacy fill's values replace them below
let metadata_defaults = [
TaggedValue::GradientForm(GradientForm::Linear),
TaggedValue::Bool(false),
TaggedValue::DAffine2(glam::DAffine2::IDENTITY),
];
for (index, value) in (4..).zip(metadata_defaults) {
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, index), NodeInput::value(value, false), network_path);
}
// Content: no change
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
@@ -2687,11 +2637,8 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
inputs_count = 7;
}
// The Fill node's `_spread_method` input moved into the `GradientRamp` value's own `gradient_spread` field. The modern shape is also 8 inputs,
// so this era is told apart by its form at 4 or its spread at 5, either of which may be wired, where the modern shape holds curvatures.
let value_at = |index: usize| node.inputs.get(index).and_then(|input| input.as_value());
let is_spread_method_fill = inputs_count == 8 && (matches!(value_at(4), Some(TaggedValue::GradientForm(_))) || matches!(value_at(5), Some(TaggedValue::GradientSpread(_))));
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER) && is_spread_method_fill {
// The Fill node's `_spread_method` input moved into the `GradientRamp` value's own `gradient_spread` field
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER) && inputs_count == 8 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
@@ -2714,36 +2661,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
inputs_count = 7;
}
// The Fill node gives its gradient paint the curvatures of a form in place of its `_gradient_form` input, and they stay shown in the graph where the form was
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER) && inputs_count == 7 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
// Content, paint, and backups keep their places, and the transform inputs move past the second curvature
for (index, input) in old_inputs.iter().enumerate().take(7) {
let index = match index {
4 => continue,
5.. => index + 1,
_ => index,
};
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input.clone(), network_path);
}
let form = old_inputs.get(4);
let curvatures = match form.and_then(|input| input.as_value()) {
Some(TaggedValue::GradientForm(form)) => form.curvatures(),
_ => GradientForm::Linear.curvatures(),
};
let exposed = form.is_some_and(NodeInput::is_exposed);
for (index, curvature) in (4..).zip(curvatures) {
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, index), NodeInput::value(TaggedValue::Number(curvature), exposed), network_path);
}
inputs_count = 8;
}
// Upgrade Stroke node to reorder parameters and add "Align" (#2644)
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER) && inputs_count == 8 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
@@ -4199,20 +4116,6 @@ fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, ne
}
}
// The removed Read Attribute Gradient Form node, under either of its names, degrades to a passthrough of its content
if let Some(DefinitionIdentifier::ProtoNode(identifier)) = document.network_interface.reference(node_id, network_path)
&& ["::ReadAttributeGradientFormNode", "::ReadAttributeGradientTypeNode"]
.iter()
.any(|name| identifier.as_str().ends_with(name))
{
let mut node_template = resolve_proto_node_type(graphene_std::ops::passthrough::IDENTIFIER)?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
if let Some(content) = old_inputs.first() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), content.clone(), network_path);
}
}
// The removed Upload Texture node, in its proto node or older wrapper network form, degrades to a passthrough of its content
let is_upload_texture = match document.network_interface.reference(node_id, network_path) {
Some(DefinitionIdentifier::Network(name)) => name == "Upload Texture",
@@ -4975,40 +4878,6 @@ mod tests {
);
}
// Read Attribute Gradient Form, under either of its names, opens as a passthrough of its content
#[test]
fn read_attribute_gradient_form_opens_as_a_passthrough() {
use crate::messages::portfolio::document_storage_io::load_legacy_document;
use graph_craft::application_io::resource::HashMapResourceStorage;
let content = NodeInput::value(TaggedValue::Color(Color::RED), false);
let name = NodeInput::value(TaggedValue::String("gradient_form".into()), false);
let identifiers = ["graphic_nodes::graphic::ReadAttributeGradientFormNode", "graphic_nodes::graphic::ReadAttributeGradientTypeNode"];
let nodes = identifiers
.iter()
.enumerate()
.map(|(index, &identifier)| {
let node_template = NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new(identifier)),
inputs: vec![content.clone(), name.clone()],
..Default::default()
};
(NodeId(index as u64), node_template)
})
.collect::<Vec<_>>();
let unchanged_ids = nodes.iter().map(|(node_id, _)| (*node_id, *node_id)).collect();
let mut document = DocumentMessageHandler::default();
document.network_interface.insert_node_group(nodes, unchanged_ids, &[]);
let opened = load_legacy_document(document.serialize_document(), &HashMapResourceStorage::new(), false).expect("the document should open");
for (index, identifier) in identifiers.iter().enumerate() {
let node = opened.network_interface.document_node(&NodeId(index as u64), &[]).expect("the node should still exist");
assert_eq!(node.implementation, DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER), "{identifier}");
assert_eq!(node.inputs, [content.clone()], "{identifier}");
}
}
// Migrating a Merge network's coercion nodes by alias would leave a reducer in the primary slot, so every alias must reset instead
#[test]
fn every_into_group_alias_resets_the_merge_definition() {
@@ -5571,204 +5440,6 @@ 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;
// Curvatures stay shown in the graph where an exposed form was
let (source_id, form_id) = (NodeId(1), NodeId(2));
for (identifier, form, curvatures, exposed) in [
("math_nodes::GradientFormNode", GradientForm::Radial, [-1., 0.5], false),
("math_nodes::GradientTypeNode", GradientForm::Linear, [0., 0.], false),
("math_nodes::GradientFormNode", GradientForm::Radial, [-1., 0.5], true),
] {
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), exposed), &[]);
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)],
curvatures.map(|curvature| Some(TaggedValue::Number(curvature))),
"{form:?} should become its curvature presets"
);
assert_eq!(
[1, 2].map(|index| node.inputs[index].is_exposed()),
[exposed; 2],
"{form:?} exposed {exposed} should leave its curvatures so"
);
assert_eq!(node.inputs.len(), 3, "{form:?} should take the curvature node's gradient and two curvatures");
}
}
// An eight-input Fill from when the spread was an input of its own, here wired, opens with its form's curvatures and keeps its placement
#[test]
fn eight_input_fills_with_a_wired_spread_take_their_form_as_curvatures() {
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
use glam::DAffine2;
let (source_id, fill_id) = (NodeId(1), NodeId(2));
let placement = DAffine2::from_scale_angle_translation(DVec2::new(40., 25.), 0.3, DVec2::new(60., 45.));
let ramp = || NodeInput::value(TaggedValue::GradientRamp(GradientRamp::default()), false);
let old_inputs = vec![
NodeInput::value(TaggedValue::None, false),
ramp(),
NodeInput::value(TaggedValue::Color(Color::BLACK), false),
ramp(),
NodeInput::value(TaggedValue::GradientForm(GradientForm::Radial), false),
NodeInput::value(TaggedValue::None, false),
NodeInput::value(TaggedValue::Bool(true), false),
NodeInput::value(TaggedValue::DAffine2(placement), false),
];
let mut document = DocumentMessageHandler::default();
let source = NodeTemplate {
inputs: vec![NodeInput::value(TaggedValue::None, false)],
..Default::default()
};
document.network_interface.insert_node(source_id, source, &[]);
let fill = NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(graphene_std::vector::fill::IDENTIFIER),
inputs: old_inputs,
..Default::default()
};
document.network_interface.insert_node(fill_id, fill, &[]);
document.network_interface.set_input(&InputConnector::node_at_index(fill_id, 5), NodeInput::node(source_id, 0), &[]);
migrate(&mut document);
let node = &document.network_interface.document_network().nodes[&fill_id];
let values: Vec<_> = node.inputs[4..].iter().map(|input| input.as_value().cloned()).collect();
let expected = [TaggedValue::Number(-1.), TaggedValue::Number(0.5), TaggedValue::Bool(true), TaggedValue::DAffine2(placement)].map(Some);
assert_eq!(values, expected, "the form should become its curvatures before the placement");
}
// A Fill that held the radial form in its input before the transform ones opens with that form's curvatures, painting as a Fill given the form now does
#[tokio::test]
async fn fills_of_the_radial_form_paint_the_same_once_migrated() {
use crate::messages::tool::common_functionality::graph_modification_utils::NodeGraphLayer;
use crate::test_utils::test_prelude::*;
use glam::DAffine2;
use graphene_std::graphic::extend;
use graphene_std::list::Item;
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
use graphene_std::vector::fill;
use graphene_std::vector::style::Gradient;
use graphene_std::vector_types::gradient_standard::GradientShape;
use graphene_std::{Appearance, Cover, Graphic};
// The SVG of the document's one layer, its IDs numbered by their order of appearance, and the shape the CPU samples its fill's gradient as
async fn painted(editor: &mut EditorTestUtils) -> (String, Option<GradientShape>) {
let instrumented = editor.eval_graph_until_finished().await.expect("the graph evaluates");
let layer = instrumented
.grab_all_input::<extend::NewInput, Item<Graphic>>(&editor.runtime)
.next()
.expect("the layer is extended onto the root");
let mut render = SvgRender::new();
layer.element().render_svg(&mut render, &RenderParams::default());
let mut markup = format!("{}{}", render.svg_defs, render.svg.to_svg_string());
let mut index = 0;
while let Some(found) = markup.find(r#"id=""#) {
let start = found + r#"id=""#.len();
let id = markup[start..start + markup[start..].find('"').unwrap_or_default()].to_string();
markup = markup.replace(&format!(r#"id="{id}""#), &format!(r#"ID="{index}""#)).replace(&format!("#{id}"), &format!("#{index}"));
index += 1;
}
let shape = match layer.element() {
Graphic::VectorList(vectors) => match vectors
.attribute::<Appearance>(graphene_std::list::ATTR_APPEARANCE, 0)
.and_then(|appearance| appearance.first_paint_of(Cover::Fill))
{
Some(Graphic::Gradient(gradient)) => Some(GradientShape::new(
gradient.attribute_cloned_or_default(graphene_std::ATTR_GRADIENT_START_CURVATURE),
gradient.attribute_cloned_or_default(graphene_std::ATTR_GRADIENT_END_CURVATURE),
gradient.attribute_cloned_or_default(graphene_std::ATTR_GRADIENT_MODEL),
gradient.attribute_cloned_or_default(graphene_std::ATTR_TRANSFORM),
)),
_ => None,
},
_ => None,
};
(markup.replace(r#"ID=""#, r#"id=""#), shape)
}
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(10., 20., 110., 70.).await;
let layer = editor.active_document().metadata().all_layers().next().expect("the rectangle is a layer");
let placement = DAffine2::from_scale_angle_translation(DVec2::new(40., 25.), 0.3, DVec2::new(60., 45.));
editor
.handle_message(GraphOperationMessage::FillGradientSet {
layer,
gradient: Gradient::from(vec![Color::BLACK, Color::WHITE]),
gradient_form: Some(GradientForm::Radial),
gradient_settings: Default::default(),
transform: Some(placement),
})
.await;
// The radial form's curvatures draw the unit circle it always drew, and the CPU samples it as the form
let (curved_svg, curved_shape) = painted(&mut editor).await;
assert!(curved_svg.contains(r#"gradientUnits="userSpaceOnUse" cx="0" cy="0" r="1""#), "{curved_svg}");
assert_eq!(curved_shape, Some(GradientShape::Radial));
// The same document saved with the form, under the name it had before 'Gradient Type' became 'Gradient Form', in place of the curvatures
let document = editor.active_document_mut();
let fill_id = NodeGraphLayer::new(layer, &document.network_interface)
.upstream_node_id_from_protonode(fill::IDENTIFIER)
.expect("the layer has a Fill");
let inputs = document.network_interface.document_network().nodes[&fill_id].inputs.clone();
let curvatures = [4, 5].map(|index| inputs[index].as_value().cloned());
assert_eq!(curvatures, GradientForm::Radial.curvatures().map(|curvature| Some(TaggedValue::Number(curvature))));
let form = NodeInput::value(TaggedValue::GradientForm(GradientForm::Radial), false);
let mut old_inputs = NodeTemplate {
inputs: [&inputs[..4], &[form], &inputs[6..]].concat(),
..Default::default()
};
document.network_interface.replace_inputs(&fill_id, &[], &mut old_inputs);
let serialized = document.serialize_document();
assert_eq!(serialized.matches(r#"{"GradientForm":"Radial"}"#).count(), 1, "the form should be saved once");
let serialized = serialized.replace(r#"{"GradientForm":"Radial"}"#, r#"{"GradientType":"Radial"}"#);
editor
.handle_message(PortfolioMessage::OpenLegacyDocumentFile {
document_name: Some("Migrated".into()),
document_path: None,
document_serialized_content: serialized,
})
.await;
let (migrated_svg, migrated_shape) = painted(&mut editor).await;
assert_eq!(migrated_svg, curved_svg);
assert_eq!(migrated_shape, curved_shape);
}
#[test]
fn test_no_duplicate_node_replacements() {
let mut hashmap = HashMap::<ProtoNodeIdentifier, u32>::new();
@@ -217,7 +217,7 @@ impl DrawingToolState {
Some(FillChoice::Gradient(ramp)) => responses.add(GraphOperationMessage::FillGradientSet {
layer,
gradient: graphene_std::vector::Gradient::from(&ramp),
gradient_form: None,
gradient_form: Default::default(),
gradient_settings: (&ramp).into(),
transform: None,
}),
@@ -1,454 +0,0 @@
//! Geometry of the Gradient tool's gizmos, in gradient space, where the gradient line runs from the start point at the origin to the end
//! point at (1, 0). Each end's contour passes through its endpoint with its center on the line, set by its curvature, as described
//! in [`graphene_std::vector::gradient_standard`].
use glam::{DAffine2, DVec2};
use graphene_std::vector::gradient_standard::{curvature_radius, radius_curvature};
use std::f64::consts::{FRAC_PI_2, PI};
/// The farthest a drawn contour bows from its chords between the points it's drawn through, in viewport pixels.
const CONTOUR_SAG_TOLERANCE: f64 = 0.25;
/// The most chords a contour is drawn with.
const CONTOUR_MAX_CHORDS: usize = 1024;
/// One of the gradient line's two ends, each with its own contour.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GradientEnd {
Start,
End,
}
impl GradientEnd {
/// Its index in a `[start, end]` pair of curvatures.
pub fn index(self) -> usize {
match self {
Self::Start => 0,
Self::End => 1,
}
}
/// Its endpoint in gradient space.
pub fn endpoint(self) -> DVec2 {
match self {
Self::Start => DVec2::ZERO,
Self::End => DVec2::X,
}
}
/// Which way along the gradient line points toward the other end, which a positive curvature bows this end's contour toward.
fn inward(self) -> f64 {
match self {
Self::Start => 1.,
Self::End => -1.,
}
}
}
/// The center of this end's contour in gradient space for its `curvature`, or `None` for a line.
pub fn contour_center(end: GradientEnd, curvature: f64) -> Option<DVec2> {
let radius = curvature_radius(curvature);
radius.is_finite().then(|| end.endpoint() + DVec2::new(end.inward() * radius, 0.))
}
/// The curvature that centers this end's contour at `axis_position` along the gradient line, as dragging its center dot there does.
pub fn center_curvature(end: GradientEnd, axis_position: f64) -> f64 {
radius_curvature((axis_position - end.endpoint().x) * end.inward())
}
/// The curvature of this end's contour through `point`, the circle through it and the endpoint with its center on the gradient line,
/// which is the line across the gradient line where `point` lies across from the endpoint. `None` at the endpoint itself.
pub fn rim_curvature(end: GradientEnd, point: DVec2) -> Option<f64> {
let offset = point - end.endpoint();
let distance_squared = offset.length_squared();
// The inverse of the radius `|offset|² / 2 offset.x`, which stays finite where the radius doesn't
(distance_squared > 0.).then(|| (2. * offset.x * end.inward() / distance_squared).atan() / FRAC_PI_2)
}
/// The signed radius that resizes this end's contour (from its `curvature`) to bring the place on its rim nearest `grabbed` as near `pointer` as it gets,
/// both in the space `unit_to_viewport` maps to, and where that place lands there. `None` for a line or a point, which no resizing moves a place on.
pub fn rim_resized_toward(end: GradientEnd, curvature: f64, grabbed: DVec2, pointer: DVec2, unit_to_viewport: DAffine2) -> Option<(f64, DVec2)> {
let radius = curvature_radius(curvature);
if !radius.is_finite() || radius == 0. {
return None;
}
let inward = DVec2::new(end.inward(), 0.);
// Each circle through the endpoint is the others scaled about it, so the place keeps its angle around them from the endpoint, measured at the center
let to_endpoint = -radius * inward;
let to_grabbed = unit_to_viewport.inverse().transform_point2(grabbed) - end.endpoint() - radius * inward;
let angle = to_endpoint.perp_dot(to_grabbed).atan2(to_endpoint.dot(to_grabbed));
// At that angle, the place lies the radius times this from the endpoint, a line the pointer projects onto
let direction = unit_to_viewport.transform_vector2(inward - DVec2::from_angle(angle).rotate(inward));
let endpoint = unit_to_viewport.transform_point2(end.endpoint());
let resized = (pointer - endpoint).dot(direction) / direction.length_squared();
resized.is_finite().then(|| (resized, endpoint + resized * direction))
}
/// Whether a gradient with these curvatures has a focus to move: a point for its start contour and a circle for its end contour.
pub fn has_focus(curvatures: [f64; 2]) -> bool {
let end_radius = curvature_radius(curvatures[1]);
curvature_radius(curvatures[0]) == 0. && end_radius.is_finite() && end_radius != 0.
}
/// A gradient line in the gradient space of the line it replaces, with the curvature it gives the end contour.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RefocusedLine {
pub start: DVec2,
pub end: DVec2,
pub end_curvature: f64,
}
/// The line of a gradient whose start point (its focus) moves to `focus` while its end circle from `end_curvature` stays put: from the focus through the
/// circle's center to its far side, with the end curvature keeping that circle. A focus on the center keeps `direction`. `None` unless the end is a circle.
pub fn refocused_line(focus: DVec2, end_curvature: f64, direction: DVec2) -> Option<RefocusedLine> {
let radius = curvature_radius(end_curvature);
if !radius.is_finite() || radius == 0. {
return None;
}
let (center, size) = (DVec2::new(1. - radius, 0.), radius.abs());
let to_center = center - focus;
let distance = to_center.length();
let direction = if distance > 0. { to_center / distance } else { direction.try_normalize()? };
Some(RefocusedLine {
start: focus,
end: center + direction * size,
end_curvature: radius_curvature(size / (distance + size)),
})
}
/// The transform placing a gradient along `line`, given in the gradient space of the `old` transform. Its frame turns and scales uniformly within
/// that space, so a contour that's a circle there keeps its shape, even where `old` stretches it into an ellipse.
pub fn transform_along(old: DAffine2, line: RefocusedLine) -> DAffine2 {
let x_axis = line.end - line.start;
old * DAffine2::from_cols(x_axis, x_axis.perp(), line.start)
}
/// One side of the gradient line, across which its perpendicular axis points one way or the other.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LineSide {
Positive,
Negative,
}
impl LineSide {
/// Which way across the gradient line its perpendicular axis points to reach this side.
pub fn sign(self) -> f64 {
match self {
Self::Positive => 1.,
Self::Negative => -1.,
}
}
}
/// The semi-minor axis to this side of this end's circle from its `curvature`, from the circle's center a radius across the gradient line to where
/// a handle stretching the gradient across its line sits, in gradient space. `None` for a line or a point.
pub fn aspect_axis(end: GradientEnd, curvature: f64, side: LineSide) -> Option<[DVec2; 2]> {
let radius = curvature_radius(curvature).abs();
let center = contour_center(end, curvature).filter(|_| radius > 0.)?;
Some([center, center + DVec2::new(0., side.sign() * radius)])
}
/// The transform stretched across its line so the point `handle` in its gradient space lies as far across the line as `pointer` does
/// (in the transform's output space), keeping the line and how far its perpendicular axis leans along it. `None` where it would collapse.
pub fn stretched_transform(transform: DAffine2, handle: DVec2, pointer: DVec2) -> Option<DAffine2> {
let x_axis = transform.matrix2.x_axis;
let along = x_axis.try_normalize()?;
let across = along.perp();
// The handle lies `handle.y` times the perpendicular axis's span across the line
let span_across = (pointer - transform.translation).dot(across) / handle.y;
if !(span_across.abs() > 1e-9 * x_axis.length()) {
return None;
}
let y_axis = along * transform.matrix2.y_axis.dot(along) + across * span_across;
Some(DAffine2::from_cols(x_axis, y_axis, transform.translation))
}
/// The smallest factor `transform` scales any length by, the least singular value of its linear part.
fn least_scale(transform: DAffine2) -> f64 {
let [x_axis, y_axis] = [transform.matrix2.x_axis, transform.matrix2.y_axis];
let determinant = transform.matrix2.determinant().abs();
// Of the singular values `√(mean ± √(mean² - determinant²))`, the least is the determinant over the greatest, which avoids cancellation
let mean = (x_axis.length_squared() + y_axis.length_squared()) / 2.;
let greatest = (mean + (mean * mean - determinant * determinant).max(0.).sqrt()).sqrt();
if greatest > 0. { determinant / greatest } else { 0. }
}
/// Points through which this end's contour is drawn in the viewport, from `unit_to_viewport`, as far as `reach` viewport pixels from
/// its endpoint along it (or around the whole circle if that's shorter). Empty for a point, or where the transform collapses.
pub fn contour_polyline(end: GradientEnd, curvature: f64, unit_to_viewport: DAffine2, reach: f64) -> Vec<DVec2> {
let radius = curvature_radius(curvature);
let endpoint = end.endpoint();
let least_scale = least_scale(unit_to_viewport);
if radius == 0. || least_scale <= 0. {
return Vec::new();
}
// A line runs straight across the gradient line through the endpoint
if radius.is_infinite() {
let Some(direction) = unit_to_viewport.transform_vector2(DVec2::Y).try_normalize() else {
return Vec::new();
};
let viewport_endpoint = unit_to_viewport.transform_point2(endpoint);
return vec![viewport_endpoint - direction * reach, viewport_endpoint + direction * reach];
}
// Sweep from the endpoint both ways around the circle, by the angle reaching `reach` pixels at the least scale
let size = radius.abs();
let sweep = (reach / (size * least_scale)).min(PI);
// Uniform steps small enough that each chord stays within the sag tolerance, even at twice the longest axis's scale (which bounds the greatest)
let viewport_radius_bound = size * unit_to_viewport.matrix2.x_axis.length().max(unit_to_viewport.matrix2.y_axis.length()) * 2.;
let step = (8. * CONTOUR_SAG_TOLERANCE / viewport_radius_bound).sqrt();
let chords_each_way = ((sweep / step).ceil() as usize).clamp(4, CONTOUR_MAX_CHORDS / 2);
let chords = 2 * chords_each_way;
// Measured from the endpoint rather than the center, the points stay precise on huge circles
(0..=chords)
.map(|index| {
let angle = sweep * (2. * index as f64 / chords as f64 - 1.);
let half_sine = (angle / 2.).sin();
let offset = DVec2::new(2. * end.inward() * radius * half_sine * half_sine, size * angle.sin());
unit_to_viewport.transform_point2(endpoint + offset)
})
.collect()
}
/// The distance from `point` to the nearest place on the polyline through `points`, or `None` if it has none.
pub fn distance_to_polyline(points: &[DVec2], point: DVec2) -> Option<f64> {
if let [only] = points {
return Some(only.distance(point));
}
points
.windows(2)
.map(|pair| {
let (start, end) = (pair[0], pair[1]);
let along = (point - start).dot(end - start) / (end - start).length_squared();
let nearest = if along.is_finite() { start.lerp(end, along.clamp(0., 1.)) } else { start };
nearest.distance(point)
})
.min_by(f64::total_cmp)
}
#[cfg(test)]
mod tests {
use super::*;
/// Curvatures through circles of each size and bend, both lines, and the points.
fn curvatures() -> impl Iterator<Item = f64> {
(-20..=20).map(|step| step as f64 * 0.05)
}
#[test]
fn a_rim_dragged_to_a_point_takes_the_curvature_of_the_circle_through_it() {
for end in [GradientEnd::Start, GradientEnd::End] {
for point in [DVec2::new(0.3, 0.4), DVec2::new(-0.7, 1.2), DVec2::new(2.5, -0.25), DVec2::new(0.5, 3.)] {
let curvature = rim_curvature(end, point).unwrap();
// The contour of that curvature passes through the point, centered on the gradient line
let center = contour_center(end, curvature).unwrap();
assert!(center.y == 0.);
let radius = center.distance(end.endpoint());
assert!((center.distance(point) - radius).abs() < 1e-9 * radius.max(1.), "{end:?} through {point}: curvature {curvature}");
}
// Straight across from the endpoint is the line, and either side of it bends toward that side
let across = end.endpoint() + DVec2::Y;
assert_eq!(rim_curvature(end, across), Some(0.));
let inward = DVec2::new(end.inward() * 0.1, 0.);
assert!(rim_curvature(end, across + inward).unwrap() > 0.);
assert!(rim_curvature(end, across - inward).unwrap() < 0.);
// The endpoint is on every contour, so it sets none
assert_eq!(rim_curvature(end, end.endpoint()), None);
}
}
#[test]
fn a_rim_dragged_along_its_own_contour_keeps_its_curvature() {
for end in [GradientEnd::Start, GradientEnd::End] {
for curvature in curvatures().filter(|curvature| curvature.abs() != 1.) {
for point in contour_polyline(end, curvature, DAffine2::IDENTITY, 3.) {
// Every point but the endpoint sets the curvature back, as a line's points beside the endpoint do
if point.distance(end.endpoint()) < 1e-6 {
continue;
}
let found = rim_curvature(end, point).unwrap();
assert!((found - curvature).abs() < 1e-9, "{end:?} curvature {curvature} at {point}: {found}");
}
}
}
}
#[test]
fn a_center_dragged_along_the_line_takes_the_curvature_centered_there() {
for end in [GradientEnd::Start, GradientEnd::End] {
for curvature in curvatures().filter(|&curvature| curvature != 0.) {
let center = contour_center(end, curvature).unwrap();
let found = center_curvature(end, center.x);
// A point is both -1 and 1, which the drag settles at -1
let expected = if curvature.abs() == 1. { -1. } else { curvature };
assert!((found - expected).abs() < 1e-9, "{end:?} curvature {curvature}: {found}");
}
// Toward the other end bows toward it, and onto the endpoint is a point
assert!(center_curvature(end, 0.5) > 0.);
assert!(center_curvature(end, end.endpoint().x - end.inward()) < 0.);
assert_eq!(center_curvature(end, end.endpoint().x), -1.);
}
// The start contour centered at the end point, and the end contour at the start point, are each the circle of radius 1 between them
assert!((center_curvature(GradientEnd::Start, 1.) - 0.5).abs() < 1e-12);
assert!((center_curvature(GradientEnd::End, 0.) - 0.5).abs() < 1e-12);
}
/// The center and radius of the end circle of a gradient along `line`, in the gradient space `line` is given in.
fn end_circle(line: RefocusedLine) -> (DVec2, f64) {
let radius = curvature_radius(line.end_curvature);
(line.start.lerp(line.end, 1. - radius), radius.abs() * line.start.distance(line.end))
}
#[test]
fn a_moved_focus_keeps_the_end_circle_in_place() {
// The end circle of radius 0.75 centered at 0.25, with foci inside it, outside it, and behind its center
let end_curvature = radius_curvature(0.75);
let (center, radius) = (DVec2::new(0.25, 0.), 0.75);
for focus in [DVec2::new(0.1, 0.3), DVec2::new(-0.2, -0.4), DVec2::new(3., 2.), DVec2::new(0.9, 0.), DVec2::new(-5., 0.)] {
let line = refocused_line(focus, end_curvature, DVec2::X).unwrap();
assert_eq!(line.start, focus);
let (new_center, new_radius) = end_circle(line);
assert!(new_center.distance(center) < 1e-12 && (new_radius - radius).abs() < 1e-12, "focus {focus}: {line:?}");
// The line runs on through the center to the circle's far side
assert!((line.end.distance(focus) - (focus.distance(center) + radius)).abs() < 1e-12, "focus {focus}: {line:?}");
}
// A focus off the circle's line still aims the line through its center
let line = refocused_line(DVec2::new(0.25, 2.), end_curvature, DVec2::X).unwrap();
assert!(line.end.abs_diff_eq(DVec2::new(0.25, -0.75), 1e-12));
}
#[test]
fn a_focus_on_the_center_keeps_the_direction_and_makes_the_radial_form() {
let end_curvature = radius_curvature(0.75);
let line = refocused_line(contour_center(GradientEnd::End, end_curvature).unwrap(), end_curvature, DVec2::new(0., 2.)).unwrap();
assert_eq!(line.end_curvature, 0.5);
assert!(line.end.abs_diff_eq(DVec2::new(0.25, 0.75), 1e-12));
assert_eq!(
graphene_std::vector::style::GradientForm::from_curvatures([-1., line.end_curvature]),
Some(graphene_std::vector::style::GradientForm::Radial)
);
// Only an end circle has a focus to move around
assert!(has_focus([-1., 0.5]) && has_focus([1., -0.3]));
assert!(!has_focus([0., 0.5]) && !has_focus([-1., 0.]) && !has_focus([-1., 1.]));
assert_eq!(refocused_line(DVec2::ZERO, 0., DVec2::X), None);
}
#[test]
fn a_refocused_transform_keeps_an_elliptical_end_contour_in_place() {
// A radial gradient squashed to half its height and skewed, whose focus moves off its line
let old = DAffine2::from_cols(DVec2::new(100., 20.), DVec2::new(-5., 50.), DVec2::new(30., 40.));
let line = refocused_line(DVec2::new(0.3, 0.4), 0.5, DVec2::X).unwrap();
let new = transform_along(old, line);
// The end contour's points land on the same ellipse before and after (within its chords' sag), though spread differently around it
let before = contour_polyline(GradientEnd::End, 0.5, old, 1e6);
let after = contour_polyline(GradientEnd::End, line.end_curvature, new, 1e6);
for point in after {
assert!(distance_to_polyline(&before, point).unwrap() <= CONTOUR_SAG_TOLERANCE, "{point} left the ellipse");
}
assert!(new.transform_point2(DVec2::ZERO).abs_diff_eq(old.transform_point2(DVec2::new(0.3, 0.4)), 1e-9));
}
#[test]
fn each_end_circle_has_an_aspect_handle_a_radius_to_either_side_of_its_center() {
use LineSide::{Negative, Positive};
// The radial form's end circle around the start point, but not its start point
assert_eq!(aspect_axis(GradientEnd::End, 0.5, Positive), Some([DVec2::ZERO, DVec2::Y]));
assert_eq!(aspect_axis(GradientEnd::End, 0.5, Negative), Some([DVec2::ZERO, -DVec2::Y]));
assert_eq!(aspect_axis(GradientEnd::Start, -1., Positive), None);
// Each of two crossing circles, and a huge nearly flat one
let radius = curvature_radius(0.6);
assert_eq!(aspect_axis(GradientEnd::Start, 0.6, Positive), Some([DVec2::new(radius, 0.), DVec2::new(radius, radius)]));
assert_eq!(aspect_axis(GradientEnd::End, 0.6, Negative), Some([DVec2::new(1. - radius, 0.), DVec2::new(1. - radius, -radius)]));
assert!(aspect_axis(GradientEnd::End, 1e-3, Positive).is_some_and(|[_, handle]| handle.y > 100.));
// Lines and points have none
for end in [GradientEnd::Start, GradientEnd::End] {
for curvature in [0., 1., -1.] {
for side in [Positive, Negative] {
assert_eq!(aspect_axis(end, curvature, side), None, "{end:?} curvature {curvature} {side:?}");
}
}
}
}
#[test]
fn stretching_moves_each_aspect_handle_across_the_line_and_keeps_the_line() {
// A skewed gradient, its perpendicular axis leaning along the line
let transform = DAffine2::from_cols(DVec2::new(80., 60.), DVec2::new(-50., 70.), DVec2::new(10., 20.));
let along = transform.matrix2.x_axis.normalize();
// The radial form's handles and those of two crossing circles of different sizes, each pulled to its own side of the line
let axes = [(GradientEnd::End, 0.5), (GradientEnd::Start, 0.6), (GradientEnd::End, 0.3)];
let handles = axes
.into_iter()
.flat_map(|(end, curvature)| [LineSide::Positive, LineSide::Negative].map(|side| (aspect_axis(end, curvature, side).unwrap()[1], side)));
for (handle, side) in handles {
let pointer = transform.transform_point2(DVec2::new(0.4, side.sign() * 0.7));
let stretched = stretched_transform(transform, handle, pointer).unwrap();
assert!(stretched.matrix2.determinant() * transform.matrix2.determinant() > 0., "the gradient shouldn't mirror");
for point in [DVec2::ZERO, DVec2::X] {
assert!(stretched.transform_point2(point).abs_diff_eq(transform.transform_point2(point), 1e-9));
}
// The handle lands as far across the line as the pointer, sliding only across it, and the lean along the line stays
let (old_handle, new_handle) = (transform.transform_point2(handle), stretched.transform_point2(handle));
assert!(((new_handle - transform.translation).dot(along.perp()) - (pointer - transform.translation).dot(along.perp())).abs() < 1e-9);
assert!((new_handle - old_handle).dot(along).abs() < 1e-9);
assert!((stretched.matrix2.y_axis.dot(along) - transform.matrix2.y_axis.dot(along)).abs() < 1e-9);
// Onto the line, it would collapse
assert_eq!(stretched_transform(transform, handle, transform.transform_point2(DVec2::new(0.5, 0.))), None);
}
}
#[test]
fn contours_are_drawn_through_their_endpoints_out_to_their_reach() {
let unit_to_viewport = DAffine2::from_scale_angle_translation(DVec2::new(200., 100.), 0.3, DVec2::new(40., 60.));
for end in [GradientEnd::Start, GradientEnd::End] {
let endpoint = unit_to_viewport.transform_point2(end.endpoint());
// A point draws nothing, and a line is one long chord through the endpoint
assert!(contour_polyline(end, 1., unit_to_viewport, 500.).is_empty());
let line = contour_polyline(end, 0., unit_to_viewport, 500.);
assert_eq!(line.len(), 2);
assert!(distance_to_polyline(&line, endpoint).unwrap() < 1e-9);
// A small circle is drawn whole, closing on itself, and a huge one only as far as its reach, nearly straight
let small = contour_polyline(end, 0.5, unit_to_viewport, 500.);
assert!(small.first().unwrap().distance(*small.last().unwrap()) < 1e-6);
let huge = contour_polyline(end, 1e-6, unit_to_viewport, 500.);
let farthest = huge.iter().map(|point| point.distance(endpoint)).fold(0., f64::max);
assert!((400. ..=1000.).contains(&farthest), "a huge circle should reach about 500 pixels, not {farthest}");
for polyline in [small, huge] {
assert!(distance_to_polyline(&polyline, endpoint).unwrap() < 1e-6);
}
}
}
}
@@ -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_curvature::IDENTIFIER,
graphene_std::math_nodes::gradient_form::IDENTIFIER,
graphene_std::math_nodes::gradient_spread::IDENTIFIER,
graphene_std::math_nodes::gradient_positions::IDENTIFIER,
graphene_std::math_nodes::gradient_midpoints::IDENTIFIER,
@@ -428,17 +428,6 @@ pub fn get_chain_source_gradient_settings(layer: LayerNodeIdentifier, network_in
Some(get_chain_source_gradient_ramp(layer, network_interface)?.into())
}
/// The start and end curvatures a 'Gradient Curvature' node holds as values, or `None` when either is fed from the graph or exposed.
pub fn gradient_curvature_values(node: &DocumentNode) -> Option<[f64; 2]> {
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, StartCurvatureInput};
let value = |input: Option<&NodeInput>| match input?.as_non_exposed_value()? {
&TaggedValue::Number(value) => Some(value),
_ => None,
};
Some([value(node.input(StartCurvatureInput))?, value(node.input(EndCurvatureInput))?])
}
/// Get the gradient stops of a layer, if any.
pub fn get_gradient_stops(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Gradient> {
// Try to find the gradient stops value that is created by a Fill node first
@@ -841,23 +830,9 @@ pub fn set_stroke_weight_for_selected_layers(weight: f64, document: &DocumentMes
}
}
/// A Fill node's curvatures, unless the graph feeds either or exposes it, read like [`gradient_curvature_values`] reads a 'Gradient Curvature' node's.
pub fn fill_node_curvatures(fill_node: &DocumentNode) -> Option<[f64; 2]> {
use graphene_std::vector::fill::{EndCurvatureInput, StartCurvatureInput};
let value = |input: Option<&NodeInput>| match input?.as_non_exposed_value()? {
&TaggedValue::Number(value) => Some(value),
_ => None,
};
Some([value(fill_node.input(StartCurvatureInput))?, value(fill_node.input(EndCurvatureInput))?])
}
/// A Fill node's decoded gradient inputs, with the transform kept in its raw form (not yet baked into `start`/`end`).
pub struct FillNodeGradient {
pub stops: Gradient,
/// Its curvatures, unless the graph feeds them, as [`fill_node_curvatures`] reads them.
pub curvatures: Option<[f64; 2]>,
/// The form its curvatures make, which is linear for any that make neither.
pub gradient_form: GradientForm,
pub settings: GradientSettings,
pub transform: DAffine2,
@@ -874,8 +849,10 @@ pub fn read_fill_node_gradient(fill_node: &DocumentNode, bounding_box: impl FnOn
};
let settings = GradientSettings::from(ramp);
let stops = Gradient::from(ramp);
let curvatures = fill_node_curvatures(fill_node);
let gradient_form = curvatures.and_then(GradientForm::from_curvatures).unwrap_or_default();
let gradient_form = match fill_node.input(fill::GradientFormInput).and_then(|input| input.as_value()) {
Some(&TaggedValue::GradientForm(value)) => value,
_ => GradientForm::default(),
};
let has_transform = matches!(fill_node.input(fill::HasTransformInput).and_then(|input| input.as_value()), Some(&TaggedValue::Bool(true)));
let transform_input = fill_node.input(fill::TransformInput).and_then(|input| input.as_value());
let transform = match (has_transform, transform_input) {
@@ -886,7 +863,6 @@ pub fn read_fill_node_gradient(fill_node: &DocumentNode, bounding_box: impl FnOn
Some(FillNodeGradient {
stops,
curvatures,
gradient_form,
settings,
transform,
@@ -1029,6 +1005,10 @@ pub fn set_fill_for_selected_layers(fill_choice: FillChoice, document: &Document
use graphene_std::vector::fill;
let fill_parameters = NodeGraphLayer::new(layer, &document.network_interface).find_node_parameters(fill::IDENTIFIER);
let gradient_form = match fill_parameters.as_ref().and_then(|parameters| parameters.value(fill::GradientFormInput)) {
Some(TaggedValue::GradientForm(value)) => *value,
_ => GradientForm::default(),
};
let has_transform = matches!(fill_parameters.as_ref().and_then(|parameters| parameters.value(fill::HasTransformInput)), Some(TaggedValue::Bool(true)));
let transform = match (has_transform, fill_parameters.as_ref().and_then(|parameters| parameters.value(fill::TransformInput))) {
(true, Some(TaggedValue::DAffine2(value))) => *value,
@@ -1039,7 +1019,7 @@ pub fn set_fill_for_selected_layers(fill_choice: FillChoice, document: &Document
responses.add(GraphOperationMessage::FillGradientSet {
layer,
gradient: Gradient::from(ramp),
gradient_form: None,
gradient_form,
gradient_settings: ramp.into(),
transform: Some(transform),
});
@@ -3,7 +3,6 @@ pub mod color_selector;
pub mod compass_rose;
pub mod edit_target;
pub mod gizmos;
pub mod gradient_gizmos;
pub mod graph_modification_utils;
pub mod layer_origin_cross;
pub mod measure;
@@ -92,8 +92,6 @@ pub struct PointOptions {
pub box_features: Option<BoxFeatures>,
/// Whether the grid is left out, as for a turn, which the grid would otherwise step at odd angles.
pub ignores_grid: bool,
/// Whether the tool marks where a press would land in its own way, so nothing marks it there unless a snap is named.
pub marked_by_tool: bool,
}
/// Which features of a gesture make up a box.
@@ -124,8 +122,6 @@ pub struct Shown {
pub features: Vec<DVec2>,
/// The index of the feature the pointer carries.
pub lead: usize,
/// Whether the tool marks where a press would land, as [`PointOptions::marked_by_tool`] tells.
pub marked_by_tool: bool,
}
/// What a kept set of constructions was found for, which it stays good for.
@@ -325,7 +321,6 @@ impl SnapSession {
features: features.iter().map(|feature| feature.position(parameters)).collect(),
lead,
outcome,
marked_by_tool: options.marked_by_tool,
});
// A crossing, or the grid, can hold the box anywhere along the track that evens out its gaps, so they are measured again where it landed
@@ -404,7 +399,6 @@ impl SnapSession {
features: vec![position_of(snapped)],
lead: 0,
outcome,
marked_by_tool: false,
});
snapped
@@ -19,24 +19,14 @@ impl SnapSession {
self.draw_awake(target, to_viewport, overlay_context);
}
let Some(Shown {
outcome,
features,
lead,
marked_by_tool,
}) = &self.shown
else {
return;
};
let Some(Shown { outcome, features, lead, .. }) = &self.shown else { return };
// Before a press, the point is marked where the press would place it, even with no snap to name
if matches!(outcome.snap, Snap::Grid | Snap::Free)
&& self.gesture.is_none()
&& let Some(&position) = features.get(*lead)
{
if !marked_by_tool {
overlay_context.square(to_viewport.transform_point2(position), Some(4.), Some(COLOR_OVERLAY_BLUE), Some(COLOR_OVERLAY_BLUE));
}
overlay_context.square(to_viewport.transform_point2(position), Some(4.), Some(COLOR_OVERLAY_BLUE), Some(COLOR_OVERLAY_BLUE));
return;
}
File diff suppressed because it is too large. Load diff
@@ -2,8 +2,6 @@
import { getContext, onMount, onDestroy } from "svelte";
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
import WidgetLayout from "/src/components/widgets/WidgetLayout.svelte";
import { createDragToggleManager, destroyDragToggleManager } from "/src/managers/drag-toggle";
import type { DragToggleListener } from "/src/managers/drag-toggle";
import { inspectorLayout } from "/src/stores/portfolio";
import { createAutoScroller } from "/src/utility-functions/auto-scroll";
import type { EditorWrapper } from "/wrapper/pkg/graphite_wasm_wrapper";
@@ -25,15 +23,7 @@
let lastDragClientY = 0;
const autoScroller = createAutoScroller(() => calculateInsertIndex(lastDragClientY));
// Everything one middle-button drag across the section headers paints is one history step
const dragToggleListener: DragToggleListener = {
groups: ["inspector-section-visibility"],
engagedChanged: (engaged) => (engaged ? editor.startTransaction() : editor.endTransaction()),
};
onMount(() => {
createDragToggleManager(dragToggleListener);
addEventListener("pointermove", draggingPointerMove);
addEventListener("pointerup", draggingPointerUp);
// A drag cut short by the pointer being canceled or the window losing focus won't get the release that ends it
@@ -46,8 +36,6 @@
});
onDestroy(() => {
destroyDragToggleManager(dragToggleListener);
removeEventListener("pointermove", draggingPointerMove);
removeEventListener("pointerup", draggingPointerUp);
removeEventListener("pointercancel", abortDrag);
@@ -331,7 +331,6 @@
}
const dragToggleListener: DragToggleListener = {
groups: ["layer-visibility", "layer-lock", "layer-chain-visibility"],
activeGroupChanged: (group) => {
activeDragToggleGroup = group;
},
@@ -343,15 +342,6 @@
editor.toggleNodeVisibilityLayerPanel(id);
}
// Middle-clicking one of the chain's node buttons toggles that node's visibility
function chainIconsAuxClick(e: MouseEvent, listing: LayerListingInfo) {
if (e.button !== 1) return;
const chainNodeButton = e.target instanceof Element ? e.target.closest("[data-chain-node]") : undefined;
const chainNode = chainNodeButton ? listing.entry?.chainNodes[Number(chainNodeButton.getAttribute("data-chain-node"))] : undefined;
if (chainNode) toggleNodeVisibilityLayerPanel(chainNode.id);
}
function toggleLayerLock(id: bigint) {
editor.toggleLayerLock(id);
}
@@ -1204,7 +1194,6 @@
on:pointerdown={(e) => layerPointerDown(e, listing)}
on:click={(e) => selectLayerWithModifiers(e, listing)}
on:dblclick={(e) => chainIconsDoubleClick(e, listing)}
on:auxclick={(e) => chainIconsAuxClick(e, listing)}
on:pointerenter={() => hoverRow(index)}
on:pointerleave={() => (hoveredRowIndex = undefined)}
>
@@ -1354,8 +1343,6 @@
data-chain-node={slot.nodeIndex}
data-chain-gap-before={slot.reorderablePosition}
data-chain-gap-after={slot.reorderablePosition === undefined ? undefined : slot.reorderablePosition + 1}
data-middle-drag-toggle-group="layer-chain-visibility"
data-drag-toggle-state={chainNode.visible ? "visible" : "hidden"}
/>
{/if}
{/if}
@@ -1372,17 +1359,12 @@
: entry.chainExpanded
? "Stop listing this layer's chain one node per row."
: "List this layer's chain one node per row, beneath the layer."}
data-middle-drag-toggle-group="layer-chain-visibility"
data-drag-toggle-state={entry.visible ? "visible" : "hidden"}
on:click={(e) => {
// Without a chain to expand, a click selects the layer as it does elsewhere in the row
if (entry.chainNodes.length === 0) return;
e.stopPropagation();
editor.toggleLayerChainExpanded(listing.id);
}}
on:auxclick={(e) => {
if (e.button === 1) toggleNodeVisibilityLayerPanel(listing.id);
}}
>
<IconLabel
icon={entry.iconName}
@@ -1413,15 +1395,10 @@
data-chain-row-node={slot.nodeIndex}
data-chain-gap-before={slot.reorderablePosition}
data-chain-gap-after={slot.reorderablePosition === undefined ? undefined : slot.reorderablePosition + 1}
data-middle-drag-toggle-group="layer-chain-visibility"
data-drag-toggle-state={chainNode.visible ? "visible" : "hidden"}
on:pointerdown={(e) => {
if (e.button === 0 && draggable) chainNodePointerDown(e, listing, chainNode);
}}
on:click={(e) => chainNodeClick(e, listing, chainNode.id)}
on:auxclick={(e) => {
if (e.button === 1) toggleNodeVisibilityLayerPanel(chainNode.id);
}}
on:dblclick={(e) => {
// Only the node's icon opens it in the graph
if (e.target instanceof Element && e.target.closest("[data-chain-node-row-icon]")) editor.showNodeInGraph(chainNode.id);
@@ -41,12 +41,6 @@
const accel = operatingSystem() === "Mac" ? e.metaKey : e.ctrlKey;
editor.toggleNodeInspectorSectionExpanded(widgetData.id, e.altKey || accel);
}
function toggleVisibilityWithMiddleClick(e: MouseEvent) {
if (e.button !== 1 || widgetData.disabled) return;
editor.toggleNodeVisibilityInspector(widgetData.id);
}
</script>
<!-- TODO: Implement collapsable sections with the Inspector system -->
@@ -82,16 +76,7 @@
{/if}
{/each}
{:else}
<button
class="header"
class:expanded
class:expandable
data-inspector-reorder-handle={reorderable ? "" : undefined}
data-middle-drag-toggle-group={widgetData.disabled ? undefined : "inspector-section-visibility"}
data-drag-toggle-state={widgetData.visible ? "visible" : "hidden"}
onclick={toggleExpandedWithModifiers}
onauxclick={toggleVisibilityWithMiddleClick}
>
<button class="header" class:expanded class:expandable data-inspector-reorder-handle={reorderable ? "" : undefined} onclick={toggleExpandedWithModifiers}>
<div
class="icon-slot"
data-tooltip-label={!expandable ? undefined : expanded ? "Collapse (All)" : "Expand (All)"}
@@ -558,10 +543,9 @@
margin-left: 8px;
}
// A label with no expose button before it lines up with the parameter names that follow one
> .text-label:first-child {
// A label alone in its row lines up with the parameter names that follow their expose buttons
> .text-label:only-child {
margin-left: calc(20px + 8px + 8px);
--wire-indent: 20px;
}
> .separator.horizontal.unrelated {
+21 -77
View File
@@ -8,30 +8,21 @@
// The gesture only engages once the pointer crosses from the source into a different sibling, so plain
// clicks still toggle as usual. When engaged, the source is clicked once (toggling it) and any sibling
// the pointer enters whose state still matches the source's recorded starting state is also clicked.
//
// Peers toggled by the middle button declare data-middle-drag-toggle-group instead, and toggle on an `auxclick`
// rather than a click. Their gesture engages on the press, which toggles the source at once.
export type DragToggleListener = {
// The groups whose gestures this listener is told about
groups: string[];
// Given the group of the pressed button, and undefined once the press ends
activeGroupChanged?: (activeGroup: string | undefined) => void;
// Told when the gesture engages, before any of its clicks, and again when it ends, so its clicks can form one history step
engagedChanged?: (engaged: boolean) => void;
};
const MIDDLE_BUTTON = 1;
const listeners = new Set<DragToggleListener>();
let activeGroup: string | undefined = undefined;
let middleButtonGesture = false;
let source: HTMLElement | undefined = undefined;
let startingState: string | undefined = undefined;
let visited = new WeakSet<Element>();
let engaged = false;
let suppressNextClickFromSource: HTMLElement | undefined = undefined;
let suppressNextAuxClick = false;
export function createDragToggleManager(listener: DragToggleListener) {
listeners.add(listener);
@@ -47,13 +38,12 @@ export function createDragToggleManager(listener: DragToggleListener) {
window.addEventListener("blur", onPointerUp);
// Capture phase on click suppresses the natural source-click before the button's handler runs
window.addEventListener("click", onClickCapture, true);
window.addEventListener("auxclick", onAuxClickCapture, true);
}
}
export function destroyDragToggleManager(listener: DragToggleListener) {
// A consumer leaving mid-gesture still hears it end
if (engaged && activeGroup && listener.groups.includes(activeGroup)) listener.engagedChanged?.(false);
if (engaged) listener.engagedChanged?.(false);
listeners.delete(listener);
// Uninstall the window event listeners only once the last consumer leaves
@@ -64,120 +54,83 @@ export function destroyDragToggleManager(listener: DragToggleListener) {
window.removeEventListener("pointercancel", onPointerUp);
window.removeEventListener("blur", onPointerUp);
window.removeEventListener("click", onClickCapture, true);
window.removeEventListener("auxclick", onAuxClickCapture, true);
activeGroup = undefined;
middleButtonGesture = false;
source = undefined;
startingState = undefined;
visited = new WeakSet();
engaged = false;
suppressNextClickFromSource = undefined;
suppressNextAuxClick = false;
}
}
function listenersOfGroup(group: string): DragToggleListener[] {
return Array.from(listeners).filter((listener) => listener.groups.includes(group));
}
function notifyActiveGroupChange(group: string | undefined) {
const previousGroup = activeGroup;
activeGroup = group;
const notifiedGroup = group || previousGroup;
if (notifiedGroup) listenersOfGroup(notifiedGroup).forEach((listener) => listener.activeGroupChanged?.(group));
listeners.forEach((listener) => listener.activeGroupChanged?.(group));
}
function groupAttribute(middleButton: boolean): string {
return middleButton ? "data-middle-drag-toggle-group" : "data-drag-toggle-group";
}
function findMember(target: EventTarget | undefined, middleButton: boolean): HTMLElement | undefined {
function findMember(target: EventTarget | undefined): HTMLElement | undefined {
if (!(target instanceof Element)) return undefined;
const found = target.closest(`[${groupAttribute(middleButton)}]`);
const found = target.closest("[data-drag-toggle-group]");
return found instanceof HTMLElement ? found : undefined;
}
function memberState(member: HTMLElement): string | undefined {
return member.getAttribute("data-drag-toggle-state") || undefined;
}
function toggle(member: HTMLElement) {
if (middleButtonGesture) member.dispatchEvent(new MouseEvent("auxclick", { button: MIDDLE_BUTTON, bubbles: true }));
else member.click();
}
function engage() {
if (!activeGroup || !source) return;
engaged = true;
visited.add(source);
listenersOfGroup(activeGroup).forEach((listener) => listener.engagedChanged?.(true));
if (memberState(source) === startingState) toggle(source);
}
function onPointerDown(e: PointerEvent) {
if (e.button !== 0 && e.button !== MIDDLE_BUTTON) return;
if (e.button !== 0) return;
suppressNextClickFromSource = undefined;
suppressNextAuxClick = false;
const middleButton = e.button === MIDDLE_BUTTON;
const found = findMember(e.target || undefined, middleButton);
const found = findMember(e.target || undefined);
if (!found) return;
// Stop the event so sibling drag/select handlers on ancestors don't also engage
e.stopPropagation();
middleButtonGesture = middleButton;
source = found;
startingState = memberState(found);
startingState = found.getAttribute("data-drag-toggle-state") || undefined;
visited = new WeakSet();
engaged = false;
notifyActiveGroupChange(found.getAttribute(groupAttribute(middleButton)) || undefined);
if (middleButton) engage();
notifyActiveGroupChange(found.getAttribute("data-drag-toggle-group") || undefined);
}
function onPointerMove(e: PointerEvent) {
if (!activeGroup || !source) return;
const member = findMember(e.target || undefined, middleButtonGesture);
if (!member || member.getAttribute(groupAttribute(middleButtonGesture)) !== activeGroup) return;
const member = findMember(e.target || undefined);
if (!member || member.getAttribute("data-drag-toggle-group") !== activeGroup) return;
// Engages only when the cursor crosses from the source to a different peer, so tiny wobbles over the source don't trigger
if (member === source || visited.has(member)) return;
// First crossing engages the drag and toggles the source as part of the operation
if (!engaged) engage();
if (!engaged) {
engaged = true;
visited.add(source);
listeners.forEach((listener) => listener.engagedChanged?.(true));
if ((source.getAttribute("data-drag-toggle-state") || undefined) === startingState) source.click();
}
// Toggle only peers still in the starting state, so we don't flip ones already at the target state
if (memberState(member) !== startingState) return;
if ((member.getAttribute("data-drag-toggle-state") || undefined) !== startingState) return;
visited.add(member);
toggle(member);
member.click();
}
function onPointerUp(e: Event) {
if (!activeGroup) return;
const endedGroup = activeGroup;
// An engaged drag already toggled the source, so its release's click won't toggle it again
if (engaged && source && e.type === "pointerup") {
if (middleButtonGesture) suppressNextAuxClick = true;
else suppressNextClickFromSource = source;
}
// An engaged drag already clicked the source, so the click its release sends is suppressed rather than toggling it again
if (engaged && source && e.type === "pointerup") suppressNextClickFromSource = source;
const wasEngaged = engaged;
middleButtonGesture = false;
source = undefined;
startingState = undefined;
visited = new WeakSet();
engaged = false;
notifyActiveGroupChange(undefined);
if (wasEngaged) listenersOfGroup(endedGroup).forEach((listener) => listener.engagedChanged?.(false));
if (wasEngaged) listeners.forEach((listener) => listener.engagedChanged?.(false));
}
function onClickCapture(e: Event) {
@@ -188,15 +141,6 @@ function onClickCapture(e: Event) {
suppressNextClickFromSource = undefined;
}
// Unlike a click, this isn't limited to the source, since a drag's auxclick lands on the ancestor shared by its press and release
function onAuxClickCapture(e: MouseEvent) {
if (!suppressNextAuxClick || e.button !== MIDDLE_BUTTON) return;
suppressNextAuxClick = false;
e.stopPropagation();
e.preventDefault();
}
// Self-accepting HMR: tear down the old instance and re-create with the new module's code
import.meta.hot?.accept((newModule) => {
const carried = Array.from(listeners);
@@ -360,11 +360,15 @@ impl NodeNetwork {
};
let value_node_id = gen_id();
let merged_node_id = map_ids(id, value_node_id);
let original_location = OriginalLocation {
let mut original_location = OriginalLocation {
path: Some(path.to_vec()),
dependants: vec![vec![id]],
..Default::default()
};
if let Some(path) = &mut original_location.path {
path.push(value_node_id);
}
collection.insert(
merged_node_id,
DocumentNode {
@@ -63,6 +63,7 @@ fn flatten_add_expected() -> NodeNetwork {
inputs: vec![NodeInput::value(TaggedValue::Integer(2), false)],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::value::ClonedNode")),
original_location: OriginalLocation {
path: Some(vec![NodeId(4)]),
dependants: vec![vec![NodeId(10)]],
..Default::default()
},
@@ -570,7 +570,6 @@ tagged_value! {
StrokeAlign(vector::style::StrokeAlign),
#[serde(alias = "GradientType")] // TODO: Eventually remove this document upgrade code
GradientForm(vector::style::GradientForm),
GradientModel(vector::style::GradientModel),
#[serde(alias = "GradientSpreadMethod")] // TODO: Eventually remove this document upgrade code
GradientSpread(vector::style::GradientSpread),
GradientSpace(vector::style::GradientSpace),
@@ -26,7 +26,7 @@ use graphene_std::vector::misc::{
ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod,
WeldMethod,
};
use graphene_std::vector::style::{DashPattern, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin};
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, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, MaskMode, MinimumMaximumMode, NoiseDistribution};
@@ -68,6 +68,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<bool>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<DAffine2>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<BlendMode>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<GradientForm>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<GradientSpread>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<GradientSpace>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<GradientHueDirection>]),
@@ -270,7 +271,6 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
StrokeAlign,
StrokeCap,
GradientForm,
GradientModel,
GradientSpread,
GradientSpace,
GradientHueDirection,
@@ -381,6 +381,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
DVec2,
DAffine2,
BlendMode,
GradientForm,
GradientSpread,
GradientSpace,
GradientHueDirection,
@@ -515,7 +516,6 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
attribute_value_node!(Item<Color>),
attribute_value_node!(Item<BlendMode>),
attribute_value_node!(Item<GradientForm>),
attribute_value_node!(Item<GradientModel>),
attribute_value_node!(Item<GradientSpread>),
attribute_value_node!(Item<GradientSpace>),
attribute_value_node!(Item<GradientHueDirection>),
+25 -116
View File
@@ -72,32 +72,31 @@ impl BlendMode {
]
}
/// The subset of [`BlendMode::list()`] that is supported by SVG.
pub fn list_svg_subset() -> [&'static [BlendMode]; 6] {
use BlendMode::*;
[
// Normal group
&[Normal],
// Darken group
&[Darken, Multiply, ColorBurn],
// Lighten group
&[Lighten, Screen, ColorDodge],
// Contrast group
&[Overlay, SoftLight, HardLight],
// Inversion group
&[Difference, Exclusion],
// Component group
&[Hue, Saturation, Color, Luminosity],
]
}
pub fn index_in_list(&self) -> Option<usize> {
Self::list().iter().flat_map(|x| x.iter()).position(|&blend_mode| blend_mode == *self)
}
/// Whether a layer in this mode reads what lies beneath it to blend, since neither SVG's `mix-blend-mode` nor Vello's layers have the mode.
/// The alpha-only utility modes, hidden from the list, draw layers normally.
pub fn reads_backdrop(&self) -> bool {
self.to_svg_style_name().is_none() && !matches!(self, BlendMode::Erase | BlendMode::Restore | BlendMode::MultiplyAlpha)
}
/// Whether a paint's strength (an effect's opacity, or a layer's fill) moves its color toward the mode's neutral color, which then blends at full strength, rather than fading the blend, for PSD interop.
pub fn strength_moves_toward_neutral(&self) -> bool {
use BlendMode::*;
matches!(self, ColorDodge | LinearDodge | ColorBurn | LinearBurn | VividLight | LinearLight | HardMix)
}
/// Whether a layer's fill moves its content toward the mode's neutral color (see [`Self::strength_moves_toward_neutral`]) rather than fading it, for PSD interop.
/// The layer then reads what lies beneath it to blend (see [`Self::layer_reads_backdrop`]).
pub fn fill_moves_layer_toward_neutral(&self) -> bool {
self.strength_moves_toward_neutral()
}
/// Whether a layer in this mode at this `fill` reads what lies beneath it to blend: in a mode neither SVG's `mix-blend-mode` nor Vello's layers have,
/// or below a full fill moving it toward the mode's neutral color, which Color Dodge and Color Burn layers otherwise blend natively without.
pub fn layer_reads_backdrop(&self, fill: f32) -> bool {
self.reads_backdrop() || (fill < 1. && self.fill_moves_layer_toward_neutral())
pub fn index_in_list_svg_subset(&self) -> Option<usize> {
Self::list_svg_subset().iter().flat_map(|x| x.iter()).position(|&blend_mode| blend_mode == *self)
}
/// Convert the enum to the CSS string for the blend mode.
@@ -131,14 +130,11 @@ impl BlendMode {
}
/// Renders the blend mode CSS style declaration.
/// A mode CSS lacks, which layers read what lies beneath to blend by, draws normally where nothing beneath can be read, as for content without bounds.
pub fn render(&self) -> String {
format!(
r#" mix-blend-mode: {};"#,
self.to_svg_style_name().unwrap_or_else(|| {
if !self.reads_backdrop() {
log::warn!("Unsupported blend mode {self:?}");
}
log::warn!("Unsupported blend mode {self:?}");
"normal"
})
)
@@ -160,7 +156,7 @@ impl Display for BlendMode {
BlendMode::Lighten => write!(f, "Lighten"),
BlendMode::Screen => write!(f, "Screen"),
BlendMode::ColorDodge => write!(f, "Color Dodge"),
BlendMode::LinearDodge => write!(f, "Linear Dodge (Add)"),
BlendMode::LinearDodge => write!(f, "Linear Dodge"),
BlendMode::LighterColor => write!(f, "Lighter Color"),
// Contrast group
BlendMode::Overlay => write!(f, "Overlay"),
@@ -251,30 +247,6 @@ pub fn apply_blend_mode(foreground: Color, background: Color, blend_mode: BlendM
}
}
/// How strongly a layer whose fill moves it toward neutral (see [`BlendMode::fill_moves_layer_toward_neutral`]) shows over a backdrop of `backdrop_alpha`: fully over an opaque one,
/// by its `fill` over nothing, and between, the harmonic mean of the two weighted by that alpha, which shows nothing at no fill.
pub fn layer_fill_shown(backdrop_alpha: f32, fill: f32) -> f32 {
let weighted = (1. - backdrop_alpha) + backdrop_alpha * fill;
if weighted <= 0. { 0. } else { (fill / weighted).min(1.) }
}
/// Like [`apply_blend_mode`], with the foreground at `strength` (from 0 to 1) moved toward the mode's neutral color where it does that (see [`BlendMode::strength_moves_toward_neutral`]),
/// for the caller to composite at full strength. Other modes take the foreground as it is, for the caller to fade the blend by the strength.
pub fn apply_blend_mode_at_strength(foreground: Color, background: Color, blend_mode: BlendMode, strength: f32) -> Color {
let toward = |neutral: f32| {
let moved = |channel: f32| neutral + strength * (channel - neutral);
Color::from_rgbaf32_unchecked(moved(foreground.r()), moved(foreground.g()), moved(foreground.b()), foreground.a())
};
match blend_mode {
BlendMode::ColorDodge | BlendMode::LinearDodge => apply_blend_mode(toward(0.), background, blend_mode),
BlendMode::ColorBurn | BlendMode::LinearBurn => apply_blend_mode(toward(1.), background, blend_mode),
BlendMode::VividLight | BlendMode::LinearLight => apply_blend_mode(toward(0.5), background, blend_mode),
BlendMode::HardMix => background.blend_rgb(foreground, |backdrop, source| Color::blend_hard_mix_at_strength(backdrop, source, strength)),
_ => apply_blend_mode(foreground, background, blend_mode),
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -289,13 +261,9 @@ mod tests {
assert_eq!(Color::blend_color_burn(0.5, source), 0., "a source of {source}");
}
// Color Dodge, like Divide, keeps a black backdrop black under any source, even white, and turns any other white under a white source.
// Divide also turns any other white under a black source.
for backdrop in [0., 1e-7, -1e-7] {
assert_eq!(Color::blend_color_dodge(backdrop, 1.), 0., "a backdrop of {backdrop}");
}
// Color Dodge gives white for a white source, and Divide keeps a black backdrop black and turns any other white under a black source
for source in [1., 1. - 1e-7, 1. + 2e-7] {
assert_eq!(Color::blend_color_dodge(0.5, source), 1., "a source of {source}");
assert_eq!(Color::blend_color_dodge(0., source), 1., "a source of {source}");
}
for backdrop in [0., 1e-7, -1e-7] {
assert_eq!(Color::blend_divide(backdrop, 0.5), 0., "a backdrop of {backdrop}");
@@ -371,65 +339,6 @@ mod tests {
assert!((blended.a() - 1.).abs() < 1e-5, "alpha was {}", blended.a());
}
#[test]
fn darker_and_lighter_color_pick_the_whole_color_by_luma() {
// Blue's luma (0.11) is below the gray's (0.3), though its mean channel (a third) is above it
let blue = Color::from_rgbaf32_unchecked(0., 0., 1., 1.);
let gray = Color::from_rgbaf32_unchecked(0.3, 0.3, 0.3, 1.);
assert_eq!(apply_blend_mode(gray, blue, BlendMode::DarkerColor), blue);
assert_eq!(apply_blend_mode(gray, blue, BlendMode::LighterColor), gray);
assert_eq!(apply_blend_mode(blue, gray, BlendMode::DarkerColor), blue);
// Where the lumas tie, the backdrop stays, with the paint's alpha
let tied = Color::from_rgbaf32_unchecked(0.3, 0.3, 0.3, 0.5);
assert_eq!(apply_blend_mode(tied, gray, BlendMode::DarkerColor), gray.with_alpha(0.5));
}
#[test]
fn hard_mix_ramps_steeper_with_strength_to_a_256th_wide_where_the_channels_sum_to_one() {
let hard_mix = |backdrop: f32, source: f32, strength: f32| Color::blend_hard_mix_at_strength(backdrop, source, strength).clamp(0., 1.);
// At full strength, white past a sum of 1 and black short of it, even a level away
assert_eq!(hard_mix(0.6, 0.5, 1.), 1.);
assert_eq!(hard_mix(0.5, 0.49, 1.), 0.);
assert_eq!(hard_mix(0.5, 0.51, 1.), 1.);
// For PSD interop, half a fill gives clamp(2b - 1 + s), and no strength leaves the backdrop as it is
for (backdrop, source) in [(0.5, 0.3), (0.4, 0.4), (0.7, 0.1)] {
let half = hard_mix(backdrop, source, 128. / 255.);
assert!((half - (2. * backdrop - 1. + source).clamp(0., 1.)).abs() < 0.01, "{backdrop}, {source}: {half}");
assert_eq!(hard_mix(backdrop, source, 0.), backdrop);
}
}
#[test]
fn strength_moves_a_paint_toward_the_modes_neutral_color() {
let backdrop = Color::from_rgbaf32_unchecked(0.4, 0.4, 0.4, 1.);
let paint = Color::from_rgbaf32_unchecked(0.8, 0.8, 0.8, 1.);
let at_half = |blend_mode: BlendMode| apply_blend_mode_at_strength(paint, backdrop, blend_mode, 0.5).r();
// Half the paint added, the paint halfway to white burned in, and the paint halfway to middle gray lighting
assert!((at_half(BlendMode::LinearDodge) - 0.8).abs() < 1e-6, "{}", at_half(BlendMode::LinearDodge));
assert!((at_half(BlendMode::LinearBurn) - 0.3).abs() < 1e-6, "{}", at_half(BlendMode::LinearBurn));
assert!((at_half(BlendMode::LinearLight) - 0.7).abs() < 1e-6, "{}", at_half(BlendMode::LinearLight));
// The modes whose strength fades their blend take the paint as it is
assert_eq!(at_half(BlendMode::Subtract), apply_blend_mode(paint, backdrop, BlendMode::Subtract).r());
// Layers read what lies beneath for the ten modes CSS lacks, of which five move their content toward neutral by their fill
let reading: Vec<BlendMode> = BlendMode::list().into_iter().flatten().copied().filter(BlendMode::reads_backdrop).collect();
assert_eq!(reading.len(), 10);
assert_eq!(reading.iter().filter(|blend_mode| blend_mode.fill_moves_layer_toward_neutral()).count(), 5);
assert!(!BlendMode::Erase.reads_backdrop());
// Color Dodge and Color Burn do too below a full fill, which they otherwise blend natively at
for blend_mode in [BlendMode::ColorDodge, BlendMode::ColorBurn] {
assert!(!blend_mode.reads_backdrop() && !blend_mode.layer_reads_backdrop(1.) && blend_mode.layer_reads_backdrop(0.5) && blend_mode.layer_reads_backdrop(0.));
}
assert!(!BlendMode::Multiply.layer_reads_backdrop(0.5) && BlendMode::LinearBurn.layer_reads_backdrop(1.));
}
#[test]
fn source_over_weights_straight_colors_by_alpha() {
let over = Color::from_rgbaf32_unchecked(1., 0., 0., 0.5);
@@ -633,20 +633,14 @@ impl Color {
c_b + c_s - 1.
}
/// Whole-color "Darker Color" blend: keeps whichever color has the lower luma (0.3 R + 0.59 G + 0.11 B), this one where they tie, with `other`'s alpha.
/// Whole-color "Darker Color" blend: keeps whichever color has the lower mean RGB, with `other`'s alpha.
#[inline(always)]
pub fn blend_darker_color(&self, other: Color) -> Color {
let darker = if self.blend_luma() <= other.blend_luma() { *self } else { other };
let darker = if self.average_rgb_channels() <= other.average_rgb_channels() { *self } else { other };
darker.with_alpha(other.alpha)
}
/// The luma that Darker Color and Lighter Color compare, as the component blend modes measure it.
#[inline(always)]
fn blend_luma(&self) -> f32 {
luma_rec_601_rounded(self.red, self.green, self.blue)
}
/// Per-channel "Screen" blend.
#[inline(always)]
pub fn blend_screen(c_b: f32, c_s: f32) -> f32 {
@@ -659,16 +653,10 @@ impl Color {
c_s.max(c_b)
}
/// Per-channel "Color Dodge" blend, where a black backdrop stays black and any other turns white under a white source, as the W3C formula orders them.
/// Per-channel "Color Dodge" blend.
#[inline(always)]
pub fn blend_color_dodge(c_b: f32, c_s: f32) -> f32 {
if c_b.abs() <= BLEND_EDGE_TOLERANCE {
0.
} else if (c_s - 1.).abs() <= BLEND_EDGE_TOLERANCE {
1.
} else {
(c_b / (1. - c_s)).min(1.)
}
if (c_s - 1.).abs() <= BLEND_EDGE_TOLERANCE { 1. } else { (c_b / (1. - c_s)).min(1.) }
}
/// Per-channel "Linear Dodge" (Add) blend.
@@ -677,10 +665,10 @@ impl Color {
c_b + c_s
}
/// Whole-color "Lighter Color" blend: keeps whichever color has the higher luma (0.3 R + 0.59 G + 0.11 B), this one where they tie, with `other`'s alpha.
/// Whole-color "Lighter Color" blend: keeps whichever color has the higher mean RGB, with `other`'s alpha.
#[inline(always)]
pub fn blend_lighter_color(&self, other: Color) -> Color {
let lighter = if self.blend_luma() >= other.blend_luma() { *self } else { other };
let lighter = if self.average_rgb_channels() >= other.average_rgb_channels() { *self } else { other };
lighter.with_alpha(other.alpha)
}
@@ -736,15 +724,9 @@ impl Color {
}
}
/// Per-channel "Hard Mix" blend: white where the channels sum to at least 1 and black below, along a ramp a 256th wide at full strength, for PSD interop.
/// Per-channel "Hard Mix" blend: thresholds Linear Light at 0.5.
pub fn blend_hard_mix(c_b: f32, c_s: f32) -> f32 {
Color::blend_hard_mix_at_strength(c_b, c_s, 1.)
}
/// Per-channel "Hard Mix" blend of a paint at `strength` (from 0 to 1), unclamped, whose ramp steepens from none (the backdrop as it is) to a 256th wide at full strength, for PSD interop.
pub fn blend_hard_mix_at_strength(c_b: f32, c_s: f32, strength: f32) -> f32 {
let steepness = 255. * strength / 256.;
(c_b - steepness * (1. - c_s)) / (1. - steepness)
if Color::blend_linear_light(c_b, c_s) < 0.5 { 0. } else { 1. }
}
/// Per-channel "Difference" blend.
+3 -3
View File
@@ -33,9 +33,9 @@ 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_EFFECTS, ATTR_END, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_MODEL,
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,
ATTR_EFFECTS, 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,
};
pub use memo::MemoHash;
pub use num_traits;
+3 -9
View File
@@ -59,14 +59,8 @@ pub const ATTR_CLIP: &str = "clip";
// TODO: Consider adding "gradient_spread_left" and "gradient_spread_right" override attributes to allow setting different gradient spreads on each side of a gradient
/// Gradient's `GradientSpread` (`Pad`, `Reflect`, `Repeat`, or `Clear`).
pub const ATTR_GRADIENT_SPREAD: &str = "gradient_spread";
/// Gradient's `f64` curvature 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, it's 0.
pub const ATTR_GRADIENT_START_CURVATURE: &str = "gradient_start_curvature";
/// Gradient's `f64` curvature 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 `GradientModel` (`Standard` or `Apollonian`), how the contours between its curved ends are laid out: as SVG 2's cone
/// between the end circles, or as the family of circles the ends span. Absent, it's `Standard`.
pub const ATTR_GRADIENT_MODEL: &str = "gradient_model";
/// Gradient's `GradientForm` (`Linear` or `Radial`).
pub const ATTR_GRADIENT_FORM: &str = "gradient_form";
/// 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
@@ -1720,7 +1714,7 @@ impl<T: CacheHash> CacheHash for List<T> {
self.element.as_slice().cache_hash(state);
// Hash every attribute (key + values) rather than just the well-known ones, so changes to user-defined keys
// (e.g., gradient_spread) invalidate downstream graph caches as expected
// (e.g., gradient_form, gradient_spread) invalidate downstream graph caches as expected
self.attributes.cache_hash_entries(state);
}
}
@@ -74,14 +74,10 @@ pub struct EffectLayers {
impl EffectLayers {
/// The layers of content drawn with `blend_mode` and faded by `fill` through `effects`, or with every effect flattened if not `layered`, as for content clipped by a mask.
/// Content in a mode CSS lacks reads what lies beneath to blend by it (see [`BlendMode::reads_backdrop`]), but the alpha-only utility modes are planned as normal.
/// Content in a mode CSS lacks is drawn normally, so it's planned that way.
pub fn plan(effects: &Effects, blend_mode: BlendMode, fill: f32, layered: bool) -> Self {
let operations: Vec<EffectOperation> = effects.operations().collect();
let blend_mode = if blend_mode.to_svg_style_name().is_some() || blend_mode.reads_backdrop() {
blend_mode
} else {
BlendMode::Normal
};
let blend_mode = if blend_mode.to_svg_style_name().is_some() { blend_mode } else { BlendMode::Normal };
// Normal content at full fill hides what lies beneath its share, so its interior pieces blend with it alone, in any mode, within its own layer.
// A Blend If fading the content by its colors acts as a fill below full wherever it hides any.
@@ -230,20 +226,9 @@ impl EffectLayers {
planned
}
/// Whether a layered piece, a Blend If fading the layers, or a layer's blend mode reads what lies beneath the content.
/// Whether a layered piece, or a Blend If fading the layers, reads what lies beneath the content.
pub fn reads_backdrop(&self) -> bool {
self.fades_by_underlying || self.reads_around_backdrop() || self.layers.iter().any(|layer| layer.blend_mode.reads_backdrop())
}
/// Whether the content's layer reads what lies beneath it to blend at the content's `fill` (see [`BlendMode::layer_reads_backdrop`]).
/// Color Dodge and Color Burn blend natively instead over a piece beneath the content it doesn't knock out, which what lies beneath the item leaves out.
pub fn content_reads_backdrop(&self, fill: f32) -> bool {
let Some(content_layer) = self.content_layer() else { return false };
let blend_mode = self.layers[content_layer].blend_mode;
let shown_beneath = |part: &LayerPart| matches!(part, LayerPart::Piece(piece) if piece.place == PiecePlace::Beneath && !piece.knocks_out);
let pieces_show_beneath = self.layers[..content_layer].iter().flat_map(|layer| &layer.parts).any(shown_beneath);
blend_mode.reads_backdrop() || (blend_mode.layer_reads_backdrop(fill) && !pieces_show_beneath)
self.fades_by_underlying || self.reads_around_backdrop()
}
/// Whether a layered piece reads what lies around each pixel beneath the content, as a background blur does, where a Blend If reads only the pixel itself.
@@ -313,30 +298,20 @@ impl EffectLayers {
}
}
/// Whether any of the effects reads what lies beneath the content, like a background blur, or may, like a shadow in a mode CSS lacks.
/// Whether any of the effects reads what lies beneath the content, like a background blur.
pub fn effects_read_backdrop(effects: &Effects) -> bool {
effects.operations().any(|operation| match &operation {
EffectOperation::BackgroundBlur { .. } => !operation.changes_nothing(),
EffectOperation::BlendIf(ranges) => !ranges.underlying.show_everything(),
_ => {
!operation.changes_nothing()
&& pieces(0, &operation)
.iter()
.any(|(piece, blend_mode)| piece.place == PiecePlace::Beneath && blend_mode.reads_backdrop())
}
_ => false,
})
}
/// Whether an effect row can draw as layered pieces, rather than being carried out within the content's image.
/// Blurs, adjustments, masks, and feathers process the pixels of everything before them. A piece in a mode CSS lacks reads what lies beneath the item to blend, so only one beneath the content
/// can, though interior pieces that `blend_into_content` blend with the content alone, which the renderers do themselves.
/// Blurs, adjustments, masks, and feathers process the pixels of everything before them, and blend modes CSS lacks can't blend against the backdrop in SVG or a GPU layer,
/// though interior pieces that `blend_into_content` blend with the content alone, which the renderers do themselves.
fn can_be_layered(operation: &EffectOperation, blend_into_content: bool) -> bool {
let layers_in = |(piece, blend_mode): (EffectPiece, BlendMode)| match piece.place {
_ if blend_mode.to_svg_style_name().is_some() => true,
PiecePlace::Beneath => blend_mode.reads_backdrop(),
PiecePlace::Within => blend_into_content,
_ => false,
};
let layers_in = |(piece, blend_mode): (EffectPiece, BlendMode)| blend_mode.to_svg_style_name().is_some() || (blend_into_content && piece.place == PiecePlace::Within);
!is_pixel_filter(operation) && pieces(0, operation).into_iter().all(layers_in)
}
@@ -492,7 +467,7 @@ fn pieces(index: usize, operation: &EffectOperation) -> Vec<(EffectPiece, BlendM
| EffectOperation::MinimumMaximum { .. }
| EffectOperation::Sharpen { .. }
| EffectOperation::HighPass { .. }
| EffectOperation::Speckle { .. }
| EffectOperation::AddNoise { .. }
| EffectOperation::Dissolve { .. }
| EffectOperation::BlendIf(_)
| EffectOperation::Adjustment(_) => Vec::new(),
@@ -587,11 +562,9 @@ mod tests {
let layers = EffectLayers::plan(&effects, BlendMode::Overlay, 1., true);
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Overlay, BlendMode::Screen, BlendMode::Normal]);
// Content in a mode CSS lacks reads what lies beneath to blend by it, and an interior piece blending within the content's layer may take one too
// A mode CSS lacks is drawn normally, so it's planned that way, and an interior piece blending within the content's layer may take one too
let layers = EffectLayers::plan(&effects, BlendMode::LinearBurn, 1., true);
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::LinearBurn, BlendMode::Screen, BlendMode::Normal]);
assert!(layers.reads_backdrop() && !layers.reads_around_backdrop());
assert!(!EffectLayers::plan(&effects, BlendMode::Overlay, 1., true).reads_backdrop());
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Normal]);
let linear_burn = Effects::from_operations([drop_shadow(red, BlendMode::Multiply), inner_shadow(red, BlendMode::LinearBurn)]);
assert_eq!(EffectLayers::plan(&linear_burn, BlendMode::Normal, 1., true).flattened, 0);
assert_eq!(EffectLayers::plan(&linear_burn, BlendMode::Normal, 0.5, true).flattened, 2);
@@ -674,11 +647,14 @@ mod tests {
let layers = EffectLayers::plan(&Effects::from_operations([with_knockout(true), inner_shadow(red, BlendMode::Screen)]), BlendMode::Normal, 0.5, true);
assert_eq!(parts(&layers)[0], [Some((1, 0, PiecePlace::Through { over: false }))]);
// One flattened before an interior piece in a mode CSS lacks covers it too
let flattening = [with_knockout(false), inner_shadow(red, BlendMode::LinearBurn), inner_shadow(red, BlendMode::Screen)];
let layers = EffectLayers::plan(&Effects::from_operations(flattening), BlendMode::Normal, 0.5, true);
assert_eq!(layers.flattened, 2);
assert_eq!(parts(&layers)[1], [Some((2, 0, through_over))]);
// One flattened for a mode CSS lacks covers it too
let mut flattened_shadow = with_knockout(false);
if let EffectOperation::DropShadow { blend_mode, .. } = &mut flattened_shadow {
*blend_mode = BlendMode::LinearBurn;
}
let layers = EffectLayers::plan(&Effects::from_operations([flattened_shadow, inner_shadow(red, BlendMode::Screen)]), BlendMode::Normal, 0.5, true);
assert_eq!(layers.flattened, 1);
assert_eq!(parts(&layers)[1], [Some((1, 0, through_over))]);
}
#[test]
@@ -785,14 +761,9 @@ mod tests {
assert_eq!((layers.flattened, layers.trailing_masks.clone()), (2, 2..2));
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., false);
assert_eq!((layers.flattened, layers.trailing_masks.clone()), (5, 5..5));
let unmerged = Effects::from_operations([
drop_shadow(RED, BlendMode::Multiply),
inner_shadow(RED, BlendMode::LinearBurn),
drop_shadow(RED, BlendMode::Multiply),
mask(),
]);
let layers = EffectLayers::plan(&unmerged, BlendMode::Normal, 0.5, true);
assert_eq!((layers.flattened, layers.trailing_masks.clone()), (4, 4..4));
let unmerged = Effects::from_operations([drop_shadow(RED, BlendMode::LinearBurn), drop_shadow(RED, BlendMode::Multiply), mask()]);
let layers = EffectLayers::plan(&unmerged, BlendMode::Normal, 1., true);
assert_eq!((layers.flattened, layers.trailing_masks.clone()), (3, 3..3));
}
#[test]
@@ -809,23 +780,19 @@ mod tests {
assert_eq!(layers.flattened, 2);
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Normal]);
// An interior piece in a mode CSS lacks, which would read the content beneath it, flattens what's before it, where one beneath the content takes a layer of its own
let effects = Effects::from_operations([inner_shadow(RED, BlendMode::Screen), inner_shadow(RED, BlendMode::LinearBurn), inner_shadow(RED, BlendMode::Multiply)]);
let effects = Effects::from_operations([inner_shadow(RED, BlendMode::Screen), drop_shadow(RED, BlendMode::LinearBurn), inner_shadow(RED, BlendMode::Multiply)]);
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 0.5, true);
assert_eq!(layers.flattened, 2);
let layers = EffectLayers::plan(&Effects::from_operations([drop_shadow(RED, BlendMode::LinearBurn)]), BlendMode::Normal, 0.5, true);
assert_eq!((layers.flattened, modes(&layers)), (0, vec![BlendMode::LinearBurn, BlendMode::Normal]));
assert!(layers.reads_backdrop());
// A flattened shadow left unmerged by a blur would cover the layered shadow after it, so everything flattens
let effects = Effects::from_operations([drop_shadow(RED, BlendMode::Multiply), inner_shadow(RED, BlendMode::LinearBurn), drop_shadow(RED, BlendMode::Multiply)]);
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 0.5, true);
assert_eq!(layers.flattened, 3);
let effects = Effects::from_operations([drop_shadow(RED, BlendMode::LinearBurn), drop_shadow(RED, BlendMode::Multiply)]);
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., true);
assert_eq!(layers.flattened, 2);
assert_eq!(modes(&layers), [BlendMode::Normal]);
// Clipped content flattens everything
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 0.5, false);
assert_eq!(layers.flattened, 3);
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., false);
assert_eq!(layers.flattened, 2);
assert_eq!(parts(&layers), [[None]]);
}
@@ -65,7 +65,7 @@ pub enum EffectKind {
/// Keeps how much each pixel differs from a blur of those around it, around middle gray.
HighPass,
/// Scatters random offsets across the colors, fixed in place on the content.
Speckle,
AddNoise,
/// Shows a random scattering of the content fully opaque and hides the rest, more where it's more opaque.
Dissolve,
/// Smears the content along a line, as if it moved while being captured.
@@ -139,7 +139,7 @@ impl std::fmt::Display for EffectKind {
Self::MinimumMaximum => "Minimum/Maximum",
Self::Sharpen => "Sharpen",
Self::HighPass => "High Pass",
Self::Speckle => "Speckle",
Self::AddNoise => "Add Noise",
Self::Dissolve => "Dissolve",
Self::MotionBlur => "Motion Blur",
Self::RadialBlur => "Radial Blur",
@@ -1099,7 +1099,7 @@ pub enum EffectOperation {
HighPass {
radius: f64,
},
Speckle {
AddNoise {
/// Percent of full brightness.
amount: f64,
distribution: NoiseDistribution,
@@ -1289,7 +1289,7 @@ impl EffectOperation {
Self::MinimumMaximum { .. } => EffectKind::MinimumMaximum,
Self::Sharpen { .. } => EffectKind::Sharpen,
Self::HighPass { .. } => EffectKind::HighPass,
Self::Speckle { .. } => EffectKind::Speckle,
Self::AddNoise { .. } => EffectKind::AddNoise,
Self::Dissolve { .. } => EffectKind::Dissolve,
Self::MotionBlur { .. } => EffectKind::MotionBlur,
Self::RadialBlur { .. } => EffectKind::RadialBlur,
@@ -1383,7 +1383,7 @@ impl EffectOperation {
Self::Feather { distance } => *distance <= 0.,
Self::ConvolutionKernel { .. } => self.convolution().is_none(),
Self::Emboss { .. } | Self::FindEdges | Self::HighPass { .. } | Self::Dissolve { .. } | Self::Adjustment(_) => false,
Self::Speckle { amount, .. } => *amount <= 0.,
Self::AddNoise { amount, .. } => *amount <= 0.,
// The four neighbors lie a fixed distance away, so only the blur needs a radius
Self::Sharpen { amount, radius, edges_only, .. } => *amount <= 0. || (!*edges_only && *radius <= 0.),
Self::MinimumMaximum { radius, .. } => *radius <= 0.,
@@ -1423,7 +1423,7 @@ impl EffectOperation {
| Self::Outline { .. }
| Self::BevelAndEmboss { .. }
| Self::Feather { .. } => false,
Self::PaintOverlay { .. } | Self::Mask { .. } | Self::BackgroundBlur { .. } | Self::Speckle { .. } | Self::Dissolve { .. } | Self::BlendIf(_) | Self::Adjustment(_) => false,
Self::PaintOverlay { .. } | Self::Mask { .. } | Self::BackgroundBlur { .. } | Self::AddNoise { .. } | Self::Dissolve { .. } | Self::BlendIf(_) | Self::Adjustment(_) => false,
}
}
@@ -1491,7 +1491,7 @@ impl EffectOperation {
Self::Ripple { .. } | Self::Wave { .. } | Self::Displace { .. } => self.displacement_reach() + 1.,
// Within the frame they paint the content's own cells or dots, reading a cell's or a dot's area around each point there, which `Effects::source_region` finds
Self::Pixelate { .. } | Self::ColorHalftone { .. } => 0.,
Self::PaintOverlay { .. } | Self::Speckle { .. } | Self::Dissolve { .. } | Self::BlendIf(_) | Self::Adjustment(_) => 0.,
Self::PaintOverlay { .. } | Self::AddNoise { .. } | Self::Dissolve { .. } | Self::BlendIf(_) | Self::Adjustment(_) => 0.,
}
}
@@ -1578,7 +1578,7 @@ impl EffectOperation {
Self::Emboss { angle, height, amount } => [angle, height, amount].into_iter().for_each(finite),
Self::MinimumMaximum { radius, .. } | Self::HighPass { radius } => finite(radius),
Self::Sharpen { amount, radius, threshold, .. } => [amount, radius, threshold].into_iter().for_each(finite),
Self::Speckle { amount, .. } => finite(amount),
Self::AddNoise { amount, .. } => finite(amount),
Self::Dissolve { opacity, .. } => finite(opacity),
Self::MotionBlur { angle, distance, .. } => [angle, distance].into_iter().for_each(finite),
Self::RadialBlur { amount, transform, .. } => {
@@ -1754,7 +1754,7 @@ impl EffectOperation {
edges_only: false,
},
EffectKind::HighPass => Self::HighPass { radius: 0. },
EffectKind::Speckle => Self::Speckle {
EffectKind::AddNoise => Self::AddNoise {
amount: 0.,
distribution: NoiseDistribution::default(),
monochromatic: false,
@@ -2100,7 +2100,7 @@ impl EffectOperation {
visitor.parameter("edges_only", edges_only, false);
}
Self::HighPass { radius } => visitor.parameter("radius", radius, 10.),
Self::Speckle {
Self::AddNoise {
amount,
distribution,
monochromatic,
@@ -2404,7 +2404,7 @@ mod tests {
threshold: 0.,
edges_only: true,
},
EffectOperation::Speckle {
EffectOperation::AddNoise {
amount: 40.,
distribution: NoiseDistribution::Gaussian,
monochromatic: true,
@@ -166,7 +166,7 @@ pub fn is_filter(operation: &EffectOperation) -> bool {
| EffectOperation::MinimumMaximum { .. }
| EffectOperation::Sharpen { .. }
| EffectOperation::HighPass { .. }
| EffectOperation::Speckle { .. }
| EffectOperation::AddNoise { .. }
| EffectOperation::Dissolve { .. }
)
}
@@ -178,7 +178,7 @@ pub fn reads_neighbors(operation: &EffectOperation) -> bool {
/// Whether the operation is a pixel filter combining each pixel with a random field fixed to the content, which changes endless content as much as any other.
pub fn is_random_field_filter(operation: &EffectOperation) -> bool {
matches!(operation, EffectOperation::Speckle { .. } | EffectOperation::Dissolve { .. })
matches!(operation, EffectOperation::AddNoise { .. } | EffectOperation::Dissolve { .. })
}
/// Whether any of the effects is a pixel filter reading the pixels around each one that changes something, which reads endless content over the area in view.
@@ -277,7 +277,7 @@ pub fn fill_shifts(reach: i32) -> Vec<[i32; 2]> {
shifts
}
/// How the random offsets Speckle gives the colors are spread.
/// How the random offsets Add Noise gives the colors are spread.
#[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)]
@@ -296,7 +296,7 @@ pub const GAUSSIAN_NOISE_LIMIT: f32 = 3.5;
/// The random fields a seed gives, each hashed apart so the fields of one seed are unrelated.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RandomField {
/// Speckle's offset for each color, or for Gaussian noise its first uniform value.
/// Add Noise's offset for each color, or for Gaussian noise its first uniform value.
NoiseOffsets,
/// Gaussian noise's second uniform value for each color, its angle.
NoiseAngles,
@@ -320,7 +320,7 @@ impl RandomField {
}
}
/// The largest offset Speckle of `amount` (a fraction) gives a color, as a fraction of full brightness, past which every color would be pushed to black or white anyway.
/// The largest offset Add Noise of `amount` (a fraction) gives a color, as a fraction of full brightness, past which every color would be pushed to black or white anyway.
pub fn noise_extent(amount: f64, distribution: NoiseDistribution) -> f64 {
let deviations = match distribution {
NoiseDistribution::Uniform => 1.,
@@ -9,17 +9,13 @@ use core_types::math::quad::Quad;
use core_types::none;
use core_types::ops::FromAnchorPosition;
use core_types::transform::Transform;
use core_types::{
ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_MODEL, ATTR_GRADIENT_SPREAD, ATTR_GRADIENT_START_CURVATURE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM,
Color,
};
use core_types::{ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_GRADIENT_SPREAD, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color};
use dyn_any::DynAny;
use glam::{DAffine2, DVec2};
use raster_types::{CPU, GPU, Raster};
pub use vector_types::Vector;
use vector_types::gradient_standard::GradientShape;
use vector_types::vector::{Path, no_paths, paths_from_item_attributes, paths_from_list_row_attributes};
use vector_types::{Gradient, GradientModel, GradientSpread};
use vector_types::{Gradient, GradientSpread};
/// The possible forms of graphical content that can be rendered by the Render node (to targets like SVG and raster) or another render boundary node.
#[derive(Clone, Debug, CacheHash, PartialEq, DynAny)]
@@ -671,11 +667,10 @@ impl Graphic {
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, and curved contours may leave gaps, leaving the rest of the region unpainted
// A `Clear` spread cuts off to transparency past the ends, leaving the rest of the region unpainted
Graphic::Gradient(item) => {
item_opacity_is_full(item)
&& item.attribute_cloned_or_default::<GradientSpread>(ATTR_GRADIENT_SPREAD) != GradientSpread::Clear
&& gradient_paints_everywhere(&|key| item.attributes().get_any(key))
&& item.element().iter().all(|stop| stop.color.is_opaque())
}
Graphic::GradientList(list) => {
@@ -683,7 +678,6 @@ impl Graphic {
&& every_item_has_full_opacity(list)
&& (0..list.len()).all(|index| {
list.attribute_cloned_or_default::<GradientSpread>(ATTR_GRADIENT_SPREAD, index) != GradientSpread::Clear
&& gradient_paints_everywhere(&|key| list.attribute_any(key, index))
&& list.element(index).is_some_and(|stops| stops.iter().all(|stop| stop.color.is_opaque()))
})
}
@@ -849,21 +843,6 @@ fn every_item_has_full_opacity<T>(list: &List<T>) -> bool {
(0..list.len()).all(|index| list.attribute_cloned_or::<f64>(ATTR_OPACITY, index, 1.) >= 1. - f64::EPSILON && list.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, index, 1.) >= 1. - f64::EPSILON)
}
/// Whether a gradient with the attributes the `attribute` lookup gives paints every point, which curved contours leaving gaps unfilled don't.
fn gradient_paints_everywhere<'a>(attribute: &dyn Fn(&str) -> Option<&'a dyn std::any::Any>) -> bool {
fn read<'a, T: 'static>(attribute: &dyn Fn(&str) -> Option<&'a dyn std::any::Any>, key: &str) -> Option<&'a T> {
attribute(key).and_then(|value| value.downcast_ref::<T>())
}
GradientShape::new(
read::<f64>(attribute, ATTR_GRADIENT_START_CURVATURE).copied().unwrap_or_default(),
read::<f64>(attribute, ATTR_GRADIENT_END_CURVATURE).copied().unwrap_or_default(),
read::<GradientModel>(attribute, ATTR_GRADIENT_MODEL).copied().unwrap_or_default(),
read::<DAffine2>(attribute, ATTR_TRANSFORM).copied().unwrap_or_default(),
)
.paints_everywhere()
}
/// Bounding box of one vector, inflated by its appearance's stroke when `include_stroke` is true.
/// Paths and stroke parameters live on the holder's attributes, out of reach of the element-level impl.
fn vector_bounding_box(vector: &Vector, paths: Option<&List<Path>>, composed_transform: DAffine2, appearance: Option<&Appearance>, include_stroke: bool) -> Option<[DVec2; 2]> {
@@ -1743,7 +1743,7 @@ impl EffectOperation {
| Self::MinimumMaximum { .. }
| Self::Sharpen { .. }
| Self::HighPass { .. }
| Self::Speckle { .. }
| Self::AddNoise { .. }
| Self::Dissolve { .. }
| Self::BackgroundBlur { .. }
| Self::BlendIf(_)
@@ -27,12 +27,12 @@ pub fn filter(plane: Plane<[f32; 4]>, full: Option<&Plane<[f32; 4]>>, operation:
match *operation {
EffectOperation::FindEdges => find_edges(&plane, document_to_pixels),
EffectOperation::MinimumMaximum { radius, mode } => neighborhood_extreme(&plane, radius, mode == MinimumMaximumMode::Maximum, document_to_pixels),
EffectOperation::Speckle {
EffectOperation::AddNoise {
amount,
distribution,
monochromatic,
seed,
} => speckle(&plane, amount / 100., distribution, monochromatic, seed, pixels_to_effect),
} => add_noise(&plane, amount / 100., distribution, monochromatic, seed, pixels_to_effect),
EffectOperation::Dissolve { opacity, seed } => dissolve(&plane, opacity / 100., seed, pixels_to_effect),
_ => plane,
}
@@ -511,7 +511,7 @@ fn noise_at(sampling: &FieldSampling, pixel: [usize; 2], distribution: NoiseDist
/// For PSD interop, each straight color offset by noise of `amount` (a fraction of full brightness) with its `distribution`, the same for every color of a pixel if it's `monochromatic`, and clamped.
/// The coverage is kept. The noise is fixed to the cells of the effect space, which `pixels_to_effect` places the plane's pixels among. O(width × height × samples per pixel).
pub fn speckle(plane: &Plane<[f32; 4]>, amount: f64, distribution: NoiseDistribution, monochromatic: bool, seed: i64, pixels_to_effect: DAffine2) -> Plane<[f32; 4]> {
pub fn add_noise(plane: &Plane<[f32; 4]>, amount: f64, distribution: NoiseDistribution, monochromatic: bool, seed: i64, pixels_to_effect: DAffine2) -> Plane<[f32; 4]> {
let sampling = FieldSampling::new(pixels_to_effect);
let extent = noise_extent(amount, distribution) as f32;
let scale = (amount * sampling.deviation_scale) as f32;
@@ -849,7 +849,7 @@ mod tests {
let amount = 0.2;
// Uniform noise spreads evenly up to the amount, with a deviation of the amount over √3
let uniform = speckle(&gray, amount, NoiseDistribution::Uniform, false, 0, DAffine2::IDENTITY);
let uniform = add_noise(&gray, amount, NoiseDistribution::Uniform, false, 0, DAffine2::IDENTITY);
let (mean, deviation, correlation) = offset_statistics(&uniform);
for channel in 0..3 {
assert!(
@@ -861,21 +861,21 @@ mod tests {
assert!(uniform.data.iter().all(|pixel| (pixel[0] - 0.5).abs() <= amount as f32 && pixel[3] == 1.));
// Gaussian noise deviates by the amount, cut off at its limit
let gaussian = speckle(&gray, amount, NoiseDistribution::Gaussian, false, 0, DAffine2::IDENTITY);
let gaussian = add_noise(&gray, amount, NoiseDistribution::Gaussian, false, 0, DAffine2::IDENTITY);
let (_, deviation, _) = offset_statistics(&gaussian);
assert!((deviation[0] / amount - 1.).abs() < 0.03, "{deviation:?}");
// Monochromatic noise shifts every color of a pixel together, and another seed gives other noise
let monochromatic = speckle(&gray, amount, NoiseDistribution::Gaussian, true, 0, DAffine2::IDENTITY);
let monochromatic = add_noise(&gray, amount, NoiseDistribution::Gaussian, true, 0, DAffine2::IDENTITY);
assert!(monochromatic.data.iter().all(|pixel| pixel[0] == pixel[1] && pixel[1] == pixel[2]));
let reseeded = speckle(&gray, amount, NoiseDistribution::Uniform, false, 1, DAffine2::IDENTITY);
let reseeded = add_noise(&gray, amount, NoiseDistribution::Uniform, false, 1, DAffine2::IDENTITY);
assert_ne!(reseeded.data[..64], uniform.data[..64]);
}
#[test]
fn noise_is_fixed_to_the_effect_spaces_cells_and_averages_where_pixels_span_several() {
let gray = |size: usize| plane(size, size, vec![[0.5, 0.5, 0.5, 1.]; size * size]);
let noise = |plane: &Plane<[f32; 4]>, pixels_to_effect| speckle(plane, 0.3, NoiseDistribution::Uniform, false, 4, pixels_to_effect);
let noise = |plane: &Plane<[f32; 4]>, pixels_to_effect| add_noise(plane, 0.3, NoiseDistribution::Uniform, false, 4, pixels_to_effect);
// A plane placed three cells right and five down holds the same noise at the same cells
let placed = noise(&gray(16), DAffine2::IDENTITY);
@@ -1,10 +1,8 @@
//! Blends a layer onto those beneath it by a blend mode, with the W3C Compositing and Blending formulas on gamma-encoded colors, as SVG and the GPU's layers blend.
//! The modes CSS lacks, which layers read what lies beneath to blend by, take the formulas the effects share (see [`crate::blending::blend_gamma`]).
//! The modes CSS lacks blend normally, since layers only ever take the others.
use crate::effect_kernels::Plane;
use core_types::Color;
use core_types::blending::{BlendMode, apply_blend_mode_at_strength, layer_fill_shown};
use core_types::color::BLEND_EDGE_TOLERANCE;
use core_types::blending::BlendMode;
/// The premultiplied gamma-encoded `layer` blended by the mode onto the layers `below` it. O(width × height).
pub fn blend_layer(layer: &Plane<[f32; 4]>, below: &Plane<[f32; 4]>, blend_mode: BlendMode) -> Plane<[f32; 4]> {
@@ -13,20 +11,6 @@ pub fn blend_layer(layer: &Plane<[f32; 4]>, below: &Plane<[f32; 4]>, blend_mode:
/// One premultiplied pixel blended onto another: its color mixes toward the blend of both as far as the backdrop covers it, and it then composites over the backdrop.
pub fn blend_pixel(source: [f32; 4], backdrop: [f32; 4], blend_mode: BlendMode) -> [f32; 4] {
blend_pixel_at_strength(source, backdrop, blend_mode, 1.)
}
/// One premultiplied pixel of a layer's full-strength content blended onto another by the mode, faded by the layer's `fill`, or over the backdrop
/// in a mode whose fill moves the content toward its neutral color (see [`BlendMode::fill_moves_layer_toward_neutral`]), moved there by it.
pub fn blend_layer_pixel(content: [f32; 4], backdrop: [f32; 4], blend_mode: BlendMode, fill: f32) -> [f32; 4] {
match blend_mode.fill_moves_layer_toward_neutral() {
true => blend_pixel_at_strength(content, backdrop, blend_mode, fill),
false => blend_pixel(content.map(|channel| channel * fill), backdrop, blend_mode),
}
}
/// [`blend_pixel`] with the source at `strength`, which moves it toward the mode's neutral color where it blends, and shows it as strongly as [`layer_fill_shown`] gives.
fn blend_pixel_at_strength(source: [f32; 4], backdrop: [f32; 4], blend_mode: BlendMode, strength: f32) -> [f32; 4] {
let (source_alpha, backdrop_alpha) = (source[3], backdrop[3]);
if source_alpha <= 0. {
return backdrop;
@@ -37,18 +21,14 @@ fn blend_pixel_at_strength(source: [f32; 4], backdrop: [f32; 4], blend_mode: Ble
false => [0.; 3],
};
let (source_color, backdrop_color) = (straight(source), straight(backdrop));
let blended = match strength < 1. {
true => blend_at_strength(backdrop_color, source_color, blend_mode, strength),
false => blend(backdrop_color, source_color, blend_mode),
};
let blended = blend(backdrop_color, source_color, blend_mode);
let shown = source_alpha * layer_fill_shown(backdrop_alpha, strength);
let mut result = [0.; 4];
for channel in 0..3 {
let mixed = (1. - backdrop_alpha) * source_color[channel] + backdrop_alpha * blended[channel];
result[channel] = shown * mixed + (1. - shown) * backdrop[channel];
result[channel] = source_alpha * mixed + (1. - source_alpha) * backdrop[channel];
}
result[3] = shown + backdrop_alpha * (1. - shown);
result[3] = source_alpha + backdrop_alpha * (1. - source_alpha);
result
}
@@ -59,22 +39,10 @@ fn blend(backdrop: [f32; 3], source: [f32; 3], blend_mode: BlendMode) -> [f32; 3
BlendMode::Saturation => set_luminosity(set_saturation(backdrop, saturation(source)), luminosity(backdrop)),
BlendMode::Color => set_luminosity(source, luminosity(backdrop)),
BlendMode::Luminosity => set_luminosity(backdrop, luminosity(source)),
blend_mode if blend_mode.reads_backdrop() => crate::blending::blend_gamma(backdrop, source, blend_mode),
_ => [0, 1, 2].map(|channel| blend_channel(backdrop[channel], source[channel], blend_mode)),
}
}
/// The blend of straight `backdrop` and `source` colors with the source at `strength`, moved toward the mode's neutral color (see [`apply_blend_mode_at_strength`]).
fn blend_at_strength(backdrop: [f32; 3], source: [f32; 3], blend_mode: BlendMode, strength: f32) -> [f32; 3] {
if !blend_mode.strength_moves_toward_neutral() {
return blend(backdrop, source, blend_mode);
}
let color = |[red, green, blue]: [f32; 3]| Color::from_rgbaf32_unchecked(red, green, blue, 1.);
let blended = apply_blend_mode_at_strength(color(source), color(backdrop), blend_mode, strength);
[blended.r(), blended.g(), blended.b()]
}
/// The mode's blend of one channel of the backdrop and source, for the modes that blend each channel on its own.
fn blend_channel(backdrop: f32, source: f32, blend_mode: BlendMode) -> f32 {
let hard_light = |backdrop: f32, source: f32| match source <= 0.5 {
@@ -88,8 +56,8 @@ fn blend_channel(backdrop: f32, source: f32, blend_mode: BlendMode) -> f32 {
BlendMode::Overlay => hard_light(source, backdrop),
BlendMode::Darken => backdrop.min(source),
BlendMode::Lighten => backdrop.max(source),
BlendMode::ColorDodge if backdrop <= BLEND_EDGE_TOLERANCE => 0.,
BlendMode::ColorDodge if source >= 1. - BLEND_EDGE_TOLERANCE => 1.,
BlendMode::ColorDodge if backdrop <= 0. => 0.,
BlendMode::ColorDodge if source >= 1. => 1.,
BlendMode::ColorDodge => (backdrop / (1. - source)).min(1.),
BlendMode::ColorBurn if backdrop >= 1. => 1.,
BlendMode::ColorBurn if source <= 0. => 0.,
@@ -174,195 +142,6 @@ mod tests {
assert!((screened[0] - (0.5 * 0.75 + 0.5 * 0.5)).abs() < 1e-6);
}
/// The reference formulas, for PSD interop, for the modes CSS lacks and for Color Burn and Color Dodge, at full strength, on a channel of straight gamma-encoded `backdrop` and `source` colors.
fn reference_formula(blend_mode: BlendMode, backdrop: [f32; 3], source: [f32; 3]) -> [f32; 3] {
let luma = |color: [f32; 3]| 0.3 * color[0] + 0.59 * color[1] + 0.11 * color[2];
let color_burn = |b: f32, s: f32| {
if b >= 1. {
1.
} else if s <= 0. {
0.
} else {
1. - ((1. - b) / s).min(1.)
}
};
let color_dodge = |b: f32, s: f32| {
if b <= 0. {
0.
} else if s >= 1. {
1.
} else {
(b / (1. - s)).min(1.)
}
};
let channels = |formula: &dyn Fn(f32, f32) -> f32| [0, 1, 2].map(|channel| formula(backdrop[channel], source[channel]).clamp(0., 1.));
match blend_mode {
BlendMode::ColorBurn => channels(&color_burn),
BlendMode::ColorDodge => channels(&color_dodge),
BlendMode::LinearBurn => channels(&|b, s| b + s - 1.),
BlendMode::LinearDodge => channels(&|b, s| b + s),
BlendMode::VividLight => channels(&|b, s| if s <= 0.5 { color_burn(b, 2. * s) } else { color_dodge(b, 2. * s - 1.) }),
BlendMode::LinearLight => channels(&|b, s| b + 2. * s - 1.),
BlendMode::PinLight => channels(&|b, s| if s <= 0.5 { b.min(2. * s) } else { b.max(2. * s - 1.) }),
BlendMode::HardMix => channels(&|b, s| 256. * b - 255. * (1. - s)),
BlendMode::Subtract => channels(&|b, s| b - s),
BlendMode::Divide => channels(&|b, s| {
if b <= 0. {
0.
} else if s <= 0. {
1.
} else {
b / s
}
}),
BlendMode::DarkerColor => {
if luma(source) < luma(backdrop) {
source
} else {
backdrop
}
}
BlendMode::LighterColor => {
if luma(source) > luma(backdrop) {
source
} else {
backdrop
}
}
_ => panic!("{blend_mode} blends natively"),
}
}
/// Pairs of a backdrop and a source color, away from Hard Mix's ramp and the lumas' ties.
const PAIRS: [([f32; 3], [f32; 3]); 4] = [
([0.2, 0.6, 0.45], [0.85, 0.3, 0.6]),
([0.9, 0.1, 0.5], [0.3, 0.7, 0.2]),
([0.55, 0.55, 0.55], [0.05, 0.95, 0.35]),
([0., 1., 0.3], [0.6, 0.15, 0.8]),
];
#[test]
fn modes_css_lacks_take_the_reference_formulas_over_any_backdrop() {
for blend_mode in BlendMode::list().into_iter().flatten().copied().filter(BlendMode::reads_backdrop) {
for (backdrop, source) in PAIRS {
let expected = reference_formula(blend_mode, backdrop, source);
let opaque = |[red, green, blue]: [f32; 3]| [red, green, blue, 1.];
// Over an opaque backdrop, the source takes the formula
let blended = blend_pixel(opaque(source), opaque(backdrop), blend_mode);
assert!(
(0..3).all(|channel| (blended[channel] - expected[channel]).abs() < 1e-5),
"{blend_mode}: {blended:?} rather than {expected:?}"
);
// Over one of half alpha, its color mixes halfway from its own to the formula's, as the 16 native modes do
let half = [backdrop[0] * 0.5, backdrop[1] * 0.5, backdrop[2] * 0.5, 0.5];
let blended = blend_pixel(opaque(source), half, blend_mode);
for channel in 0..3 {
let mixed = 0.5 * source[channel] + 0.5 * expected[channel];
assert!((blended[channel] - mixed).abs() < 1e-5, "{blend_mode} over half alpha: {blended:?}");
}
}
}
}
#[test]
fn fills_move_the_content_toward_neutral_in_seven_modes_and_fade_it_in_the_others() {
let fill = 0.5;
let reading = BlendMode::list().into_iter().flatten().copied().filter(BlendMode::reads_backdrop);
for blend_mode in reading.chain([BlendMode::ColorDodge, BlendMode::ColorBurn]) {
for (backdrop, source) in PAIRS {
let blended = blend_layer_pixel([source[0], source[1], source[2], 1.], [backdrop[0], backdrop[1], backdrop[2], 1.], blend_mode, fill);
let expected = match blend_mode {
// The paint at full strength once moved halfway toward black, white, or middle gray
BlendMode::ColorDodge | BlendMode::LinearDodge => reference_formula(blend_mode, backdrop, source.map(|channel| fill * channel)),
BlendMode::ColorBurn | BlendMode::LinearBurn => reference_formula(blend_mode, backdrop, source.map(|channel| 1. - fill * (1. - channel))),
BlendMode::VividLight | BlendMode::LinearLight => reference_formula(blend_mode, backdrop, source.map(|channel| 0.5 + fill * (channel - 0.5))),
// A ramp a fill of half makes `clamp(2b - 1 + s)`
BlendMode::HardMix => [0, 1, 2].map(|channel| Color::blend_hard_mix_at_strength(backdrop[channel], source[channel], fill).clamp(0., 1.)),
// Halfway from the backdrop to the blend
_ => {
let full = reference_formula(blend_mode, backdrop, source);
[0, 1, 2].map(|channel| backdrop[channel] + (full[channel] - backdrop[channel]) * fill)
}
};
assert!(
(0..3).all(|channel| (blended[channel] - expected[channel]).abs() < 1e-5),
"{blend_mode}: {blended:?} rather than {expected:?}"
);
assert!((blended[3] - 1.).abs() < 1e-6, "{blend_mode} covers the opaque backdrop");
}
}
// Where nothing lies beneath, the fill fades the content as it is, as a fill fades content in the other modes
let faded = blend_layer_pixel([0.8, 0.4, 0.2, 1.], [0.; 4], BlendMode::LinearDodge, fill);
assert!(faded.iter().zip([0.4, 0.2, 0.1, 0.5]).all(|(channel, expected)| (channel - expected).abs() < 1e-6), "{faded:?}");
}
#[test]
fn fills_moving_layers_toward_neutral_blend_their_share_at_full_strength_over_opaque_backdrops_and_change_nothing_at_no_fill() {
let close = |ours: [f32; 4], expected: [f32; 4]| ours.iter().zip(expected).all(|(ours, expected)| (ours - expected).abs() < 1e-5);
let premultiplied = |[red, green, blue]: [f32; 3], alpha: f32| [red * alpha, green * alpha, blue * alpha, alpha];
let pushed = |blend_mode: BlendMode, source: [f32; 3], fill: f32| {
source.map(|channel| match blend_mode {
BlendMode::ColorDodge | BlendMode::LinearDodge => fill * channel,
BlendMode::ColorBurn | BlendMode::LinearBurn => 1. - fill * (1. - channel),
_ => 0.5 + fill * (channel - 0.5),
})
};
let modes = [
BlendMode::ColorDodge,
BlendMode::ColorBurn,
BlendMode::LinearDodge,
BlendMode::LinearBurn,
BlendMode::VividLight,
BlendMode::LinearLight,
];
for blend_mode in modes {
for (backdrop, source) in PAIRS {
for alpha in [1., 0.5] {
for fill in [0., 0.3, 1.] {
// Over an opaque backdrop, the content's share blends the paint moved toward neutral at full strength, the rest showing the backdrop, for PSD interop
let full = reference_formula(blend_mode, backdrop, pushed(blend_mode, source, fill));
let expected = [0, 1, 2].map(|channel| alpha * full[channel] + (1. - alpha) * backdrop[channel]);
let blended = blend_layer_pixel(premultiplied(source, alpha), premultiplied(backdrop, 1.), blend_mode, fill);
assert!(close(blended, premultiplied(expected, 1.)), "{blend_mode} at fill {fill}, alpha {alpha}: {blended:?}");
// Over nothing, the fill fades the content as it is
let blended = blend_layer_pixel(premultiplied(source, alpha), [0.; 4], blend_mode, fill);
assert!(close(blended, premultiplied(source, alpha * fill)), "{blend_mode} at fill {fill} over nothing: {blended:?}");
}
for backdrop_alpha in [0.25, 0.5, 0.75] {
let beneath = premultiplied(backdrop, backdrop_alpha);
// No fill leaves a partly covering backdrop as it is, alpha included
let unfilled = blend_layer_pixel(premultiplied(source, alpha), beneath, blend_mode, 0.);
assert!(close(unfilled, beneath), "{blend_mode} at no fill over alpha {backdrop_alpha}: {unfilled:?}");
// A full fill blends by the W3C's general formula, mixing toward the blend as far as the backdrop covers
let blend = reference_formula(blend_mode, backdrop, source);
let mixed = [0, 1, 2].map(|channel| (1. - backdrop_alpha) * source[channel] + backdrop_alpha * blend[channel]);
let expected = [0, 1, 2]
.map(|channel| alpha * mixed[channel] + (1. - alpha) * beneath[channel])
.into_iter()
.chain([alpha + (1. - alpha) * backdrop_alpha])
.collect::<Vec<f32>>();
let filled = blend_layer_pixel(premultiplied(source, alpha), beneath, blend_mode, 1.);
assert!(close(filled, expected.try_into().unwrap()), "{blend_mode} at full fill over alpha {backdrop_alpha}: {filled:?}");
}
}
}
}
// An opaque layer at no fill over half alpha leaves that alpha
let unfilled = blend_layer_pixel([0.8, 0.4, 0.2, 1.], [0.25, 0.25, 0.25, 0.5], BlendMode::LinearDodge, 0.);
assert!((unfilled[3] - 0.5).abs() < 1e-6, "{unfilled:?}");
}
#[test]
fn the_luminosity_of_black_over_any_gray_is_black() {
for level in 0..=255 {
@@ -13,7 +13,7 @@ use crate::warp_kernels::WarpRasterizer;
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_MODEL, ATTR_GRADIENT_START_CURVATURE, Item, List};
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_FORM, Item, List};
use core_types::transfer_curve::TransferCurve;
use core_types::{ATTR_BLEND_MODE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color};
use glam::{DAffine2, DMat2, DVec2};
@@ -33,8 +33,7 @@ use raster_types::parallel_rows::fill_rows;
use raster_types::{CPU, Image, Raster};
use std::collections::HashMap;
use std::ops::Range;
use vector_types::gradient::{Gradient, GradientSettings, GradientSpread};
use vector_types::gradient_standard::GradientShape;
use vector_types::gradient::{Gradient, GradientForm, GradientSettings, GradientSpread};
mod styles;
@@ -729,7 +728,7 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
| EffectOperation::MinimumMaximum { .. }
| EffectOperation::Sharpen { .. }
| EffectOperation::HighPass { .. }
| EffectOperation::Speckle { .. }
| EffectOperation::AddNoise { .. }
| EffectOperation::Dissolve { .. } => {
merge_beneath(&mut full, &mut filled, &mut beneath);
// A filter sharpening the coverage fades the fill's result by the share of the full-strength coverage each pixel's fill left, as if the fill faded the result
@@ -1230,7 +1229,7 @@ fn drawn_paint_colors(operation: &EffectOperation, transform: DAffine2, size: DV
Some(colors)
}
/// Samples the paint's color at points in the space its placement maps into, faded by its opacity, for the paints the CPU can draw: colors, images, generators, gradients, and those nested in a placement of their own.
/// Samples the paint's color at points in the space its placement maps into, faded by its opacity, for the paints the CPU can draw: colors, images, generators, linear or radial gradients, and those nested in a placement of their own.
/// The paint's own adjustments are carried out first, and an image's own effects too.
fn paint_sampler(paint: &Graphic) -> Option<Box<dyn Fn(DVec2) -> Color + Sync + '_>> {
let inverse = |placement: DAffine2| (placement.matrix2.determinant() != 0.).then(|| placement.inverse());
@@ -1261,11 +1260,7 @@ fn paint_sampler(paint: &Graphic) -> Option<Box<dyn Fn(DVec2) -> Color + Sync +
let item = evaluate_gradient_effects(item.clone());
let position = gradient_position(&item)?;
let evaluator = item.element().evaluator(GradientSettings::from_item_attributes(&item));
let spread = evaluator.settings().spread;
Some(Box::new(move |point| {
let color = position(point).map_or(Color::TRANSPARENT, |position| evaluator.evaluate(spread_position(position, spread)));
faded(color, opacity)
}))
Some(Box::new(move |point| faded(evaluator.evaluate(position(point)), opacity)))
}
Graphic::Graphic(item) => nested_sampler(item.element(), &|key| item.attributes().get_any(key)),
Graphic::GraphicList(list) => {
@@ -1413,9 +1408,7 @@ fn displacement_map_sampler(map: &Graphic) -> Option<Box<dyn Fn(DVec2) -> [f32;
let samples = gradient.interpolated_samples(settings);
Some(Box::new(move |point| {
let color = position(point).map_or(Color::TRANSPARENT, |position| {
drawn_gradient_color(&samples, settings.spread, spread_position(position, settings.spread))
});
let color = drawn_gradient_color(&samples, settings.spread, position(point));
premultiplied_gamma_channels(color).map(|channel| channel * opacity)
}))
}
@@ -1502,49 +1495,22 @@ fn drawn_gradient_color(samples: &[(f64, Color, Option<f64>)], spread: GradientS
}
}
/// How far along the gradient each point lies, or `None` where it's unpainted, or no function where its placement collapses a form.
/// A solid end stop's color is that end's infinite position, which [`spread_position`] keeps on that end under every spread.
fn gradient_position(item: &Item<Gradient>) -> Option<Box<dyn Fn(DVec2) -> Option<f64> + Sync>> {
/// How far along the gradient each point lies, or `None` where its placement collapses it.
fn gradient_position(item: &Item<Gradient>) -> Option<Box<dyn Fn(DVec2) -> f64 + Sync>> {
let placement: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
let shape = GradientShape::new(
item.attribute_cloned_or_default(ATTR_GRADIENT_START_CURVATURE),
item.attribute_cloned_or_default(ATTR_GRADIENT_END_CURVATURE),
item.attribute_cloned_or_default(ATTR_GRADIENT_MODEL),
placement,
);
let to_unit = (placement.matrix2.determinant() != 0.).then(|| placement.inverse());
match shape {
match item.attribute_cloned_or_default::<GradientForm>(ATTR_GRADIENT_FORM) {
// Measured along the line across the bands, which stay parallel to the placement's sheared y axis as the renderers draw them
GradientShape::Linear => {
GradientForm::Linear => {
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| Some((point - origin).dot(line) / line.length_squared())) as Box<dyn Fn(DVec2) -> Option<f64> + Sync>)
(line.length_squared() > 0.).then(|| Box::new(move |point: DVec2| (point - origin).dot(line) / line.length_squared()) as Box<dyn Fn(DVec2) -> f64 + Sync>)
}
GradientShape::Radial => {
let to_unit = to_unit?;
Some(Box::new(move |point| Some(to_unit.transform_point2(point).length())))
GradientForm::Radial => {
let to_unit = (placement.matrix2.determinant() != 0.).then(|| placement.inverse())?;
Some(Box::new(move |point| to_unit.transform_point2(point).length()))
}
// Any other curvatures draw in the gradient space the full placement maps from, which a collapsed placement leaves a solid color needing none
GradientShape::Standard(gradient) => {
let to_unit = to_unit.unwrap_or_default();
Some(Box::new(move |point| gradient.t(to_unit.transform_point2(point))))
}
// Apollonian circles paint every point, and a collapsed placement takes the Standard model's solid color instead
GradientShape::Apollonian(parameters) => {
let to_unit = to_unit?;
Some(Box::new(move |point| Some(parameters.t(to_unit.transform_point2(point)))))
}
}
}
/// The position a `spread` reads along the ramp for one of a gradient's positions, which keeps an infinite one (a solid end stop) on that end's color under every spread but Clear.
fn spread_position(position: f64, spread: GradientSpread) -> f64 {
match (position.is_infinite(), spread) {
(true, GradientSpread::Repeat | GradientSpread::Reflect) if position > 0. => 1. - f64::EPSILON,
(true, GradientSpread::Repeat | GradientSpread::Reflect) => 0.,
_ => position,
}
}
@@ -1761,7 +1727,7 @@ mod tests {
#[test]
fn random_fields_move_and_scale_with_the_content_after_them() {
let noise = EffectOperation::Speckle {
let noise = EffectOperation::AddNoise {
amount: 30.,
distribution: graphic_types::NoiseDistribution::Uniform,
monochromatic: false,
@@ -1911,7 +1877,9 @@ mod tests {
// A ramp from black to white across far more than the content, which lights flat ground wherever it reaches
let stops = [(0., Color::BLACK), (1., Color::WHITE)].map(|(position, color)| GradientStop { position, midpoint: 0.5, color });
let ramp = Item::new_from_element(Gradient::new(stops)).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::splat(-100.)) * DAffine2::from_scale(DVec2::splat(300.)));
let ramp = Item::new_from_element(Gradient::new(stops))
.with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::splat(-100.)) * DAffine2::from_scale(DVec2::splat(300.)))
.with_attribute(ATTR_GRADIENT_FORM, GradientForm::Linear);
let mut emboss = EffectOperation::default_for(graphic_types::EffectKind::BevelAndEmboss);
if let EffectOperation::BevelAndEmboss { style, size, texture, .. } = &mut emboss {
@@ -1,7 +1,7 @@
//! What SVG can't express, which the GPU renders as images for an SVG to take, once the SVG is drawn.
//! An effect whose coverage SVG filters can't work out, like the shadows and glows shaped for PSD interop, goes in its filter as a map of that coverage, while the content keeps its own markup.
//! Content with an effect no filter can carry out or a paint SVG only approximates (like a gradient of Apollonian circles), and a backdrop whose copy in markup would nest,
//! are drawn as images in place of markup. Placeholders stand in for each until it's resolved, leaving an SVG that never is short of those effects.
//! Content with an effect no filter can carry out, and a backdrop whose copy in markup would nest, are drawn as images in place of markup.
//! Placeholders stand in for each until it's resolved, leaving an SVG that never is short of those effects.
use crate::renderer::{CanvasImage, Render, RenderOutputType, RenderParams, RenderSvgSegmentList, SvgRender, format_transform_matrix, render_raster_cpu_image_svg};
use crate::vello_scene_builder::{MAX_EFFECTS_AREA_PER_VIEWPORT_AREA, VelloSceneBuilder};
@@ -209,7 +209,7 @@ pub struct DeferredImage {
/// What the GPU renders an image of for an SVG.
#[derive(Clone)]
pub enum DeferredContent {
/// An item with effects SVG filters can't carry out or a paint SVG only approximates, but without its opacity and blend mode, which the image takes instead.
/// An item with effects SVG filters can't carry out, but without its opacity and blend mode, which the image takes instead.
Item(Graphic),
/// What lies beneath content reading its backdrop, drawn in order, for which the markers stand around no markup.
/// The outline of the backdrop root's `clip`, a path in the document filled by the nonzero rule, cuts it as it's drawn, as it cuts what a copy of it would hold.
@@ -4,7 +4,6 @@ pub mod render_ext;
mod renderer;
mod svg_backdrop;
mod svg_blend_if;
mod svg_layer_blend;
pub mod to_peniko;
pub mod vello_scene_builder;
@@ -1,14 +1,14 @@
use crate::renderer::{
ItemRef, RenderParams, SvgGradientLayer, composite_paint_colors, faded_paint_color, format_transform_matrix, gradient_placement, gradient_shape, painted_gradient, spread_adjusted_samples,
svg_gradient_standard, transform_is_invertible, with_two_stops_at_least, write_svg_gradient_paint,
ItemRef, RenderParams, composite_paint_colors, faded_paint_color, format_transform_matrix, gradient_placement, painted_gradient, spread_adjusted_samples, transform_is_invertible,
};
use crate::{Render, RenderSvgSegmentList, SvgRender};
use core_types::color::SRGBA8;
use core_types::list::List;
use core_types::uuid::generate_uuid;
use core_types::{ATTR_TRANSFORM, Color};
use core_types::{ATTR_GRADIENT_FORM, ATTR_TRANSFORM, Color};
use glam::{DAffine2, DVec2};
use graphic_types::Graphic;
use graphic_types::vector_types::gradient::GradientForm;
use graphic_types::vector_types::vector::style::{Stroke, StrokeAlign, StrokeCap, StrokeJoin};
use std::fmt::Write;
use vector_types::Gradient;
@@ -86,27 +86,17 @@ impl RenderExt for List<Color> {
}
}
/// Adds one gradient item's paint server into `svg_defs` and returns its ID, or `None` when the item is absent or paints nothing.
/// One painted through a mask fills a pattern spanning `bounds`, which `stroke_transform` places in the painted element's space.
/// Adds one gradient item's def into `svg_defs` and returns the gradient ID, or `None` when the item is absent.
/// `for_mask` keeps the fill opacity at full, as [`ItemRef::paint_opacity`] explains.
fn render_gradient_paint(
item: Option<ItemRef<'_, Gradient>>,
svg_defs: &mut String,
item_transform: DAffine2,
element_transform: DAffine2,
stroke_transform: DAffine2,
bounds: DAffine2,
for_mask: bool,
) -> Option<u64> {
fn render_gradient_paint(item: Option<ItemRef<'_, Gradient>>, svg_defs: &mut String, item_transform: DAffine2, element_transform: DAffine2, for_mask: bool) -> Option<u64> {
let mut stop = String::new();
let item = item?;
let (stops, settings) = painted_gradient(item)?;
let shape = gradient_shape(item);
let gradient_form: GradientForm = item.attribute_cloned_or_default(ATTR_GRADIENT_FORM);
let local_gradient_transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
let mut samples = spread_adjusted_samples(&stops, settings, shape.reaches_before_start());
with_two_stops_at_least(shape, &mut samples);
let mut samples = spread_adjusted_samples(&stops, settings, gradient_form);
let paint_opacity = item.paint_opacity(for_mask);
if paint_opacity < 1. {
@@ -115,7 +105,7 @@ fn render_gradient_paint(
}
}
for &(position, color, original_midpoint) in &samples {
for (position, color, original_midpoint) in samples {
stop.push_str("<stop");
if position != 0. {
let _ = write!(stop, r#" offset="{}""#, (position * 1_000_000.).round() / 1_000_000.);
@@ -148,7 +138,13 @@ fn render_gradient_paint(
let document_transform = item_transform * local_gradient_transform;
let gradient_transform = element_transform_inverse * gradient_placement(document_transform, shape);
let placement = gradient_placement(document_transform, gradient_form);
let gradient_transform = format_transform_matrix(element_transform_inverse * placement);
let gradient_transform = if gradient_transform.is_empty() {
String::new()
} else {
format!(r#" gradientTransform="{gradient_transform}""#)
};
let gradient_spread = if matches!(settings.spread, GradientSpread::Pad | GradientSpread::Clear) {
String::new()
@@ -156,45 +152,26 @@ fn render_gradient_paint(
format!(r#" spreadMethod="{}""#, settings.spread.svg_name())
};
// A paint drawn through a mask fills a pattern of the box around the painted area, which the masks are drawn over
let masked = svg_gradient_standard(shape).is_some_and(|gradient| gradient.is_masked());
let pattern_area = if masked {
let inverse = |length: f64| if length > 0. { 1. / length } else { 0. };
let inflate = DVec2::new(inverse(item_transform.matrix2.x_axis.length()), inverse(item_transform.matrix2.y_axis.length()));
let (local_min, local_max) = (bounds.transform_point2(DVec2::ZERO) - inflate, bounds.transform_point2(DVec2::ONE) + inflate);
let gradient_id = generate_uuid();
let corners = [local_min, DVec2::new(local_max.x, local_min.y), DVec2::new(local_min.x, local_max.y), local_max].map(|corner| stroke_transform.transform_point2(corner));
let min = corners.into_iter().reduce(DVec2::min)?;
let size = corners.into_iter().reduce(DVec2::max)? - min;
if !(size.x > 0. && size.y > 0. && size.is_finite() && min.is_finite()) {
return None;
match gradient_form {
GradientForm::Linear => {
let _ = write!(
svg_defs,
r#"<linearGradient id="{}" gradientUnits="userSpaceOnUse" x1="0" y1="0" x2="1" y2="0"{gradient_spread}{gradient_transform}>{}</linearGradient>"#,
gradient_id, stop
);
}
GradientForm::Radial => {
let _ = write!(
svg_defs,
r#"<radialGradient id="{}" gradientUnits="userSpaceOnUse" cx="0" cy="0" r="1"{gradient_spread}{gradient_transform}>{}</radialGradient>"#,
gradient_id, stop
);
}
Some((min, size))
} else {
None
};
let area = pattern_area.map_or(String::new(), |(min, size)| format!(r#"rect x="{}" y="{}" width="{}" height="{}""#, min.x, min.y, size.x, size.y));
let layers = write_svg_gradient_paint(svg_defs, shape, &samples, &stop, &gradient_spread, gradient_transform, &area);
if let [SvgGradientLayer { paint, mask: None }] = layers.as_slice() {
return Some(*paint);
}
let (min, size) = pattern_area?;
let pattern_id = generate_uuid();
let _ = write!(
svg_defs,
r#"<pattern id="{pattern_id}" patternUnits="userSpaceOnUse" x="{}" y="{}" width="{}" height="{}" viewBox="{} {} {} {}">"#,
min.x, min.y, size.x, size.y, min.x, min.y, size.x, size.y
);
for SvgGradientLayer { paint, mask } in layers {
let mask = mask.map(|mask| format!(r#" mask="url(#{mask})""#)).unwrap_or_default();
let _ = write!(svg_defs, r#"<{area} fill="url(#{paint})"{mask} />"#);
}
svg_defs.push_str("</pattern>");
Some(pattern_id)
Some(gradient_id)
}
impl RenderExt for List<Gradient> {
@@ -208,8 +185,8 @@ impl RenderExt for List<Gradient> {
_paint_reach: f64,
item_transform: DAffine2,
element_transform: DAffine2,
stroke_transform: DAffine2,
bounds: DAffine2,
_stroke_transform: DAffine2,
_bounds: DAffine2,
render_params: &RenderParams,
_target: PaintTarget,
) -> Self::Output {
@@ -218,8 +195,6 @@ impl RenderExt for List<Gradient> {
svg_defs,
item_transform,
element_transform,
stroke_transform,
bounds,
render_params.for_mask,
)
}
@@ -317,7 +292,7 @@ impl RenderExt for Graphic {
render_params,
target,
),
Graphic::Gradient(item) => render_gradient_paint(Some(ItemRef::Item(item)), svg_defs, item_transform, element_transform, stroke_transform, bounds, render_params.for_mask)
Graphic::Gradient(item) => render_gradient_paint(Some(ItemRef::Item(item)), svg_defs, item_transform, element_transform, render_params.for_mask)
.map(|gradient_id| format!(r##" {paint_attr}="url(#{gradient_id})""##))
.unwrap_or_else(|| format!(r#" {paint_attr}="none""#)),
// One gradient resolves to a paint server; stacking several needs them composited, which only the pattern below can do
File diff suppressed because it is too large. Load diff
@@ -96,10 +96,10 @@ impl SvgFilterPrimitives {
match *operation {
// The Euclidean length of the gradient loses too much precision through the 8-bit results between primitives
EffectOperation::FindEdges => self.uncovered_map(image, capture, Surroundings::Matted(1.)),
EffectOperation::MinimumMaximum { .. } | EffectOperation::Speckle { .. } | EffectOperation::Dissolve { .. } if forked => self.map_showing(capture, image),
EffectOperation::MinimumMaximum { .. } | EffectOperation::AddNoise { .. } | EffectOperation::Dissolve { .. } if forked => self.map_showing(capture, image),
EffectOperation::MinimumMaximum { radius, mode } => self.neighborhood_extreme(image, radius, mode == MinimumMaximumMode::Maximum),
// Random fields come from the GPU, one map for both the content and the fill since they don't depend on either
EffectOperation::Speckle { amount, distribution, .. } => self.speckle(image, noise_extent(amount / 100., distribution), EffectCapture { plane: 0, ..capture }),
EffectOperation::AddNoise { amount, distribution, .. } => self.add_noise(image, noise_extent(amount / 100., distribution), EffectCapture { plane: 0, ..capture }),
EffectOperation::Dissolve { .. } => self.dissolve(image, EffectCapture { plane: 0, ..capture }),
_ => image.to_string(),
}
@@ -124,7 +124,7 @@ impl SvgFilterPrimitives {
Some(convolution) => native && LatticeKernel::new(&convolution).is_some(),
None => matches!(
operation,
EffectOperation::MinimumMaximum { .. } | EffectOperation::Sharpen { .. } | EffectOperation::HighPass { .. } | EffectOperation::Speckle { .. } | EffectOperation::Dissolve { .. }
EffectOperation::MinimumMaximum { .. } | EffectOperation::Sharpen { .. } | EffectOperation::HighPass { .. } | EffectOperation::AddNoise { .. } | EffectOperation::Dissolve { .. }
),
}
}
@@ -275,9 +275,9 @@ impl SvgFilterPrimitives {
self.push("feColorMatrix", &format!(r#"in="{image}" type="matrix" values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 255 0""#), "")
}
/// The image with each straight color offset by the noise in the GPU's map for `capture`, which holds offsets up to `extent` either way around middle gray, matching the GPU's `speckle`.
/// The image with each straight color offset by the noise in the GPU's map for `capture`, which holds offsets up to `extent` either way around middle gray, matching the GPU's `add_noise`.
/// Until the map is resolved, its middle gray offsets nothing.
fn speckle(&mut self, image: &str, extent: f64, capture: EffectCapture) -> String {
fn add_noise(&mut self, image: &str, extent: f64, capture: EffectCapture) -> String {
let colors = self.opaque_colors(image);
let noise = self.map_unresolved_as(capture, Color::from(SRGBA8::new(128, 128, 128, 255)));
let attributes = format!(r#"in="{colors}" in2="{noise}" operator="arithmetic" k2="1" k3="{}" k4="{}""#, 2. * extent, -extent);
@@ -719,8 +719,8 @@ mod tests {
#[test]
fn random_fields_come_from_the_gpu_combined_with_the_live_content() {
// Speckle adds the map's offsets, scaled out from middle gray to their extent, to the opaque colors within the live coverage
let noise = EffectOperation::Speckle {
// Add Noise adds the map's offsets, scaled out from middle gray to their extent, to the opaque colors within the live coverage
let noise = EffectOperation::AddNoise {
amount: 40.,
distribution: NoiseDistribution::Uniform,
monochromatic: false,
@@ -760,13 +760,13 @@ mod tests {
use core_types::list::{ATTR_EFFECTS, List};
use core_types::transform::Footprint;
// A color with Speckle after Levels draws through a filter over the view, with the noise's map and the Levels within it
// A color with Add Noise after Levels draws through a filter over the view, with the noise's map and the Levels within it
let levels = graphic_types::Adjustment::Exposure {
exposure: 1.,
offset: 0.,
gamma_correction: 1.,
};
let noise = EffectOperation::Speckle {
let noise = EffectOperation::AddNoise {
amount: 20.,
distribution: NoiseDistribution::Uniform,
monochromatic: false,
@@ -800,7 +800,7 @@ mod tests {
// A gradient mask without a transform lies across the color's own unit square, as on the GPU, rather than across the view
let stops = [(0., core_types::Color::BLACK), (1., core_types::Color::WHITE)].map(|(position, color)| GradientStop { position, midpoint: 0.5, color });
let noise = EffectOperation::Speckle {
let noise = EffectOperation::AddNoise {
amount: 20.,
distribution: NoiseDistribution::Uniform,
monochromatic: false,
@@ -134,9 +134,17 @@ impl SvgRender {
/// Markup showing what lies beneath the content drawn next, within the `region` of the current user space it reads, or `None` if nothing does.
/// It copies the markup drawn since the backdrop root, or where that holds a copy already, stands for an image the GPU renders of it or else leaves held copies out.
/// The image is embedded `for_mask`, since a mask can't render canvases.
/// The image is embedded `for_mask`, which draws no canvas.
pub(crate) fn backdrop_copy(&mut self, render_params: &RenderParams, region: [DVec2; 2], read_reach: f64, for_mask: bool) -> Option<BackdropCopy> {
let root = self.backdrop_root()?;
if self.drawing_deferred_markup || !self.transform.matrix2.determinant().is_normal() {
return None;
}
let root = self.open_groups.groups.iter().rposition(|group| group.isolates)?;
// A clip's own stack lies over nothing, as in the GPU's layer for it, though a group isolated within it still reads what it drew
if root == 0 && self.open_groups.clip {
return None;
}
// The backdrop root's own clip cuts every level's copy as it cuts the originals, from a group around them in the space of its content
let root_group = &self.open_groups.groups[root];
@@ -144,9 +152,8 @@ impl SvgRender {
let clip = root_group.clip_path.clone().zip(root_group.user_to_document);
let copies_to_document = clip.as_ref().map_or(self.transform, |(_, root_to_document)| *root_to_document);
// In the viewport, images draw to canvases in `<foreignObject>` elements, which a mask can't render, so a mask reads the GPU's image of what lies beneath instead, as later readers do
let draws_canvases = self.draws_canvases_since(root, render_params);
let images = holds_backdrop || (for_mask && draws_canvases);
// A mask draws no canvas, so where one stands in for what lies beneath, the GPU's image of it shows what's displayed, as it does for later readers
let images = holds_backdrop || (for_mask && self.draws_canvases_since(root, render_params));
// An image needs the outline of the root's clip, if it has one, to cut what it holds by
let image_clip = match images && self.images_replace_markup(render_params) {
@@ -160,7 +167,7 @@ impl SvgRender {
// Elsewhere, copies leave out the blurred copies earlier content holds, so they never nest, losing only the blur of a blur where it overlaps
let image = images && image_clip.is_some();
let copies = match (images, image_clip) {
(false, _) => self.backdrop_markup_copies(root, copies_to_document, render_params.to_canvas() || draws_canvases, false),
(false, _) => self.backdrop_markup_copies(root, copies_to_document, render_params.to_canvas(), false),
(true, Some(clip)) => {
let image_params = RenderParams {
embeds_images: render_params.embeds_images || for_mask,
@@ -187,42 +194,11 @@ impl SvgRender {
Some(BackdropCopy { markup, image })
}
/// The group isolating the content drawn next from what lies beneath it, its backdrop root, as an index of the open groups, or `None` if it reads nothing beneath.
fn backdrop_root(&self) -> Option<usize> {
if self.drawing_deferred_markup || !self.transform.matrix2.determinant().is_normal() {
return None;
}
let root = self.open_groups.groups.iter().rposition(|group| group.isolates)?;
// A clip's own stack lies over nothing, as in the GPU's layer for it, though a group isolated within it still reads what it drew
(root > 0 || !self.open_groups.clip).then_some(root)
}
/// Whether anything is drawn beneath the content drawn next for [`Self::backdrop_copy`] to show, as markup it copies or content it has the GPU draw again.
/// O(segments drawn since the backdrop root).
pub(crate) fn draws_beneath(&self) -> bool {
let Some(root) = self.backdrop_root() else { return false };
(root..self.open_groups.groups.len()).any(|level| {
let group = &self.open_groups.groups[level];
let markup = &self.svg[group.content_start..self.level_content_end(level)];
let copied = group.user_to_document.is_some() && markup.iter().any(|segment| segment.as_str().contains('<'));
copied || group.drawn.iter().any(|drawn| drawn.count > 0)
})
}
/// Where the markup drawn directly inside the open group at `level` ends among the render's segments, at the tag of the group open inside it, if any.
fn level_content_end(&self, level: usize) -> usize {
self.open_groups.groups.get(level + 1).map_or(self.svg.len(), |inner| inner.tag_start)
}
/// Whether the markup drawn since the backdrop `root` draws through canvases, as images and the GPU's images of content do in the viewport the `render_params` draw in,
/// even where the content reading it embeds its own images. O(segments drawn since the root).
/// Whether the markup drawn since the backdrop `root` draws through canvases, as images and the GPU's images of content do in the viewport. O(segments drawn since the root).
fn draws_canvases_since(&self, root: usize, render_params: &RenderParams) -> bool {
let in_viewport = !(render_params.for_export || render_params.thumbnail || render_params.for_mask || render_params.inside_pattern);
let start = self.open_groups.groups[root].content_start;
let draws_canvas = |segment: &SvgSegment| segment.as_str().contains("data-canvas-placeholder") || deferred_image::holds_image_markers(segment.as_str());
in_viewport && self.svg[start..].iter().any(draws_canvas)
render_params.to_canvas() && self.svg[start..].iter().any(draws_canvas)
}
/// Copies of the content drawn at each level of the groups open since the backdrop `root`, in the space `copies_to_document` maps into the document, or `None` if there's none.
@@ -236,7 +212,8 @@ impl SvgRender {
let mut copies = Vec::new();
for level in (root..=current).rev() {
let group = &self.open_groups.groups[level];
let (start, end) = (group.content_start, self.level_content_end(level));
let start = group.content_start;
let end = self.open_groups.groups.get(level + 1).map_or(self.svg.len(), |inner| inner.tag_start);
let drawn = self.svg[start..end].iter().filter(kept).any(|segment| segment.as_str().contains('<'));
let Some(user_to_document) = group.user_to_document.filter(|_| drawn) else { continue };
@@ -294,7 +271,6 @@ impl SvgRender {
}
/// Markup showing what lies beneath content (see [`SvgRender::backdrop_copy`]).
#[derive(Clone)]
pub(crate) struct BackdropCopy {
pub markup: String,
/// Whether the markup stands for an image the GPU renders of what lies beneath, rather than copying what's drawn.
@@ -49,7 +49,7 @@ pub(crate) fn weight(push: &mut impl FnMut(&str, &str, &str) -> String, image: &
/// The viewport's copy of what lies beneath as `markup`, with what a mask can't draw, so SVG can't read, covered by rectangles of the `key` color the ranges show in full.
/// What's drawn over a cover still hides it, as it hides the image the cover stands in for.
pub(crate) fn with_unreadable_covered(markup: &str, key: &str) -> String {
fn with_unreadable_covered(markup: &str, key: &str) -> String {
with_canvases_covered(&with_deferred_images_marked_for_covers(markup, key), key)
}
@@ -1,571 +0,0 @@
//! Layers in the blend modes `mix-blend-mode` lacks, or below a full fill moving them toward neutral in Color Dodge and Color Burn, built all natively from what SVG composites,
//! over a copy of what lies beneath (see [`SvgRender::backdrop_copy`]).
//! The layer's alpha, times [`layer_fill_shown`] where its fill moves it toward neutral, shows an opaque result: the layer made opaque, and over it the blend, shown by the alpha of what lies beneath,
//! as the W3C's general formula mixes them. The blend draws the layer, recolored and made opaque, over an opaque copy of what lies beneath, where `s` is the layer moved toward neutral by its fill:
//! - Linear Burn, Subtract: Lighten by `x`, then Difference by `x`, which leaves `max(0, b - x)` exactly, for `x` of `1 - s` or `s`.
//! - Linear Dodge: that over the inverted copy, inverted back. Linear Light: Linear Burn by `2s`, then Linear Dodge by `2s - 1`.
//! - Hard Mix: at full strength, the copy where it and the layer sum to white exactly, and white where they sum past it, each where Color Dodge reaches white.
//! Below it, Linear Burn by `q (1 - s)`, stretched by `1 / (1 - q)`.
//! - Divide: Color Dodge by the inverted layer. Pin Light: Darken by `2s`, then Lighten by `2s - 1`. Vivid Light: Color Burn by `2s`, then Color Dodge by `2s - 1`.
//! - Darker Color, Lighter Color: the layer over the copy, masked to where Luminosity moves the copy's color down (or up) by a level or more.
//! - Color Dodge, Color Burn: themselves by `s`.
use crate::renderer::{RenderParams, SvgRender, SvgSegment};
use crate::svg_backdrop::BackdropCopy;
use crate::svg_blend_if::with_unreadable_covered;
use core_types::blending::{BlendMode, layer_fill_shown};
use core_types::uuid::generate_uuid;
use glam::DVec2;
use std::fmt::Write;
/// A layer blending by a mode `mix-blend-mode` lacks, with what it reads to blend onto what lies beneath.
pub(crate) struct SvgLayerBlend {
blend_mode: BlendMode,
/// The copy of what lies beneath, taken before any of the item is drawn, or `None` with nothing beneath.
copy: Option<BackdropCopy>,
/// The region of the current user space the layer covers, which the blend's filters and masks cover too.
region: [DVec2; 2],
/// The fill moving the layer toward the mode's neutral color (see [`BlendMode::fill_moves_layer_toward_neutral`]), or 1 where the layer is faded by its fill already.
fill: f64,
}
impl SvgLayerBlend {
/// Copies what lies beneath the `region` of the current user space, before any of the layer is drawn, for it to blend onto by the mode.
pub(crate) fn new(render: &mut SvgRender, render_params: &RenderParams, blend_mode: BlendMode, region: [DVec2; 2], fill: f64) -> Self {
Self {
blend_mode,
copy: render.backdrop_copy(render_params, region, 0., true),
region,
fill,
}
}
/// The blend of another layer of the same item by its own `blend_mode` at full strength, onto the same copy of what lies beneath.
pub(crate) fn with_mode(&self, blend_mode: BlendMode) -> Self {
Self {
blend_mode,
copy: self.copy.clone(),
region: self.region,
fill: 1.,
}
}
/// Whether the layer blends onto what lies beneath, rather than over nothing.
pub(crate) fn blends(&self) -> bool {
self.copy.is_some() && recipe(self.blend_mode, self.fill).is_some()
}
/// Whether the blend moves the layer toward the mode's neutral color by a fill below full, which the layer itself then leaves out.
pub(crate) fn moves_by_fill(&self) -> bool {
self.fill < 1.
}
}
/// A map of each straight color channel, `scale × channel + offset`, clamped to 0 to 1.
#[derive(Clone, Copy, Debug, PartialEq)]
struct Recolor {
scale: f64,
offset: f64,
}
impl Recolor {
const IDENTITY: Self = Self { scale: 1., offset: 0. };
const INVERT: Self = Self { scale: -1., offset: 1. };
}
/// One step building a mode SVG lacks: the layer recolored and made opaque, then drawn by a native mode.
#[derive(Clone, Copy, Debug)]
struct BlendStep {
recolor: Recolor,
blend_mode: BlendMode,
}
/// A stage of steps over its base (the copy of what lies beneath, or the stage before), recolored, whose result it then recolors by `stretch`.
#[derive(Clone, Debug)]
struct BlendStage {
base: Recolor,
steps: Vec<BlendStep>,
stretch: Recolor,
}
/// How SVG builds a mode it lacks over an opaque copy of what lies beneath.
#[derive(Clone, Debug)]
enum BlendRecipe {
Stages(Vec<BlendStage>),
/// Hard Mix at full strength: the copy where it and the layer sum to white exactly, and white where they sum past it.
HardMixThreshold,
/// The layer's whole color where its luma is lower than that of what lies beneath, or higher if `lighter`.
Pick {
lighter: bool,
},
}
/// The recipe for a mode SVG lacks at the `fill` moving the layer's color toward neutral where the mode does that, or `None` for a mode SVG has at it.
fn recipe(blend_mode: BlendMode, fill: f64) -> Option<BlendRecipe> {
use BlendMode::*;
let step = |scale: f64, offset: f64, blend_mode: BlendMode| BlendStep {
recolor: Recolor { scale, offset },
blend_mode,
};
// Lightening by `x`, then the difference from it, leaves `max(0, b - x)` in whole levels
let burn_by = |scale: f64, offset: f64| vec![step(scale, offset, Lighten), step(scale, offset, Difference)];
let stage = |base: Recolor, steps: Vec<BlendStep>, stretch: Recolor| BlendStage { base, steps, stretch };
let (identity, invert) = (Recolor::IDENTITY, Recolor::INVERT);
let steepness = 255. * fill / 256.;
let stages = match blend_mode {
LinearBurn => vec![stage(identity, burn_by(-fill, fill), identity)],
Subtract => vec![stage(identity, burn_by(1., 0.), identity)],
LinearDodge => vec![stage(invert, burn_by(fill, 0.), invert)],
LinearLight => vec![stage(identity, burn_by(-2. * fill, fill), identity), stage(invert, burn_by(2. * fill, -fill), invert)],
HardMix if fill >= 1. => return Some(BlendRecipe::HardMixThreshold),
HardMix => vec![stage(
identity,
burn_by(-steepness, steepness),
Recolor {
scale: 1. / (1. - steepness),
offset: 0.,
},
)],
Divide => vec![stage(identity, vec![step(-1., 1., ColorDodge)], identity)],
ColorDodge if fill < 1. => vec![stage(identity, vec![step(fill, 0., ColorDodge)], identity)],
ColorBurn if fill < 1. => vec![stage(identity, vec![step(fill, 1. - fill, ColorBurn)], identity)],
PinLight => vec![stage(identity, vec![step(2., 0., Darken), step(2., -1., Lighten)], identity)],
VividLight => vec![stage(identity, vec![step(2. * fill, 1. - fill, ColorBurn), step(2. * fill, -fill, ColorDodge)], identity)],
DarkerColor => return Some(BlendRecipe::Pick { lighter: false }),
LighterColor => return Some(BlendRecipe::Pick { lighter: true }),
_ => return None,
};
Some(BlendRecipe::Stages(stages))
}
/// The filters and masks one blended layer writes into the render's defs, each within the layer's region.
struct BlendDefs<'a> {
defs: &'a mut String,
region: String,
uuid: u64,
recolors: Vec<(Recolor, String)>,
}
impl BlendDefs<'_> {
/// Writes a def named `name` with the `tag`, the `attributes` past its ID, and the `children`, returning a reference to it.
fn write(&mut self, name: &str, tag: &str, attributes: &str, children: &str) -> String {
let id = format!("layer-blend-{name}-{}", self.uuid);
write!(self.defs, r#"<{tag} id="{id}" {attributes} {}>{children}</{tag}>"#, self.region).unwrap();
format!("url(#{id})")
}
/// A filter named `name` of the `primitives` on gamma-encoded colors.
fn filter(&mut self, name: &str, primitives: &str) -> String {
self.write(name, "filter", r#"filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB""#, primitives)
}
/// A mask named `name` showing what the `markup` covers, by its alpha.
fn mask(&mut self, name: &str, markup: &str) -> String {
self.write(name, "mask", r#"mask-type="alpha" maskUnits="userSpaceOnUse""#, markup)
}
/// A filter making what it draws opaque in its straight color, recolored, written once for each recoloring.
fn recolor(&mut self, recolor: Recolor) -> String {
if let Some((_, reference)) = self.recolors.iter().find(|(written, _)| *written == recolor) {
return reference.clone();
}
let Recolor { scale, offset } = recolor;
let name = format!("recolor-{}", self.recolors.len());
let reference = self.filter(
&name,
&format!(r#"<feColorMatrix type="matrix" values="{scale} 0 0 0 {offset} 0 {scale} 0 0 {offset} 0 0 {scale} 0 {offset} 0 0 0 0 1" />"#),
);
self.recolors.push((recolor, reference.clone()));
reference
}
}
/// What a blended layer draws around it, with its defs written.
struct BlendGroups {
/// The attributes of each group around the layer made opaque and the blend over it, outermost first.
around: Vec<Vec<(&'static str, String)>>,
/// The filter making the layer opaque, beneath the blend.
opaque: String,
/// The ID the layer's own group takes, for copies of it to reference.
layer_id: String,
/// The blend's markup, drawn over the layer made opaque, which copies of what lies beneath leave out so they never nest.
blended: String,
}
/// Writes the defs of the `blend` of a layer at `opacity` and returns what it draws around the layer, or `None` with nothing beneath to blend onto.
fn blend_groups(render: &mut SvgRender, blend: &SvgLayerBlend, opacity: f32) -> Option<BlendGroups> {
let (Some(copy), Some(recipe)) = (&blend.copy, recipe(blend.blend_mode, blend.fill)) else {
return None;
};
let uuid = generate_uuid();
let layer_id = format!("layer-blend-layer-{uuid}");
let [min, max] = blend.region;
let mut defs = BlendDefs {
defs: &mut render.svg_defs,
region: format!(r#"x="{}" y="{}" width="{}" height="{}""#, min.x, min.y, max.x - min.x, max.y - min.y),
uuid,
recolors: Vec::new(),
};
// Copies of the layer reference it, and masks read what lies beneath from an image or a copy covering what they can't draw
let layer = format!(r##"<use href="#{layer_id}" />"##);
let beneath_in_mask = if copy.image { copy.markup.clone() } else { with_unreadable_covered(&copy.markup, "#000000") };
let opaque = defs.recolor(Recolor::IDENTITY);
let drawn = |filter: &str, blend_mode: BlendMode, markup: &str| format!(r#"<g filter="{filter}" style="{}">{markup}</g>"#, blend_mode.render().trim());
let blend_markup = match recipe {
// Each stage's steps blend over its base alone, within a group recoloring what they leave
BlendRecipe::Stages(stages) => {
let mut result = copy.markup.clone();
for stage in stages {
let base = format!(r#"<g filter="{}">{result}</g>"#, defs.recolor(stage.base));
let steps: String = stage.steps.iter().map(|step| drawn(&defs.recolor(step.recolor), step.blend_mode, &layer)).collect();
result = format!(r#"<g filter="{}">{base}{steps}</g>"#, defs.recolor(stage.stretch));
}
result
}
// Color Dodge reaches white exactly where the layer and the copy sum to white or past it, or past it alone for the layer a level darker
BlendRecipe::HardMixThreshold => {
let white = defs.filter("white", r#"<feComponentTransfer><feFuncR type="linear" slope="255" intercept="-254" /><feFuncG type="linear" slope="255" intercept="-254" /><feFuncB type="linear" slope="255" intercept="-254" /></feComponentTransfer>"#);
let mut reaches_white = |offset: f64| {
format!(
r#"<g filter="{opaque}">{}</g>{}"#,
copy.markup,
drawn(&defs.recolor(Recolor { scale: 1., offset }), BlendMode::ColorDodge, &layer)
)
};
let (sums_to_white, sums_past_white) = (reaches_white(0.), reaches_white(-1. / 255.));
format!(
r#"<g filter="{opaque}">{}</g><g filter="{white}" style="mix-blend-mode: multiply;">{sums_to_white}</g><g filter="{white}" style="mix-blend-mode: lighten;">{sums_past_white}</g>"#,
copy.markup
)
}
// Luminosity moves the copy's color by the layer's luma less its own, which the change in any channel shows the direction of
BlendRecipe::Pick { lighter } => {
let any_channel = defs.filter("any-channel", r#"<feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 255 255 255 0 0" />"#);
let toward = if lighter { BlendMode::Lighten } else { BlendMode::Darken };
let moved = format!(
r#"<g filter="{any_channel}"><g filter="{opaque}">{beneath_in_mask}</g>{}{}{}</g>"#,
drawn(&opaque, BlendMode::Luminosity, &layer),
drawn(&opaque, toward, &beneath_in_mask),
drawn(&opaque, BlendMode::Difference, &beneath_in_mask)
);
let picked = defs.mask("picked", &moved);
format!(r#"<g filter="{opaque}">{}</g><g filter="{opaque}" mask="{picked}">{layer}</g>"#, copy.markup)
}
};
// The blend shows by the alpha of what lies beneath, and the whole by the layer's own alpha, at its opacity
let beneath = defs.mask("beneath", &beneath_in_mask);
let blended = format!(r#"<g mask="{beneath}">{blend_markup}</g>"#);
let mut outer = vec![("mask", defs.mask("shown", &layer))];
if opacity < 1. {
outer.push(("opacity", opacity.to_string()));
}
let mut around = vec![outer];
// A fill moving the layer toward neutral shows it by how much lies beneath, by a table of each level of alpha there
if blend.fill < 1. {
let table: Vec<String> = (0..=255).map(|level| format!("{:.5}", layer_fill_shown(level as f32 / 255., blend.fill as f32))).collect();
let weight = defs.filter(
"fill-weight",
&format!(r#"<feComponentTransfer><feFuncA type="table" tableValues="{}" /></feComponentTransfer>"#, table.join(" ")),
);
around.push(vec![("mask", defs.mask("fill-shown", &format!(r#"<g filter="{weight}">{beneath_in_mask}</g>"#)))]);
}
Some(BlendGroups { around, opaque, layer_id, blended })
}
/// Draws the layer `draw_layer` draws, blended by the mode onto what lies beneath it and faded by `opacity`.
pub(crate) fn draw_blended_layer(render: &mut SvgRender, blend: &SvgLayerBlend, opacity: f32, draw_layer: impl FnOnce(&mut SvgRender)) {
let Some(BlendGroups { around, opaque, layer_id, blended }) = blend_groups(render, blend, opacity) else {
// Over nothing, the layer shows as it is, faded by a fill it would otherwise move toward neutral
let opacity = opacity as f64 * blend.fill;
return render.parent_tag(
"g",
|attributes| {
if opacity < 1. {
attributes.push("opacity", opacity.to_string());
}
},
draw_layer,
);
};
nest_groups(render, &around, |render| {
render.parent_tag(
"g",
|attributes| attributes.push("filter", opaque),
|render| render.parent_tag("g", |attributes| attributes.push("id", layer_id), draw_layer),
);
render.leaf_node(SvgSegment::Backdrop(blended));
});
}
/// Wraps the markup drawn since the segment at `start`, an image of the layer the GPU renders, in what [`draw_blended_layer`] draws around a layer. Returns whether it blends.
pub(crate) fn wrap_blended_layer(render: &mut SvgRender, blend: &SvgLayerBlend, opacity: f32, start: usize) -> bool {
let Some(BlendGroups { around, opaque, layer_id, blended }) = blend_groups(render, blend, opacity) else {
return false;
};
let opening = |attributes: &Vec<(&'static str, String)>| format!("<g{}>", attributes.iter().map(|(name, value)| format!(r#" {name}="{value}""#)).collect::<String>());
let mut opened: String = around.iter().map(opening).collect();
write!(opened, r#"<g filter="{opaque}"><g id="{layer_id}">"#).unwrap();
render.svg.insert(start, opened.into());
render.svg.push("</g></g>".into());
render.svg.push(SvgSegment::Backdrop(blended));
render.svg.push("</g>".repeat(around.len()).into());
true
}
/// Opens a group of each of the `groups`' attributes, outermost first, around what `inner` draws.
fn nest_groups(render: &mut SvgRender, groups: &[Vec<(&'static str, String)>], inner: impl FnOnce(&mut SvgRender)) {
let Some((attributes, nested)) = groups.split_first() else { return inner(render) };
render.parent_tag(
"g",
|tag| attributes.iter().for_each(|(name, value)| tag.push(*name, value.clone())),
|render| nest_groups(render, nested, inner),
);
}
#[cfg(test)]
mod tests {
use super::*;
use raster_kernels::layer_blending::{blend_layer_pixel, blend_pixel};
/// The modes SVG builds from native compositing.
const MODES: [BlendMode; 10] = [
BlendMode::LinearBurn,
BlendMode::DarkerColor,
BlendMode::LinearDodge,
BlendMode::LighterColor,
BlendMode::VividLight,
BlendMode::LinearLight,
BlendMode::PinLight,
BlendMode::HardMix,
BlendMode::Subtract,
BlendMode::Divide,
];
/// The modes SVG has, which it builds from native compositing too below a full fill moving the layer toward neutral.
const BELOW_FULL_FILL: [BlendMode; 2] = [BlendMode::ColorDodge, BlendMode::ColorBurn];
/// A value as the 8-bit buffers browsers hold the results of filters and groups in keep it.
fn quantized(value: f64) -> f64 {
(value.clamp(0., 1.) * 255.).round() / 255.
}
/// The opaque color an opaque `source` composites natively by the mode onto an opaque `backdrop`, by the W3C's formula, held in 8 bits.
fn native(blend_mode: BlendMode, backdrop: [f64; 3], source: [f64; 3]) -> [f64; 3] {
let opaque = |[red, green, blue]: [f64; 3]| [red as f32, green as f32, blue as f32, 1.];
let blended = blend_pixel(opaque(source), opaque(backdrop), blend_mode);
[0, 1, 2].map(|channel| quantized(blended[channel] as f64))
}
/// A color recolored, held in 8 bits.
fn recolored(recolor: Recolor, color: [f64; 3]) -> [f64; 3] {
color.map(|channel| quantized(recolor.scale * channel + recolor.offset))
}
/// The opaque color the `recipe` builds from an opaque `layer` over an opaque `backdrop`, compositing natively by the W3C's formulas, each result held in 8 bits.
fn emulated(recipe: &BlendRecipe, backdrop: [f64; 3], layer: [f64; 3]) -> [f64; 3] {
match recipe {
BlendRecipe::Stages(stages) => {
let mut result = backdrop;
for stage in stages {
result = recolored(stage.base, result);
for step in &stage.steps {
result = native(step.blend_mode, result, recolored(step.recolor, layer));
}
result = recolored(stage.stretch, result);
}
result
}
BlendRecipe::HardMixThreshold => {
let reaches_white = |offset: f64| native(BlendMode::ColorDodge, backdrop, recolored(Recolor { scale: 1., offset }, layer)).map(|channel| quantized(255. * channel - 254.));
let at_white = native(BlendMode::Multiply, backdrop, reaches_white(0.));
native(BlendMode::Lighten, at_white, reaches_white(-1. / 255.))
}
BlendRecipe::Pick { lighter } => {
let moved = native(BlendMode::Luminosity, backdrop, layer);
let toward = native(if *lighter { BlendMode::Lighten } else { BlendMode::Darken }, moved, backdrop);
let change = native(BlendMode::Difference, toward, backdrop);
let layer_wins = change.iter().sum::<f64>() * 255. >= 1.;
if layer_wins { layer } else { backdrop }
}
}
}
/// Colors on the 8-bit grid, which a render's inputs lie on.
fn levels(colors: &[[u8; 3]]) -> Vec<[f64; 3]> {
colors.iter().map(|color| color.map(|level| level as f64 / 255.)).collect()
}
/// How many levels the recipe's result may stray from the CPU's at a `fill` below full, where the layer's recolored channels round to whole levels:
/// none at full strength, which leaves them whole, a level otherwise, and on Hard Mix's ramp half a level stretched by `1 / (1 - steepness)`, more past a level.
fn tolerance(blend_mode: BlendMode, fill: f64) -> f64 {
match (fill < 1., blend_mode) {
(false, _) => 0.5,
(true, BlendMode::HardMix) => 1. + 0.5 / (1. - 255. * fill / 256.),
// Burning and dodging by a nearly black or white layer stretch its rounding most, by up to a fifth across these colors
(true, BlendMode::VividLight | BlendMode::ColorDodge | BlendMode::ColorBurn) => 3.,
(true, _) => 1.,
}
}
#[test]
fn recipes_build_each_mode_from_native_compositing_at_full_strength_exactly() {
// Every level of a gray backdrop under every level of a gray layer, and a spread of colors
let grays: Vec<[f64; 3]> = (0..=255).map(|level| [level as f64 / 255.; 3]).collect();
let colors = levels(&[
[0, 0, 0],
[255, 255, 255],
[204, 51, 128],
[30, 200, 90],
[128, 128, 128],
[250, 180, 20],
[64, 96, 230],
[127, 129, 140],
]);
let opaque = |[red, green, blue]: [f64; 3]| [red as f32, green as f32, blue as f32, 1.];
for blend_mode in MODES.into_iter().filter(|blend_mode| !matches!(blend_mode, BlendMode::DarkerColor | BlendMode::LighterColor)) {
let recipe = recipe(blend_mode, 1.).expect("SVG lacks the mode");
for (backdrops, layers) in [(&grays, &grays), (&colors, &colors)] {
for &backdrop in backdrops {
for &layer in layers {
let svg = emulated(&recipe, backdrop, layer);
let cpu = blend_layer_pixel(opaque(layer), opaque(backdrop), blend_mode, 1.);
for channel in 0..3 {
assert!(
(svg[channel] - cpu[channel] as f64).abs() * 255. <= 0.5 + 1e-4,
"{blend_mode} of {layer:?} over {backdrop:?} gives {svg:?} in SVG and {cpu:?} on the CPU"
);
}
}
}
}
}
}
#[test]
fn recipes_build_each_mode_from_native_compositing_below_full_strength_within_their_rounding() {
let colors = levels(&[
[0, 0, 0],
[255, 255, 255],
[204, 51, 128],
[30, 200, 90],
[128, 128, 128],
[250, 180, 20],
[64, 96, 230],
[127, 129, 140],
]);
let opaque = |[red, green, blue]: [f64; 3]| [red as f32, green as f32, blue as f32, 1.];
for blend_mode in MODES.into_iter().filter(BlendMode::fill_moves_layer_toward_neutral).chain(BELOW_FULL_FILL) {
for fill in [0.8, 0.6, 0.25, 0.] {
let recipe = recipe(blend_mode, fill).expect("SVG lacks the mode");
for &backdrop in &colors {
for &layer in &colors {
let svg = emulated(&recipe, backdrop, layer);
let cpu = blend_layer_pixel(opaque(layer), opaque(backdrop), blend_mode, fill as f32);
for channel in 0..3 {
let difference = (svg[channel] - cpu[channel] as f64).abs() * 255.;
assert!(
difference <= tolerance(blend_mode, fill),
"{blend_mode} at fill {fill} of {layer:?} over {backdrop:?} gives {svg:?} in SVG and {cpu:?} on the CPU"
);
}
}
}
}
}
}
#[test]
fn darker_and_lighter_color_pick_as_on_the_cpu_but_may_keep_the_backdrop_within_half_a_level_of_luma() {
let opaque = |[red, green, blue]: [f64; 3]| [red as f32, green as f32, blue as f32, 1.];
let luma = |color: [f64; 3]| 255. * (0.3 * color[0] + 0.59 * color[1] + 0.11 * color[2]);
// Pairs of colors around ties of luma, by a fraction of a level or a level or more, with channels at black and white where Luminosity clips
let colors = levels(&[
[0, 0, 255],
[0, 48, 0],
[0, 47, 0],
[0, 49, 0],
[255, 0, 0],
[0, 130, 0],
[10, 120, 40],
[128, 128, 128],
[100, 140, 140],
[255, 255, 255],
[0, 0, 0],
[255, 254, 255],
]);
for lighter in [false, true] {
let blend_mode = if lighter { BlendMode::LighterColor } else { BlendMode::DarkerColor };
for &backdrop in &colors {
for &layer in &colors {
let svg = emulated(&BlendRecipe::Pick { lighter }, backdrop, layer);
let difference = luma(layer) - luma(backdrop);
let cpu = blend_layer_pixel(opaque(layer), opaque(backdrop), blend_mode, 1.);
let cpu = [cpu[0] as f64, cpu[1] as f64, cpu[2] as f64];
// It picks what the CPU picks, or within half a level of a tie, where Luminosity may move no channel a level, it may keep the backdrop, as at a tie
let near_tie = difference.abs() < 0.5;
assert!(svg == cpu.map(quantized) || (near_tie && svg == backdrop), "{blend_mode} of {layer:?} over {backdrop:?} picks {svg:?}");
}
}
}
// Blue's luma lies just under green's, so Darker Color keeps the blue backdrop
let (blue, green) = ([0., 0., 1.], [0., 48. / 255., 0.]);
assert_eq!(emulated(&BlendRecipe::Pick { lighter: false }, blue, green), blue);
}
#[test]
fn layers_blend_by_the_alpha_beneath_and_their_own_as_on_the_cpu() {
let (backdrop, layer) = ([0.2, 0.6, 0.45], [0.85, 0.3, 0.6]);
// Color Dodge and Color Burn blend so only below a full fill
let cases = [(1., 0.5, 1., 1.), (0.5, 1., 0.6, 1.), (0.75, 0.25, 0.4, 0.7), (1., 0., 0.5, 1.), (1., 0.5, 0., 1.)];
let modes_and_cases = MODES.into_iter().chain(BELOW_FULL_FILL).flat_map(|blend_mode| cases.map(|case| (blend_mode, case)));
for (blend_mode, (layer_alpha, backdrop_alpha, fill, opacity)) in modes_and_cases.filter(|(blend_mode, (_, _, fill, _))| *fill < 1. || blend_mode.reads_backdrop()) {
// Only a fill moving the layer toward neutral reaches the blend, which shows it by the alpha beneath, and the layer is otherwise already faded by it
let moves = blend_mode.fill_moves_layer_toward_neutral();
let blend_fill = if moves { fill } else { 1. };
let drawn_alpha = if moves { layer_alpha } else { layer_alpha * fill };
let blend = emulated(&recipe(blend_mode, blend_fill).unwrap(), backdrop, layer);
// The layer made opaque, the blend over it by the alpha beneath, all shown by the layer's alpha, its fill's weight, and its opacity over what lies beneath
let shown = opacity * drawn_alpha * layer_fill_shown(backdrop_alpha as f32, blend_fill as f32) as f64;
let svg: Vec<f64> = (0..3)
.map(|channel| shown * (backdrop_alpha * blend[channel] + (1. - backdrop_alpha) * layer[channel]) + (1. - shown) * backdrop_alpha * backdrop[channel])
.chain([shown + (1. - shown) * backdrop_alpha])
.collect();
// The CPU blends the full-strength content by the fill, then the opacity mixes from what lies beneath to that
let premultiplied = |color: [f64; 3], alpha: f64| [color[0] * alpha, color[1] * alpha, color[2] * alpha, alpha].map(|channel| channel as f32);
let beneath = premultiplied(backdrop, backdrop_alpha);
let blended = blend_layer_pixel(premultiplied(layer, layer_alpha), beneath, blend_mode, fill as f32);
for channel in 0..4 {
let cpu = beneath[channel] as f64 + (blended[channel] - beneath[channel]) as f64 * opacity;
assert!(
(svg[channel] - cpu).abs() * 255. <= 2.,
"{blend_mode} at layer alpha {layer_alpha}, alpha beneath {backdrop_alpha}, fill {fill}, and opacity {opacity}: {svg:?} in SVG against {cpu} in channel {channel} on the CPU"
);
}
}
}
#[test]
fn modes_svg_has_take_no_recipe() {
for blend_mode in BlendMode::list().into_iter().flatten() {
assert_eq!(recipe(*blend_mode, 1.).is_some(), blend_mode.reads_backdrop(), "{blend_mode}");
}
}
}
@@ -42,7 +42,7 @@ impl BlendModeExt for BlendMode {
BlendMode::Saturation => peniko::Mix::Saturation,
BlendMode::Color => peniko::Mix::Color,
BlendMode::Luminosity => peniko::Mix::Luminosity,
// Vello lacks the rest, so they draw normally, and layers in those reading what lies beneath blend in an effects group (see `BlendMode::reads_backdrop`)
// Like SVG, the modes that layers can't blend by fall back to normal
_ => peniko::Mix::Normal,
}
}
@@ -11,7 +11,7 @@ use kurbo::{Affine, BezPath, PathEl, Point, Rect, Shape, Stroke};
use std::borrow::Cow;
use std::collections::HashMap;
use vello_gpu::peniko::{self, BlendMode, BrushRef, Fill};
use vello_gpu::{Image, ImageSource, PaintType, PencilGradient, TextureId, TextureRegion};
use vello_gpu::{Image, ImageSource, PaintType, TextureId, TextureRegion};
/// Tolerance for turning shapes other than paths into paths, matching Vello's own.
const SHAPE_TOLERANCE: f64 = 0.1;
@@ -94,51 +94,6 @@ pub trait EffectsRenderer: Send {
}
}
/// What a fill or stroke paints with.
#[derive(Clone, Copy, Debug)]
pub enum SceneBrush<'b> {
/// A solid color, gradient, or image.
Peniko(BrushRef<'b>),
/// A gradient whose contours are Apollonian circles, which only Vello GPU's fork draws.
Apollonian(&'b PencilGradient),
}
impl<'b> From<BrushRef<'b>> for SceneBrush<'b> {
fn from(brush: BrushRef<'b>) -> Self {
Self::Peniko(brush)
}
}
impl<'b> From<&'b peniko::Brush> for SceneBrush<'b> {
fn from(brush: &'b peniko::Brush) -> Self {
Self::Peniko(brush.into())
}
}
impl<'b> From<&'b peniko::Gradient> for SceneBrush<'b> {
fn from(gradient: &'b peniko::Gradient) -> Self {
Self::Peniko(gradient.into())
}
}
impl From<peniko::Color> for SceneBrush<'_> {
fn from(color: peniko::Color) -> Self {
Self::Peniko(color.into())
}
}
impl From<&peniko::Color> for SceneBrush<'_> {
fn from(color: &peniko::Color) -> Self {
Self::Peniko((*color).into())
}
}
impl<'b> From<&'b PencilGradient> for SceneBrush<'b> {
fn from(gradient: &'b PencilGradient) -> Self {
Self::Apollonian(gradient)
}
}
/// The pixels behind an image the scene draws.
#[derive(Clone, Debug)]
pub enum SceneImage {
@@ -315,41 +270,44 @@ impl<'a> VelloSceneBuilder<'a> {
}
/// Fills a shape given in the space of `transform`, with the brush placed by `transform * brush_transform`.
pub fn fill<'b>(&mut self, fill_rule: Fill, transform: Affine, brush: impl Into<SceneBrush<'b>>, brush_transform: Option<Affine>, shape: &impl Shape) {
pub fn fill<'b>(&mut self, fill_rule: Fill, transform: Affine, brush: impl Into<BrushRef<'b>>, brush_transform: Option<Affine>, shape: &impl Shape) {
self.fill_path(fill_rule, transform, brush, brush_transform, &shape.to_path(SHAPE_TOLERANCE));
}
/// Like [`Self::fill`] for a path, which it draws without copying.
pub fn fill_path<'b>(&mut self, fill_rule: Fill, transform: Affine, brush: impl Into<SceneBrush<'b>>, brush_transform: Option<Affine>, path: &BezPath) {
pub fn fill_path<'b>(&mut self, fill_rule: Fill, transform: Affine, brush: impl Into<BrushRef<'b>>, brush_transform: Option<Affine>, path: &BezPath) {
if !self.drawing {
return;
}
let Some(paint_to_brush) = self.set_paint(brush.into()) else { return };
let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return };
self.scene.set_transform(self.view * transform);
self.scene.set_fill_rule(fill_rule);
self.scene.set_paint(paint);
self.scene.set_paint_transform(brush_transform.unwrap_or(Affine::IDENTITY) * paint_to_brush);
self.scene.fill_path(&finite_path(path));
}
/// Strokes a shape given in the space of `transform`, with the brush placed by `transform * brush_transform`.
pub fn stroke<'b>(&mut self, stroke: &Stroke, transform: Affine, brush: impl Into<SceneBrush<'b>>, brush_transform: Option<Affine>, shape: &impl Shape) {
pub fn stroke<'b>(&mut self, stroke: &Stroke, transform: Affine, brush: impl Into<BrushRef<'b>>, brush_transform: Option<Affine>, shape: &impl Shape) {
if !self.drawing {
return;
}
let Some(paint_to_brush) = self.set_paint(brush.into()) else { return };
let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return };
self.scene.set_transform(self.view * transform);
self.scene.set_stroke(stroke.clone());
self.scene.set_paint(paint);
self.scene.set_paint_transform(brush_transform.unwrap_or(Affine::IDENTITY) * paint_to_brush);
self.scene.stroke_path(&finite_path(&shape.to_path(SHAPE_TOLERANCE)));
}
/// Fills the whole scene, which is how content without bounds (like a color or gradient layer) paints, with the brush placed by `brush_transform` in the space of the drawn content.
pub fn fill_viewport<'b>(&mut self, brush: impl Into<SceneBrush<'b>>, brush_transform: Option<Affine>) {
pub fn fill_viewport<'b>(&mut self, brush: impl Into<BrushRef<'b>>, brush_transform: Option<Affine>) {
if !self.drawing {
return;
}
let Some(paint_to_brush) = self.set_paint(brush.into()) else { return };
let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return };
self.scene.set_transform(Affine::IDENTITY);
self.scene.set_paint(paint);
self.scene.set_paint_transform(self.view * brush_transform.unwrap_or(Affine::IDENTITY) * paint_to_brush);
self.scene.fill_rect(&Rect::new(0., 0., self.width() as f64, self.height() as f64));
}
@@ -654,7 +612,7 @@ impl<'a> VelloSceneBuilder<'a> {
// What lies beneath, for the effects that read it, where each of the effects texture's pixels lands in it.
// Content without bounds reads nothing, as in SVG, and content reading past the scene's edges asks for the scene to be rendered grown by as much.
let reads_backdrop = (layers.reads_backdrop() || layers.content_reads_backdrop(fill)) && capture.is_none() && bounds.is_some() && self.backdrop_readable();
let reads_backdrop = layers.reads_backdrop() && capture.is_none() && bounds.is_some() && self.backdrop_readable();
if reads_backdrop && layers.reads_around_backdrop() {
// A box reaches as far along each axis of the view as its square turned into it does, and a Gaussian as far every way as its widest stretch
let readers = (effects.operations()).filter(|operation| matches!(operation, graphic_types::EffectOperation::BackgroundBlur { .. }) && !operation.changes_nothing());
@@ -740,27 +698,22 @@ impl<'a> VelloSceneBuilder<'a> {
self.scene.fill_rect(&Rect::new(0., 0., width as f64, height as f64));
}
/// Paints with `brush`, returning the transform from the paint's space into the brush's (which differ for an image drawn from a downscaled texture).
fn set_paint(&mut self, brush: SceneBrush<'_>) -> Option<Affine> {
let (paint, paint_to_brush) = match brush {
SceneBrush::Apollonian(gradient) => {
self.scene.set_pencil_gradient_paint(gradient.clone());
return Some(Affine::IDENTITY);
}
SceneBrush::Peniko(BrushRef::Solid(color)) => (PaintType::Solid(color), Affine::IDENTITY),
SceneBrush::Peniko(BrushRef::Gradient(gradient)) => (PaintType::Gradient(gradient.clone()), Affine::IDENTITY),
SceneBrush::Peniko(BrushRef::Image(image)) => {
/// The Vello GPU paint for a brush, plus the transform from the paint's space into the brush's (which differ for an image drawn from a downscaled texture).
fn paint(&mut self, brush: BrushRef<'_>) -> Option<(PaintType, Affine)> {
match brush {
BrushRef::Solid(color) => Some((PaintType::Solid(color), Affine::IDENTITY)),
BrushRef::Gradient(gradient) => Some((PaintType::Gradient(gradient.clone()), Affine::IDENTITY)),
BrushRef::Image(image) => {
let (source, texture_to_image, _) = self.image_source(SceneImage::Pixels(image.image.clone()))?;
let paint = PaintType::Image(Image {
image: source,
sampler: image.sampler,
});
(paint, texture_to_image)
Some((
PaintType::Image(Image {
image: source,
sampler: image.sampler,
}),
texture_to_image,
))
}
};
self.scene.set_paint(paint);
Some(paint_to_brush)
}
}
/// The external texture standing for an image, with the transform from its texture's pixels onto the image's own pixels and its texture's size.
@@ -1,6 +1,6 @@
use crate::{affine, color};
use core_types::list::{ATTR_POSITION, Item};
use core_types::{ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_GRADIENT_START_CURVATURE, ATTR_TRANSFORM};
use core_types::{ATTR_GRADIENT_FORM, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_TRANSFORM};
use glam::{DAffine2, DVec2};
use graphic_types::Graphic;
use graphic_types::vector_types::{Gradient, GradientForm, GradientSpace, GradientSpread};
@@ -31,9 +31,7 @@ fn paint(gradient: &usvg::BaseGradient, form: GradientForm, unit_placement: DAff
let mut item = Item::new_from_element(Gradient(stops)).with_attribute(ATTR_GRADIENT_SPACE, GradientSpace::RgbGamma);
if form != GradientForm::default() {
let [start_curvature, end_curvature] = form.curvatures();
item.set_attribute(ATTR_GRADIENT_START_CURVATURE, start_curvature);
item.set_attribute(ATTR_GRADIENT_END_CURVATURE, end_curvature);
item.set_attribute(ATTR_GRADIENT_FORM, form);
}
let spread = match gradient.spread_method() {
usvg::SpreadMethod::Pad => GradientSpread::Pad,
@@ -1,8 +1,5 @@
use core_types::list::{ATTR_APPEARANCE, Item, List};
use core_types::{
ATTR_BLEND_MODE, ATTR_EFFECTS, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_GRADIENT_START_CURVATURE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, BlendMode,
Color,
};
use core_types::{ATTR_BLEND_MODE, ATTR_EFFECTS, ATTR_GRADIENT_FORM, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, BlendMode, Color};
use glam::{DAffine2, DVec2};
use graphic_types::effects::shadow_offset;
use graphic_types::raster_types::{Image, Raster};
@@ -180,11 +177,7 @@ fn a_bounding_box_radial_gradient_on_a_wide_shape_is_placed_as_an_ellipse() -> R
let content = converted(r#"<radialGradient id="g"><stop stop-color="red"/><stop offset="1" stop-color="blue"/></radialGradient><rect width="8" height="4" fill="url(#g)"/>"#)?;
let gradient = gradient_of(&content, Cover::Fill);
let curvature = |key| gradient.and_then(|gradient| gradient.attribute::<f64>(key)).copied();
assert_eq!(
[curvature(ATTR_GRADIENT_START_CURVATURE), curvature(ATTR_GRADIENT_END_CURVATURE)],
GradientForm::Radial.curvatures().map(Some)
);
assert_eq!(gradient.and_then(|gradient| gradient.attribute::<GradientForm>(ATTR_GRADIENT_FORM)), Some(&GradientForm::Radial));
assert_eq!(
gradient.and_then(|gradient| gradient.attribute::<DAffine2>(ATTR_TRANSFORM)),
Some(&DAffine2::from_cols(DVec2::new(4., 0.), DVec2::new(0., 2.), DVec2::new(4., 2.)))
@@ -17,40 +17,6 @@ pub enum GradientForm {
Radial,
}
/// The curvatures of the linear form: both ends are lines.
pub const LINEAR_CURVATURES: [f64; 2] = [0., 0.];
/// The curvatures of the radial form: the start is a point at the center, and the end is the circle around it through the end point.
/// The point is -1 rather than 1 since animating from the linear form toward -1 keeps each circle nested in the next.
pub const RADIAL_CURVATURES: [f64; 2] = [-1., 0.5];
impl GradientForm {
/// The curvatures of the start and end contours that make this form.
pub fn curvatures(self) -> [f64; 2] {
match self {
Self::Linear => LINEAR_CURVATURES,
Self::Radial => RADIAL_CURVATURES,
}
}
/// The form these curvatures make, if either, once wrapped like [`wrapped_curvature`].
pub fn from_curvatures(curvatures: [f64; 2]) -> Option<Self> {
match curvatures.map(|curvature| wrapped_curvature(curvature, f64::NAN)) {
LINEAR_CURVATURES => Some(Self::Linear),
RADIAL_CURVATURES => Some(Self::Radial),
_ => None,
}
}
}
/// A curvature wrapped into the range starting at -1, since -1 and 1 are both the end's own point, or `preset` if it isn't finite.
pub fn wrapped_curvature(curvature: f64, preset: f64) -> f64 {
match curvature {
_ if (-1. ..1.).contains(&curvature) => curvature,
_ if curvature.is_finite() => (curvature + 1.).rem_euclid(2.) - 1.,
_ => preset,
}
}
/// A gradient's stops: a list of colors (linear, unassociated alpha) whose optional `position` and `midpoint`
/// attributes place each stop along the 0 to 1 range. Stops lacking the `position` attribute distribute evenly,
/// and stops lacking the `midpoint` attribute interpolate linearly (`0.5`).
@@ -1843,19 +1809,6 @@ impl GradientEvaluator {
}
}
#[repr(C)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Default, PartialEq, Eq, Clone, Copy, Debug, Hash, graphene_hash::CacheHash, DynAny, node_macro::ChoiceType)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[widget(Radio)]
pub enum GradientModel {
/// Draws the contours between the two ends the way SVG and other apps do, each a circle interpolated between the two end circles. Where the end circles don't nest, it leaves gaps unpainted.
#[default]
Standard,
/// Draws the contours between the two ends as a single family of circles that never cross one another, except at points they all share, and together fill the whole plane. SVG exports include it as an image, and PDF exports show an approximation.
Apollonian,
}
#[repr(C)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Default, PartialEq, Eq, Clone, Copy, Debug, Hash, graphene_hash::CacheHash, DynAny, node_macro::ChoiceType)]
@@ -2110,19 +2063,6 @@ impl core_types::bounds::BoundingBox for Gradient {
mod tests {
use super::*;
#[test]
fn curvatures_make_a_form_only_at_its_presets_once_wrapped() {
assert_eq!(GradientForm::from_curvatures([0., 0.]), Some(GradientForm::Linear));
assert_eq!(GradientForm::from_curvatures([1., 0.5]), Some(GradientForm::Radial));
assert_eq!(GradientForm::from_curvatures([-1., 0.5]), Some(GradientForm::Radial));
assert_eq!(GradientForm::from_curvatures([3., 0.5]), Some(GradientForm::Radial));
assert_eq!(GradientForm::from_curvatures([2., -2.]), Some(GradientForm::Linear));
assert_eq!(GradientForm::from_curvatures([0.5, 0.25]), None);
assert_eq!(GradientForm::from_curvatures([f64::NAN, 0.]), None);
assert_eq!(GradientForm::from_curvatures([f64::INFINITY, 0.5]), None);
}
#[test]
fn default_is_empty_and_black_to_white_is_the_artist_starting_gradient() {
assert!(Gradient::default().is_empty());
@@ -1,530 +0,0 @@
//! The Apollonian drawing of a gradient's curved end contours: the contours between them fill in as the family of circles the
//! two end contours span, which never cross except where every one of them meets, and fill the whole plane.
//!
//! Everything here is in gradient space, laid out as in [`crate::gradient_standard`]. Each member of the family is spaced by where it
//! crosses the gradient line, within the band between the end contours' crossings that lies nearest to the line's span from 0 to 1.
//! Where the band is that span, a stop at 0.3 sits where the 0.3 contour crosses the line. This reproduces the linear and radial
//! forms exactly, since their contours cross the line at a distance in proportion to their place along the ramp.
use crate::gradient_standard::{AxisRamp, Cone, GradientStandard, curvature_radius};
use glam::DVec2;
use std::f64::consts::FRAC_PI_2;
/// Stands in for a t of infinity, on the contours that cross the gradient line at infinity.
const UNBOUNDED_T: f64 = 1e6;
/// A generalized circle `a(x² + y²) + bx + c = 0` with its center on the gradient line: a circle, a line where `a` is zero,
/// or a point where it has zero radius.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct AxisCircle {
pub a: f64,
pub b: f64,
pub c: f64,
}
impl AxisCircle {
/// The contour through the start point at the origin, curved by `alpha` toward the end point.
pub fn start(alpha: f64) -> Self {
let (sin, cos) = (alpha * FRAC_PI_2).sin_cos();
Self { a: sin, b: -2. * cos, c: 0. }
}
/// The contour through the end point at (1, 0), curved by `alpha` toward the start point.
pub fn end(alpha: f64) -> Self {
let (sin, cos) = (alpha * FRAC_PI_2).sin_cos();
Self {
a: sin,
b: 2. * cos - 2. * sin,
c: sin - 2. * cos,
}
}
pub fn value(&self, point: DVec2) -> f64 {
self.a * point.length_squared() + self.b * point.x + self.c
}
/// The points where it crosses the gradient line, in homogeneous form.
fn crossings(&self) -> [Homogeneous; 2] {
solve_quadratic(self.a, self.b, self.c)
}
/// The member of the family `self·weight + other·other_weight`.
fn combine(&self, weight: f64, other: &Self, other_weight: f64) -> Self {
Self {
a: self.a * weight + other.a * other_weight,
b: self.b * weight + other.b * other_weight,
c: self.c * weight + other.c * other_weight,
}
}
}
/// A point on the gradient line in homogeneous form, `numerator / denominator`, so the point at infinity is just a zero denominator.
#[derive(Debug, Clone, Copy, PartialEq)]
struct Homogeneous {
numerator: f64,
denominator: f64,
}
impl Homogeneous {
const INFINITY: Self = Self { numerator: 1., denominator: 0. };
fn value(&self) -> Option<f64> {
(self.denominator != 0.).then(|| self.numerator / self.denominator)
}
/// Scaled so the larger of its two parts has a magnitude of 1, keeping products of points in range.
fn normalized(self) -> Self {
let scale = self.numerator.abs().max(self.denominator.abs());
if scale == 0. {
return self;
}
Self {
numerator: self.numerator / scale,
denominator: self.denominator / scale,
}
}
}
/// The roots of `a y² + b y + c = 0`, in homogeneous form so a vanishing `a` puts a root at infinity rather than dividing by zero.
fn solve_quadratic(a: f64, b: f64, c: f64) -> [Homogeneous; 2] {
let discriminant = (b * b - 4. * a * c).max(0.);
let sign = if b >= 0. { 1. } else { -1. };
let q = -0.5 * (b + sign * discriminant.sqrt());
[Homogeneous { numerator: q, denominator: a }.normalized(), Homogeneous { numerator: c, denominator: q }.normalized()]
}
/// How the crossing of a pixel's contour is told apart from the other place the same circle crosses the gradient line.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum CrossingSelection {
/// The end contours cross, so every member passes through the two points where they cross, and the gradient line is split by
/// the line through those points at `radical_x`. Each side of a member circle is its own contour, crossing the gradient line
/// on the same side of `radical_x` as the pixel.
SameSideAs { radical_x: f64 },
/// The end contours don't cross, so the members nest around two limit points that split the gradient line into two arcs, and
/// every member crosses each arc once. The crossing on the arc holding the gradient's band is the one where
/// `quadratic[0] y² + quadratic[1] y + quadratic[2]` (with `y` in homogeneous form) is smallest.
OnArc { quadratic: [f64; 3] },
}
/// Where the arc holding the band passes through infinity, the crossings beyond infinity on its other side.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Wrap {
/// A point on the gradient line between the two limit points, which separates the arc's two sides of infinity.
pub reference_x: f64,
/// Which side of `reference_x` the band is on, `1` or `-1`.
pub band_side: f64,
/// The t of the crossings on the far side of infinity.
pub t: f64,
}
/// Everything needed to find the t of any pixel in an Apollonian gradient.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GradientApollonian {
pub start: AxisCircle,
pub end: AxisCircle,
pub selection: CrossingSelection,
pub wrap: Option<Wrap>,
/// The t of a crossing at `y` is `y * t_scale + t_offset`.
pub t_scale: f64,
pub t_offset: f64,
/// What SVG draws in place of the Apollonian circles where no image the GPU renders of them can replace it.
pub svg_stand_in: GradientStandard,
}
impl GradientApollonian {
/// The parameters of the gradient with these two curvatures, which must be finite and within -1 to 1.
pub fn new(start_curvature: f64, end_curvature: f64) -> Self {
let svg_stand_in = svg_stand_in(start_curvature, end_curvature);
let start = AxisCircle::start(start_curvature);
let end = AxisCircle::end(end_curvature);
// The members of the family that are points have a zero discriminant, which as a quadratic form in the two members'
// weights has these coefficients. Its determinant says whether the family has two such points (it's hyperbolic), none
// (elliptic, where the end contours cross), or one (parabolic, where they touch).
let point_quadratic_start = start.b * start.b - 4. * start.a * start.c;
let point_quadratic_cross = start.b * end.b - 2. * (start.a * end.c + end.a * start.c);
let point_quadratic_end = end.b * end.b - 4. * end.a * end.c;
let determinant = point_quadratic_start * point_quadratic_end - point_quadratic_cross * point_quadratic_cross;
let scale = point_quadratic_start.abs().max(point_quadratic_end.abs()).max(point_quadratic_cross.abs()).max(f64::MIN_POSITIVE);
if determinant > 1e-12 * scale * scale {
// The line through the two points where the end contours cross is the member with no curvature
let line = start.combine(end.a, &end, -start.a);
let radical_x = -line.c / line.b;
return Self::with_band(start, end, CrossingSelection::SameSideAs { radical_x }, None, 0., 1., svg_stand_in);
}
// The limit points are where the point members sit, with a point member of no curvature being the point at infinity
let limit_points = point_member_weights(point_quadratic_start, point_quadratic_cross, point_quadratic_end).map(|(start_weight, end_weight)| {
let member = start.combine(start_weight, &end, end_weight);
let magnitude = member.a.abs().max(member.b.abs()).max(member.c.abs());
if member.a.abs() <= 1e-12 * magnitude {
return Homogeneous::INFINITY;
}
Homogeneous {
numerator: -member.b,
denominator: 2. * member.a,
}
.normalized()
});
// Each crossing's place relative to the limit points, negative between them and positive beyond them
let arc_quadratic = arc_quadratic(limit_points);
let arc_of = |point: Homogeneous| evaluate_homogeneous_quadratic(arc_quadratic, point.normalized());
// Find each end contour's crossing on each arc, where a point contour (a limit point itself) lies on both
let choose_on_arc = |crossings: [Homogeneous; 2], negative_arc: bool| {
crossings
.into_iter()
.min_by(|a, b| {
let (a, b) = (arc_of(*a), arc_of(*b));
if negative_arc { a.total_cmp(&b) } else { b.total_cmp(&a) }
})
.unwrap_or(Homogeneous::INFINITY)
};
let candidates = [true, false].map(|negative_arc| {
let band_start = choose_on_arc(start.crossings(), negative_arc);
let band_end = choose_on_arc(end.crossings(), negative_arc);
(negative_arc, band_start, band_end)
});
// A band through infinity would give a contour within it an infinite t, so it's unusable. On the outer arc between finite limit
// points, that's a band with its ends on opposite sides of their midpoint, which counts an end on a limit point as on its side.
let limit_values = limit_points.map(|point| point.value());
let usable = |negative_arc: bool, band_start: Homogeneous, band_end: Homogeneous| {
let (Some(band_start), Some(band_end)) = (band_start.value(), band_end.value()) else {
return false;
};
match limit_values {
[Some(first), Some(second)] if !negative_arc => {
let reference_x = (first + second) / 2.;
(band_start > reference_x) == (band_end > reference_x)
}
_ => true,
}
};
// Among the rest, prefer the band nearest to running from 0 to 1, measured continuously so the choice can't jump as a contour nears a point
let distance_from_unit_band = |&(_, band_start, band_end): &(bool, Homogeneous, Homogeneous)| {
band_start.value().map_or(f64::INFINITY, f64::abs) + band_end.value().map_or(f64::INFINITY, |band_end| (band_end - 1.).abs())
};
let chosen = candidates
.into_iter()
.filter(|&(negative_arc, band_start, band_end)| usable(negative_arc, band_start, band_end))
.min_by(|a, b| distance_from_unit_band(a).total_cmp(&distance_from_unit_band(b)))
.unwrap_or(candidates[1]);
let (negative_arc, band_start, band_end) = chosen;
// Choosing the smallest value picks the crossing on the chosen arc
let sign = if negative_arc { 1. } else { -1. };
let selection = CrossingSelection::OnArc {
quadratic: arc_quadratic.map(|coefficient| coefficient * sign),
};
let band_start = band_start.value().unwrap_or(0.);
let band_end = band_end.value().unwrap_or(1.);
// An outer arc between two finite limit points passes through infinity, beyond which its crossings belong past the band's far end
let wrap = match (negative_arc, limit_values) {
(false, [Some(first), Some(second)]) if (first - second).abs() > 0. => {
let reference_x = (first + second) / 2.;
let band_side = if band_start > reference_x { 1. } else { -1. };
let t_direction = (band_end - band_start).signum();
Some(Wrap {
reference_x,
band_side,
t: band_side * t_direction * UNBOUNDED_T,
})
}
_ => None,
};
Self::with_band(start, end, selection, wrap, band_start, band_end, svg_stand_in)
}
fn with_band(start: AxisCircle, end: AxisCircle, selection: CrossingSelection, wrap: Option<Wrap>, band_start: f64, band_end: f64, svg_stand_in: GradientStandard) -> Self {
let width = band_end - band_start;
let width = if width.abs() < 1e-12 { 1e-12_f64.copysign(width) } else { width };
Self {
start,
end,
selection,
wrap,
t_scale: 1. / width,
t_offset: -band_start / width,
svg_stand_in,
}
}
/// The gradient's t at `point` in gradient space, by the same steps the renderer's shader takes.
pub fn t(&self, point: DVec2) -> f64 {
let start_value = self.start.value(point);
let end_value = self.end.value(point);
let scale = start_value.abs().max(end_value.abs());
if scale == 0. {
return 0.;
}
let (start_value, end_value) = (start_value / scale, end_value / scale);
// The pixel's contour is the member where the end contours' values keep this ratio, which crosses the gradient line at the
// roots of this quadratic
let a = end_value * self.start.a - start_value * self.end.a;
let b = end_value * self.start.b - start_value * self.end.b;
let c = end_value * self.start.c - start_value * self.end.c;
let roots = solve_quadratic(a, b, c);
let crossing = match self.selection {
CrossingSelection::SameSideAs { radical_x } => {
// A pixel on the dividing line itself is on the line member, which crosses at the finite root
let side = |root: Homogeneous| (root.numerator - radical_x * root.denominator) * root.denominator * (point.x - radical_x);
let (first, second) = (side(roots[0]), side(roots[1]));
let first_wins = if first == second {
roots[0].denominator.abs() >= roots[1].denominator.abs()
} else {
first > second
};
if first_wins { roots[0] } else { roots[1] }
}
CrossingSelection::OnArc { quadratic } => {
if evaluate_homogeneous_quadratic(quadratic, roots[0]) <= evaluate_homogeneous_quadratic(quadratic, roots[1]) {
roots[0]
} else {
roots[1]
}
}
};
if let Some(wrap) = self.wrap
&& (crossing.numerator - wrap.reference_x * crossing.denominator) * crossing.denominator * wrap.band_side < 0.
{
return wrap.t;
}
if crossing.denominator == 0. {
let direction = crossing.numerator * self.t_scale;
return if direction == 0. { 0. } else { direction.signum() * UNBOUNDED_T };
}
crossing.numerator / crossing.denominator * self.t_scale + self.t_offset
}
}
/// SVG 2's own drawing of these curvatures where the end circles nest so it paints the whole plane, which is exact when they're concentric, or else the plain ramp.
fn svg_stand_in(start_curvature: f64, end_curvature: f64) -> GradientStandard {
let drawn = GradientStandard::new(start_curvature, end_curvature);
let (start_radius, end_radius) = (curvature_radius(start_curvature), curvature_radius(end_curvature));
let nested = if start_radius.is_finite() && end_radius.is_finite() {
Cone::between(start_radius, end_radius).is_nested()
} else {
drawn.paints_everywhere()
};
if nested { drawn } else { GradientStandard::Ramp { ramp: AxisRamp::PLAIN, keep: None } }
}
/// The weights of the two members that are points, the roots of the homogeneous quadratic form `start s² + 2·cross·s·e + end e²`.
fn point_member_weights(start: f64, cross: f64, end: f64) -> [(f64, f64); 2] {
let discriminant = (cross * cross - start * end).max(0.).sqrt();
if start.abs() < 1e-12 && end.abs() < 1e-12 {
// Both end contours are points already
[(1., 0.), (0., 1.)]
} else if start.abs() >= end.abs() {
[((-cross + discriminant) / start, 1.), ((-cross - discriminant) / start, 1.)]
} else {
[(1., (-cross + discriminant) / end), (1., (-cross - discriminant) / end)]
}
}
/// The quadratic in a homogeneous point that is negative between the two limit points and positive beyond them.
fn arc_quadratic([first, second]: [Homogeneous; 2]) -> [f64; 3] {
// (y·d₁ - n₁)(y·d₂ - n₂) with the denominators kept nonnegative, so its sign doesn't depend on how each point is scaled
let orient = |point: Homogeneous| {
if point.denominator < 0. {
Homogeneous {
numerator: -point.numerator,
denominator: -point.denominator,
}
} else {
point
}
};
let (first, second) = (orient(first), orient(second));
[
first.denominator * second.denominator,
-(first.denominator * second.numerator + first.numerator * second.denominator),
first.numerator * second.numerator,
]
}
fn evaluate_homogeneous_quadratic([a, b, c]: [f64; 3], point: Homogeneous) -> f64 {
let Homogeneous { numerator, denominator } = point;
a * numerator * numerator + b * numerator * denominator + c * denominator * denominator
}
#[cfg(test)]
mod tests {
use super::*;
use crate::gradient::{LINEAR_CURVATURES, RADIAL_CURVATURES};
use crate::gradient_standard::{GradientStandard, radius_curvature};
fn assert_close(actual: f64, expected: f64, context: &str) {
assert!((actual - expected).abs() < 1e-6, "{context}: expected {expected}, got {actual}");
}
#[test]
fn radial_curvatures_space_contours_by_radius() {
let parameters = GradientApollonian::new(RADIAL_CURVATURES[0], RADIAL_CURVATURES[1]);
for radius in [0.1, 0.3, 0.75, 1., 1.5, 4.] {
for angle in [0., 0.7, 2., 3.1, 4.5] {
let point = DVec2::from_angle(angle) * radius;
assert_close(parameters.t(point), radius, &format!("radius {radius} at angle {angle}"));
}
}
}
#[test]
fn linear_curvatures_space_contours_by_distance_along_the_line() {
let parameters = GradientApollonian::new(LINEAR_CURVATURES[0], LINEAR_CURVATURES[1]);
for point in [DVec2::new(0.25, 0.), DVec2::new(0.6, 3.), DVec2::new(-2., -7.), DVec2::new(5., 0.5)] {
assert_close(parameters.t(point), point.x, &format!("point {point}"));
}
}
#[test]
fn concentric_curvatures_draw_what_svg_2_draws() {
// End circles sharing a center, where the start circle is centered at `k` and the end circle at `1 - k`, so they're concentric when the end's `k` is 1 minus the start's
for start_radius in [-1., -0.5, 0.25, 2., 3.] {
let curvatures = [radius_curvature(start_radius), radius_curvature(1. - start_radius)];
let (apollonian, cone) = (GradientApollonian::new(curvatures[0], curvatures[1]), GradientStandard::new(curvatures[0], curvatures[1]));
for x in -30..=40 {
for y in -25..=25 {
let point = DVec2::new(x as f64 * 0.1 + 0.0013, y as f64 * 0.1 + 0.0007);
let Some(expected) = cone.t(point) else {
panic!("concentric circles with start radius {start_radius} leave {point} unpainted");
};
assert!((apollonian.t(point) - expected).abs() < 1e-6 * expected.abs().max(1.), "start radius {start_radius} at {point}");
}
}
}
}
#[test]
fn point_curvatures_space_contours_by_distance_ratio() {
let parameters = GradientApollonian::new(1., 1.);
for point in [DVec2::new(0.5, 0.), DVec2::new(0.5, 2.), DVec2::new(0.2, 0.3), DVec2::new(3., -1.)] {
// The contours are the circles of Apollonius, each crossing the line between the points at y / (1 - y) = ratio
let ratio = point.length() / (point - DVec2::X).length();
assert_close(parameters.t(point), ratio / (1. + ratio), &format!("point {point}"));
}
}
#[test]
fn curvatures_near_a_preset_render_like_it() {
let radial = GradientApollonian::new(RADIAL_CURVATURES[0], RADIAL_CURVATURES[1]);
let near_radial = GradientApollonian::new(RADIAL_CURVATURES[0] + 1e-7, RADIAL_CURVATURES[1] + 1e-7);
let linear = GradientApollonian::new(LINEAR_CURVATURES[0], LINEAR_CURVATURES[1]);
let near_linear = GradientApollonian::new(LINEAR_CURVATURES[0] + 1e-7, LINEAR_CURVATURES[1] - 1e-7);
for point in [DVec2::new(0.3, 0.2), DVec2::new(-0.5, 0.4), DVec2::new(0.9, -0.1)] {
assert!((radial.t(point) - near_radial.t(point)).abs() < 1e-4, "near radial at {point}");
assert!((linear.t(point) - near_linear.t(point)).abs() < 1e-4, "near linear at {point}");
}
}
#[test]
fn focal_gradient_pads_everywhere_outside_its_end_circle() {
// The start point sits inside the end circle, off its center
let parameters = GradientApollonian::new(1., 0.6);
assert_close(parameters.t(DVec2::X), 1., "end point");
let inside = parameters.t(DVec2::new(0.5, 0.));
assert!(inside > 0. && inside < 1., "inside: {inside}");
for point in [DVec2::new(-5., 0.), DVec2::new(-0.5, 0.), DVec2::new(5., 0.), DVec2::new(0.3, 4.), DVec2::new(-40., 30.)] {
let t = parameters.t(point);
assert!(t > 1., "outside at {point}: {t}");
}
}
#[test]
fn crossing_contours_fan_through_their_lens() {
let parameters = GradientApollonian::new(0.6, 0.6);
assert!(matches!(parameters.selection, CrossingSelection::SameSideAs { .. }));
for x in [0., 0.1, 0.25, 0.5, 0.8, 1.] {
assert_close(parameters.t(DVec2::new(x, 0.)), x, &format!("on the line at {x}"));
}
// Mirrored across the gradient line
assert_close(parameters.t(DVec2::new(0.3, 0.2)), parameters.t(DVec2::new(0.3, -0.2)), "mirror");
}
#[test]
fn every_curvature_pair_gives_a_number_everywhere() {
for start_step in -10..=10 {
for end_step in -10..=10 {
let parameters = GradientApollonian::new(start_step as f64 / 10., end_step as f64 / 10.);
for x in -8..=8 {
for y in -8..=8 {
let point = DVec2::new(x as f64 * 0.37, y as f64 * 0.41);
let t = parameters.t(point);
assert!(!t.is_nan(), "curvatures ({start_step}, {end_step}) at {point}");
}
}
}
}
}
#[test]
fn every_curvature_pair_puts_the_start_point_at_0_and_the_end_point_at_1() {
for start_step in -100..=100 {
for end_step in -100..=100 {
let (start_curvature, end_curvature) = (start_step as f64 / 100., end_step as f64 / 100.);
let parameters = GradientApollonian::new(start_curvature, end_curvature);
assert_close(parameters.t(DVec2::ZERO), 0., &format!("start point with curvatures ({start_curvature}, {end_curvature})"));
assert_close(parameters.t(DVec2::X), 1., &format!("end point with curvatures ({start_curvature}, {end_curvature})"));
}
}
}
#[test]
fn curvatures_reaching_a_line_or_a_point_change_the_gradient_continuously() {
let nudge = 1e-6;
for (curvatures, nearby_curvatures) in [
// The start crossing the line, with the end a small circle
([nudge, 0.8], [-nudge, 0.8]),
// The end crossing the line, with the start a small circle
([0.8, nudge], [0.8, -nudge]),
// The start shrinking to a point inside the end circle, on either side of its center
([1., 0.2], [1. - nudge, 0.2]),
([1., 0.6], [1. - nudge, 0.6]),
// The end shrinking to a point outside the start circle
([0.8, 1.], [0.8, 1. - nudge]),
([0.8, -1.], [0.8, -1. + nudge]),
// The start's point from either side of the curvature's wrap seam
([1. - nudge, 0.2], [-1. + nudge, 0.2]),
] {
let (parameters, nearby_parameters) = (
GradientApollonian::new(curvatures[0], curvatures[1]),
GradientApollonian::new(nearby_curvatures[0], nearby_curvatures[1]),
);
for x in -6..=10 {
for y in -8..=8 {
let point = DVec2::new(x as f64 * 0.25 + 0.013, y as f64 * 0.25 + 0.007);
// Clamped as the padded ramp draws it
let (t, nearby_t) = (parameters.t(point).clamp(0., 1.), nearby_parameters.t(point).clamp(0., 1.));
assert!(
(t - nearby_t).abs() < 1e-3,
"curvatures {curvatures:?} against {nearby_curvatures:?} at {point}: {t} against {nearby_t}"
);
}
}
}
}
}
@@ -1,820 +0,0 @@
//! Gradients with each of their two ends a contour curved between a line, a circle, and a point, drawn as SVG 2's focal radial
//! gradient (the two-point cone) between the two end circles, and extended to the settings SVG 2 can't express.
//!
//! Everything here is in gradient space, where the gradient line runs from the start point at the origin to the end point
//! at (1, 0). Each end's contour passes through its endpoint with its center on the line, and is described by its curvature
//! `α ∈ [-1, 1]`, which sets its signed radius `k = cot(απ/2)` in gradient lengths: 0 is the line perpendicular to the
//! gradient line, ±1 is the endpoint itself, and in between is a circle bowing toward (positive) or away from (negative) the
//! other endpoint. The start circle is centered at `(k₀, 0)` and the end circle at `(1 - k₁, 0)`.
//!
//! Where SVG 2 leaves the plane unpainted, so does it. A line end takes SVG 2's own limit as that end's circle flattens bowing
//! toward the other end. The Apollonian drawing of the same curvatures is in [`crate::gradient_apollonian`].
use crate::gradient::{GradientForm, GradientModel, wrapped_curvature};
use crate::gradient_apollonian::GradientApollonian;
use glam::{DAffine2, DVec2};
use std::f64::consts::FRAC_PI_2;
/// Past this radius, in gradient lengths, the cone is drawn as its own profile along the gradient line, carried straight across it.
/// Renderers draw a cone this flat wrongly in single precision (Chromium already does at 10,000), while its circles sag from straight by
/// only about `y² / 2r`, within about 0.002 of the profile.
pub const NEAR_LINE_RADIUS: f64 = 2000.;
/// The flattest an end contour other than a line is drawn, as a radius in gradient lengths, which keeps every position renderers receive within single precision's range.
/// A curvature nearer 0 than this radius allows is drawn this flat on its own side, so only a curvature of exactly 0 is a line.
const FLATTEST_RADIUS: f64 = 1e30;
/// The narrowest a ramp along the gradient line is drawn, in gradient lengths, below which it's a step from its first to its last stop.
/// Vello draws a gradient with ends closer than 10⁻⁶ as its first stop's color.
const NARROWEST_RAMP: f64 = 1e-5;
/// The signed radius of an end contour in gradient lengths for its `curvature`: infinite for a line, 0 for a point, and otherwise at most 10³⁰ in size.
pub fn curvature_radius(curvature: f64) -> f64 {
if curvature == 0. {
return f64::INFINITY;
}
if curvature.abs() == 1. {
return 0.;
}
let (sin, cos) = (curvature * FRAC_PI_2).sin_cos();
(cos / sin).clamp(-FLATTEST_RADIUS, FLATTEST_RADIUS)
}
/// The curvature of an end contour with this signed radius in gradient lengths, the inverse of [`curvature_radius`] (giving -1 for a point).
pub fn radius_curvature(radius: f64) -> f64 {
if radius == 0. { -1. } else { radius.recip().atan() / FRAC_PI_2 }
}
/// SVG 2's two-point conical gradient: circle `t` has its center and radius interpolated between the start and end circles,
/// both centered on the gradient line, for every real `t`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Cone {
pub start_center: f64,
pub start_radius: f64,
pub end_center: f64,
pub end_radius: f64,
}
impl Cone {
/// The largest `t` whose circle passes through `point` with a radius of at least 0, or `None` where SVG 2 leaves it unpainted.
pub fn t(&self, point: DVec2) -> Option<f64> {
let (delta_center, delta_radius) = (self.end_center - self.start_center, self.end_radius - self.start_radius);
let scale = delta_center * delta_center + delta_radius * delta_radius;
// The circles through `point` are the roots of `a t² - 2 b t + c`
let offset = point.x - self.start_center;
let a = delta_center * delta_center - delta_radius * delta_radius;
let b = offset * delta_center + self.start_radius * delta_radius;
let c = offset * offset + point.y * point.y - self.start_radius * self.start_radius;
let valid = |t: f64| (self.start_radius + t * delta_radius >= 0.).then_some(t);
let largest = |first: Option<f64>, second: Option<f64>| match (first, second) {
(Some(first), Some(second)) => Some(first.max(second)),
(first, second) => first.or(second),
};
// Internally tangent circles leave one finite root
if a.abs() < 1e-12 * scale {
return (b != 0.).then(|| c / (2. * b)).and_then(valid);
}
// Nested circles pass one circle through every point, which rounding mustn't lose where its two roots meet
let discriminant = b * b - a * c;
let discriminant = if a < 0. { discriminant.max(0.) } else { discriminant };
if discriminant < 0. {
return None;
}
// The roots `q / a` and `c / q`, found without the cancellation of subtracting nearly equal terms
let q = b + discriminant.sqrt().copysign(if b >= 0. { 1. } else { -1. });
let near_root = (q != 0.).then(|| c / q).and_then(valid);
largest(valid(q / a), near_root)
}
/// The cone between the end circles with these signed radii.
pub fn between(start: f64, end: f64) -> Self {
Self {
start_center: start,
start_radius: start.abs(),
end_center: 1. - end,
end_radius: end.abs(),
}
}
/// Whether its end circles are too close to tell apart, as renderers can't.
pub fn is_identical(&self) -> bool {
(self.end_center - self.start_center).abs() < 1e-6 && (self.end_radius - self.start_radius).abs() < 1e-6
}
/// Whether every point lies on a circle of the cone, which happens where one end circle lies within the other without touching it.
pub fn is_nested(&self) -> bool {
let (delta_center, delta_radius) = (self.end_center - self.start_center, self.end_radius - self.start_radius);
let a = delta_center * delta_center - delta_radius * delta_radius;
a < -1e-12 * (delta_center * delta_center + delta_radius * delta_radius)
}
}
/// A ramp along the gradient line, from `t = 0` where it crosses `x = start` to `t = 1` where it crosses `x = end`.
/// Each end is kept as exactly as it was found, and `width` (from `start` to `end`) without the cancellation of subtracting distant ends.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct AxisRamp {
pub start: f64,
pub end: f64,
pub width: f64,
}
impl AxisRamp {
pub const PLAIN: Self = Self { start: 0., end: 1., width: 1. };
pub fn new(start: f64, end: f64) -> Self {
Self { start, end, width: end - start }
}
/// Whether it's too narrow to draw as a ramp, so it's drawn as a step from its first stop's color to its last stop's at `start`.
pub fn is_step(&self) -> bool {
self.width.abs() < NARROWEST_RAMP
}
/// Its end nearer the gradient's start, as `(x, t)`, which keeps positions measured from it precise near the start.
pub fn anchor(&self) -> (f64, f64) {
if self.end.abs() < self.start.abs() { (self.end, 1.) } else { (self.start, 0.) }
}
/// The position along the ramp at `x`, or a step's first or last end's [`RampEnd::t`].
pub fn t(&self, x: f64) -> f64 {
if self.is_step() {
let after = (x - self.start) * self.width >= 0.;
return if after { RampEnd::Last.t() } else { RampEnd::First.t() };
}
let (anchor, anchor_t) = self.anchor();
anchor_t + (x - anchor) / self.width
}
}
/// The side of the line `x = at` across the gradient line that a paint is kept to, leaving the other side unpainted.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct HalfPlane {
pub at: f64,
/// Whether it keeps the side before `at` along the gradient line, rather than the side after.
pub keeps_before: bool,
}
impl HalfPlane {
pub fn keeps(&self, x: f64) -> bool {
if self.keeps_before { x < self.at } else { x > self.at }
}
}
/// One of a ramp's two end stops.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RampEnd {
First,
Last,
}
impl RampEnd {
/// The position along the ramp, past every end and repeat, that a padded ramp shows this end's color at.
pub fn t(self) -> f64 {
match self {
Self::First => f64::NEG_INFINITY,
Self::Last => f64::INFINITY,
}
}
}
/// How a gradient with curved end contours is drawn, in gradient space.
// TODO: Under the Repeat and Reflect spreads, SVG 2's limits at a line end are `max(x, 0)` at an end line and `min(x / ℓ₁, 1)` at a start line, which are drawn
// as under the Pad spread instead, then repeated or reflected. Likewise, every Apollonian circle past the family's infinity takes the phase of the finite position standing in for it.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum GradientStandard {
/// SVG 2's cone.
Cone(Cone),
/// A ramp along the gradient line, kept to `keep` if given.
Ramp { ramp: AxisRamp, keep: Option<HalfPlane> },
/// An end stop's color, kept to `keep` if given.
Solid { end: RampEnd, keep: Option<HalfPlane> },
/// A nearly flat cone's profile along the gradient line, carried straight across it: a ramp before the line across it at `split` and another after.
Profile { split: f64, before: AxisRamp, after: AxisRamp },
/// Identical end circles, which SVG 2 leaves unpainted.
Nothing,
}
impl GradientStandard {
/// How a gradient with these two curvatures is drawn.
pub fn new(start_curvature: f64, end_curvature: f64) -> Self {
let (start, end) = (curvature_radius(start_curvature), curvature_radius(end_curvature));
match (start.is_infinite(), end.is_infinite()) {
(true, true) => Self::Ramp { ramp: AxisRamp::PLAIN, keep: None },
(false, true) => Self::end_line(start, true),
(true, false) => Self::start_line(end, true),
_ if start.abs().max(end.abs()) > NEAR_LINE_RADIUS => Self::profile(start, end),
_ => Self::cone(start, end),
}
}
/// SVG 2's cone between the start and end circles with these signed radii.
fn cone(start: f64, end: f64) -> Self {
// SVG 2 paints nothing between identical circles
let cone = Cone::between(start, end);
if cone.is_identical() { Self::Nothing } else { Self::Cone(cone) }
}
/// SVG 2's cone between nearly flat end circles with these signed radii, as its profile along the gradient line carried straight across it.
/// On the line, circle `t` passes through `x` where either edge of its diameter does, each edge moving in proportion to `t`. So each side
/// of the apex, where the circles shrink to a point, takes one ramp: the larger of the edges' `t` for circles of a radius of at least 0.
fn profile(start: f64, end: f64) -> Self {
// Each edge of the circles' diameters along the gradient line runs from `2s` on the start circle to `1 - 2e` on the end circle, each
// either an end's radius or 0, and moves by `1 - 2(s + e)`, summed first so distant edges don't lose the 1 to rounding
let edge = |start_radius: f64, end_radius: f64| AxisRamp {
start: 2. * start_radius,
end: 1. - 2. * end_radius,
width: 1. - 2. * (start_radius + end_radius),
};
let left = edge(start.min(0.), end.max(0.));
let right = edge(start.max(0.), end.min(0.));
let (start_left, start_right, delta_left) = (left.start, right.start, left.width);
let growth = 2. * (end.abs() - start.abs());
// An edge that moves, with its direction, whose `t` is the cone's on the side of the apex where its circles have a radius of at least 0
let edges = [left, right].into_iter().filter(|edge| edge.width != 0.).map(|edge| (edge, edge.width));
// With equal radii there's no apex, and the edge leading in `t` leads everywhere
if growth == 0. {
let leading = edges.max_by(|(a, _), (b, _)| a.t(0.).total_cmp(&b.t(0.))).map(|(ramp, _)| ramp);
return Self::sides(0., leading, leading);
}
// After the apex, the valid edges are those moving the way the diameter grows, and the steeper in `t` leads, while before it the reverse holds
let side = |after: bool| {
let valid = edges.clone().filter(|&(_, delta)| ((delta > 0.) == (growth > 0.)) == after);
let leading = valid.max_by(|(_, a), (_, b)| {
let steeper = a.recip().total_cmp(&b.recip());
if after { steeper } else { steeper.reverse() }
});
leading.map(|(ramp, _)| ramp)
};
// The apex lies where the diameter shrinks to 0
let apex_t = -(start_right - start_left) / growth;
let apex = start_left + apex_t * delta_left;
if !apex.is_finite() || apex.abs() > FLATTEST_RADIUS {
let ramp = side(apex < 0.);
return Self::sides(0., ramp, ramp);
}
Self::sides(apex, side(false), side(true))
}
/// The ramp `before` the line across the gradient line at `split` and the one `after`, each unpainted where `None`.
fn sides(split: f64, before: Option<AxisRamp>, after: Option<AxisRamp>) -> Self {
let keep = |keeps_before| Some(HalfPlane { at: split, keeps_before });
match (before, after) {
(Some(before), Some(after)) if before == after => Self::Ramp { ramp: before, keep: None },
(Some(before), Some(after)) => Self::Profile { split, before, after },
(Some(ramp), None) => Self::Ramp { ramp, keep: keep(true) },
(None, Some(ramp)) => Self::Ramp { ramp, keep: keep(false) },
(None, None) => Self::Nothing,
}
}
/// SVG 2's limit as the end contour flattens into a line, bowing `inward` toward the start or away from it, beside the start circle of signed radius `start`.
fn end_line(start: f64, inward: bool) -> Self {
// The start circle's crossing of the gradient line that the flattening end circles meet
let crossing = if inward { (2. * start).max(0.) } else { (2. * start).min(0.) };
if (crossing - 1.).abs() < 1e-9 {
return Self::Solid {
end: RampEnd::First,
keep: Some(HalfPlane { at: 1., keeps_before: true }),
};
}
// Unpainted past the crossing, except where it falls before the end point bowing inward
Self::Ramp {
ramp: AxisRamp::new(crossing, 1.),
keep: (!inward || crossing > 1.).then_some(HalfPlane { at: crossing, keeps_before: inward }),
}
}
/// SVG 2's limit as the start contour flattens into a line, bowing `inward` toward the end or away from it, beside the end circle of signed radius `end`.
fn start_line(end: f64, inward: bool) -> Self {
// Bowing inward, the flattening start circles meet the end circle's backward crossing, or else its forward one
let crossing = if inward { (1. - 2. * end).min(1.) } else { (1. - 2. * end).max(1.) };
if inward && crossing > 0. {
return Self::Ramp {
ramp: AxisRamp::new(0., crossing),
keep: None,
};
}
// The last stop's color fills the side of the crossing that SVG 2 paints
Self::Solid {
end: RampEnd::Last,
keep: Some(HalfPlane { at: crossing, keeps_before: !inward }),
}
}
/// Whether it draws as a paint masked to one side of a line: a paint kept to that side, or a profile's two sides.
pub fn is_masked(&self) -> bool {
matches!(self, Self::Ramp { keep: Some(_), .. } | Self::Solid { keep: Some(_), .. } | Self::Profile { .. })
}
/// Whether it paints every point, rather than leaving some unpainted.
pub fn paints_everywhere(&self) -> bool {
match self {
Self::Cone(cone) => cone.is_nested(),
Self::Ramp { keep, .. } | Self::Solid { keep, .. } => keep.is_none(),
Self::Profile { .. } => true,
Self::Nothing => false,
}
}
/// The position along the ramp at `point`, or `None` where it's unpainted. An end stop's solid color is that end's [`RampEnd::t`].
pub fn t(&self, point: DVec2) -> Option<f64> {
let kept = |keep: &Option<HalfPlane>| keep.is_none_or(|keep| keep.keeps(point.x));
match self {
Self::Cone(cone) => cone.t(point),
Self::Ramp { ramp, keep } => kept(keep).then(|| ramp.t(point.x)),
Self::Solid { end, keep } => kept(keep).then(|| end.t()),
Self::Profile { split, before, after } => Some(if point.x < *split { before.t(point.x) } else { after.t(point.x) }),
Self::Nothing => None,
}
}
}
/// How a gradient's contours are laid out, decided by its curvatures and model.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum GradientShape {
/// The linear form: both ends are lines.
Linear,
/// The radial form: the start is a point at the center of the end circle.
Radial,
/// Any other curvatures, drawn as SVG 2 draws them.
Standard(GradientStandard),
/// Any other curvatures, drawn as Apollonian circles.
Apollonian(GradientApollonian),
}
impl GradientShape {
/// The shape of a gradient with these curvatures, each wrapped like [`wrapped_curvature`] and a line where it isn't finite, placed by `transform`.
/// With curvatures other than a form's, a collapsed placement (like a zero-length gradient line) leaves the last stop's color, as SVG does.
pub fn new(start_curvature: f64, end_curvature: f64, model: GradientModel, transform: DAffine2) -> Self {
let [start, end] = [start_curvature, end_curvature].map(|curvature| wrapped_curvature(curvature, 0.));
match GradientForm::from_curvatures([start, end]) {
Some(GradientForm::Linear) => Self::Linear,
Some(GradientForm::Radial) => Self::Radial,
None if !transform.matrix2.determinant().recip().is_finite() => Self::Standard(GradientStandard::Solid { end: RampEnd::Last, keep: None }),
None if model == GradientModel::Apollonian => {
// Identical end circles span no family of circles, so they draw the plain ramp
let (start_radius, end_radius) = (curvature_radius(start), curvature_radius(end));
if start_radius.is_finite() && end_radius.is_finite() && Cone::between(start_radius, end_radius).is_identical() {
return Self::Standard(GradientStandard::Ramp { ramp: AxisRamp::PLAIN, keep: None });
}
Self::Apollonian(GradientApollonian::new(start, end))
}
None => Self::Standard(GradientStandard::new(start, end)),
}
}
/// Whether its position can fall before the start, which only a radial gradient's can't since its distance from the center never goes below zero.
pub fn reaches_before_start(&self) -> bool {
!matches!(self, Self::Radial)
}
/// Whether it paints every point, rather than leaving some unpainted.
pub fn paints_everywhere(&self) -> bool {
match self {
Self::Linear | Self::Radial | Self::Apollonian(_) => true,
Self::Standard(gradient) => gradient.paints_everywhere(),
}
}
/// Whether SVG draws it exactly, which it does unless it's Apollonian circles, other than those between concentric end circles drawn as SVG 2's cone.
pub fn svg_draws_exactly(&self) -> bool {
let Self::Apollonian(GradientApollonian { start, end, svg_stand_in, .. }) = self else {
return true;
};
// Each end circle is centered at `-b / 2a`, so they share a center where these products match
let (start_product, end_product) = (start.b * end.a, end.b * start.a);
let concentric = (start_product - end_product).abs() <= 1e-9 * (start_product.abs() + end_product.abs());
concentric && matches!(svg_stand_in, GradientStandard::Cone(_))
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Points spread over a view around the gradient line, kept off its exact rational coordinates.
fn sample_points() -> impl Iterator<Item = DVec2> {
(-30..=40).flat_map(|x| (-25..=25).map(move |y| DVec2::new(x as f64 * 0.1 + 0.0013, y as f64 * 0.1 + 0.0007)))
}
/// The position a padded ramp shows, or `None` where unpainted.
fn padded(t: Option<f64>) -> Option<f64> {
t.map(|t| t.clamp(0., 1.))
}
/// SVG 2's cone written independently in its circles' crossings of the gradient line, which stays precise for huge circles:
/// circle `t` spans the diameter from `left(t)` to `right(t)`, each interpolated between the end circles' own, and counts
/// where `right(t) >= left(t)`.
fn reference_t(start: f64, end: f64, point: DVec2) -> Option<f64> {
let (start_left, start_right) = ((2. * start).min(0.), (2. * start).max(0.));
let (end_left, end_right) = ((1. - 2. * end).min(1.), (1. - 2. * end).max(1.));
let (delta_left, delta_right) = (end_left - start_left, end_right - start_right);
let scale = (delta_left * delta_left + delta_right * delta_right) / 2.;
// `(x - left(t))(x - right(t)) + y² = 0`, expanded in `t`
let a = delta_left * delta_right;
let b = -((point.x - start_left) * delta_right + (point.x - start_right) * delta_left);
let c = (point.x - start_left) * (point.x - start_right) + point.y * point.y;
let discriminant = b * b - 4. * a * c;
let roots = match (a.abs() < 1e-12 * scale, discriminant >= 0.) {
(true, _) => vec![-c / b],
(false, true) => vec![(-b + discriminant.sqrt()) / (2. * a), (-b - discriminant.sqrt()) / (2. * a)],
(false, false) => Vec::new(),
};
roots
.into_iter()
.filter(|t| (start_right - start_left) + t * (delta_right - delta_left) >= -1e-9)
.max_by(|a, b| a.total_cmp(b))
}
/// Settings for each kind of pair of end circles, given by their signed radii, with what each is.
const CONE_SETTINGS: [(f64, f64, &str); 6] = [
(0., 0.75, "focal point inside the end circle, off its center"),
(0.2, 1.5, "focal circle nested inside the end circle"),
(2., -0.5, "end circle nested inside the start circle"),
(0.6, 0.6, "crossing circles"),
(-0.3, -0.3, "separate circles"),
(0., -0.4, "focal point outside the end circle"),
];
#[test]
fn cones_take_svg_2s_largest_valid_circle() {
for (start, end, setting) in CONE_SETTINGS {
let gradient = GradientStandard::new(radius_curvature(start), radius_curvature(end));
let GradientStandard::Cone(cone) = gradient else {
panic!("{setting} should draw as a cone, not {gradient:?}");
};
let mut unpainted = 0;
for point in sample_points() {
let (expected, actual) = (reference_t(start, end, point), gradient.t(point));
match (expected, actual) {
(Some(expected), Some(actual)) => {
assert!((expected - actual).abs() < 1e-6 * expected.abs().max(1.), "{setting} at {point}: {actual} rather than {expected}");
}
(None, None) => unpainted += 1,
_ => panic!("{setting} at {point}: {actual:?} rather than {expected:?}"),
}
}
// Only circles neither inside the other leave some of the plane unpainted
assert_eq!(unpainted > 0, !cone.is_nested(), "{setting}");
}
}
#[test]
fn a_focal_point_off_center_takes_svg_2s_largest_circle() {
// The focus at the start point, and the end circle of radius 0.75 centered at 0.25
let gradient = GradientStandard::new(-1., radius_curvature(0.75));
assert!((gradient.t(DVec2::new(-0.25, 0.)).unwrap() - 0.5).abs() < 1e-12);
}
#[test]
fn line_ends_are_svg_2s_limits_from_their_side() {
const FLAT: f64 = 1e6;
// The other end's signed radius, through circles of each size and bend and a point
let others = (-20..=20).filter(|&step| step != 0).map(|step| curvature_radius(step as f64 * 0.049)).chain([0.]);
for other in others {
for inward in [true, false] {
let flat = if inward { FLAT } else { -FLAT };
for (limit, [start, end], which) in [
(GradientStandard::end_line(other, inward), [other, flat], "end"),
(GradientStandard::start_line(other, inward), [flat, other], "start"),
] {
let cut = match limit {
GradientStandard::Ramp { keep, .. } | GradientStandard::Solid { keep, .. } => keep,
_ => panic!("an {which} line should draw as a ramp or solid color, not {limit:?}"),
};
for point in sample_points() {
// The cone's unpainted edge nears the cut line at a rate of the square root of its radius
if cut.is_some_and(|cut| (point.x - cut.at).abs() < 0.02) {
continue;
}
let (expected, actual) = (padded(reference_t(start, end, point)), padded(limit.t(point)));
let context = format!("{which} line bowing inward {inward}, beside radius {other} at {point}");
match (expected, actual) {
(Some(expected), Some(actual)) => assert!((expected - actual).abs() < 0.01, "{context}: {actual} rather than {expected}"),
(None, None) => {}
_ => panic!("{context}: {actual:?} rather than {expected:?}"),
}
}
}
}
}
}
#[test]
fn the_line_settings_take_the_chosen_limits() {
// Both lines, and an end line beside a start bowing away from it, are the plain ramp
assert_eq!(GradientStandard::new(0., 0.), GradientStandard::Ramp { ramp: AxisRamp::PLAIN, keep: None });
assert_eq!(GradientStandard::new(-0.3, 0.), GradientStandard::Ramp { ramp: AxisRamp::PLAIN, keep: None });
// An end line beside a start circle reaching past the end point is cut off past the start circle's far crossing
let start = 0.8;
let GradientStandard::Ramp { ramp, keep: Some(keep) } = GradientStandard::new(radius_curvature(start), 0.) else {
panic!("an end line beyond a large start circle should be cut off");
};
assert!((ramp.start - 2. * start).abs() < 1e-12 && ramp.end == 1.);
assert!(keep.keeps_before && (keep.at - 2. * start).abs() < 1e-12);
// A start line takes the ramp to the end circle's backward crossing, or the last stop past that crossing once the end circle reaches the start point
let GradientStandard::Ramp { ramp, keep: None } = GradientStandard::new(0., radius_curvature(0.25)) else {
panic!("a start line beside a small end circle should be a ramp");
};
assert!(ramp.start == 0. && (ramp.end - 0.5).abs() < 1e-12);
let GradientStandard::Solid { end: RampEnd::Last, keep: Some(keep) } = GradientStandard::new(0., radius_curvature(2.)) else {
panic!("a start line beside an end circle reaching the start point should be the last stop");
};
assert!(!keep.keeps_before && (keep.at + 3.).abs() < 1e-12);
}
#[test]
fn nearly_flat_cones_draw_their_profile_along_the_line() {
let settings = [
(0.3, 2500.),
(0.3, -2500.),
(2500., 0.2),
(-2500., 0.2),
(-0.4, 3000.),
(0., -2200.),
// Both ends nearly flat: equal radii bowing apart and together, and an apex before the start at x = -3
(-3000., 3000.),
(3000., -3000.),
(3000., -4000.),
];
for (start, end) in settings {
let profile = GradientStandard::new(radius_curvature(start), radius_curvature(end));
let split = match profile {
GradientStandard::Profile { split, .. } => Some(split),
GradientStandard::Ramp { keep, .. } => keep.map(|keep| keep.at),
GradientStandard::Nothing => None,
_ => panic!("({start}, {end}) should draw as its profile, not {profile:?}"),
};
// Within a level or two of the cone itself, except beside the apex, where the cone's circles are small and its edges lean
for point in sample_points() {
if split.is_some_and(|split| (point.x - split).abs() < 0.05 + 0.05 * point.y.abs()) {
continue;
}
let (expected, actual) = (padded(reference_t(start, end, point)), padded(profile.t(point)));
let context = format!("({start}, {end}) at {point}");
match (expected, actual) {
(Some(expected), Some(actual)) => assert!((expected - actual).abs() < 0.01, "{context}: {actual} rather than {expected}"),
(None, None) => {}
_ => panic!("{context}: {actual:?} rather than {expected:?}"),
}
}
}
// Codex's example, where the last stop shows everywhere
let both_flat = GradientStandard::new(radius_curvature(-3000.), radius_curvature(3000.));
assert_eq!(padded(both_flat.t(DVec2::new(0.5, 0.2))), Some(1.));
}
#[test]
fn the_profile_of_a_flattening_end_nears_the_line_limits() {
const FLAT: f64 = 1e9;
// The other end's signed radius, through circles of each size and bend and a point, and the start circle reaching the end point
let others = (-20..=20).filter(|&step| step != 0).map(|step| curvature_radius(step as f64 * 0.049)).chain([0., 0.5]);
for other in others {
for inward in [true, false] {
let flat = if inward { FLAT } else { -FLAT };
for (limit, profile, which) in [
(GradientStandard::end_line(other, inward), GradientStandard::profile(other, flat), "end"),
(GradientStandard::start_line(other, inward), GradientStandard::profile(flat, other), "start"),
] {
let cuts = [limit, profile].map(|gradient| match gradient {
GradientStandard::Ramp { keep, .. } | GradientStandard::Solid { keep, .. } => keep.map(|keep| keep.at),
GradientStandard::Profile { split, .. } => Some(split),
_ => None,
});
for point in sample_points() {
if cuts.iter().flatten().any(|cut| (point.x - cut).abs() < 1e-3) {
continue;
}
let (expected, actual) = (padded(limit.t(point)), padded(profile.t(point)));
let context = format!("{which} line bowing inward {inward}, beside radius {other} at {point}");
match (expected, actual) {
(Some(expected), Some(actual)) => assert!((expected - actual).abs() < 1e-6, "{context}: {actual} rather than {expected}"),
(None, None) => {}
_ => panic!("{context}: {actual:?} rather than {expected:?}"),
}
}
}
}
}
}
#[test]
fn an_end_line_through_a_start_circle_reaching_the_end_point_shows_the_first_stop() {
let before_end_point = Some(HalfPlane { at: 1., keeps_before: true });
assert_eq!(
GradientStandard::end_line(0.5, true),
GradientStandard::Solid {
end: RampEnd::First,
keep: before_end_point
}
);
let profile = GradientStandard::profile(0.5, 1e9);
for point in sample_points().filter(|point| (point.x - 1.).abs() > 1e-3) {
let t = padded(profile.t(point));
assert!(if point.x < 1. { t.is_some_and(|t| t < 1e-6) } else { t.is_none() }, "at {point}: {t:?}");
}
}
#[test]
fn internally_tangent_circles_leave_the_far_side_of_their_tangent_line_unpainted() {
// The start circle of radius 1 and the end circle of radius 0.5 touch at the start point
let gradient = GradientStandard::new(radius_curvature(1.), radius_curvature(0.5));
assert_eq!(gradient.t(DVec2::new(-1., 0.)), None);
assert!(gradient.t(DVec2::new(0.5, 0.)).is_some_and(|t| (t - 1.5).abs() < 1e-12));
}
#[test]
fn nearly_flat_cones_keep_their_ramps_ends_and_widths() {
// Equal radii of a million ramp from 2 million to the end point, reaching 1 exactly there so the Clear spread clears past it
let gradient = GradientStandard::profile(1e6, 1e6);
assert!((gradient.t(DVec2::new(0.75, 0.)).unwrap() - (1. + 0.25 / 1_999_999.)).abs() < 1e-15);
assert_eq!(gradient.t(DVec2::X), Some(1.));
// A ramp a gradient length wide, 200,000 gradient lengths before the start, stays a ramp
let gradient = GradientStandard::profile(-1e5, 1e5);
assert!((gradient.t(DVec2::new(-199_999.5, 0.)).unwrap() - 0.5).abs() < 1e-9);
// Opposite radii of 10¹⁶ keep the 1 that their distant edges differ by, which makes the start's edge lead
let at = DVec2::new(0.5, 0.);
assert!((GradientStandard::profile(-1e16, 1e16).t(at).unwrap() - (2e16 + 0.5)).abs() < 4.);
assert!((GradientStandard::profile(1e16, -1e16).t(at).unwrap() - 0.5).abs() < 1e-12);
}
#[test]
fn extreme_curvatures_compute_finitely() {
// Curvatures so near a line that their radii overflow when doubled, and either side of radii of 10³⁰ gradient lengths
let extremes = [4e-309, -4e-309, 1e-300, 6e-31, -6e-31, 7e-31, -7e-31, 1e-17, -1e-17];
let curvatures = extremes.iter().flat_map(|&extreme| {
[
[extreme, 0.],
[0., extreme],
[extreme, 0.3],
[-0.3, extreme],
[extreme, extreme],
[extreme, -extreme],
[extreme, 1. - 1e-16],
]
});
for [start, end] in curvatures {
let gradient = GradientStandard::new(start, end);
for point in sample_points() {
// A position may be an end stop's infinity but not a number lost to overflow
let t = gradient.t(point);
assert!(t.is_none_or(|t| !t.is_nan()), "curvatures ({start}, {end}) at {point}: {gradient:?}");
}
}
assert_eq!((curvature_radius(4e-309), curvature_radius(-4e-309)), (FLATTEST_RADIUS, -FLATTEST_RADIUS));
}
#[test]
fn curvatures_beside_zero_keep_their_side() {
// Beside a start circle reaching past the midpoint, an end flattening from either side nears a different limit than the line
let start = radius_curvature(0.4);
for side in [1., -1.] {
let beside_zero = GradientStandard::new(start, side * 1e-40);
let flattening = GradientStandard::new(start, radius_curvature(side * 1e20));
for point in sample_points() {
let (expected, actual) = (padded(flattening.t(point)), padded(beside_zero.t(point)));
let context = format!("end curvature beside 0 on side {side} at {point}");
match (expected, actual) {
(Some(expected), Some(actual)) => assert!((expected - actual).abs() < 1e-6, "{context}: {actual} rather than {expected}"),
(None, None) => {}
_ => panic!("{context}: {actual:?} rather than {expected:?}"),
}
}
}
}
#[test]
fn identical_circles_leave_nothing() {
let curvature = radius_curvature(0.5);
assert_eq!(GradientStandard::new(curvature, curvature), GradientStandard::Nothing);
}
#[test]
fn the_radial_preset_draws_distance_from_its_center() {
let gradient = GradientStandard::new(-1., 0.5);
for point in sample_points() {
let t = gradient.t(point).unwrap();
assert!((t - point.length()).abs() < 1e-9, "at {point}: {t}");
}
}
#[test]
fn a_zero_length_gradient_line_leaves_the_last_stop_once_curved() {
let collapsed = DAffine2::from_cols(DVec2::ZERO, DVec2::Y, DVec2::new(3., 4.));
for model in [GradientModel::Standard, GradientModel::Apollonian] {
let shape = |[start, end]: [f64; 2]| GradientShape::new(start, end, model, collapsed);
assert_eq!(shape([0.3, 0.2]), GradientShape::Standard(GradientStandard::Solid { end: RampEnd::Last, keep: None }));
// The forms keep drawing as they always have
assert_eq!(shape([0., 0.]), GradientShape::Linear);
assert_eq!(shape([-1., 0.5]), GradientShape::Radial);
}
}
#[test]
fn apollonian_gradients_stand_in_for_svg_with_its_own_drawing_where_that_paints_everywhere() {
let placement = DAffine2::IDENTITY;
let stand_in = |curvatures: [f64; 2]| match GradientShape::new(curvatures[0], curvatures[1], GradientModel::Apollonian, placement) {
GradientShape::Apollonian(apollonian) => apollonian.svg_stand_in,
shape => panic!("curvatures {curvatures:?} should draw Apollonian circles, not {shape:?}"),
};
// Concentric end circles draw SVG 2's own drawing, a cone or for huge ones its profile, while crossing ones draw the plain ramp however flat they are
let plain_ramp = GradientStandard::Ramp { ramp: AxisRamp::PLAIN, keep: None };
for concentric in [[radius_curvature(2.), radius_curvature(-1.)], [radius_curvature(3000.), radius_curvature(-2999.)]] {
let drawn = GradientStandard::new(concentric[0], concentric[1]);
assert!(drawn.paints_everywhere(), "{drawn:?}");
assert_eq!(stand_in(concentric), drawn);
}
for crossing in [0.6, 3000.] {
assert_eq!(stand_in([radius_curvature(crossing), radius_curvature(crossing)]), plain_ramp, "radii of {crossing}");
}
// Identical end circles span no family of circles, so they draw the plain ramp everywhere
let identical = radius_curvature(0.5);
assert_eq!(GradientShape::new(identical, identical, GradientModel::Apollonian, placement), GradientShape::Standard(plain_ramp));
// The forms stay native under either model
assert_eq!(GradientShape::new(0., 0., GradientModel::Apollonian, placement), GradientShape::Linear);
assert_eq!(GradientShape::new(-1., 0.5, GradientModel::Apollonian, placement), GradientShape::Radial);
}
#[test]
fn svg_draws_every_shape_exactly_but_apollonian_circles_it_cant_draw_as_a_cone() {
let exact = |curvatures: [f64; 2], model: GradientModel| GradientShape::new(curvatures[0], curvatures[1], model, DAffine2::IDENTITY).svg_draws_exactly();
// Concentric end circles, the start centered at its radius and the end at 1 minus its own, have Apollonian circles that are SVG 2's cone
for [start, end] in [[2., -1.], [-0.5, 1.5], [0.25, 0.75]] {
let curvatures = [radius_curvature(start), radius_curvature(end)];
assert!(matches!(
GradientShape::new(curvatures[0], curvatures[1], GradientModel::Apollonian, DAffine2::IDENTITY),
GradientShape::Apollonian(_)
));
assert!(exact(curvatures, GradientModel::Apollonian), "radii {start} and {end}");
}
// Crossing, nested off center, a line beside a circle, a point beside a circle, and concentric ones so large SVG draws them by their profile
let off_center = [
[radius_curvature(0.6), radius_curvature(0.6)],
[radius_curvature(2.), radius_curvature(-0.5)],
[0., radius_curvature(0.5)],
[1., 0.3],
];
for curvatures in off_center.into_iter().chain([[radius_curvature(3000.), radius_curvature(-2999.)]]) {
assert!(!exact(curvatures, GradientModel::Apollonian), "curvatures {curvatures:?}");
assert!(exact(curvatures, GradientModel::Standard), "curvatures {curvatures:?} drawn as SVG 2 draws them");
}
// The forms stay native under either model
assert!(exact([0., 0.], GradientModel::Apollonian) && exact([-1., 0.5], GradientModel::Apollonian));
}
#[test]
fn radius_curvatures_invert_curvature_radii() {
for curvature in [-0.9, -0.5, -0.1, 0.1, 0.5, 0.9] {
assert!((radius_curvature(curvature_radius(curvature)) - curvature).abs() < 1e-12);
}
assert_eq!(curvature_radius(radius_curvature(0.)), 0.);
}
}
+1 -3
View File
@@ -2,14 +2,12 @@
extern crate log;
pub mod gradient;
pub mod gradient_apollonian;
pub mod gradient_standard;
pub mod math;
pub mod vector;
// Re-export commonly used types at the crate root
pub use core_types as gcore;
pub use gradient::{Gradient, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStop};
pub use gradient::{Gradient, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStop};
pub use math::QuadExt;
pub use vector::Vector;
pub use vector::reference_point::ReferencePoint;
@@ -3,6 +3,7 @@ use crate::vector::flatten::WorkingVector;
use crate::vector::misc::{BezierHandles, HandleId, HandleType};
use crate::vector::path::{CurveType, Path, curve_types_of};
use core_types::list::{ATTR_ID, List};
use core_types::uuid::generate_uuid;
use dyn_any::DynAny;
use glam::DVec2;
use rustc_hash::{FxHashMap, FxHashSet};
@@ -1085,49 +1086,16 @@ impl VectorModification {
}
}
// Hash sets and maps are hashed in key order, so equal modifications hash equally regardless of iteration order
impl graphene_hash::CacheHash for PointModification {
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.add.cache_hash(state);
sorted_set(&self.remove).cache_hash(state);
sorted_map(&self.delta).cache_hash(state);
}
}
impl graphene_hash::CacheHash for SegmentModification {
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.add.cache_hash(state);
sorted_set(&self.remove).cache_hash(state);
sorted_map(&self.start_point).cache_hash(state);
sorted_map(&self.end_point).cache_hash(state);
sorted_map(&self.handle_primary).cache_hash(state);
sorted_map(&self.handle_end).cache_hash(state);
}
}
// Intentionally non-deterministic: fields contain HashMaps with non-deterministic iteration order,
// so we use a UUID to always bust the cache and force re-evaluation when any modification is present.
// This will not actually lead to a cache invalidation in most cases due to the
// graph inputs being wrapped in a `MemoHash` wrapper.
impl graphene_hash::CacheHash for VectorModification {
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.points.cache_hash(state);
self.segments.cache_hash(state);
sorted_set(&self.add_g1_continuous).cache_hash(state);
sorted_set(&self.remove_g1_continuous).cache_hash(state);
sorted_set(&self.path_breaks).cache_hash(state);
sorted_set(&self.turned_on_load).cache_hash(state);
core::hash::Hash::hash(&generate_uuid(), state);
}
}
fn sorted_set<T: Ord>(set: &HashSet<T>) -> Vec<&T> {
let mut items: Vec<_> = set.iter().collect();
items.sort_unstable();
items
}
fn sorted_map<K: Ord, V>(map: &HashMap<K, V>) -> Vec<(&K, &V)> {
let mut entries: Vec<_> = map.iter().collect();
entries.sort_unstable_by_key(|&(key, _)| key);
entries
}
// TODO: Do we want to enforce that all serialized/deserialized hashmaps are a vec of tuples?
// TODO: Eventually remove this document upgrade code
/// Serializes as sorted `[[key, value], ...]` (sequence of pairs)
@@ -1295,23 +1263,6 @@ mod tests {
format!("{anchors:?}\n{segments:?}\n{strokes:?}\n{pairs:?}")
}
fn cache_hash(modification: &VectorModification) -> u64 {
let mut hasher = std::hash::DefaultHasher::new();
graphene_hash::CacheHash::cache_hash(modification, &mut hasher);
std::hash::Hasher::finish(&hasher)
}
#[test]
fn equal_modifications_hash_equally() {
let (vector, paths) = mixed_geometry();
let first = VectorModification::create_from_vector(&vector, &paths);
let second = VectorModification::create_from_vector(&vector, &paths);
assert_eq!(cache_hash(&first), cache_hash(&first));
assert_eq!(cache_hash(&first), cache_hash(&second));
}
/// Every curve type, a weld where they change, a smooth anchor, and a second subpath.
fn mixed_geometry() -> (Vector, List<Path>) {
let mut bezpath = BezPath::new();
@@ -1630,11 +1630,7 @@ fn blend_lighten(c_b: f32, c_s: f32) -> f32 {
return max(c_s, c_b);
}
// A black backdrop stays black, and any other turns white under a white source, as the W3C formula orders them
fn blend_color_dodge(c_b: f32, c_s: f32) -> f32 {
if abs(c_b) <= BLEND_EDGE_TOLERANCE {
return 0.;
}
if abs(c_s - 1.) <= BLEND_EDGE_TOLERANCE {
return 1.;
}
@@ -1730,8 +1726,7 @@ fn blend_channel(mode: u32, c_b: f32, c_s: f32) -> f32 {
return blend_pin_light(c_b, c_s);
}
case BLEND_HARD_MIX: {
// A ramp a 256th wide around where the channels sum to 1, matching `blend_hard_mix`
return (c_b - 255. / 256. * (1. - c_s)) * 256.;
return select(1., 0., blend_linear_light(c_b, c_s) < 0.5);
}
case BLEND_DIFFERENCE: {
return abs(c_b - c_s);
@@ -1756,11 +1751,11 @@ fn blend_channel(mode: u32, c_b: f32, c_s: f32) -> f32 {
fn apply_blend_mode(foreground: vec4<f32>, background: vec4<f32>, mode: u32) -> vec4<f32> {
switch mode {
case BLEND_DARKER_COLOR: {
let background_is_darker = luma_rec_601_rounded(background.rgb) <= luma_rec_601_rounded(foreground.rgb);
let background_is_darker = (background.r + background.g + background.b) / 3. <= (foreground.r + foreground.g + foreground.b) / 3.;
return vec4<f32>(select(foreground.rgb, background.rgb, background_is_darker), foreground.a);
}
case BLEND_LIGHTER_COLOR: {
let background_is_lighter = luma_rec_601_rounded(background.rgb) >= luma_rec_601_rounded(foreground.rgb);
let background_is_lighter = (background.r + background.g + background.b) / 3. >= (foreground.r + foreground.g + foreground.b) / 3.;
return vec4<f32>(select(foreground.rgb, background.rgb, background_is_lighter), foreground.a);
}
case BLEND_HUE, BLEND_SATURATION, BLEND_COLOR, BLEND_LUMINOSITY: {
@@ -21,7 +21,6 @@ use wgpu::util::DeviceExt;
mod blend_if;
mod filters;
mod layer_blend;
mod masks;
mod resample;
mod styles;
@@ -168,7 +167,7 @@ impl EffectPasses {
log::warn!("This GPU can't render into the formats layer effects need, so content draws without its effects");
}
// The filters', resampling, styles', masks', Blend If's, and layer blending's passes live in files of their own, sharing this one's bindings and helpers
// The filters', resampling, styles', masks', and Blend If's passes live in files of their own, sharing this one's bindings and helpers
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("vello_effects.wgsl"),
source: wgpu::ShaderSource::Wgsl(
@@ -180,8 +179,7 @@ impl EffectPasses {
include_str!("vello_warp.wgsl"),
include_str!("vello_styles.wgsl"),
include_str!("vello_masks.wgsl"),
include_str!("vello_blend_if.wgsl"),
include_str!("vello_layer_blend.wgsl")
include_str!("vello_blend_if.wgsl")
)
.into(),
),
@@ -265,8 +263,7 @@ impl EffectPasses {
.clone()
}
/// Carries out `effects` on `content`, a texture of premultiplied pixels, returning each of the `layers` they draw in a pooled texture of [`WORKING_FORMAT`] the same size, with the mode it blends by
/// (normal for one in a mode Vello's layers lack, which comes back blended onto the `backdrop` already).
/// Carries out `effects` on `content`, a texture of premultiplied pixels, returning each of the `layers` they draw in a pooled texture of [`WORKING_FORMAT`] the same size, with the mode it blends by.
/// `effect_to_pixels` places the effects' space on the texture's pixels, `fill` fades the content but not the shadows and glows cast from it, and `opacity` fades the layers.
/// The `frame`, in the texture's pixels, is the content's extent, which displacements take as their own.
/// `paints` holds the effects' drawn paints in order, each rendered over the same pixels as the content.
@@ -300,16 +297,6 @@ impl EffectPasses {
let lengths_to_pixels = effect_to_pixels.matrix2;
let length_scale = lengths_to_pixels.determinant().abs().sqrt();
// A fill moving the content toward its layer mode's neutral color leaves the content at full strength, for its layer to blend by that fill.
// Color Dodge and Color Burn layers blend so only where they read what lies beneath (see `EffectLayers::content_reads_backdrop`), and with nothing to read, natively.
let content_mode = layers.content_layer().map(|layer| layers.layers[layer].blend_mode);
let natively_otherwise = content_mode.is_some_and(|blend_mode| !blend_mode.reads_backdrop());
let content_blends_onto_backdrop = layers.content_reads_backdrop(fill) && !(natively_otherwise && backdrop.is_none());
let (fill, blend_fill) = match content_blends_onto_backdrop && content_mode.is_some_and(|blend_mode| blend_mode.fill_moves_layer_toward_neutral()) {
true => (1., fill),
false => (fill, 1.),
};
// The content at full strength, which casts every silhouette, read from the content itself (whatever its format) until a pass replaces it
let mut full: Option<wgpu::Texture> = None;
// The content faded by the fill, which shows in the result
@@ -845,7 +832,7 @@ impl EffectPasses {
| EffectOperation::MinimumMaximum { .. }
| EffectOperation::Sharpen { .. }
| EffectOperation::HighPass { .. }
| EffectOperation::Speckle { .. }
| EffectOperation::AddNoise { .. }
| EffectOperation::Dissolve { .. } => {
recorder.merge_beneath(content, &mut full, &mut filled, beneath.take());
let captured_plane = capture.filter(|capture| capture.index == index).map(|capture| capture.plane);
@@ -1143,7 +1130,7 @@ impl EffectPasses {
// Each layer stacks its parts in order: what lies beneath the content, then the content with what lies within it
let mut content_image = Some(content_image);
let (mut results, mut content_result) = (Vec::new(), None);
let mut results = Vec::new();
for (index, layer) in layers.layers.iter().enumerate() {
let holds_content = Some(index) == content_layer;
let mut stack = if holds_content { beneath.take() } else { None };
@@ -1212,16 +1199,9 @@ impl EffectPasses {
let faded = recorder.run("apply_mask", WORKING_FORMAT, recorder.size, &result, Some(fade), None, Parameters::default());
recorder.replace(&mut result, faded);
}
if holds_content {
content_result = Some(results.len());
}
results.push((result, layer.blend_mode));
}
// A layer in a mode Vello's layers lack blends onto what lies beneath here, before the Blend Ifs fade the blended layer
let content_result = content_result.filter(|_| content_blends_onto_backdrop);
recorder.blend_onto_backdrop(backdrop, blend_fill, content_result, &mut results);
// Blend If's ranges of what lies beneath fade every layer, like the opacity varying across them
let underlying = underlying_ranges(&every_operation);
if let Some(backdrop) = backdrop.filter(|_| !underlying.is_empty()) {
@@ -431,13 +431,14 @@ fn composite_beneath(@builtin(position) position: vec4<f32>) -> @location(0) vec
// The paint mixed with the backdrop by a blend mode besides the component ones, numbered in the order `BlendMode` declares them
fn blend(backdrop: vec3<f32>, paint: vec3<f32>, mode: u32) -> vec3<f32> {
let average = vec3<f32>(1. / 3.);
switch mode {
// Darker Color and Lighter Color keep whichever whole color has the lower or higher luma, the backdrop where they tie
// Darker Color and Lighter Color keep whichever whole color has the lower or higher mean
case 5u: {
return select(paint, backdrop, luma(backdrop) <= luma(paint));
return select(paint, backdrop, dot(backdrop, average) <= dot(paint, average));
}
case 10u: {
return select(paint, backdrop, luma(backdrop) >= luma(paint));
return select(paint, backdrop, dot(backdrop, average) >= dot(paint, average));
}
default: {
return vec3<f32>(blend_channel(backdrop.r, paint.r, mode), blend_channel(backdrop.g, paint.g, mode), blend_channel(backdrop.b, paint.b, mode));
@@ -503,7 +504,7 @@ fn blend_channel(backdrop: f32, paint: f32, mode: u32) -> f32 {
result = select(max(2. * paint - 1., backdrop), min(2. * paint, backdrop), paint <= 0.5);
}
case 17u: {
result = hard_mix(backdrop, paint, 1.);
result = select(1., 0., linear_light(backdrop, paint) < 0.5);
}
// Difference, Exclusion, Subtract, Divide
case 18u: {
@@ -544,11 +545,7 @@ fn color_burn(backdrop: f32, paint: f32) -> f32 {
return 1. - min((1. - backdrop) / paint, 1.);
}
// A black backdrop stays black, and any other turns white under white paint, as the W3C formula orders them
fn color_dodge(backdrop: f32, paint: f32) -> f32 {
if abs(backdrop) <= BLEND_EDGE_TOLERANCE {
return 0.;
}
if abs(paint - 1.) <= BLEND_EDGE_TOLERANCE {
return 1.;
}
@@ -571,12 +568,6 @@ fn linear_light(backdrop: f32, paint: f32) -> f32 {
return select(2. * paint - 1. + backdrop, 2. * paint + backdrop - 1., paint <= 0.5);
}
// Hard Mix of a paint at `strength`, unclamped, whose ramp steepens to a 256th wide at full strength, matching the CPU's `blend_hard_mix_at_strength`
fn hard_mix(backdrop: f32, paint: f32, strength: f32) -> f32 {
let steepness = 255. * strength / 256.;
return (backdrop - steepness * (1. - paint)) / (1. - steepness);
}
// Hue, Saturation, Color, and Luminosity on gamma-encoded channels, as the compositing specification constructs them
fn blend_components(backdrop: vec3<f32>, paint: vec3<f32>, mode: u32) -> vec3<f32> {
switch mode {
@@ -50,7 +50,7 @@ pub(super) fn field_parameters(sampling: &FieldSampling, first_seed: u32, second
fn field_passes(operation: &EffectOperation, effect_to_pixels: DAffine2) -> Option<(&'static str, &'static str, Parameters)> {
let sampling = FieldSampling::new(effect_to_pixels.inverse());
match *operation {
EffectOperation::Speckle {
EffectOperation::AddNoise {
amount,
distribution,
monochromatic,
@@ -67,7 +67,7 @@ fn field_passes(operation: &EffectOperation, effect_to_pixels: DAffine2) -> Opti
],
..field_parameters(&sampling, RandomField::NoiseOffsets.seed(seed), RandomField::NoiseAngles.seed(seed))
};
Some(("speckle_map", "speckle", parameters))
Some(("noise_map", "add_noise", parameters))
}
EffectOperation::Dissolve { opacity, seed } => {
let parameters = Parameters {
@@ -412,7 +412,7 @@ fn sample_offset(column: u32, row: u32) -> vec2<f32> {
return ((vec2<f32>(f32(column), f32(row)) + 0.5) / parameters.taps[2].xy - 0.5) * parameters.taps[2].zw;
}
// The offsets Speckle gives a texel's colors, matching the CPU's `speckle`: its noise averaged over its samples (Gaussian with `values.z` 1), the same for every color with `values.w` 1,
// The offsets Add Noise gives a texel's colors, matching the CPU's `add_noise`: its noise averaged over its samples (Gaussian with `values.z` 1), the same for every color with `values.w` 1,
// scaled by `values.x` and kept within `values.y` either way
fn noise_offsets(position: vec2<f32>) -> vec3<f32> {
let counts = sample_counts();
@@ -439,15 +439,15 @@ fn noise_offsets(position: vec2<f32>) -> vec3<f32> {
return clamp(noise * parameters.values.x, vec3<f32>(-parameters.values.y), vec3<f32>(parameters.values.y));
}
// The offsets Speckle gives each color, around middle gray and scaled to fill the range, which an SVG adds to the colors
// The offsets Add Noise gives each color, around middle gray and scaled to fill the range, which an SVG adds to the colors
@fragment
fn speckle_map(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
fn noise_map(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
return vec4<f32>(0.5 + noise_offsets(position.xy) / (2. * parameters.values.y), 1.);
}
// Each straight color offset by noise and clamped, with the coverage kept
@fragment
fn speckle(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
fn add_noise(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
let color = textureLoad(source, vec2<i32>(position.xy), 0);
if color.a <= 0. {
return vec4<f32>(0.);
@@ -1,40 +0,0 @@
//! The GPU pass blending a layer by a mode Vello's layers lack, onto what lies beneath it, matching the CPU's `blend_layer_pixel` and SVG's layers built from native compositing.
use super::{Parameters, PassRecorder, WORKING_FORMAT};
use core_types::blending::BlendMode;
use vello_gpu::kurbo::Affine;
impl PassRecorder<'_> {
/// Blends onto the scene's `backdrop` each layer's image in `results` whose mode reads what lies beneath (see [`BlendMode::reads_backdrop`]), and the `content` one if it reads it at its fill,
/// leaving what it then draws normally. The `fill` moves only the content toward its mode's neutral color (see [`BlendMode::fill_moves_layer_toward_neutral`]). Without a backdrop, nothing lies beneath.
pub(super) fn blend_onto_backdrop(&mut self, backdrop: Option<(&wgpu::Texture, Affine)>, fill: f32, content: Option<usize>, results: &mut [(wgpu::Texture, BlendMode)]) {
for (index, (image, blend_mode)) in results.iter_mut().enumerate() {
let holds_content = Some(index) == content;
if !holds_content && !blend_mode.reads_backdrop() {
continue;
}
let strength = if holds_content && blend_mode.fill_moves_layer_toward_neutral() { fill } else { 1. };
match backdrop {
Some((backdrop, placement)) => {
let placed = Parameters::placed_in_backdrop(placement);
let [x, y, ..] = placed.values;
let parameters = Parameters {
values: [x, y, *blend_mode as u32 as f32, strength],
..placed
};
let blended = self.run("blend_onto_backdrop", WORKING_FORMAT, self.size, backdrop, Some(image), None, parameters);
self.replace(image, blended);
}
// Over nothing, the layer shows as it is, faded by a fill it would otherwise move toward neutral
None if strength < 1. => {
let faded = self.scale(image, strength);
self.replace(image, faded);
}
None => {}
}
*blend_mode = BlendMode::Normal;
}
}
}
@@ -1,48 +0,0 @@
// The pass blending a layer by a mode that reads what lies beneath, appended to the effect passes, matching the CPU's `blend_layer_pixel`
// A paint at `strength` blended by the mode, moved toward the mode's neutral color where its strength does that, matching `apply_blend_mode_at_strength`
fn blend_gamma_at_strength(backdrop: vec3<f32>, paint: vec3<f32>, mode: u32, strength: f32) -> vec3<f32> {
// Hard Mix steepens its ramp with the strength instead
if mode == 17u {
let mixed = vec3<f32>(hard_mix(backdrop.r, paint.r, strength), hard_mix(backdrop.g, paint.g, strength), hard_mix(backdrop.b, paint.b, strength));
return clamp(mixed, vec3<f32>(0.), vec3<f32>(1.));
}
// Color Dodge and Linear Dodge move toward black, Color Burn and Linear Burn toward white, and Vivid Light and Linear Light toward middle gray
var moved = paint;
if mode == 8u || mode == 9u {
moved = strength * paint;
} else if mode == 3u || mode == 4u {
moved = 1. - strength * (1. - paint);
} else if mode == 14u || mode == 15u {
moved = 0.5 + strength * (paint - 0.5);
}
return blend_gamma(backdrop, moved, mode);
}
// How strongly a layer whose fill `strength` moves it toward neutral shows over a backdrop of `backdrop_alpha`, matching the CPU's `layer_fill_shown`
fn layer_fill_shown(backdrop_alpha: f32, strength: f32) -> f32 {
return min(strength / max((1. - backdrop_alpha) + backdrop_alpha * strength, 1e-6), 1.);
}
// A layer's image (`secondary`) blended by the mode in `values.z` onto what lies beneath it, sampled from the scene's backdrop (`source`) where each pixel lands as `sample_backdrop` places it.
// It's what the layer then draws normally: its color mixed toward the blend as far as the backdrop covers it, shown as strongly as a fill `values.w` moving it toward neutral leaves it.
@fragment
fn blend_onto_backdrop(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
let layer = textureLoad(secondary, vec2<i32>(position.xy), 0);
let backdrop = textureSampleLevel(source, linear_sampler, backdrop_point(position.xy) / vec2<f32>(textureDimensions(source)), 0.);
if layer.a <= 0. {
return vec4<f32>(0.);
}
let paint = clamp(layer.rgb / layer.a, vec3<f32>(0.), vec3<f32>(1.));
var beneath = vec3<f32>(0.);
if backdrop.a > 0. {
beneath = clamp(backdrop.rgb / backdrop.a, vec3<f32>(0.), vec3<f32>(1.));
}
let strength = parameters.values.w;
let blended = blend_gamma_at_strength(beneath, paint, u32(parameters.values.z), strength);
let shown = layer.a * layer_fill_shown(backdrop.a, strength);
return vec4<f32>(shown * ((1. - backdrop.a) * paint + backdrop.a * blended), shown);
}
@@ -7,7 +7,6 @@ use crate::WgpuExecutor;
use core_types::blending::BlendMode;
use glam::{DAffine2, UVec2};
use graphic_types::MinimumMaximumMode;
use graphic_types::vector_types::gradient::{GradientModel, GradientSpread};
use rendering::vello_scene_builder::VelloSceneBuilder;
use vello_gpu::kurbo::{Affine, BezPath, Line, ParamCurve, PathSeg, Point, Rect, Stroke, Vec2};
use vello_gpu::peniko::{self, Color, Fill};
@@ -370,304 +369,6 @@ fn degenerate_strokes_render() {
let Some(_) = render(size, draw) else { return };
}
/// A gradient from black to white read in gamma, placed by `placement`, with these curvatures and model, or none if `None`.
fn curved_black_to_white_gradient(placement: DAffine2, curvatures: Option<[f64; 2]>, model: GradientModel) -> graphic_types::Graphic {
use core_types::list::{ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_MODEL, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_START_CURVATURE, Item};
use core_types::{ATTR_TRANSFORM, Color as GraphicColor};
use graphic_types::vector_types::gradient::{Gradient, GradientSpace};
let mut item = Item::new_from_element(Gradient::from(vec![GraphicColor::BLACK, GraphicColor::WHITE]))
.with_attribute(ATTR_GRADIENT_SPACE, GradientSpace::RgbGamma)
.with_attribute(ATTR_TRANSFORM, placement);
if let Some([start, end]) = curvatures {
item.set_attribute(ATTR_GRADIENT_START_CURVATURE, start);
item.set_attribute(ATTR_GRADIENT_END_CURVATURE, end);
item.set_attribute(ATTR_GRADIENT_MODEL, model);
}
graphic_types::Graphic::Gradient(item)
}
#[test]
fn curved_gradients_match_their_cpu_evaluation() {
use glam::DVec2;
use graphic_types::vector_types::gradient_standard::radius_curvature;
use std::fmt::Write;
// Gradient space spans 4 units across the render, with the gradient line from (60, 100) to (110, 100), and then sheared
let placements = [
DAffine2::from_scale_angle_translation(DVec2::splat(50.), 0., DVec2::new(60., 100.)),
DAffine2::from_cols(DVec2::new(50., 10.), DVec2::new(15., 35.), DVec2::new(60., 100.)),
];
let radius = radius_curvature;
let settings = [
([-1., radius(0.75)], "a focal point inside the end circle, off its center"),
([radius(0.2), radius(1.5)], "a focal circle nested inside the end circle"),
([radius(2.), radius(-0.5)], "an end circle nested inside the start circle"),
([radius(0.6), radius(0.6)], "crossing circles"),
([0.5, 0.25], "crossing circles of different sizes"),
([radius(-0.3), radius(-0.3)], "separate circles of the same size"),
([radius(-0.2), radius(-0.4)], "separate circles of different sizes"),
([-1., radius(-0.4)], "a focal point outside the end circle"),
([-1., -1.], "two points"),
([radius(0.5), radius(0.5)], "identical circles"),
([radius(0.3), radius(2500.)], "an end nearly a line"),
([radius(0.8), 0.], "an end line beside a start circle reaching past the end"),
([radius(-0.4), 0.], "an end line beside a start circle bowing away"),
([0., radius(2.)], "a start line beside an end circle reaching past the start"),
([radius(1.), radius(0.5)], "internally tangent circles"),
([radius(3000.), radius(-4000.)], "both ends nearly flat around an apex"),
([radius(-3000.), radius(3000.)], "both ends nearly flat, bowing apart"),
([7e-31, 0.3], "a start nearly too flat to draw as a circle"),
([4e-309, -1e-300], "both ends past computing as circles"),
];
let mut report = String::new();
for (curvatures, setting) in settings {
for placement in placements {
let Some(line) = compare_curved_gradient_with_cpu(curvatures, placement, GradientSpread::Pad, setting) else {
return;
};
let _ = writeln!(report, "{line}");
}
}
eprintln!("{report}");
}
#[test]
fn far_and_wide_curved_ramps_match_their_cpu_evaluation() {
use glam::DVec2;
use graphic_types::vector_types::gradient_standard::radius_curvature;
// Equal radii of a million ramp from 2 million to the end point, where t reaches 1 exactly, so Clear clears and Repeat restarts just past it
let placement = DAffine2::from_scale_angle_translation(DVec2::splat(50.), 0., DVec2::new(60., 100.));
for spread in [GradientSpread::Clear, GradientSpread::Repeat] {
let curvatures = [radius_curvature(1e6), radius_curvature(1e6)];
let Some(line) = compare_curved_gradient_with_cpu(curvatures, placement, spread, "equal radii of a million") else {
return;
};
eprintln!("{line}");
}
// A ramp a gradient length wide, 200,000 gradient lengths before the start, drawn across 100 pixels
let placement = DAffine2::from_scale_angle_translation(DVec2::splat(100.), 0., DVec2::new(100. * 200_000., 100.));
let curvatures = [radius_curvature(-1e5), radius_curvature(1e5)];
let Some(line) = compare_curved_gradient_with_cpu(curvatures, placement, GradientSpread::Pad, "a ramp 200,000 back") else {
return;
};
eprintln!("{line}");
}
/// Renders a black to white gradient with these curvatures, placed by `placement` and read with `spread`, into a 200 by 200 view, and checks
/// each pixel against the CPU's evaluation, returning a line describing how they compare, or `None` without a GPU.
fn compare_curved_gradient_with_cpu(curvatures: [f64; 2], placement: DAffine2, spread: GradientSpread, setting: &str) -> Option<String> {
use core_types::list::ATTR_GRADIENT_SPREAD;
use glam::DVec2;
use graphic_types::vector_types::gradient_standard::GradientStandard;
use rendering::{Render, RenderParams};
let size = UVec2::new(200, 200);
let graphic = match curved_black_to_white_gradient(placement, Some(curvatures), GradientModel::Standard) {
graphic_types::Graphic::Gradient(item) => graphic_types::Graphic::Gradient(item.with_attribute(ATTR_GRADIENT_SPREAD, spread)),
graphic => graphic,
};
let pixels = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))?;
// The CPU's level at a point on the screen, or `None` where it's unpainted
let gradient = GradientStandard::new(curvatures[0], curvatures[1]);
let to_gradient = placement.inverse();
let level_at = |point: DVec2| {
let t = gradient.t(to_gradient.transform_point2(point))?;
let position = match spread {
GradientSpread::Clear if !(0. ..=1.).contains(&t) => return None,
GradientSpread::Repeat if t.is_infinite() => (t > 0.) as u8 as f64,
GradientSpread::Repeat => t - t.floor(),
_ => t.clamp(0., 1.),
};
Some((position * 255.).round() as i32)
};
let center = |x: i32, y: i32| DVec2::new(x as f64 + 0.5, y as f64 + 0.5);
let expected = |x: i32, y: i32| level_at(center(x, y));
// Each pixel takes the level at its center, except that one beside a step in the ramp or an edge of the painted area may land anywhere between its neighbors' levels
let (mut worst, mut beside_steps, mut out_of_range, mut disagreements) = (0, 0, Vec::new(), 0);
for y in 1..size.y as i32 - 1 {
for x in 1..size.x as i32 - 1 {
let neighborhood: Vec<Option<i32>> = (-1..=1).flat_map(|dy| (-1..=1).map(move |dx| (x + dx, y + dy))).map(|(x, y)| expected(x, y)).collect();
let painted_neighbors = neighborhood.iter().filter(|level| level.is_some()).count();
let levels = neighborhood.iter().flatten();
let (lowest, highest) = (*levels.clone().min().unwrap_or(&0), *levels.max().unwrap_or(&255));
let [red, _, _, alpha] = pixel(&pixels, size, x as u32, y as u32);
let red = red as i32;
match (alpha, expected(x, y)) {
(0, None) => {}
(255, Some(level)) if painted_neighbors == 9 && highest - lowest <= 32 => worst = worst.max((red - level).abs()),
(255, Some(_)) => {
beside_steps += 1;
// A center on a step (to within single precision) may take either side's level, which a sliver thinner than a pixel can hide from every neighbor
let nudged = [DVec2::X, -DVec2::X, DVec2::Y, -DVec2::Y].map(|direction| level_at(center(x, y) + direction * 1e-3));
let (lowest, highest) = nudged.iter().flatten().fold((lowest, highest), |(lowest, highest), &level| (lowest.min(level), highest.max(level)));
if red < lowest - 3 || red > highest + 3 {
let point = to_gradient.transform_point2(center(x, y));
out_of_range.push(format!("pixel ({x}, {y}) at {point} is {red} beside {lowest} to {highest}"));
}
}
_ if painted_neighbors != 0 && painted_neighbors != 9 => {}
_ => disagreements += 1,
}
}
}
let context = format!("{setting} {curvatures:?}, {spread:?}, placed by {placement:?}");
assert!(worst <= 3, "{context}: up to {worst} levels from the CPU");
assert!(out_of_range.is_empty(), "{context}: pixels beside steps out of their neighbors' range: {out_of_range:?}");
assert_eq!(disagreements, 0, "{context}: pixels disagreeing with the CPU on being painted");
Some(format!(
"{context}: within {worst} levels, {beside_steps} pixels beside steps in their neighbors' range, {disagreements} disagree on being painted"
))
}
#[test]
fn apollonian_gradients_match_their_cpu_evaluation() {
use glam::DVec2;
use graphic_types::vector_types::gradient_standard::GradientShape;
use rendering::{Render, RenderParams};
let size = UVec2::new(200, 200);
// Gradient space spans 4 units across the render, with the gradient line from (60, 100) to (110, 100)
let placement = DAffine2::from_scale_angle_translation(DVec2::splat(50.), 0., DVec2::new(60., 100.));
for curvatures in [
[1., 0.6],
[0.6, 0.6],
[-0.5, 0.2952],
[1., 1.],
[0.5, 0.25],
[0.3, -0.3],
[0.8, 1.],
[0.9, 0.2],
[0.9, 0.9],
[0.001, 0.8],
// The outer arc through infinity, with the band offset from the start and with the wrap's t negative
[0.9, 0.6],
[0.6, 1.],
] {
let GradientShape::Apollonian(parameters) = GradientShape::new(curvatures[0], curvatures[1], GradientModel::Apollonian, placement) else {
panic!("curvatures {curvatures:?} should draw Apollonian circles");
};
let graphic = curved_black_to_white_gradient(placement, Some(curvatures), GradientModel::Apollonian);
let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
return;
};
let mut worst = 0_i32;
for y in (5..195).step_by(10) {
for x in (5..195).step_by(10) {
let point = placement.inverse().transform_point2(DVec2::new(x as f64 + 0.5, y as f64 + 0.5));
let expected = (parameters.t(point).clamp(0., 1.) * 255.).round() as i32;
worst = worst.max((expected - pixel(&pixels, size, x, y)[0] as i32).abs());
}
}
assert!(worst <= 3, "curvatures {curvatures:?} differ from the CPU evaluation by up to {worst} levels");
}
}
#[test]
fn one_stop_curved_gradients_leave_their_gaps_unpainted() {
use core_types::list::{ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_START_CURVATURE, Item};
use core_types::{ATTR_TRANSFORM, Color as GraphicColor};
use glam::DVec2;
use graphic_types::vector_types::gradient::Gradient;
use graphic_types::vector_types::gradient_standard::radius_curvature;
use rendering::{Render, RenderParams};
let size = UVec2::new(200, 200);
let placement = DAffine2::from_scale_angle_translation(DVec2::splat(50.), 0., DVec2::new(60., 100.));
// Crossing circles of radius 0.6, whose cone paints the strip within 0.6 of the gradient line, in one half-transparent red stop
let item = Item::new_from_element(Gradient::from(vec![GraphicColor::from_rgbaf32_unchecked(1., 0., 0., 0.5)]))
.with_attribute(ATTR_TRANSFORM, placement)
.with_attribute(ATTR_GRADIENT_START_CURVATURE, radius_curvature(0.6))
.with_attribute(ATTR_GRADIENT_END_CURVATURE, radius_curvature(0.6));
let graphic = graphic_types::Graphic::Gradient(item);
let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
return;
};
// At (0.5, 0) on the cone and (0.5, 1) in its gap
let (on_cone, in_gap) = (pixel(&pixels, size, 85, 100)[3], pixel(&pixels, size, 85, 150)[3]);
assert!(on_cone.abs_diff(128) <= 1, "on the cone: alpha {on_cone}");
assert_eq!(in_gap, 0, "in the gap: alpha {in_gap}");
}
#[test]
fn gradient_presets_render_on_the_gpu_as_their_forms_did() {
use glam::DVec2;
use graphic_types::vector_types::GradientForm;
use rendering::{Render, RenderParams};
let size = UVec2::new(160, 120);
let placement = DAffine2::from_cols(DVec2::new(40., 10.), DVec2::new(-12., 30.), DVec2::new(70., 55.));
let render_graphic = |graphic: &graphic_types::Graphic| render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()));
for form in [GradientForm::Linear, GradientForm::Radial] {
// The brush each form was drawn with before curvatures: the unit line placed without shear, or the unit circle placed as is
let (kind, brush_placement): (peniko::GradientKind, DAffine2) = match form {
GradientForm::Linear => {
let line = placement.matrix2.x_axis.project_onto(placement.matrix2.y_axis.perp());
let desheared = DAffine2::from_cols(line, line.perp(), placement.translation);
(
peniko::LinearGradientPosition {
start: Point::ORIGIN,
end: Point::new(1., 0.),
}
.into(),
desheared,
)
}
GradientForm::Radial => (
peniko::RadialGradientPosition {
start_center: Point::ORIGIN,
start_radius: 0.,
end_center: Point::ORIGIN,
end_radius: 1.,
}
.into(),
placement,
),
};
let brush = peniko::Brush::Gradient(
peniko::Gradient {
kind,
interpolation_alpha_space: peniko::InterpolationAlphaSpace::Unpremultiplied,
..Default::default()
}
.with_stops([Color::from_rgb8(0, 0, 0), Color::from_rgb8(255, 255, 255)]),
);
let Some(by_brush) = render(size, |scene| scene.fill_viewport(&brush, Some(Affine::new(brush_placement.to_cols_array())))) else {
return;
};
// Its curvatures draw those pixels under either model, and absent curvatures are the linear form's
let absent = (form == GradientForm::Linear).then_some((None, GradientModel::Apollonian));
for (curvatures, model) in [(Some(form.curvatures()), GradientModel::Standard), (Some(form.curvatures()), GradientModel::Apollonian)]
.into_iter()
.chain(absent)
{
let Some(by_curvatures) = render_graphic(&curved_black_to_white_gradient(placement, curvatures, model)) else {
return;
};
assert!(
by_curvatures == by_brush,
"{form:?} with curvatures {curvatures:?} and the {model:?} model should draw the pixels of its brush from before curvatures"
);
}
}
}
/// Renders an opaque white square from (`min`, `min`) to (`max`, `max`) through `effects` with `fill`.
fn render_square_with_effects(effects: Vec<graphic_types::EffectOperation>, fill: f32, min: f64, max: f64, size: UVec2) -> Option<Vec<[u8; 4]>> {
render_square_with_effects_in(effects, DAffine2::IDENTITY, fill, min, max, size)
@@ -1207,7 +908,7 @@ fn random_fields_match_the_cpu_zoomed_out_and_away_from_the_origin() {
let (width, origin) = (32, glam::DVec2::new(-1000., -600.));
let placement = DAffine2::from_translation(origin) * DAffine2::from_scale(glam::DVec2::splat(2. * width as f64));
let view = DAffine2::from_scale(glam::DVec2::splat(0.5)) * DAffine2::from_translation(-origin);
let noise = |amount, distribution, monochromatic| EffectOperation::Speckle {
let noise = |amount, distribution, monochromatic| EffectOperation::AddNoise {
amount,
distribution,
monochromatic,
@@ -1258,7 +959,7 @@ fn random_fields_stay_in_place_far_from_the_origin() {
// Noise over an endless color whose cells lie past where 32-bit floats hold every integer, rendered there and a pixel further right
let size = UVec2::splat(16);
let noise = EffectOperation::Speckle {
let noise = EffectOperation::AddNoise {
amount: 40.,
distribution: NoiseDistribution::Uniform,
monochromatic: false,
@@ -1675,46 +1376,6 @@ fn a_clipping_base_clips_by_its_blur_but_not_by_its_shadow() {
}
}
#[test]
fn endless_layers_clip_to_the_shape_beneath_them() {
use core_types::list::{ATTR_APPEARANCE, Item, List};
use core_types::{ATTR_CLIPPING_MASK, Color as GraphicColor};
use graphic_types::generator::Generator;
use graphic_types::vector_types::gradient::Gradient;
use graphic_types::{Appearance, Coverage, Graphic, Vector};
use rendering::{Render, RenderParams};
use vello_gpu::kurbo::Shape;
let size = UVec2::new(128, 128);
let mut square = Vector::item_from_bezpath(&Rect::new(30., 30., 80., 80.).to_path(0.1));
square.set_attribute(
ATTR_APPEARANCE,
Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(GraphicColor::WHITE))),
);
let base = Item::new_from_element(Graphic::VectorList(List::new_from_item(square)));
// Layers of a color, a gradient, and noise, each clipped to a square beneath it
let layers = [
("color", Graphic::from(Item::new_from_element(GraphicColor::RED).with_attribute(ATTR_CLIPPING_MASK, true))),
(
"gradient",
Graphic::from(Item::new_from_element(Gradient::from(vec![GraphicColor::RED, GraphicColor::BLUE])).with_attribute(ATTR_CLIPPING_MASK, true)),
),
("noise", Graphic::from(Item::new_from_element(Generator::Noise).with_attribute(ATTR_CLIPPING_MASK, true))),
];
for (name, layer) in layers {
let graphic = Graphic::GraphicList([base.clone(), Item::new_from_element(layer)].into_iter().collect());
let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
return;
};
assert_eq!(pixel(&pixels, size, 55, 55)[3], 255, "{name}: the layer shows within the square");
for (x, y) in [(10, 10), (100, 55), (55, 100), (120, 120)] {
assert_eq!(pixel(&pixels, size, x, y)[3], 0, "{name}: the layer is clipped away at ({x}, {y}), past the square");
}
}
}
#[test]
fn feathers_fade_the_content_to_nothing_at_its_edges() {
use graphic_types::EffectOperation;
@@ -3787,8 +3448,8 @@ fn captured_box_blurs_hold_their_results_for_svg_however_slight() {
fn cpu_evaluated_effects_match_the_gpu_passes() {
use core_types::Color as GraphicColor;
use core_types::blending::BlendMode;
use core_types::list::ATTR_GRADIENT_FORM;
use core_types::list::Item;
use core_types::list::{ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_MODEL, ATTR_GRADIENT_START_CURVATURE};
use core_types::transfer_curve::TransferCurve;
use core_types::{ATTR_OPACITY_FILL, ATTR_TRANSFORM};
use glam::DVec2;
@@ -4098,30 +3759,17 @@ fn cpu_evaluated_effects_match_the_gpu_passes() {
blend_mode: BlendMode::Normal,
opacity: 100.,
});
let gradient_item = |transform: DAffine2| {
let gradient = |form: GradientForm, transform: DAffine2| {
let stops = [(0., [0.9, 0.1, 0.4, 1.]), (0.5, [0.2, 0.3, 0.9, 0.5]), (1., [1., 0.9, 0.7, 1.])].map(|(position, [red, green, blue, alpha])| GradientStop {
position,
midpoint: 0.5,
color: GraphicColor::from_rgbaf32_unchecked(red, green, blue, alpha),
});
Item::new_from_element(Gradient::new(stops)).with_attribute(ATTR_TRANSFORM, transform)
};
let gradient = |form: GradientForm, transform: DAffine2| {
let [start_curvature, end_curvature] = form.curvatures();
Graphic::from(
gradient_item(transform)
.with_attribute(ATTR_GRADIENT_START_CURVATURE, start_curvature)
.with_attribute(ATTR_GRADIENT_END_CURVATURE, end_curvature),
)
let item = Item::new_from_element(Gradient::new(stops)).with_attribute(ATTR_TRANSFORM, transform);
Graphic::from(item.with_attribute(ATTR_GRADIENT_FORM, form))
};
let linear = gradient(GradientForm::Linear, DAffine2::from_translation(DVec2::new(45., 60.)) * DAffine2::from_scale(DVec2::splat(60.)));
let radial = gradient(GradientForm::Radial, DAffine2::from_translation(DVec2::splat(75.)) * DAffine2::from_scale(DVec2::splat(30.)));
// Curvatures between the two forms, with crossing end circles whose cone leaves gaps unpainted, and the same curvatures drawn as Apollonian circles
let curved_item = gradient_item(DAffine2::from_translation(DVec2::new(55., 70.)) * DAffine2::from_scale(DVec2::splat(30.)))
.with_attribute(ATTR_GRADIENT_START_CURVATURE, 0.5)
.with_attribute(ATTR_GRADIENT_END_CURVATURE, 0.25);
let curved = Graphic::from(curved_item.clone());
let apollonian = Graphic::from(curved_item.with_attribute(ATTR_GRADIENT_MODEL, GradientModel::Apollonian));
// A checkerboard spanning the render from `start` to `end` with a pixel for each of the render's, so sampling it needs no interpolation
let checkerboard = |start: u32, end: u32| {
@@ -4162,15 +3810,11 @@ fn cpu_evaluated_effects_match_the_gpu_passes() {
overlay(&linear, BlendMode::Normal, 40.),
overlay(&radial, BlendMode::Multiply, 100.),
overlay(&checker, BlendMode::Screen, 100.),
overlay(&curved, BlendMode::Normal, 100.),
overlay(&apollonian, BlendMode::Normal, 100.),
]);
// Outlines drawn with paints placed on their own, the image covering the outline as well as the content
paint_cases.extend([
vec![outline(linear.clone(), 6., StrokeAlign::Outside, false)],
vec![outline(radial.clone(), 8., StrokeAlign::Center, false)],
vec![outline(curved.clone(), 8., StrokeAlign::Center, false)],
vec![outline(apollonian.clone(), 8., StrokeAlign::Center, false)],
vec![outline(checkerboard(min - 10, max + 10), 9., StrokeAlign::Center, false)],
]);
// Bevels with gloss contours, contours, and textures
@@ -4291,7 +3935,6 @@ fn cpu_evaluated_effects_match_the_gpu_passes() {
vec![mask(&mask_image, MaskMode::Alpha, 70., 3., true)],
vec![mask(&linear, MaskMode::Luminance, 100., 6., false)],
vec![mask(&radial, MaskMode::Alpha, 100., 0., false)],
vec![mask(&curved, MaskMode::Luminance, 100., 0., false)],
vec![mask(&mask_image, MaskMode::Luminance, 100., 2., false), mask_shadow.clone()],
vec![mask_shadow.clone(), mask(&linear, MaskMode::Luminance, 80., 0., true)],
vec![blur(2., false, false), mask(&radial, MaskMode::Luminance, 100., 1.5, false), mask_shadow.clone()],
@@ -4472,7 +4115,7 @@ fn cpu_evaluated_effects_match_the_gpu_passes() {
vec![blur(2., false, false), edges_only(200., 0.)],
vec![blur(2., false, false), unsharp(150., 0., 0.)],
]);
let noise = |amount, distribution, monochromatic| EffectOperation::Speckle {
let noise = |amount, distribution, monochromatic| EffectOperation::AddNoise {
amount,
distribution,
monochromatic,
@@ -5038,10 +4681,10 @@ fn gpu_color_adjustments_match_the_cpu_kernels() {
];
let mut runs: Vec<(String, Vec<Adjustment>)> = runs.into_iter().map(|(name, adjustment)| (name.to_string(), vec![adjustment])).collect();
// Every blend mode, overlaying an opaque color and a translucent one, each with a luma apart from every test color's, which Darker Color and Lighter Color compare, and off Hard Mix's steep ramp over them
// Every blend mode, overlaying an opaque color and a translucent one, each with channels summing to what no test color's do, which Darker Color and Lighter Color compare
for blend_mode in BlendMode::list().into_iter().flatten().chain(&[BlendMode::Erase, BlendMode::Restore, BlendMode::MultiplyAlpha]) {
for (color, opacity) in [
(Color::from_gamma_srgb_channels(0.9, 0.462, 0.239, 1.), 70.),
(Color::from_gamma_srgb_channels(0.9, 0.453, 0.2, 1.), 70.),
(Color::from_gamma_srgb_channels(0.1, 0.6, 0.853, 0.4), 100.),
] {
let overlay = Adjustment::ColorOverlay {
@@ -11866,474 +11509,3 @@ fn endless_layers_fade_by_blend_ifs_reading_each_effect_run_as_the_runs_before_i
};
assert!(worst <= 3, "the half-filled color mask differs between the CPU and GPU by up to {worst} levels");
}
/// A raster of `size` texels placed a texel to each of the render's pixels from `corner`, each of the straight 8-bit color `level` gives at its column and row.
fn leveled_image(corner: UVec2, size: UVec2, level: impl Fn(u32, u32) -> [u8; 4]) -> core_types::list::Item<graphic_types::raster_types::Raster<graphic_types::raster_types::CPU>> {
use core_types::color::SRGBA8;
use graphic_types::raster_types::{Image, Raster};
let data = (0..size.x * size.y)
.map(|index| {
let [red, green, blue, alpha] = level(index % size.x, index / size.x);
core_types::Color::from(SRGBA8::new(red, green, blue, alpha))
})
.collect();
let placement = DAffine2::from_translation(corner.as_dvec2()) * DAffine2::from_scale(size.as_dvec2());
core_types::list::Item::new_from_element(Raster::new_cpu(Image { width: size.x, height: size.y, data })).with_attribute(core_types::ATTR_TRANSFORM, placement)
}
/// The premultiplied gamma-encoded channels of a straight 8-bit color, from 0 to 1.
fn premultiplied_gamma([red, green, blue, alpha]: [u8; 4]) -> [f32; 4] {
let alpha = alpha as f32 / 255.;
[red, green, blue]
.map(|channel| channel as f32 / 255. * alpha)
.into_iter()
.chain([alpha])
.collect::<Vec<_>>()
.try_into()
.unwrap()
}
/// What lies beneath layers blending by the modes Vello's layers lack: red rising across and green rising down over a constant blue, opaque in the top half and fading across the bottom half to a quarter.
fn blend_backdrop_level(x: u32, y: u32) -> [u8; 4] {
let alpha = if y < 48 { 255 } else { 255 - x * 191 / 95 };
[(x * 255 / 95) as u8, (y * 255 / 95) as u8, 140, alpha as u8]
}
/// The layer blending onto it, 80 texels across from the corner at 8: red falling down, green rising across, and blue rising across both, with a band of half alpha.
fn blend_content_level(x: u32, y: u32) -> [u8; 4] {
let alpha = if (50..62).contains(&y) { 128 } else { 255 };
[(230 - 2 * y) as u8, (20 + 2 * x) as u8, ((x + 2 * y) * 255 / 237) as u8, alpha]
}
/// Whether a blend is ill-conditioned for the colors, where it stretches the rounding of what lies beneath far: on or near Hard Mix's steep ramp,
/// where a burn or dodge (Vivid Light's too) is by a paint dark or light enough to stretch each level more than fourfold, and near a tie of luma for Darker or Lighter Color.
fn blend_ill_conditioned(blend_mode: BlendMode, content: [f32; 4], backdrop: [f32; 4], fill: f32) -> bool {
let straight = |pixel: [f32; 4]| [0, 1, 2].map(|channel| if pixel[3] > 0. { pixel[channel] / pixel[3] } else { 0. });
let (source, beneath) = (straight(content), straight(backdrop));
let luma = |color: [f32; 3]| 0.3 * color[0] + 0.59 * color[1] + 0.11 * color[2];
let strength = if blend_mode.fill_moves_layer_toward_neutral() { fill } else { 1. };
let steepness = 255. * strength / 256.;
match blend_mode {
BlendMode::HardMix => (0..3).any(|channel| (-0.01..1. - steepness + 0.01).contains(&(beneath[channel] - steepness * (1. - source[channel])))),
BlendMode::VividLight => source.iter().any(|&channel| (2. * (0.5 + strength * (channel - 0.5)) - 1.).abs() > 0.75),
BlendMode::ColorDodge => source.iter().any(|&channel| strength * channel > 0.75),
BlendMode::ColorBurn => source.iter().any(|&channel| 1. - strength * (1. - channel) < 0.25),
BlendMode::DarkerColor | BlendMode::LighterColor => (luma(source) - luma(beneath)).abs() < 2. / 255.,
_ => false,
}
}
/// The reference formula, for PSD interop, for one opaque channel of a layer in a mode Vello's layers lack, or in Color Dodge or Color Burn, with its fill, over an opaque backdrop channel.
fn reference_blend(blend_mode: BlendMode, backdrop: f32, source: f32, fill: f32) -> f32 {
let color_burn = |backdrop: f32, source: f32| {
if backdrop >= 1. {
1.
} else if source <= 0. {
0.
} else {
1. - ((1. - backdrop) / source).min(1.)
}
};
let color_dodge = |backdrop: f32, source: f32| {
if backdrop <= 0. {
0.
} else if source >= 1. {
1.
} else {
(backdrop / (1. - source)).min(1.)
}
};
let mix = |blended: f32| backdrop + (blended.clamp(0., 1.) - backdrop) * fill;
match blend_mode {
BlendMode::ColorDodge => color_dodge(backdrop, fill * source),
BlendMode::ColorBurn => color_burn(backdrop, 1. - fill * (1. - source)),
BlendMode::LinearBurn => (backdrop + (1. - fill * (1. - source)) - 1.).clamp(0., 1.),
BlendMode::LinearDodge => (backdrop + fill * source).clamp(0., 1.),
BlendMode::VividLight => {
let source = 0.5 + fill * (source - 0.5);
if source <= 0.5 {
color_burn(backdrop, 2. * source)
} else {
color_dodge(backdrop, 2. * source - 1.)
}
}
BlendMode::LinearLight => (backdrop + 2. * (0.5 + fill * (source - 0.5)) - 1.).clamp(0., 1.),
BlendMode::HardMix => {
let steepness = 255. * fill / 256.;
((backdrop - steepness * (1. - source)) / (1. - steepness)).clamp(0., 1.)
}
BlendMode::PinLight => mix(if source <= 0.5 { backdrop.min(2. * source) } else { backdrop.max(2. * source - 1.) }),
BlendMode::Subtract => mix(backdrop - source),
BlendMode::Divide => mix(if backdrop <= 0. {
0.
} else if source <= 0. {
1.
} else {
backdrop / source
}),
_ => panic!("{blend_mode} picks whole colors or blends natively"),
}
}
#[test]
fn layers_in_modes_vello_lacks_blend_onto_partly_covering_backdrops_as_on_the_cpu_and_by_the_reference_formulas() {
use core_types::list::List;
use core_types::{ATTR_BLEND_MODE, ATTR_OPACITY, ATTR_OPACITY_FILL};
use graphic_types::Graphic;
use raster_kernels::layer_blending::blend_layer_pixel;
use rendering::{Render, RenderParams};
let size = UVec2::splat(96);
let (corner, content_size) = (UVec2::splat(8), UVec2::splat(80));
let modes = BlendMode::list().into_iter().flatten().copied().filter(BlendMode::reads_backdrop);
for blend_mode in modes.chain([BlendMode::ColorDodge, BlendMode::ColorBurn]) {
for (fill, opacity) in [(1., 1.), (0.5, 1.), (0.7, 0.6)] {
let content = leveled_image(corner, content_size, blend_content_level)
.with_attribute(ATTR_BLEND_MODE, blend_mode)
.with_attribute(ATTR_OPACITY_FILL, fill as f64)
.with_attribute(ATTR_OPACITY, opacity as f64);
let mut list = List::new_from_item(leveled_image(UVec2::ZERO, size, blend_backdrop_level));
list.push(content);
let graphic = Graphic::RasterCPUList(list);
let Some(gpu) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
return;
};
let (mut worst, mut worst_at) = (0., UVec2::ZERO);
for y in 0..size.y {
for x in 0..size.x {
let backdrop = premultiplied_gamma(blend_backdrop_level(x, y));
let inside = (corner.x..corner.x + content_size.x).contains(&x) && (corner.y..corner.y + content_size.y).contains(&y);
let content = if inside { premultiplied_gamma(blend_content_level(x - corner.x, y - corner.y)) } else { [0.; 4] };
if blend_ill_conditioned(blend_mode, content, backdrop, fill) {
continue;
}
// The CPU blends the content by its fill, then its opacity mixes from what lies beneath to that
let blended = blend_layer_pixel(content, backdrop, blend_mode, fill);
let gpu = premultiplied_gamma(pixel(&gpu, size, x, y));
for channel in 0..4 {
let cpu = backdrop[channel] + (blended[channel] - backdrop[channel]) * opacity;
let difference = (cpu - gpu[channel]).abs() * 255.;
if difference > worst {
(worst, worst_at) = (difference, UVec2::new(x, y));
}
}
}
}
assert!(
worst <= 3.,
"{blend_mode} at fill {fill} and opacity {opacity} differs from the CPU by up to {worst} levels at {worst_at}"
);
// Over the opaque top half, the opaque layer takes the reference formula
if opacity < 1. || matches!(blend_mode, BlendMode::DarkerColor | BlendMode::LighterColor) {
continue;
}
for (x, y) in [(20, 12), (50, 30), (80, 44), (14, 40)] {
let backdrop = premultiplied_gamma(blend_backdrop_level(x, y));
let content = premultiplied_gamma(blend_content_level(x - corner.x, y - corner.y));
if blend_ill_conditioned(blend_mode, content, backdrop, fill) {
continue;
}
let gpu = premultiplied_gamma(pixel(&gpu, size, x, y));
for channel in 0..3 {
let expected = reference_blend(blend_mode, backdrop[channel], content[channel], fill);
assert!(
(expected - gpu[channel]).abs() * 255. <= 3.,
"{blend_mode} at fill {fill} gives {gpu:?} at ({x}, {y}) rather than {expected} in channel {channel}"
);
}
}
}
}
}
#[test]
fn darker_and_lighter_color_layers_pick_whole_colors_by_luma_on_the_gpu() {
use core_types::ATTR_BLEND_MODE;
use core_types::list::List;
use graphic_types::Graphic;
use rendering::{Render, RenderParams};
// Blue's luma (0.11) is below the gray's (0.3), though its mean channel (a third) is above it
let size = UVec2::splat(32);
let gray = |_: u32, _: u32| [77, 77, 77, 255];
let blue = |_: u32, _: u32| [0, 0, 255, 255];
for (blend_mode, expected) in [(BlendMode::DarkerColor, [0, 0, 255, 255]), (BlendMode::LighterColor, [77, 77, 77, 255])] {
let mut list = List::new_from_item(leveled_image(UVec2::ZERO, size, blue));
list.push(leveled_image(UVec2::splat(8), UVec2::splat(16), gray).with_attribute(ATTR_BLEND_MODE, blend_mode));
let graphic = Graphic::RasterCPUList(list);
let Some(gpu) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
return;
};
let picked = pixel(&gpu, size, 16, 16);
assert!(picked.iter().zip(expected).all(|(gpu, expected)| gpu.abs_diff(expected) <= 1), "{blend_mode} picks {picked:?}");
}
}
#[test]
fn effect_pieces_beneath_the_content_blend_by_their_own_modes_unmoved_by_its_fill() {
use core_types::Color as GraphicColor;
use glam::DVec2;
use graphic_types::EffectOperation;
use raster_kernels::layer_blending::blend_layer_pixel;
let size = UVec2::new(128, 128);
let (backdrop, content, shadow, glow) = ([153, 128, 102], [204, 153, 77], [179, 77, 230], [102, 51, 128]);
let levels = |color: [u8; 3]| color.map(|level| level as f32 / 255.);
let piece_color = |color: [u8; 3]| GraphicColor::from_gamma_srgb_channels(levels(color)[0], levels(color)[1], levels(color)[2], 1.);
let shadow_in = |mode: BlendMode| {
let mut operation = drop_shadow(piece_color(shadow), DVec2::splat(10.), 0., 0.);
if let EffectOperation::DropShadow { blend_mode, .. } = &mut operation {
*blend_mode = mode;
}
operation
};
let dodging_glow = EffectOperation::OuterGlow {
color: piece_color(glow).into(),
blend_mode: BlendMode::ColorDodge,
technique: Default::default(),
spread: 100.,
size: 5.,
range: 50.,
contour: Default::default(),
noise: 0.,
jitter: 0.,
seed: 0,
};
// Each piece, outside the content, and the content, over a piece it knocks out, at a fill moving only the content toward neutral
let cases = [
("a Linear Burn shadow under normal content", shadow_in(BlendMode::LinearBurn), shadow, (85, 85), BlendMode::Normal, 1.),
(
"a normal shadow under Linear Burn content at half fill",
shadow_in(BlendMode::Normal),
shadow,
(85, 85),
BlendMode::LinearBurn,
0.5,
),
("a Color Dodge glow under Color Dodge content at half fill", dodging_glow, glow, (82, 55), BlendMode::ColorDodge, 0.5),
(
"a Linear Burn shadow under Linear Burn content at half fill",
shadow_in(BlendMode::LinearBurn),
shadow,
(85, 85),
BlendMode::LinearBurn,
0.5,
),
];
for (case, piece, piece_level, piece_at, content_mode, fill) in cases {
let piece_mode = match &piece {
EffectOperation::DropShadow { blend_mode, .. } | EffectOperation::OuterGlow { blend_mode, .. } => *blend_mode,
_ => unreachable!(),
};
let [red, green, blue] = backdrop;
let backdrop_color = Color::from_rgb8(red, green, blue);
let [red, green, blue] = content;
let Some(gpu) = render_square_over_backdrop(vec![piece], fill, 1., content_mode, Some(backdrop_color), Color::from_rgb8(red, green, blue), 30., 80., size) else {
return;
};
// The reference formula, which the CPU blends by, for an opaque layer at a fill over the opaque backdrop
let opaque = |color: [f32; 3]| [color[0], color[1], color[2], 1.];
for (blend_mode, source, fill, (x, y)) in [(piece_mode, levels(piece_level), 1., piece_at), (content_mode, levels(content), fill, (50, 50))] {
let expected = match blend_mode {
BlendMode::Normal => source,
_ => [0, 1, 2].map(|channel| reference_blend(blend_mode, levels(backdrop)[channel], source[channel], fill)),
};
let cpu = blend_layer_pixel(opaque(source), opaque(levels(backdrop)), blend_mode, fill);
let gpu = premultiplied_gamma(pixel(&gpu, size, x, y));
for channel in 0..3 {
assert!(
(cpu[channel] - expected[channel]).abs() * 255. <= 0.5,
"{case}: the CPU gives {cpu:?} at ({x}, {y}) rather than {expected:?}"
);
assert!(
(gpu[channel] - expected[channel]).abs() * 255. <= 3.,
"{case}: the GPU gives {gpu:?} at ({x}, {y}) rather than {expected:?}"
);
}
}
}
}
#[test]
fn color_dodge_and_burn_layers_blend_natively_over_a_shadow_beneath_them_not_knocked_out() {
use core_types::Color as GraphicColor;
use glam::DVec2;
use graphic_types::EffectOperation;
use graphic_types::effect_layers::EffectLayers;
use graphic_types::effects::{EffectCapture, Effects};
use raster_kernels::layer_blending::blend_pixel;
let size = UVec2::new(128, 128);
let (backdrop, content, shadow, fill) = ([153, 128, 102], [102, 179, 77], [51, 77, 128], 0.5);
let levels = |color: [u8; 3]| color.map(|level| level as f32 / 255.);
let mut shadow_not_knocked_out = drop_shadow(
GraphicColor::from_gamma_srgb_channels(levels(shadow)[0], levels(shadow)[1], levels(shadow)[2], 1.),
DVec2::splat(10.),
0.,
0.,
);
if let EffectOperation::DropShadow { knockout, .. } = &mut shadow_not_knocked_out {
*knockout = false;
}
for blend_mode in [BlendMode::ColorDodge, BlendMode::ColorBurn] {
// What lies beneath the item leaves out the shadow the content blends onto, so the layer blends natively, faded by its fill
let layers = EffectLayers::plan(&Effects::from_operations([shadow_not_knocked_out.clone()]), blend_mode, fill, true);
assert!(!layers.content_reads_backdrop(fill) && layers.layer_of(EffectCapture { index: 0, plane: 0 }).is_some(), "{blend_mode}");
let [red, green, blue] = backdrop;
let backdrop_color = Color::from_rgb8(red, green, blue);
let [red, green, blue] = content;
let Some(gpu) = render_square_over_backdrop(
vec![shadow_not_knocked_out.clone()],
fill,
1.,
blend_mode,
Some(backdrop_color),
Color::from_rgb8(red, green, blue),
30.,
80.,
size,
) else {
return;
};
// Over the shadow, and past it over what lies beneath the item, the content faded by its fill blends natively, as the CPU blends it
let opaque = |color: [f32; 3]| [color[0], color[1], color[2], 1.];
let faded = [levels(content)[0] * fill, levels(content)[1] * fill, levels(content)[2] * fill, fill];
for (beneath, (x, y)) in [(levels(shadow), (60, 60)), (levels(backdrop), (35, 35))] {
let expected = blend_pixel(faded, opaque(beneath), blend_mode);
let gpu = premultiplied_gamma(pixel(&gpu, size, x, y));
for channel in 0..3 {
assert!(
(gpu[channel] - expected[channel]).abs() * 255. <= 3.,
"{blend_mode} gives {gpu:?} at ({x}, {y}) rather than {expected:?}"
);
}
}
}
}
#[test]
fn color_dodge_layers_blending_natively_fade_by_their_fill_in_their_first_effect_run() {
use core_types::list::List;
use core_types::{ATTR_BLEND_MODE, ATTR_OPACITY_FILL, ATTR_TRANSFORM};
use glam::DVec2;
use graphic_types::adjustment::Adjustment;
use graphic_types::{Effect, EffectOperation, Graphic, stamp_effect};
use rendering::{Render, RenderParams};
// Opaque 0.4 gray in Color Dodge at half fill, made opaque, then scaled, then casting a normal shadow it doesn't knock out, over opaque 0.3 gray
let size = UVec2::splat(128);
let mut content = leveled_image(UVec2::splat(20), UVec2::splat(40), |_, _| [102, 102, 102, 255])
.with_attribute(ATTR_BLEND_MODE, BlendMode::ColorDodge)
.with_attribute(ATTR_OPACITY_FILL, 0.5);
stamp_effect(&mut content, Effect::new(&EffectOperation::Adjustment(Adjustment::MakeOpaque { strength: 100. })));
content.set_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::splat(20.)) * DAffine2::from_scale(DVec2::splat(60.)));
let mut shadow = drop_shadow(core_types::Color::from_gamma_srgb_channels(0.2, 0.2, 0.2, 1.), DVec2::splat(10.), 0., 0.);
if let EffectOperation::DropShadow { knockout, .. } = &mut shadow {
*knockout = false;
}
stamp_effect(&mut content, Effect::new(&shadow));
let mut list = List::new_from_item(leveled_image(UVec2::ZERO, size, |_, _| [77, 77, 77, 255]));
list.push(content);
let graphic = Graphic::RasterCPUList(list);
let Some(gpu) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
return;
};
// As in SVG, the fill fades the content before Make Opaque restores its alpha, so past the shadow it dodges at full strength: 0.3 / (1 - 0.4)
let dodged = pixel(&gpu, size, 25, 25);
assert!(dodged[..3].iter().all(|&channel| channel.abs_diff(128) <= 3), "{dodged:?}");
}
#[test]
fn layers_in_modes_vello_lacks_blend_only_onto_what_their_faded_group_drew() {
use core_types::list::{Item, List};
use core_types::{ATTR_BLEND_MODE, ATTR_OPACITY};
use graphic_types::Graphic;
use raster_kernels::layer_blending::blend_layer_pixel;
use rendering::{Render, RenderParams};
// White beneath a faded group of dark blue and a layer adding a gray over it, which over the white would add up to white
let size = UVec2::splat(48);
let white = |_: u32, _: u32| [255, 255, 255, 255];
let dark_blue = |_: u32, _: u32| [20, 30, 120, 255];
let gray = |_: u32, _: u32| [100, 100, 100, 255];
let mut inner = List::new_from_item(leveled_image(UVec2::splat(4), UVec2::splat(40), dark_blue));
inner.push(leveled_image(UVec2::splat(12), UVec2::splat(24), gray).with_attribute(ATTR_BLEND_MODE, BlendMode::LinearDodge));
let group = Item::new_from_element(Graphic::RasterCPUList(inner)).with_attribute(ATTR_OPACITY, 0.5_f64);
let mut list = List::new_from_item(Item::new_from_element(Graphic::RasterCPUList(List::new_from_item(leveled_image(UVec2::ZERO, size, white)))));
list.push(group);
let graphic = Graphic::GraphicList(list);
let Some(gpu) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
return;
};
// The layer adds onto the dark blue alone, and the group then fades over the white
let added = blend_layer_pixel(premultiplied_gamma(gray(0, 0)), premultiplied_gamma(dark_blue(0, 0)), BlendMode::LinearDodge, 1.);
let expected: Vec<f32> = (0..3).map(|channel| 1. + (added[channel] - 1.) * 0.5).collect();
let shown = premultiplied_gamma(pixel(&gpu, size, 24, 24));
for channel in 0..3 {
assert!((shown[channel] - expected[channel]).abs() * 255. <= 2., "{shown:?} rather than {expected:?}");
}
// A group in the mode adds all it draws onto what lies beneath it
let mut list = List::new_from_item(Item::new_from_element(Graphic::RasterCPUList(List::new_from_item(leveled_image(UVec2::ZERO, size, dark_blue)))));
list.push(Item::new_from_element(Graphic::RasterCPUList(List::new_from_item(leveled_image(UVec2::splat(12), UVec2::splat(24), gray)))).with_attribute(ATTR_BLEND_MODE, BlendMode::LinearDodge));
let graphic = Graphic::GraphicList(list);
let Some(gpu) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
return;
};
let shown = premultiplied_gamma(pixel(&gpu, size, 24, 24));
assert!((0..3).all(|channel| (shown[channel] - added[channel]).abs() * 255. <= 2.), "{shown:?} rather than {added:?}");
}
#[test]
fn blend_ifs_fade_a_layer_once_it_blends_by_a_mode_vello_lacks() {
use core_types::ATTR_BLEND_MODE;
use core_types::list::List;
use graphic_types::blend_if::BlendIfRanges;
use graphic_types::{Effect, EffectOperation, Graphic, stamp_effect};
use raster_kernels::layer_blending::blend_layer_pixel;
use rendering::{Render, RenderParams};
// Shown over grays from a quarter up, fully from a half, with columns of gray beneath from dark to light
let mut ranges = BlendIfRanges::default();
ranges.underlying.gray = blend_range([64., 128., 255., 255.]);
let size = UVec2::new(64, 16);
let columns = |x: u32, _: u32| {
let level = (x * 4) as u8;
[level, level, level, 255]
};
let orange = |_: u32, _: u32| [230, 140, 60, 255];
let mut content = leveled_image(UVec2::ZERO, size, orange).with_attribute(ATTR_BLEND_MODE, BlendMode::LinearBurn);
stamp_effect(&mut content, Effect::new(&EffectOperation::BlendIf(Box::new(ranges))));
let mut list = List::new_from_item(leveled_image(UVec2::ZERO, size, columns));
list.push(content);
let graphic = Graphic::RasterCPUList(list);
let Some(gpu) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
return;
};
// Each column shows the blend as strongly as Blend If shows the gray beneath it
for x in 0..size.x {
let beneath = premultiplied_gamma(columns(x, 0));
let blended = blend_layer_pixel(premultiplied_gamma(orange(0, 0)), beneath, BlendMode::LinearBurn, 1.);
let weight = ranges.underlying.weight([beneath[0], beneath[1], beneath[2]].map(f64::from)) as f32;
let shown = premultiplied_gamma(pixel(&gpu, size, x, 8));
for channel in 0..3 {
let expected = beneath[channel] + (blended[channel] - beneath[channel]) * weight;
assert!((shown[channel] - expected).abs() * 255. <= 3., "column {x} shows {shown:?} rather than {expected} in channel {channel}");
}
}
}
+2 -5
View File
@@ -685,7 +685,7 @@ fn paint_overlay<T: PaintFitBounds>(
mod test {
use core_types::blending::BlendMode;
use core_types::list::{ATTR_EFFECTS, Item};
use core_types::{ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_START_CURVATURE, ATTR_TRANSFORM, Color};
use core_types::{ATTR_GRADIENT_FORM, ATTR_TRANSFORM, Color};
use glam::{DAffine2, DVec2};
use graphic_types::raster_types::{Image, Raster};
use graphic_types::{Effects, Graphic};
@@ -825,10 +825,7 @@ mod test {
}
fn gradient_paints(transform: Option<DAffine2>, form: GradientForm) -> [Graphic; 2] {
let [start_curvature, end_curvature] = form.curvatures();
let mut gradient = Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE]))
.with_attribute(ATTR_GRADIENT_START_CURVATURE, start_curvature)
.with_attribute(ATTR_GRADIENT_END_CURVATURE, end_curvature);
let mut gradient = Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE])).with_attribute(ATTR_GRADIENT_FORM, form);
if let Some(transform) = transform {
gradient.set_attribute(ATTR_TRANSFORM, transform);
}
Loaded 100 of 106 files, more files were not shown because too many files have changed in this diff. Show more