mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5a16e18b2a | ||
|
|
3c5e1b8a38 | ||
|
|
404d9f3047 | ||
|
|
c8667edacc | ||
|
|
2fa6b743fe | ||
|
|
daa8b6a5a4 | ||
|
|
39425ca7ea | ||
|
|
48e776c1af | ||
|
|
c19f79977b | ||
|
|
5c580f9dac | ||
|
|
e3b968f7e2 | ||
|
|
8f1b2bed5f | ||
|
|
c111308c67 | ||
|
|
20af96c1d9 | ||
|
|
2df0bd25c3 |
No files matched your search
Generated
+35
-23
@@ -1375,7 +1375,8 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "dpi"
|
||||
version = "0.1.2"
|
||||
source = "git+https://github.com/rust-windowing/winit.git#bd6fef1d80ba063cbe91e150b3fb343927cdc72b"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
@@ -7667,8 +7668,9 @@ checksum = "271414315aff87387382ec3d271b52d7ae78726f5d44ac98b4f4030c91880486"
|
||||
|
||||
[[package]]
|
||||
name = "winit"
|
||||
version = "0.30.12"
|
||||
source = "git+https://github.com/rust-windowing/winit.git#bd6fef1d80ba063cbe91e150b3fb343927cdc72b"
|
||||
version = "0.31.0-beta.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2879d2854d1a43e48f67322d4bd097afcb6eb8f8f775c8de0260a71aea1df1aa"
|
||||
dependencies = [
|
||||
"bitflags 2.11.0",
|
||||
"cfg_aliases",
|
||||
@@ -7694,8 +7696,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "winit-android"
|
||||
version = "0.30.12"
|
||||
source = "git+https://github.com/rust-windowing/winit.git#bd6fef1d80ba063cbe91e150b3fb343927cdc72b"
|
||||
version = "0.31.0-beta.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "51d9c0d2cd93efec3a9f9ad819cfaf0834782403af7c0d248c784ec0c61761df"
|
||||
dependencies = [
|
||||
"android-activity",
|
||||
"bitflags 2.11.0",
|
||||
@@ -7709,8 +7712,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "winit-appkit"
|
||||
version = "0.30.12"
|
||||
source = "git+https://github.com/rust-windowing/winit.git#bd6fef1d80ba063cbe91e150b3fb343927cdc72b"
|
||||
version = "0.31.0-beta.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "21310ca07851a49c348e0c2cc768e36b52ca65afda2c2354d78ed4b90074d8aa"
|
||||
dependencies = [
|
||||
"bitflags 2.11.0",
|
||||
"block2 0.6.2",
|
||||
@@ -7731,8 +7735,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "winit-common"
|
||||
version = "0.30.12"
|
||||
source = "git+https://github.com/rust-windowing/winit.git#bd6fef1d80ba063cbe91e150b3fb343927cdc72b"
|
||||
version = "0.31.0-beta.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "45375fbac4cbb77260d83a30b1f9d8105880dbac99a9ae97f56656694680ff69"
|
||||
dependencies = [
|
||||
"memmap2 0.9.10",
|
||||
"objc2 0.6.3",
|
||||
@@ -7746,8 +7751,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "winit-core"
|
||||
version = "0.30.12"
|
||||
source = "git+https://github.com/rust-windowing/winit.git#bd6fef1d80ba063cbe91e150b3fb343927cdc72b"
|
||||
version = "0.31.0-beta.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e4f0ccd7abb43740e2c6124ac7cae7d865ecec74eec63783e8922577ac232583"
|
||||
dependencies = [
|
||||
"bitflags 2.11.0",
|
||||
"cursor-icon",
|
||||
@@ -7761,8 +7767,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "winit-orbital"
|
||||
version = "0.30.12"
|
||||
source = "git+https://github.com/rust-windowing/winit.git#bd6fef1d80ba063cbe91e150b3fb343927cdc72b"
|
||||
version = "0.31.0-beta.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "51ea1fb262e7209f265f12bd0cc792c399b14355675e65531e9c8a87db287d46"
|
||||
dependencies = [
|
||||
"bitflags 2.11.0",
|
||||
"dpi",
|
||||
@@ -7776,8 +7783,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "winit-uikit"
|
||||
version = "0.30.12"
|
||||
source = "git+https://github.com/rust-windowing/winit.git#bd6fef1d80ba063cbe91e150b3fb343927cdc72b"
|
||||
version = "0.31.0-beta.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "680a356e798837d8eb274d4556e83bceaf81698194e31aafc5cfb8a9f2fab643"
|
||||
dependencies = [
|
||||
"bitflags 2.11.0",
|
||||
"block2 0.6.2",
|
||||
@@ -7797,8 +7805,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "winit-wayland"
|
||||
version = "0.30.12"
|
||||
source = "git+https://github.com/rust-windowing/winit.git#bd6fef1d80ba063cbe91e150b3fb343927cdc72b"
|
||||
version = "0.31.0-beta.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8ce5afb2ba07da603f84b722c95f9f9396d2cedae3944fb6c0cda4a6f88de545"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bitflags 2.11.0",
|
||||
@@ -7823,8 +7832,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "winit-web"
|
||||
version = "0.30.12"
|
||||
source = "git+https://github.com/rust-windowing/winit.git#bd6fef1d80ba063cbe91e150b3fb343927cdc72b"
|
||||
version = "0.31.0-beta.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8c2490a953fb776fbbd5e295d54f1c3847f4f15b6c3929ec53c09acda6487a92"
|
||||
dependencies = [
|
||||
"atomic-waker",
|
||||
"bitflags 2.11.0",
|
||||
@@ -7845,8 +7855,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "winit-win32"
|
||||
version = "0.30.12"
|
||||
source = "git+https://github.com/rust-windowing/winit.git#bd6fef1d80ba063cbe91e150b3fb343927cdc72b"
|
||||
version = "0.31.0-beta.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "644ea78af0e858aa3b092e5d1c67c41995a98220c81813f1353b28bc8bb91eaa"
|
||||
dependencies = [
|
||||
"bitflags 2.11.0",
|
||||
"cursor-icon",
|
||||
@@ -7861,8 +7872,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "winit-x11"
|
||||
version = "0.30.12"
|
||||
source = "git+https://github.com/rust-windowing/winit.git#bd6fef1d80ba063cbe91e150b3fb343927cdc72b"
|
||||
version = "0.31.0-beta.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aa5b600756534c7041aa93cd0d244d44b09fca1b89e202bd1cd80dd9f3636c46"
|
||||
dependencies = [
|
||||
"bitflags 2.11.0",
|
||||
"bytemuck",
|
||||
|
||||
+1
-3
@@ -160,7 +160,7 @@ web-sys = { version = "=0.3.98", features = [
|
||||
"HtmlImageElement",
|
||||
"ImageBitmapRenderingContext",
|
||||
] }
|
||||
winit = { git = "https://github.com/rust-windowing/winit.git" }
|
||||
winit = "0.31.0-beta.2"
|
||||
keyboard-types = "0.8"
|
||||
url = "2.5"
|
||||
tokio = { version = "1.29", features = ["fs", "macros", "io-std", "rt", "rt-multi-thread"] }
|
||||
@@ -260,8 +260,6 @@ lto = "thin"
|
||||
debug = true
|
||||
|
||||
[patch.crates-io]
|
||||
# Force cargo to use only one version of the dpi crate (vendoring breaks without this)
|
||||
dpi = { git = "https://github.com/rust-windowing/winit.git" }
|
||||
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
|
||||
cef = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite-149" }
|
||||
cef-dll-sys = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite-149" }
|
||||
+32
-56
@@ -9,19 +9,21 @@ use std::sync::mpsc::{Receiver, SyncSender};
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant};
|
||||
use winit::application::ApplicationHandler;
|
||||
use winit::dpi::{PhysicalPosition, PhysicalSize};
|
||||
use winit::event::{ButtonSource, ElementState, MouseButton, StartCause, WindowEvent};
|
||||
use winit::dpi::PhysicalSize;
|
||||
use winit::event::{ElementState, MouseButton, StartCause, WindowEvent};
|
||||
use winit::event_loop::run_on_demand::EventLoopExtRunOnDemand;
|
||||
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
|
||||
use winit::window::WindowId;
|
||||
|
||||
use crate::dirs;
|
||||
use crate::event::{AppEvent, AppEventScheduler};
|
||||
use crate::input::{InputAction, InputState};
|
||||
use crate::persist;
|
||||
use crate::preferences;
|
||||
use crate::render::{RenderError, RenderState};
|
||||
use crate::ui::{UiCommand, UiInstance};
|
||||
use crate::window::Window;
|
||||
use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, InputMessage, MouseKeys, MouseState, Preferences};
|
||||
use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, Preferences};
|
||||
use crate::wrapper::{DesktopWrapper, MmapResourceStorage, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
|
||||
|
||||
pub(crate) struct App {
|
||||
@@ -33,8 +35,7 @@ pub(crate) struct App {
|
||||
window_maximized: bool,
|
||||
window_fullscreen: bool,
|
||||
window_pending_drag: bool,
|
||||
pointer_position: PhysicalPosition<f64>,
|
||||
pointer_lock_position: Option<PhysicalPosition<f64>>,
|
||||
input_state: InputState,
|
||||
ui_scale: f64,
|
||||
app_event_receiver: Receiver<AppEvent>,
|
||||
app_event_scheduler: AppEventScheduler,
|
||||
@@ -106,8 +107,7 @@ impl App {
|
||||
window_maximized: false,
|
||||
window_fullscreen: false,
|
||||
window_pending_drag: false,
|
||||
pointer_position: Default::default(),
|
||||
pointer_lock_position: Default::default(),
|
||||
input_state: InputState::new(),
|
||||
ui_scale: 1.,
|
||||
app_event_receiver,
|
||||
app_event_scheduler,
|
||||
@@ -125,8 +125,8 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn run(mut self, event_loop: EventLoop) -> ExitReason {
|
||||
event_loop.run_app(&mut self).unwrap();
|
||||
pub(crate) fn run(mut self, mut event_loop: EventLoop) -> ExitReason {
|
||||
event_loop.run_app_on_demand(&mut self).unwrap();
|
||||
self.exit_reason
|
||||
}
|
||||
|
||||
@@ -264,6 +264,8 @@ impl App {
|
||||
});
|
||||
}
|
||||
DesktopFrontendMessage::UpdateViewportPhysicalBounds { x, y, width, height } => {
|
||||
self.input_state.set_viewport_info(x, y, width, height, self.window_scale);
|
||||
|
||||
if let Some(render_state) = &mut self.render_state
|
||||
&& let Some(window) = &self.window
|
||||
{
|
||||
@@ -342,7 +344,7 @@ impl App {
|
||||
}
|
||||
}
|
||||
DesktopFrontendMessage::PointerLock => {
|
||||
self.pointer_lock_position = Some(self.pointer_position);
|
||||
self.input_state.lock_pointer();
|
||||
if let Some(window) = &self.window {
|
||||
window.start_pointer_lock();
|
||||
}
|
||||
@@ -535,14 +537,13 @@ impl ApplicationHandler for App {
|
||||
|
||||
fn window_event(&mut self, _event_loop: &dyn ActiveEventLoop, _window_id: WindowId, event: WindowEvent) {
|
||||
// Handle pointer lock release
|
||||
if let Some(pointer_lock_position) = self.pointer_lock_position
|
||||
&& let WindowEvent::PointerButton {
|
||||
state: ElementState::Released,
|
||||
button: ButtonSource::Mouse(MouseButton::Left),
|
||||
..
|
||||
} = event
|
||||
if let WindowEvent::PointerButton {
|
||||
state: ElementState::Released,
|
||||
button,
|
||||
..
|
||||
} = &event && button.clone().mouse_button() == Some(MouseButton::Left)
|
||||
&& let Some(pointer_lock_position) = self.input_state.unlock_pointer()
|
||||
{
|
||||
self.pointer_lock_position = None;
|
||||
if let Some(window) = &self.window {
|
||||
window.end_pointer_lock();
|
||||
}
|
||||
@@ -554,7 +555,12 @@ impl ApplicationHandler for App {
|
||||
}));
|
||||
}
|
||||
|
||||
self.ui.send(UiCommand::Input(event.clone()));
|
||||
for action in self.input_state.process(&event) {
|
||||
match action {
|
||||
InputAction::Ui(event) => self.ui.send(UiCommand::Input(event)),
|
||||
InputAction::Editor(message) => self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message)),
|
||||
}
|
||||
}
|
||||
|
||||
match event {
|
||||
WindowEvent::CloseRequested => {
|
||||
@@ -611,50 +617,20 @@ impl ApplicationHandler for App {
|
||||
}
|
||||
}
|
||||
|
||||
// Forward and Back buttons are not supported by CEF and thus need to be directly forwarded the editor
|
||||
WindowEvent::PointerButton {
|
||||
button: ButtonSource::Mouse(button),
|
||||
state: ElementState::Pressed,
|
||||
..
|
||||
} => {
|
||||
let mouse_keys = match button {
|
||||
MouseButton::Back => Some(MouseKeys::BACK),
|
||||
MouseButton::Forward => Some(MouseKeys::FORWARD),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(mouse_keys) = mouse_keys {
|
||||
let message = DesktopWrapperMessage::Input(InputMessage::PointerDown {
|
||||
editor_mouse_state: MouseState { mouse_keys, ..Default::default() },
|
||||
modifier_keys: Default::default(),
|
||||
});
|
||||
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
|
||||
|
||||
let message = DesktopWrapperMessage::Input(InputMessage::PointerUp {
|
||||
editor_mouse_state: Default::default(),
|
||||
modifier_keys: Default::default(),
|
||||
});
|
||||
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
|
||||
}
|
||||
}
|
||||
|
||||
WindowEvent::PointerMoved { position, .. } | WindowEvent::PointerLeft { position: Some(position), .. } | WindowEvent::PointerEntered { position, .. }
|
||||
if self.pointer_lock_position.is_none() =>
|
||||
WindowEvent::PointerMoved { .. } | WindowEvent::PointerLeft { position: Some(_), .. } | WindowEvent::PointerEntered { .. }
|
||||
if !self.input_state.pointer_locked() && self.window_pending_drag =>
|
||||
{
|
||||
self.pointer_position = position;
|
||||
|
||||
if self.window_pending_drag {
|
||||
self.window_pending_drag = false;
|
||||
if let Some(window) = &self.window {
|
||||
window.start_drag();
|
||||
}
|
||||
self.window_pending_drag = false;
|
||||
if let Some(window) = &self.window {
|
||||
window.start_drag();
|
||||
}
|
||||
}
|
||||
|
||||
WindowEvent::PointerButton {
|
||||
button: ButtonSource::Mouse(MouseButton::Left),
|
||||
button,
|
||||
state: ElementState::Released,
|
||||
..
|
||||
} => {
|
||||
} if button.clone().mouse_button() == Some(MouseButton::Left) => {
|
||||
self.window_pending_drag = false;
|
||||
}
|
||||
|
||||
@@ -663,7 +639,7 @@ impl ApplicationHandler for App {
|
||||
}
|
||||
|
||||
fn device_event(&mut self, _event_loop: &dyn ActiveEventLoop, _device_id: Option<winit::event::DeviceId>, event: winit::event::DeviceEvent) {
|
||||
if self.pointer_lock_position.is_some()
|
||||
if self.input_state.pointer_locked()
|
||||
&& let winit::event::DeviceEvent::PointerMotion { delta: (x, y) } = event
|
||||
{
|
||||
let message = DesktopWrapperMessage::PointerLockMove { x, y };
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
use std::time::Instant;
|
||||
use winit::dpi::PhysicalPosition;
|
||||
use winit::event::{ButtonSource, ElementState, MouseButton, MouseScrollDelta, PointerSource, TabletToolData, TabletToolKind, WindowEvent};
|
||||
|
||||
use crate::ui::{MULTICLICK_ALLOWED_TRAVEL, MULTICLICK_TIMEOUT, PINCH_ZOOM_SPEED, SCROLL_LINE_HEIGHT, SCROLL_LINE_WIDTH, SCROLL_SPEED_X, SCROLL_SPEED_Y};
|
||||
use crate::wrapper::messages::{DesktopWrapperMessage, InputMessage, ModifierKeys, MouseKeys, PointerState, ScrollDelta};
|
||||
|
||||
pub(crate) struct InputState {
|
||||
start: Instant,
|
||||
viewport_info: Option<ViewportInfo>,
|
||||
pointer_lock_position: Option<PhysicalPosition<f64>>,
|
||||
modifier_keys: ModifierKeys,
|
||||
pointer_position: PhysicalPosition<f64>,
|
||||
pointer_keys: MouseKeys,
|
||||
ui_capture: bool,
|
||||
multiclick: Option<Multiclick>,
|
||||
}
|
||||
|
||||
pub(crate) enum InputAction {
|
||||
Ui(WindowEvent),
|
||||
Editor(DesktopWrapperMessage),
|
||||
}
|
||||
|
||||
impl InputAction {
|
||||
fn editor(message: InputMessage) -> Self {
|
||||
Self::Editor(DesktopWrapperMessage::Input(message))
|
||||
}
|
||||
}
|
||||
|
||||
impl InputState {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
start: Instant::now(),
|
||||
viewport_info: None,
|
||||
pointer_lock_position: None,
|
||||
modifier_keys: ModifierKeys::empty(),
|
||||
pointer_position: PhysicalPosition::default(),
|
||||
pointer_keys: MouseKeys::empty(),
|
||||
ui_capture: true,
|
||||
multiclick: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn set_viewport_info(&mut self, x: f64, y: f64, width: f64, height: f64, scale: f64) {
|
||||
self.viewport_info = Some(ViewportInfo { x, y, width, height, scale });
|
||||
}
|
||||
|
||||
pub(crate) fn lock_pointer(&mut self) {
|
||||
self.pointer_lock_position = Some(self.pointer_position);
|
||||
}
|
||||
|
||||
pub(crate) fn unlock_pointer(&mut self) -> Option<PhysicalPosition<f64>> {
|
||||
let position = self.pointer_lock_position.take();
|
||||
if let Some(position) = position {
|
||||
self.pointer_position = position;
|
||||
}
|
||||
position
|
||||
}
|
||||
|
||||
pub(crate) fn pointer_locked(&self) -> bool {
|
||||
self.pointer_lock_position.is_some()
|
||||
}
|
||||
|
||||
pub(crate) fn process(&mut self, event: &WindowEvent) -> Vec<InputAction> {
|
||||
match event {
|
||||
WindowEvent::PointerMoved { position, source, .. } => {
|
||||
self.pointer_position = *position;
|
||||
|
||||
let PointerSource::TabletTool { kind, data } = source else {
|
||||
return vec![InputAction::Ui(event.clone())];
|
||||
};
|
||||
let ui_capture = if self.pointer_keys.is_empty() {
|
||||
self.pointer_locked() || !self.in_viewport(*position)
|
||||
} else {
|
||||
self.ui_capture
|
||||
};
|
||||
if ui_capture {
|
||||
return vec![InputAction::Ui(event.clone())];
|
||||
}
|
||||
|
||||
vec![InputAction::editor(InputMessage::PointerMove {
|
||||
editor_mouse_state: self.tablet_pointer_state(kind, data),
|
||||
modifier_keys: self.modifier_keys,
|
||||
})]
|
||||
}
|
||||
WindowEvent::PointerEntered { position, .. } | WindowEvent::PointerLeft { position: Some(position), .. } => {
|
||||
self.pointer_position = *position;
|
||||
vec![InputAction::Ui(event.clone())]
|
||||
}
|
||||
WindowEvent::PointerButton { state, button, position, .. } => {
|
||||
self.pointer_position = *position;
|
||||
|
||||
let tablet = matches!(button, ButtonSource::TabletTool { .. });
|
||||
|
||||
// Stroke keeps capture decided from first button press until all buttons are released.
|
||||
if state.is_pressed() && self.pointer_keys.is_empty() {
|
||||
self.ui_capture = self.pointer_locked() || !tablet || !self.in_viewport(*position);
|
||||
}
|
||||
|
||||
let mouse_button = button.clone().mouse_button();
|
||||
let keys = match mouse_button {
|
||||
Some(MouseButton::Left) => MouseKeys::LEFT,
|
||||
Some(MouseButton::Right) => MouseKeys::RIGHT,
|
||||
Some(MouseButton::Middle) => MouseKeys::MIDDLE,
|
||||
Some(MouseButton::Back) => MouseKeys::BACK,
|
||||
Some(MouseButton::Forward) => MouseKeys::FORWARD,
|
||||
_ => MouseKeys::NONE,
|
||||
};
|
||||
match state {
|
||||
ElementState::Pressed => self.pointer_keys.insert(keys),
|
||||
ElementState::Released => self.pointer_keys.remove(keys),
|
||||
}
|
||||
|
||||
let back_or_forward = matches!(mouse_button, Some(MouseButton::Back | MouseButton::Forward));
|
||||
if self.pointer_locked() || !(back_or_forward || (tablet && !self.ui_capture)) {
|
||||
return vec![InputAction::Ui(event.clone())];
|
||||
}
|
||||
|
||||
let editor_mouse_state = match button {
|
||||
ButtonSource::TabletTool { kind, data, .. } => self.tablet_pointer_state(kind, data),
|
||||
_ => self.pointer_state(),
|
||||
};
|
||||
let modifier_keys = self.modifier_keys;
|
||||
match state {
|
||||
ElementState::Pressed => vec![InputAction::editor(InputMessage::PointerDown { editor_mouse_state, modifier_keys })],
|
||||
ElementState::Released => {
|
||||
let mut actions = vec![InputAction::editor(InputMessage::PointerUp { editor_mouse_state, modifier_keys })];
|
||||
if let Some(mouse_button) = mouse_button
|
||||
&& self.track_multiclick(mouse_button, *position)
|
||||
{
|
||||
actions.push(InputAction::editor(InputMessage::DoubleClick {
|
||||
editor_mouse_state: PointerState {
|
||||
mouse_keys: keys,
|
||||
..editor_mouse_state
|
||||
},
|
||||
modifier_keys,
|
||||
}));
|
||||
}
|
||||
actions
|
||||
}
|
||||
}
|
||||
}
|
||||
WindowEvent::MouseWheel { delta, .. } => {
|
||||
if self.pointer_locked() || !self.in_viewport(self.pointer_position) {
|
||||
return vec![InputAction::Ui(event.clone())];
|
||||
}
|
||||
|
||||
let (x, y) = match delta {
|
||||
MouseScrollDelta::LineDelta(x, y) => (f64::from(*x) * SCROLL_LINE_WIDTH, f64::from(*y) * SCROLL_LINE_HEIGHT),
|
||||
MouseScrollDelta::PixelDelta(position) => (position.x, position.y),
|
||||
};
|
||||
|
||||
let scroll_delta = ScrollDelta::new(-x * SCROLL_SPEED_X, -y * SCROLL_SPEED_Y, 0.);
|
||||
|
||||
vec![InputAction::editor(InputMessage::WheelScroll {
|
||||
editor_mouse_state: PointerState { scroll_delta, ..self.pointer_state() },
|
||||
modifier_keys: self.modifier_keys,
|
||||
})]
|
||||
}
|
||||
WindowEvent::PinchGesture { delta, .. } => {
|
||||
if self.pointer_locked() || !self.in_viewport(self.pointer_position) || !delta.is_normal() {
|
||||
return vec![InputAction::Ui(event.clone())];
|
||||
}
|
||||
|
||||
// TODO: This is a temporary solution to handle pinch gestures, we should handle pinch gestures editor-side instead.
|
||||
let scroll_delta = ScrollDelta::new(0., -delta * PINCH_ZOOM_SPEED, 0.);
|
||||
vec![InputAction::editor(InputMessage::WheelScroll {
|
||||
editor_mouse_state: PointerState { scroll_delta, ..self.pointer_state() },
|
||||
modifier_keys: self.modifier_keys | ModifierKeys::CONTROL,
|
||||
})]
|
||||
}
|
||||
WindowEvent::ModifiersChanged(modifiers) => {
|
||||
let modifiers = modifiers.state();
|
||||
self.modifier_keys = ModifierKeys::empty();
|
||||
self.modifier_keys.set(ModifierKeys::SHIFT, modifiers.shift_key());
|
||||
self.modifier_keys.set(ModifierKeys::CONTROL, modifiers.control_key());
|
||||
self.modifier_keys.set(ModifierKeys::ALT, modifiers.alt_key());
|
||||
self.modifier_keys.set(ModifierKeys::META_OR_COMMAND, modifiers.meta_key());
|
||||
|
||||
vec![InputAction::Ui(event.clone())]
|
||||
}
|
||||
_ => vec![InputAction::Ui(event.clone())],
|
||||
}
|
||||
}
|
||||
|
||||
fn scale(&self) -> f64 {
|
||||
self.viewport_info.as_ref().map_or(1., |info| info.scale)
|
||||
}
|
||||
|
||||
fn in_viewport(&self, position: PhysicalPosition<f64>) -> bool {
|
||||
self.viewport_info.as_ref().is_some_and(|info| info.contains(position))
|
||||
}
|
||||
|
||||
fn pointer_state(&self) -> PointerState {
|
||||
PointerState {
|
||||
editor_position: (self.pointer_position.x / self.scale(), self.pointer_position.y / self.scale()).into(),
|
||||
mouse_keys: self.pointer_keys,
|
||||
time: Some(self.start.elapsed().as_secs_f64() * 1000.),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn tablet_pointer_state(&self, kind: &TabletToolKind, data: &TabletToolData) -> PointerState {
|
||||
PointerState {
|
||||
pressure: data.force.map(|force| force.normalized(None)),
|
||||
tilt: data.clone().tilt().map(|tilt| (f64::from(tilt.x), f64::from(tilt.y)).into()),
|
||||
twist: data.twist.map(f64::from),
|
||||
wheel: data.tangential_force.map(f64::from),
|
||||
eraser: matches!(kind, TabletToolKind::Eraser),
|
||||
..self.pointer_state()
|
||||
}
|
||||
}
|
||||
|
||||
fn track_multiclick(&mut self, button: MouseButton, position: PhysicalPosition<f64>) -> bool {
|
||||
let now = Instant::now();
|
||||
let travel = MULTICLICK_ALLOWED_TRAVEL as f64;
|
||||
let double = self.multiclick.take().is_some_and(|click| {
|
||||
click.button == button && now.duration_since(click.time) <= MULTICLICK_TIMEOUT && (position.x - click.position.x).abs() <= travel && (position.y - click.position.y).abs() <= travel
|
||||
});
|
||||
if !double {
|
||||
self.multiclick = Some(Multiclick { button, time: now, position });
|
||||
}
|
||||
double
|
||||
}
|
||||
}
|
||||
|
||||
struct ViewportInfo {
|
||||
x: f64,
|
||||
y: f64,
|
||||
width: f64,
|
||||
height: f64,
|
||||
scale: f64,
|
||||
}
|
||||
|
||||
impl ViewportInfo {
|
||||
fn contains(&self, position: PhysicalPosition<f64>) -> bool {
|
||||
position.x >= self.x && position.y >= self.y && position.x <= self.x + self.width && position.y <= self.y + self.height
|
||||
}
|
||||
}
|
||||
|
||||
struct Multiclick {
|
||||
button: MouseButton,
|
||||
time: Instant,
|
||||
position: PhysicalPosition<f64>,
|
||||
}
|
||||
@@ -17,6 +17,7 @@ mod cli;
|
||||
mod dirs;
|
||||
mod event;
|
||||
mod gpu_context;
|
||||
mod input;
|
||||
mod persist;
|
||||
mod preferences;
|
||||
mod render;
|
||||
|
||||
@@ -344,6 +344,14 @@ unsafe fn position_helper(main: HWND, helper: HWND) {
|
||||
let h = (r.bottom - r.top) + RESIZE_BAND_THICKNESS * 2;
|
||||
|
||||
let _ = unsafe { SetWindowPos(helper, Some(main), x, y, w, h, SWP_NOACTIVATE | SWP_NOSENDCHANGING) };
|
||||
|
||||
let outer = unsafe { CreateRectRgn(0, 0, w, h) };
|
||||
let inner = unsafe { CreateRectRgn(RESIZE_BAND_THICKNESS, RESIZE_BAND_THICKNESS, w - RESIZE_BAND_THICKNESS, h - RESIZE_BAND_THICKNESS) };
|
||||
let _ = unsafe { CombineRgn(Some(outer), Some(outer), Some(inner), RGN_DIFF) };
|
||||
let _ = unsafe { DeleteObject(inner.into()) };
|
||||
if unsafe { SetWindowRgn(helper, Some(outer), false) } == 0 {
|
||||
let _ = unsafe { DeleteObject(outer.into()) };
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn calculate_hit(helper: HWND, lparam: LPARAM) -> u32 {
|
||||
|
||||
+18
-18
@@ -1,5 +1,23 @@
|
||||
use std::time::Duration;
|
||||
|
||||
pub const MULTICLICK_TIMEOUT: Duration = Duration::from_millis(500);
|
||||
pub const MULTICLICK_ALLOWED_TRAVEL: usize = 4;
|
||||
|
||||
pub const SCROLL_LINE_HEIGHT: f64 = 40.;
|
||||
pub const SCROLL_LINE_WIDTH: f64 = 40.;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub const SCROLL_SPEED_X: f64 = 3.;
|
||||
#[cfg(target_os = "linux")]
|
||||
pub const SCROLL_SPEED_Y: f64 = 3.;
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
pub const SCROLL_SPEED_X: f64 = 1.;
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
pub const SCROLL_SPEED_Y: f64 = 1.;
|
||||
|
||||
pub const PINCH_ZOOM_SPEED: f64 = 300.;
|
||||
|
||||
pub(crate) const RESOURCE_SCHEME: &str = "resources";
|
||||
pub(crate) const RESOURCE_DOMAIN: &str = "resources";
|
||||
|
||||
@@ -17,21 +35,3 @@ pub(crate) const HOST_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(crate) const IPC_BOOTSTRAP_PREFIX: &str = "art.graphite.Graphite.ipc.";
|
||||
|
||||
pub(crate) const SCROLL_LINE_HEIGHT: usize = 40;
|
||||
pub(crate) const SCROLL_LINE_WIDTH: usize = 40;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(crate) const SCROLL_SPEED_X: f32 = 3.;
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(crate) const SCROLL_SPEED_Y: f32 = 3.;
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
pub(crate) const SCROLL_SPEED_X: f32 = 1.;
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
pub(crate) const SCROLL_SPEED_Y: f32 = 1.;
|
||||
|
||||
pub(crate) const PINCH_ZOOM_SPEED: f64 = 300.;
|
||||
|
||||
pub(crate) const MULTICLICK_TIMEOUT: Duration = Duration::from_millis(500);
|
||||
pub(crate) const MULTICLICK_ALLOWED_TRAVEL: usize = 4;
|
||||
@@ -82,14 +82,16 @@ pub(crate) fn translate(input_state: &mut InputState, event: &WindowEvent) -> Ve
|
||||
}
|
||||
WindowEvent::PointerButton { state, button, position, .. } => {
|
||||
let mouse_button = match button {
|
||||
ButtonSource::Mouse(mouse_button) => mouse_button,
|
||||
_ => {
|
||||
return Vec::new(); // TODO: Handle touch input
|
||||
}
|
||||
ButtonSource::Mouse(mouse_button) => Some(*mouse_button),
|
||||
ButtonSource::TabletTool { button, .. } => (*button).into(),
|
||||
_ => None, // TODO: Handle touch input
|
||||
};
|
||||
let Some(mouse_button) = mouse_button else {
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let _ = input_state.cursor_move(position);
|
||||
let click_count = input_state.mouse_input(mouse_button, state).into();
|
||||
let click_count = input_state.mouse_input(&mouse_button, state).into();
|
||||
let up = matches!(state, ElementState::Released);
|
||||
let button = match mouse_button {
|
||||
MouseButton::Left => MouseButtonKind::Left,
|
||||
@@ -110,8 +112,8 @@ pub(crate) fn translate(input_state: &mut InputState, event: &WindowEvent) -> Ve
|
||||
MouseScrollDelta::LineDelta(x, y) => (x * SCROLL_LINE_WIDTH as f32, y * SCROLL_LINE_HEIGHT as f32),
|
||||
MouseScrollDelta::PixelDelta(physical_position) => (physical_position.x as f32, physical_position.y as f32),
|
||||
};
|
||||
delta_x *= SCROLL_SPEED_X;
|
||||
delta_y *= SCROLL_SPEED_Y;
|
||||
delta_x *= SCROLL_SPEED_X as f32;
|
||||
delta_y *= SCROLL_SPEED_Y as f32;
|
||||
|
||||
vec![InputEvent::MouseWheel {
|
||||
data: input_state.mouse_data(),
|
||||
|
||||
@@ -22,6 +22,8 @@ mod resources;
|
||||
mod utility;
|
||||
mod view;
|
||||
|
||||
pub use consts::{MULTICLICK_ALLOWED_TRAVEL, MULTICLICK_TIMEOUT, PINCH_ZOOM_SPEED, SCROLL_LINE_HEIGHT, SCROLL_LINE_WIDTH, SCROLL_SPEED_X, SCROLL_SPEED_Y};
|
||||
|
||||
pub struct UiContext<S: Stage = Started> {
|
||||
inner: S::ContextData,
|
||||
}
|
||||
|
||||
@@ -4,8 +4,8 @@ use std::path::PathBuf;
|
||||
pub(crate) use graphite_editor::messages::prelude::Message as EditorMessage;
|
||||
|
||||
pub use graphite_editor::messages::frontend::utility_types::{DocumentInfo, PersistedState};
|
||||
pub use graphite_editor::messages::input_mapper::utility_types::input_keyboard::{Key, ModifierKeys};
|
||||
pub use graphite_editor::messages::input_mapper::utility_types::input_mouse::{EditorMouseState as MouseState, EditorPosition as Position, MouseKeys};
|
||||
pub use graphite_editor::messages::input_mapper::utility_types::keyboard::{Key, ModifierKeys};
|
||||
pub use graphite_editor::messages::input_mapper::utility_types::pointer::{EditorPointerState as PointerState, EditorPosition as Position, MouseKeys, ScrollDelta};
|
||||
pub use graphite_editor::messages::prelude::DocumentId;
|
||||
pub use graphite_editor::messages::prelude::InputPreprocessorMessage as InputMessage;
|
||||
pub use graphite_editor::messages::prelude::PreferencesMessageHandler as Preferences;
|
||||
|
||||
@@ -3,7 +3,7 @@ pub(crate) mod menu {
|
||||
use base64::engine::Engine;
|
||||
use base64::engine::general_purpose::STANDARD as BASE64;
|
||||
|
||||
use graphite_editor::messages::input_mapper::utility_types::input_keyboard::{Key, LabeledKeyOrMouseMotion, LabeledShortcut};
|
||||
use graphite_editor::messages::input_mapper::utility_types::keyboard::{Key, LabeledKeyOrMouseMotion, LabeledShortcut};
|
||||
use graphite_editor::messages::input_mapper::utility_types::misc::ActionShortcut;
|
||||
use graphite_editor::messages::layout::LayoutMessage;
|
||||
use graphite_editor::messages::tool::tool_messages::tool_prelude::{Layout, LayoutGroup, LayoutTarget, MenuListEntry, Widget, WidgetId, WidgetRow};
|
||||
|
||||
@@ -12,10 +12,10 @@ use graph_craft::application_io::resource::{DataSource, ResourceHash};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::raster::Image;
|
||||
use graphene_std::subpath::BezierHandles;
|
||||
use graphene_std::vector::misc::HandleId;
|
||||
use graphene_std::vector::misc::{BezierHandles, HandleId, point_to_dvec2, segment_to_handles};
|
||||
use graphene_std::vector::{PointId, SegmentId, VectorModificationType};
|
||||
use graphite_proc_macros::{ExtractField, message_handler_data};
|
||||
use kurbo::ParamCurve;
|
||||
use std::sync::Arc;
|
||||
|
||||
const CLIPBOARD_PREFIX: &str = "graphite: ";
|
||||
@@ -425,7 +425,7 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
|
||||
// Create new segment ids and add the segments into the existing Vector path
|
||||
let mut segments_map = HashMap::new();
|
||||
for (segment_id, bezier, start, end) in new_vector.segment_bezier_iter() {
|
||||
for (segment_id, segment, start, end) in new_vector.segment_iter() {
|
||||
let (Some(&start_point), Some(&end_point)) = (points_map.get(&start), points_map.get(&end)) else {
|
||||
warn!("Skipping pasted vector segment with an unknown endpoint");
|
||||
continue;
|
||||
@@ -434,10 +434,12 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
let new_segment_id = SegmentId::generate();
|
||||
segments_map.insert(segment_id, new_segment_id);
|
||||
|
||||
let handles = match bezier.handles {
|
||||
let segment_start = point_to_dvec2(segment.start());
|
||||
let segment_end = point_to_dvec2(segment.end());
|
||||
let handles = match segment_to_handles(&segment) {
|
||||
BezierHandles::Linear => [None, None],
|
||||
BezierHandles::Quadratic { handle } => [Some(handle - bezier.start), None],
|
||||
BezierHandles::Cubic { handle_start, handle_end } => [Some(handle_start - bezier.start), Some(handle_end - bezier.end)],
|
||||
BezierHandles::Quadratic { handle } => [Some(handle - segment_start), None],
|
||||
BezierHandles::Cubic { handle_start, handle_end } => [Some(handle_start - segment_start), Some(handle_end - segment_end)],
|
||||
};
|
||||
|
||||
let points = [start_point, end_point];
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::Key;
|
||||
use crate::messages::input_mapper::utility_types::input_mouse::MouseButton;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::Key;
|
||||
use crate::messages::input_mapper::utility_types::pointer::MouseButton;
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
#[impl_message(Message, KeyMappingMessage, Lookup)]
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::utility_types::input_keyboard::KeysGroup;
|
||||
use super::utility_types::keyboard::KeysGroup;
|
||||
use super::utility_types::misc::Mapping;
|
||||
use crate::application::Editor;
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::{self, Key};
|
||||
use crate::messages::input_mapper::utility_types::keyboard::{self, Key};
|
||||
use crate::messages::input_mapper::utility_types::misc::MappingEntry;
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
@@ -58,7 +58,7 @@ impl InputMapperMessageHandler {
|
||||
.map(|i| {
|
||||
// TODO: Use a safe solution eventually
|
||||
assert!(
|
||||
i < input_keyboard::NUMBER_OF_KEYS,
|
||||
i < keyboard::NUMBER_OF_KEYS,
|
||||
"Attempting to convert a Key with enum index {i}, which is larger than the number of Key enums",
|
||||
);
|
||||
(i as u8).try_into().unwrap()
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
use crate::application::Editor;
|
||||
use crate::consts::{BIG_NUDGE_AMOUNT, BRUSH_SIZE_CHANGE_KEYBOARD, NUDGE_AMOUNT};
|
||||
use crate::messages::input_mapper::key_mapping::MappingVariant;
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::{Key, KeyStates};
|
||||
use crate::messages::input_mapper::utility_types::input_mouse::MouseButton;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::{Key, KeyStates};
|
||||
use crate::messages::input_mapper::utility_types::macros::*;
|
||||
use crate::messages::input_mapper::utility_types::misc::MappingEntry;
|
||||
use crate::messages::input_mapper::utility_types::misc::{KeyMappingEntries, Mapping};
|
||||
use crate::messages::input_mapper::utility_types::pointer::MouseButton;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::Direction;
|
||||
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::messages::input_mapper::input_mapper_message_handler::InputMapperMessageContext;
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::KeysGroup;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::KeysGroup;
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
#[derive(ExtractField)]
|
||||
|
||||
File renamed without changes.
@@ -162,7 +162,7 @@ macro_rules! action_shortcut {
|
||||
macro_rules! action_shortcut_manual {
|
||||
($($keys:expr),*) => {
|
||||
Some(crate::messages::input_mapper::utility_types::misc::ActionShortcut::Shortcut(
|
||||
crate::messages::input_mapper::utility_types::input_keyboard::LabeledShortcut(vec![$($keys.into()),*]).into(),
|
||||
crate::messages::input_mapper::utility_types::keyboard::LabeledShortcut(vec![$($keys.into()),*]).into(),
|
||||
))
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::input_keyboard::{KeysGroup, LabeledShortcut, all_required_modifiers_pressed};
|
||||
use super::keyboard::{KeysGroup, LabeledShortcut, all_required_modifiers_pressed};
|
||||
use crate::messages::input_mapper::key_mapping::MappingVariant;
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::{KeyStates, NUMBER_OF_KEYS};
|
||||
use crate::messages::input_mapper::utility_types::input_mouse::NUMBER_OF_MOUSE_BUTTONS;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::{KeyStates, NUMBER_OF_KEYS};
|
||||
use crate::messages::input_mapper::utility_types::pointer::NUMBER_OF_MOUSE_BUTTONS;
|
||||
use crate::messages::prelude::*;
|
||||
use core::time::Duration;
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
pub mod input_keyboard;
|
||||
pub mod input_mouse;
|
||||
pub mod keyboard;
|
||||
pub mod pointer;
|
||||
|
||||
pub mod macros;
|
||||
pub mod misc;
|
||||
+27
-9
@@ -50,15 +50,21 @@ impl ScrollDelta {
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Document the difference between this and EditorMouseState
|
||||
// TODO: Document the difference between this and EditorPointerState
|
||||
#[derive(Debug, Copy, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct MouseState {
|
||||
pub struct PointerState {
|
||||
pub position: ViewportPosition,
|
||||
pub mouse_keys: MouseKeys,
|
||||
pub scroll_delta: ScrollDelta,
|
||||
pub time: Option<f64>,
|
||||
pub pressure: Option<f64>,
|
||||
pub tilt: Option<DVec2>,
|
||||
pub twist: Option<f64>,
|
||||
pub wheel: Option<f64>,
|
||||
pub eraser: bool,
|
||||
}
|
||||
|
||||
impl MouseState {
|
||||
impl PointerState {
|
||||
pub fn finish_transaction(&self, drag_start: DVec2, responses: &mut VecDeque<Message>) {
|
||||
let drag_too_small = drag_start.distance(self.position) <= DRAG_THRESHOLD;
|
||||
let response = if drag_too_small { DocumentMessage::AbortTransaction } else { DocumentMessage::EndTransaction };
|
||||
@@ -66,15 +72,21 @@ impl MouseState {
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Document the difference between this and MouseState
|
||||
// TODO: Document the difference between this and PointerState
|
||||
#[derive(Debug, Copy, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct EditorMouseState {
|
||||
pub struct EditorPointerState {
|
||||
pub editor_position: EditorPosition,
|
||||
pub mouse_keys: MouseKeys,
|
||||
pub scroll_delta: ScrollDelta,
|
||||
pub time: Option<f64>,
|
||||
pub pressure: Option<f64>,
|
||||
pub tilt: Option<DVec2>,
|
||||
pub twist: Option<f64>,
|
||||
pub wheel: Option<f64>,
|
||||
pub eraser: bool,
|
||||
}
|
||||
|
||||
impl EditorMouseState {
|
||||
impl EditorPointerState {
|
||||
pub fn from_keys_and_editor_position(keys: u8, editor_position: EditorPosition) -> Self {
|
||||
// TODO: Some graphic tablets send key codes not mentioned in the spec. In the future we would like to support these as well.
|
||||
let mouse_keys = MouseKeys::from_bits_truncate(keys);
|
||||
@@ -82,15 +94,21 @@ impl EditorMouseState {
|
||||
Self {
|
||||
editor_position,
|
||||
mouse_keys,
|
||||
scroll_delta: ScrollDelta::default(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_mouse_state(&self, viewport: &ViewportMessageHandler) -> MouseState {
|
||||
MouseState {
|
||||
pub fn to_pointer_state(&self, viewport: &ViewportMessageHandler) -> PointerState {
|
||||
PointerState {
|
||||
position: (viewport.logical(self.editor_position) - viewport.offset()).into(),
|
||||
mouse_keys: self.mouse_keys,
|
||||
scroll_delta: self.scroll_delta,
|
||||
time: self.time,
|
||||
pressure: self.pressure,
|
||||
tilt: self.tilt,
|
||||
twist: self.twist,
|
||||
wheel: self.wheel,
|
||||
eraser: self.eraser,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,17 @@
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::{Key, ModifierKeys};
|
||||
use crate::messages::input_mapper::utility_types::input_mouse::EditorMouseState;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::{Key, ModifierKeys};
|
||||
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
#[impl_message(Message, InputPreprocessor)]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum InputPreprocessorMessage {
|
||||
DoubleClick { editor_mouse_state: EditorMouseState, modifier_keys: ModifierKeys },
|
||||
DoubleClick { editor_mouse_state: EditorPointerState, modifier_keys: ModifierKeys },
|
||||
KeyDown { key: Key, key_repeat: bool, modifier_keys: ModifierKeys },
|
||||
KeyUp { key: Key, key_repeat: bool, modifier_keys: ModifierKeys },
|
||||
PointerDown { editor_mouse_state: EditorMouseState, modifier_keys: ModifierKeys },
|
||||
PointerMove { editor_mouse_state: EditorMouseState, modifier_keys: ModifierKeys },
|
||||
PointerUp { editor_mouse_state: EditorMouseState, modifier_keys: ModifierKeys },
|
||||
PointerShake { editor_mouse_state: EditorMouseState, modifier_keys: ModifierKeys },
|
||||
PointerDown { editor_mouse_state: EditorPointerState, modifier_keys: ModifierKeys },
|
||||
PointerMove { editor_mouse_state: EditorPointerState, modifier_keys: ModifierKeys },
|
||||
PointerUp { editor_mouse_state: EditorPointerState, modifier_keys: ModifierKeys },
|
||||
PointerShake { editor_mouse_state: EditorPointerState, modifier_keys: ModifierKeys },
|
||||
CurrentTime { timestamp: u64 },
|
||||
WheelScroll { editor_mouse_state: EditorMouseState, modifier_keys: ModifierKeys },
|
||||
WheelScroll { editor_mouse_state: EditorPointerState, modifier_keys: ModifierKeys },
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
use crate::application::Editor;
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::{Key, KeyStates, ModifierKeys};
|
||||
use crate::messages::input_mapper::utility_types::input_mouse::{MouseButton, MouseKeys, MouseState};
|
||||
use crate::messages::input_mapper::utility_types::keyboard::{Key, KeyStates, ModifierKeys};
|
||||
use crate::messages::input_mapper::utility_types::misc::FrameTimeInfo;
|
||||
use crate::messages::input_mapper::utility_types::pointer::{MouseButton, MouseKeys, PointerState};
|
||||
use crate::messages::prelude::*;
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -15,7 +15,8 @@ pub struct InputPreprocessorMessageHandler {
|
||||
pub frame_time: FrameTimeInfo,
|
||||
pub time: u64,
|
||||
pub keyboard: KeyStates,
|
||||
pub mouse: MouseState,
|
||||
pub mouse: PointerState,
|
||||
pointer_down_time: f64,
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
@@ -27,10 +28,10 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
|
||||
InputPreprocessorMessage::DoubleClick { editor_mouse_state, modifier_keys } => {
|
||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||
|
||||
let mouse_state = editor_mouse_state.to_mouse_state(viewport);
|
||||
self.mouse.position = mouse_state.position;
|
||||
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
|
||||
self.mouse.position = pointer_state.position;
|
||||
|
||||
for key in mouse_state.mouse_keys {
|
||||
for key in pointer_state.mouse_keys {
|
||||
responses.add(InputMapperMessage::DoubleClick(match key {
|
||||
MouseKeys::LEFT => MouseButton::Left,
|
||||
MouseKeys::RIGHT => MouseButton::Right,
|
||||
@@ -60,35 +61,35 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
|
||||
InputPreprocessorMessage::PointerDown { editor_mouse_state, modifier_keys } => {
|
||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||
|
||||
let mouse_state = editor_mouse_state.to_mouse_state(viewport);
|
||||
self.mouse.position = mouse_state.position;
|
||||
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
|
||||
self.mouse.position = pointer_state.position;
|
||||
|
||||
self.translate_mouse_event(mouse_state, true, responses);
|
||||
self.translate_mouse_event(pointer_state, true, responses);
|
||||
}
|
||||
InputPreprocessorMessage::PointerMove { editor_mouse_state, modifier_keys } => {
|
||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||
|
||||
let mouse_state = editor_mouse_state.to_mouse_state(viewport);
|
||||
self.mouse.position = mouse_state.position;
|
||||
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
|
||||
self.mouse.position = pointer_state.position;
|
||||
|
||||
responses.add(InputMapperMessage::PointerMove);
|
||||
|
||||
// While any pointer button is already down, additional button down events are not reported, but they are sent as `pointermove` events
|
||||
self.translate_mouse_event(mouse_state, false, responses);
|
||||
self.translate_mouse_event(pointer_state, false, responses);
|
||||
}
|
||||
InputPreprocessorMessage::PointerUp { editor_mouse_state, modifier_keys } => {
|
||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||
|
||||
let mouse_state = editor_mouse_state.to_mouse_state(viewport);
|
||||
self.mouse.position = mouse_state.position;
|
||||
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
|
||||
self.mouse.position = pointer_state.position;
|
||||
|
||||
self.translate_mouse_event(mouse_state, false, responses);
|
||||
self.translate_mouse_event(pointer_state, false, responses);
|
||||
}
|
||||
InputPreprocessorMessage::PointerShake { editor_mouse_state, modifier_keys } => {
|
||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||
|
||||
let mouse_state = editor_mouse_state.to_mouse_state(viewport);
|
||||
self.mouse.position = mouse_state.position;
|
||||
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
|
||||
self.mouse.position = pointer_state.position;
|
||||
|
||||
responses.add(InputMapperMessage::PointerShake);
|
||||
}
|
||||
@@ -100,9 +101,9 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
|
||||
InputPreprocessorMessage::WheelScroll { editor_mouse_state, modifier_keys } => {
|
||||
self.update_states_of_modifier_keys(modifier_keys, responses);
|
||||
|
||||
let mouse_state = editor_mouse_state.to_mouse_state(viewport);
|
||||
self.mouse.position = mouse_state.position;
|
||||
self.mouse.scroll_delta = mouse_state.scroll_delta;
|
||||
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
|
||||
self.mouse.position = pointer_state.position;
|
||||
self.mouse.scroll_delta = pointer_state.scroll_delta;
|
||||
|
||||
responses.add(InputMapperMessage::WheelScroll);
|
||||
}
|
||||
@@ -116,7 +117,7 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
|
||||
}
|
||||
|
||||
impl InputPreprocessorMessageHandler {
|
||||
fn translate_mouse_event(&mut self, mut new_state: MouseState, allow_first_button_down: bool, responses: &mut VecDeque<Message>) {
|
||||
fn translate_mouse_event(&mut self, mut new_state: PointerState, allow_first_button_down: bool, responses: &mut VecDeque<Message>) {
|
||||
let click_mappings = [
|
||||
(MouseKeys::LEFT, Key::MouseLeft),
|
||||
(MouseKeys::RIGHT, Key::MouseRight),
|
||||
@@ -144,6 +145,13 @@ impl InputPreprocessorMessageHandler {
|
||||
}
|
||||
}
|
||||
|
||||
let raw_time = new_state.time.unwrap_or(self.time as f64);
|
||||
if self.mouse.mouse_keys == MouseKeys::empty() {
|
||||
self.pointer_down_time = raw_time;
|
||||
}
|
||||
let interacting = (self.mouse.mouse_keys | new_state.mouse_keys) != MouseKeys::empty();
|
||||
new_state.time = interacting.then_some(raw_time - self.pointer_down_time);
|
||||
|
||||
self.mouse = new_state;
|
||||
}
|
||||
|
||||
@@ -185,18 +193,17 @@ impl InputPreprocessorMessageHandler {
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::{Key, ModifierKeys};
|
||||
use crate::messages::input_mapper::utility_types::input_mouse::{EditorMouseState, MouseKeys, ScrollDelta};
|
||||
use crate::messages::input_mapper::utility_types::keyboard::{Key, ModifierKeys};
|
||||
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
#[test]
|
||||
fn process_action_mouse_move_handle_modifier_keys() {
|
||||
let mut input_preprocessor = InputPreprocessorMessageHandler::default();
|
||||
|
||||
let editor_mouse_state = EditorMouseState {
|
||||
let editor_mouse_state = EditorPointerState {
|
||||
editor_position: (4., 809.).into(),
|
||||
mouse_keys: MouseKeys::default(),
|
||||
scroll_delta: ScrollDelta::default(),
|
||||
..Default::default()
|
||||
};
|
||||
let modifier_keys = ModifierKeys::ALT;
|
||||
let message = InputPreprocessorMessage::PointerMove { editor_mouse_state, modifier_keys };
|
||||
@@ -216,7 +223,7 @@ mod test {
|
||||
fn process_action_mouse_down_handle_modifier_keys() {
|
||||
let mut input_preprocessor = InputPreprocessorMessageHandler::default();
|
||||
|
||||
let editor_mouse_state = EditorMouseState::default();
|
||||
let editor_mouse_state = EditorPointerState::default();
|
||||
let modifier_keys = ModifierKeys::CONTROL;
|
||||
let message = InputPreprocessorMessage::PointerDown { editor_mouse_state, modifier_keys };
|
||||
|
||||
@@ -235,7 +242,7 @@ mod test {
|
||||
fn process_action_mouse_up_handle_modifier_keys() {
|
||||
let mut input_preprocessor = InputPreprocessorMessageHandler::default();
|
||||
|
||||
let editor_mouse_state = EditorMouseState::default();
|
||||
let editor_mouse_state = EditorPointerState::default();
|
||||
let modifier_keys = ModifierKeys::SHIFT;
|
||||
let message = InputPreprocessorMessage::PointerUp { editor_mouse_state, modifier_keys };
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::KeysGroup;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::KeysGroup;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
@@ -2,7 +2,7 @@ use super::widgets::button_widgets::*;
|
||||
use super::widgets::input_widgets::*;
|
||||
use super::widgets::label_widgets::*;
|
||||
use crate::application::generate_uuid;
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::KeysGroup;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::KeysGroup;
|
||||
use crate::messages::prelude::*;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
|
||||
@@ -233,6 +233,24 @@ pub struct ColorInput {
|
||||
pub on_commit: WidgetCallback<()>,
|
||||
}
|
||||
|
||||
/// Shortens a breadcrumb label to fit the trail, replacing the tail with an ellipsis.
|
||||
/// Quotes delimit a string value, so a quoted label budgets only the text between them.
|
||||
pub fn truncate_breadcrumb_label(label: &str) -> String {
|
||||
const MAX_CHARACTERS: usize = 40;
|
||||
|
||||
let quoted = label.len() >= 2 && label.starts_with('"') && label.ends_with('"');
|
||||
let content = if quoted { &label[1..label.len() - 1] } else { label };
|
||||
|
||||
if content.chars().count() <= MAX_CHARACTERS {
|
||||
return label.to_string();
|
||||
}
|
||||
|
||||
let mut truncated: String = content.chars().take(MAX_CHARACTERS - 1).collect();
|
||||
truncated.push('…');
|
||||
|
||||
if quoted { format!("\"{truncated}\"") } else { truncated }
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, Default, WidgetBuilder)]
|
||||
#[derivative(Debug, PartialEq)]
|
||||
|
||||
@@ -64,6 +64,8 @@ pub struct TextLabel {
|
||||
pub italic: bool,
|
||||
pub monospace: bool,
|
||||
pub multiline: bool,
|
||||
pub enquote: bool,
|
||||
pub selectable: bool,
|
||||
#[serde(rename = "centerAlign")]
|
||||
pub center_align: bool,
|
||||
#[serde(rename = "tableAlign")]
|
||||
|
||||
@@ -39,6 +39,5 @@ pub enum VectorTableTab {
|
||||
#[default]
|
||||
Points,
|
||||
Segments,
|
||||
Regions,
|
||||
Handles,
|
||||
}
|
||||
@@ -13,17 +13,18 @@ use graphene_std::color::SRGBA8;
|
||||
use graphene_std::extract_xy::XY;
|
||||
use graphene_std::gradient::Gradient;
|
||||
use graphene_std::list::{Item, List, NodeIdPath};
|
||||
use graphene_std::math::float_noise::round_away_float_noise;
|
||||
use graphene_std::memo::IORecord;
|
||||
use graphene_std::raster::{
|
||||
CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, LuminanceCalculation, NoiseType, RedGreenBlue, RedGreenBlueAlpha, RelativeAbsolute, SelectiveColorChoice,
|
||||
};
|
||||
use graphene_std::raster_types::{CPU, GPU, Raster};
|
||||
use graphene_std::subpath::BezierHandles;
|
||||
use graphene_std::text::TextAlign;
|
||||
use graphene_std::text_nodes::StringCapitalization;
|
||||
use graphene_std::transform::{ReferencePoint, ScaleType};
|
||||
use graphene_std::vector::misc::{
|
||||
ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridType, InterpolationDistribution, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns, SpiralType,
|
||||
ArcType, BezierHandles, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridType, InterpolationDistribution, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns,
|
||||
SpiralType,
|
||||
};
|
||||
use graphene_std::vector::style::{
|
||||
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin,
|
||||
@@ -150,7 +151,8 @@ impl DataPanelMessageHandler {
|
||||
|
||||
// Element path breadcrumbs
|
||||
if !layout_data.breadcrumbs.is_empty() {
|
||||
let breadcrumb = BreadcrumbTrailButtons::new(layout_data.breadcrumbs)
|
||||
let labels = layout_data.breadcrumbs.iter().map(|label| truncate_breadcrumb_label(label)).collect();
|
||||
let breadcrumb = BreadcrumbTrailButtons::new(labels)
|
||||
.on_update(|&len| DataPanelMessage::TruncateElementPath { len: len as usize }.into())
|
||||
.widget_instance();
|
||||
widgets.push(breadcrumb);
|
||||
@@ -647,7 +649,7 @@ impl TableItemLayout for Vector {
|
||||
)
|
||||
}
|
||||
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
let table_tab_entries = [VectorTableTab::Points, VectorTableTab::Segments, VectorTableTab::Regions, VectorTableTab::Handles]
|
||||
let table_tab_entries = [VectorTableTab::Points, VectorTableTab::Segments, VectorTableTab::Handles]
|
||||
.into_iter()
|
||||
.map(|tab| {
|
||||
RadioEntryData::new(format!("{tab:?}"))
|
||||
@@ -694,17 +696,6 @@ impl TableItemLayout for Vector {
|
||||
]
|
||||
}));
|
||||
}
|
||||
VectorTableTab::Regions => {
|
||||
table_rows.push(column_headings(&["", "segment_range"]));
|
||||
table_rows.extend(self.region_domain.iter().map(|(id, segment_range, _)| {
|
||||
vec![
|
||||
TextLabel::new(format!("{}", id.inner())).narrow(true).widget_instance(),
|
||||
TextLabel::new(format!("Segment {} – Segment {}", segment_range.start().inner(), segment_range.end().inner()))
|
||||
.narrow(true)
|
||||
.widget_instance(),
|
||||
]
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
vec![LayoutGroup::row(table_tabs), LayoutGroup::table(table_rows, false)]
|
||||
@@ -807,18 +798,41 @@ impl TableItemLayout for Gradient {
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! impl_table_item_layout_for_number {
|
||||
($($ty:ty => $type_name:literal),* $(,)?) => {
|
||||
$(
|
||||
impl TableItemLayout for $ty {
|
||||
fn type_name() -> &'static str {
|
||||
$type_name
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
format!("{self}")
|
||||
}
|
||||
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
|
||||
}
|
||||
}
|
||||
)*
|
||||
}
|
||||
}
|
||||
impl_table_item_layout_for_number!(
|
||||
f32 => "Number (f32)",
|
||||
u32 => "Number (u32)",
|
||||
i32 => "Number (i32)",
|
||||
u64 => "Number (u64)",
|
||||
i64 => "Number (i64)",
|
||||
);
|
||||
|
||||
// Denoised so 0.1 + 0.2 reads as 0.3 rather than 0.30000000000000004. We don't do this for f32 because it lacks precision to reliably distinguish between intentional digits and noise.
|
||||
impl TableItemLayout for f64 {
|
||||
fn type_name() -> &'static str {
|
||||
"Number (f64)"
|
||||
"Number"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
format!("{self}")
|
||||
format!("{}", round_away_float_noise(*self))
|
||||
}
|
||||
// Values fall back to the default drill-in button (labeled via `identifier`); the value page shows the rich `NumberInput`.
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(vec![
|
||||
NumberInput::new(Some(*self)).disabled(true).max_width(220).display_decimal_places(20).widget_instance(),
|
||||
])]
|
||||
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -827,88 +841,10 @@ impl TableItemLayout for u8 {
|
||||
"Byte"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
format!("{self:02X}")
|
||||
format!("0x{self:02X} ({self})")
|
||||
}
|
||||
// Values fall back to the default drill-in button (labeled with the hex string via `identifier`); the value page shows the same hex value as a label.
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(vec![TextLabel::new(self.identifier()).widget_instance()])]
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for f32 {
|
||||
fn type_name() -> &'static str {
|
||||
"Number (f32)"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
format!("{self}")
|
||||
}
|
||||
// Values fall back to the default drill-in button (labeled via `identifier`); the value page shows the rich `NumberInput`.
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(vec![
|
||||
NumberInput::new(Some(*self as f64)).disabled(true).max_width(220).display_decimal_places(20).widget_instance(),
|
||||
])]
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for u32 {
|
||||
fn type_name() -> &'static str {
|
||||
"Number (u32)"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
format!("{self}")
|
||||
}
|
||||
// Values fall back to the default drill-in button (labeled via `identifier`); the value page shows the rich `NumberInput`.
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(vec![
|
||||
NumberInput::new(Some(*self as f64)).disabled(true).max_width(220).display_decimal_places(20).widget_instance(),
|
||||
])]
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for i32 {
|
||||
fn type_name() -> &'static str {
|
||||
"Number (i32)"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
format!("{self}")
|
||||
}
|
||||
// Values fall back to the default drill-in button (labeled via `identifier`); the value page shows the rich `NumberInput`.
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(vec![
|
||||
NumberInput::new(Some(*self as f64)).disabled(true).max_width(220).display_decimal_places(20).widget_instance(),
|
||||
])]
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for i64 {
|
||||
fn type_name() -> &'static str {
|
||||
"Number (i64)"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
format!("{self}")
|
||||
}
|
||||
// Values fall back to the default drill-in button (labeled via `identifier`); the value page shows the rich `NumberInput`.
|
||||
// TODO: Make this robust for large i64 values that don't fit in f64 (beyond roughly 2^53), as with u64.
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(vec![
|
||||
NumberInput::new(Some(*self as f64)).disabled(true).max_width(220).display_decimal_places(20).widget_instance(),
|
||||
])]
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for u64 {
|
||||
fn type_name() -> &'static str {
|
||||
"Number (u64)"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
format!("{self}")
|
||||
}
|
||||
// Values fall back to the default drill-in button (labeled via `identifier`); the value page shows the rich `NumberInput`.
|
||||
// TODO: Make this robust for large u64 values that don't fit in f64 (above roughly 2^53). Perhaps using a bigint kind of approach through the widget's data flow.
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(vec![
|
||||
NumberInput::new(Some(*self as f64)).disabled(true).max_width(220).display_decimal_places(20).widget_instance(),
|
||||
])]
|
||||
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -932,20 +868,50 @@ impl TableItemLayout for String {
|
||||
"String"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
// Show the first line, and if there are more, indicate that with an ellipsis
|
||||
let first_line = self.lines().next().unwrap_or("");
|
||||
if self.lines().count() > 1 {
|
||||
format!("\"{} …\"", first_line)
|
||||
} else {
|
||||
format!("\"{}\"", first_line)
|
||||
}
|
||||
format!("\"{}\"", string_preview(self))
|
||||
}
|
||||
fn layout_with_breadcrumb(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
data.breadcrumbs.push(character_count_label(self));
|
||||
self.value_page(data)
|
||||
}
|
||||
// The preview truncates for length and line breaks, so a button beside it reaches the full text, labeled by length
|
||||
fn value_widgets(&self, target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
vec![
|
||||
TextLabel::new(string_preview(self)).enquote(true).selectable(true).monospace(true).narrow(true).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
TextButton::new(character_count_label(self))
|
||||
.on_update(move |_| DataPanelMessage::PushToElementPath { step: target.clone() }.into())
|
||||
.narrow(true)
|
||||
.widget_instance(),
|
||||
]
|
||||
}
|
||||
// Values fall back to the default drill-in button (labeled with the truncated quoted preview via `identifier`); the value page shows the full multi-line text in a `TextAreaInput`.
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(vec![TextAreaInput::new(self.to_string()).monospace(true).disabled(true).widget_instance()])]
|
||||
}
|
||||
}
|
||||
|
||||
fn character_count_label(value: &str) -> String {
|
||||
let character_count = value.chars().count();
|
||||
|
||||
format!("{character_count} Char{}", if character_count == 1 { "" } else { "s" })
|
||||
}
|
||||
|
||||
/// Shortens a string to fit a table cell, cutting at the first line break or 40 characters with an ellipsis.
|
||||
/// The 40 matches `truncate_breadcrumb_label`, so a preview reaching the trail isn't cut twice.
|
||||
fn string_preview(value: &str) -> String {
|
||||
const MAX_CHARACTERS: usize = 40;
|
||||
|
||||
let first_line = value.lines().next().unwrap_or_default();
|
||||
let cut_by_line_break = value.contains('\n');
|
||||
let cut_by_length = first_line.chars().count() > MAX_CHARACTERS;
|
||||
|
||||
if !cut_by_line_break && !cut_by_length {
|
||||
return value.to_string();
|
||||
}
|
||||
|
||||
first_line.chars().take(MAX_CHARACTERS - 1).chain(['…']).collect()
|
||||
}
|
||||
|
||||
impl TableItemLayout for Option<f64> {
|
||||
fn type_name() -> &'static str {
|
||||
"Option<f64>"
|
||||
@@ -954,7 +920,12 @@ impl TableItemLayout for Option<f64> {
|
||||
"Option<f64>".to_string()
|
||||
}
|
||||
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
vec![TextLabel::new(format!("{self:?}")).narrow(true).widget_instance()]
|
||||
let text = match self {
|
||||
Some(value) => format!("Some({})", round_away_float_noise(*value)),
|
||||
None => "None".to_string(),
|
||||
};
|
||||
|
||||
vec![TextLabel::new(text).selectable(true).narrow(true).widget_instance()]
|
||||
}
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(self.value_widgets(PathStep::Element(0), _data))]
|
||||
@@ -999,7 +970,7 @@ impl TableItemLayout for DAffine2 {
|
||||
"Transform".to_string()
|
||||
}
|
||||
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
vec![TextLabel::new(format_transform_matrix(*self)).narrow(true).widget_instance()]
|
||||
transform_widgets(*self)
|
||||
}
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(self.value_widgets(PathStep::Element(0), _data))]
|
||||
@@ -1014,8 +985,7 @@ impl TableItemLayout for Affine2 {
|
||||
"Transform".to_string()
|
||||
}
|
||||
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
let matrix = DAffine2::from_cols_array(&self.to_cols_array().map(|x| x as f64));
|
||||
vec![TextLabel::new(format_transform_matrix(matrix)).narrow(true).widget_instance()]
|
||||
transform_widgets(DAffine2::from_cols_array(&self.to_cols_array().map(|x| x as f64)))
|
||||
}
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
vec![LayoutGroup::row(self.value_widgets(PathStep::Element(0), _data))]
|
||||
@@ -1396,7 +1366,8 @@ fn drilldown_attribute_layout(any: &dyn Any, data: &mut LayoutData) -> Option<Ve
|
||||
None
|
||||
}
|
||||
|
||||
fn format_transform_matrix(transform: DAffine2) -> String {
|
||||
/// Decomposes a transform into location, rotation, and scale, each headed by the icon of its Layer menu action.
|
||||
fn transform_widgets(transform: DAffine2) -> Vec<WidgetInstance> {
|
||||
let (scale, angle, translation) = if transform.matrix2.determinant().abs() <= f64::EPSILON {
|
||||
let [col_0, col_1] = transform.matrix2.to_cols_array_2d().map(|[x, y]| DVec2::new(x, y));
|
||||
|
||||
@@ -1414,15 +1385,24 @@ fn format_transform_matrix(transform: DAffine2) -> String {
|
||||
} else {
|
||||
transform.to_scale_angle_translation()
|
||||
};
|
||||
let rotation = format_rounded(angle.to_degrees(), 3);
|
||||
|
||||
format!(
|
||||
"Location: ({} px, {} px) — Rotation: {rotation}° — Scale: ({}x, {}x)",
|
||||
format_rounded(translation.x, 3),
|
||||
format_rounded(translation.y, 3),
|
||||
format_rounded(scale.x, 3),
|
||||
format_rounded(scale.y, 3)
|
||||
)
|
||||
let location_text = format!("({} px, {} px)", format_rounded(translation.x, 3), format_rounded(translation.y, 3));
|
||||
let rotation_text = format!("{}°", format_rounded(angle.to_degrees(), 3));
|
||||
let scale_text = format!("({}x, {}x)", format_rounded(scale.x, 3), format_rounded(scale.y, 3));
|
||||
|
||||
vec![
|
||||
IconLabel::new("TransformationGrab").tooltip_label("Location").widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
TextLabel::new(location_text).narrow(true).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
IconLabel::new("TransformationRotate").tooltip_label("Rotation").widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
TextLabel::new(rotation_text).narrow(true).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
IconLabel::new("TransformationScale").tooltip_label("Scale").widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
TextLabel::new(scale_text).narrow(true).widget_instance(),
|
||||
]
|
||||
}
|
||||
|
||||
fn format_dvec2(value: DVec2) -> String {
|
||||
|
||||
@@ -2,7 +2,7 @@ use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::utility_types::misc::{GroupFolderType, SnappingState};
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::Key;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::Key;
|
||||
use crate::messages::portfolio::document::data_panel::DataPanelMessage;
|
||||
use crate::messages::portfolio::document::overlays::utility_types::{OverlayContext, OverlaysType};
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
|
||||
@@ -41,12 +41,12 @@ use graphene_std::Cover;
|
||||
use graphene_std::math::quad::Quad;
|
||||
use graphene_std::path_bool_nodes::boolean_intersect;
|
||||
use graphene_std::raster::BlendMode;
|
||||
use graphene_std::subpath::Subpath;
|
||||
use graphene_std::vector::algorithms::bezpath_algorithms::bezpath_is_inside_bezpath;
|
||||
use graphene_std::vector::click_target::{ClickTarget, ClickTargetType};
|
||||
use graphene_std::vector::graphic_types;
|
||||
use graphene_std::vector::misc::dvec2_to_point;
|
||||
use graphene_std::vector::style::RenderMode;
|
||||
use graphene_std::vector::{PointId, graphic_types};
|
||||
use kurbo::{Affine, BezPath, Line, PathSeg};
|
||||
use kurbo::{Affine, BezPath, Line, PathSeg, Shape};
|
||||
use std::collections::HashSet;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
@@ -299,7 +299,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
graph_operation_message_handler.process_message(message, responses, context);
|
||||
}
|
||||
DocumentMessage::Resource(message) => {
|
||||
let context = ResourceMessageContext { document_id, fonts };
|
||||
let context = ResourceMessageContext { document_id, fonts, resource_storage };
|
||||
self.resources.process_message(message, responses, context);
|
||||
}
|
||||
DocumentMessage::AlignSelectedLayers { axis, aggregate } => {
|
||||
@@ -1831,16 +1831,16 @@ impl DocumentMessageHandler {
|
||||
self.intersect_quad(viewport_quad, viewport).filter(|layer| !self.network_interface.is_artboard(&layer.to_node(), &[]))
|
||||
}
|
||||
|
||||
/// Runs an intersection test with all layers and a viewport space subpath
|
||||
pub fn intersect_polygon<'a>(&'a self, mut viewport_polygon: Subpath<PointId>, viewport: &ViewportMessageHandler) -> impl Iterator<Item = LayerNodeIdentifier> + use<'a> {
|
||||
/// Runs an intersection test with all layers and a viewport space polygon path
|
||||
pub fn intersect_polygon<'a>(&'a self, mut viewport_polygon: BezPath, viewport: &ViewportMessageHandler) -> impl Iterator<Item = LayerNodeIdentifier> + use<'a> {
|
||||
let document_to_viewport = self.navigation_handler.calculate_offset_transform(viewport.center_in_viewport_space().into(), &self.document_ptz);
|
||||
viewport_polygon.apply_transform(document_to_viewport.inverse());
|
||||
viewport_polygon.apply_affine(Affine::new(document_to_viewport.inverse().to_cols_array()));
|
||||
|
||||
ClickXRayIter::new(&self.network_interface, XRayTarget::Polygon(viewport_polygon))
|
||||
ClickXRayIter::new(&self.network_interface, XRayTarget::Path(viewport_polygon))
|
||||
}
|
||||
|
||||
/// Runs an intersection test with all layers and a viewport space subpath; ignoring artboards
|
||||
pub fn intersect_polygon_no_artboards<'a>(&'a self, viewport_polygon: Subpath<PointId>, viewport: &ViewportMessageHandler) -> impl Iterator<Item = LayerNodeIdentifier> + use<'a> {
|
||||
/// Runs an intersection test with all layers and a viewport space polygon path; ignoring artboards
|
||||
pub fn intersect_polygon_no_artboards<'a>(&'a self, viewport_polygon: BezPath, viewport: &ViewportMessageHandler) -> impl Iterator<Item = LayerNodeIdentifier> + use<'a> {
|
||||
self.intersect_polygon(viewport_polygon, viewport)
|
||||
.filter(|layer| !self.network_interface.is_artboard(&layer.to_node(), &[]))
|
||||
}
|
||||
@@ -1868,29 +1868,24 @@ impl DocumentMessageHandler {
|
||||
layer_left >= quad_left && layer_right <= quad_right && layer_top <= quad_top && layer_bottom >= quad_bottom
|
||||
}
|
||||
|
||||
pub fn is_layer_fully_inside_polygon(&self, layer: &LayerNodeIdentifier, viewport: &ViewportMessageHandler, mut viewport_polygon: Subpath<PointId>) -> bool {
|
||||
pub fn is_layer_fully_inside_polygon(&self, layer: &LayerNodeIdentifier, viewport: &ViewportMessageHandler, mut viewport_polygon: BezPath) -> bool {
|
||||
let document_to_viewport = self.navigation_handler.calculate_offset_transform(viewport.center_in_viewport_space().into(), &self.document_ptz);
|
||||
viewport_polygon.apply_transform(document_to_viewport.inverse());
|
||||
viewport_polygon.apply_affine(Affine::new(document_to_viewport.inverse().to_cols_array()));
|
||||
|
||||
let layer_click_targets = self.network_interface.document_metadata().click_targets(*layer);
|
||||
let layer_transform = self.network_interface.document_metadata().transform_to_document(*layer);
|
||||
|
||||
layer_click_targets.is_some_and(|targets| {
|
||||
targets.iter().all(|target| match target.target_type() {
|
||||
ClickTargetType::Subpath(subpath) => {
|
||||
let mut subpath = subpath.clone();
|
||||
subpath.apply_transform(layer_transform);
|
||||
subpath.is_inside_subpath(&viewport_polygon, None, None)
|
||||
ClickTargetType::Path(path) => {
|
||||
let mut path = path.clone();
|
||||
path.apply_affine(Affine::new(layer_transform.to_cols_array()));
|
||||
bezpath_is_inside_bezpath(&path, &viewport_polygon, None, None)
|
||||
}
|
||||
ClickTargetType::CompoundPath(subpaths) => subpaths.iter().all(|subpath| {
|
||||
let mut subpath = subpath.clone();
|
||||
subpath.apply_transform(layer_transform);
|
||||
subpath.is_inside_subpath(&viewport_polygon, None, None)
|
||||
}),
|
||||
ClickTargetType::FreePoint(point) => {
|
||||
let mut point = *point;
|
||||
point.apply_transform(layer_transform);
|
||||
viewport_polygon.contains_point(point.position)
|
||||
viewport_polygon.contains(dvec2_to_point(point.position))
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -3791,7 +3786,6 @@ enum XRayTarget {
|
||||
Point(DVec2),
|
||||
Quad(Quad),
|
||||
Path(BezPath),
|
||||
Polygon(Subpath<PointId>),
|
||||
}
|
||||
|
||||
/// The result for the [`ClickXRayIter`] on the layer
|
||||
@@ -3814,13 +3808,7 @@ fn quad_to_kurbo(quad: Quad) -> BezPath {
|
||||
|
||||
fn click_targets_to_kurbo<'a>(click_targets: impl Iterator<Item = &'a ClickTarget>, transform: DAffine2) -> BezPath {
|
||||
let segments = click_targets
|
||||
.filter_map(|target| {
|
||||
if let ClickTargetType::Subpath(subpath) = target.target_type() {
|
||||
Some(subpath.iter())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.filter_map(|target| if let ClickTargetType::Path(path) = target.target_type() { Some(path.segments()) } else { None })
|
||||
.flatten()
|
||||
.map(|bezier| Affine::new(transform.to_cols_array()) * bezier);
|
||||
BezPath::from_path_segments(segments)
|
||||
@@ -3891,10 +3879,6 @@ impl<'a> ClickXRayIter<'a> {
|
||||
}
|
||||
XRayTarget::Quad(quad) => self.check_layer_area_target(click_targets, clip, layer, quad_to_kurbo(*quad), transform),
|
||||
XRayTarget::Path(path) => self.check_layer_area_target(click_targets, clip, layer, path.clone(), transform),
|
||||
XRayTarget::Polygon(polygon) => {
|
||||
let polygon = BezPath::from_path_segments(polygon.iter_closed());
|
||||
self.check_layer_area_target(click_targets, clip, layer, polygon, transform)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,10 +8,9 @@ use graphene_std::Color;
|
||||
use graphene_std::brush::brush_stroke::BrushStroke;
|
||||
use graphene_std::raster::BlendMode;
|
||||
use graphene_std::raster_types::Image;
|
||||
use graphene_std::subpath::Subpath;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::style::{GradientForm, GradientHueDirection, GradientInterpolation, GradientSettings, GradientSpace, GradientSpread, PaintOrder, Stroke};
|
||||
use graphene_std::vector::{Gradient, PointId, VectorModificationType};
|
||||
use graphene_std::vector::{Gradient, VectorModificationType};
|
||||
|
||||
#[impl_message(Message, DocumentMessage, GraphOperation)]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
@@ -162,12 +161,6 @@ pub enum GraphOperationMessage {
|
||||
parent: LayerNodeIdentifier,
|
||||
insert_index: usize,
|
||||
},
|
||||
NewVectorLayer {
|
||||
id: NodeId,
|
||||
subpaths: Vec<Subpath<PointId>>,
|
||||
parent: LayerNodeIdentifier,
|
||||
insert_index: usize,
|
||||
},
|
||||
NewTextLayer {
|
||||
id: NodeId,
|
||||
text: String,
|
||||
|
||||
+2
-9
@@ -363,13 +363,6 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
network_interface.move_layer_to_stack(layer, parent, insert_index, &[]);
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
GraphOperationMessage::NewVectorLayer { id, subpaths, parent, insert_index } => {
|
||||
let mut modify_inputs = ModifyInputsContext::new(network_interface, responses);
|
||||
let layer = modify_inputs.create_layer(id);
|
||||
modify_inputs.insert_vector(subpaths, layer, true, true, true);
|
||||
network_interface.move_layer_to_stack(layer, parent, insert_index, &[]);
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
GraphOperationMessage::NewTextLayer {
|
||||
id,
|
||||
text,
|
||||
@@ -856,13 +849,13 @@ fn import_usvg_node_inner(
|
||||
|
||||
/// Helper to apply path data (vector geometry, fill, stroke, transform) to a layer.
|
||||
fn import_usvg_path(modify_inputs: &mut ModifyInputsContext, node: &usvg::Node, path: &usvg::Path, layer: LayerNodeIdentifier, gradient_info: &SvgGradientInfo) {
|
||||
let subpaths = convert_usvg_path(path);
|
||||
let bezpath = convert_usvg_path(path);
|
||||
|
||||
// Skip creating a Transform node entirely when the SVG-native transform is identity.
|
||||
let node_transform = usvg_transform(node.abs_transform());
|
||||
let has_transform = node_transform != DAffine2::IDENTITY;
|
||||
|
||||
modify_inputs.insert_vector(subpaths, layer, has_transform, path.fill().is_some(), path.stroke().is_some());
|
||||
modify_inputs.insert_vector(bezpath, layer, has_transform, path.fill().is_some(), path.stroke().is_some());
|
||||
|
||||
if has_transform && let Some(transform_node_id) = modify_inputs.existing_proto_node_id(graphene_std::transform_nodes::transform::IDENTIFIER, false) {
|
||||
transform_utils::update_transform(modify_inputs.network_interface, &transform_node_id, node_transform);
|
||||
|
||||
@@ -2,9 +2,7 @@ use crate::messages::portfolio::document::utility_types::network_interface::{Inp
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use graphene_std::subpath::Subpath;
|
||||
use graphene_std::transform::Transform;
|
||||
use graphene_std::vector::PointId;
|
||||
|
||||
/// Update the inputs of the transform node to match a new transform
|
||||
pub fn update_transform(network_interface: &mut NodeNetworkInterface, node_id: &NodeId, transform: DAffine2) {
|
||||
@@ -87,32 +85,6 @@ pub fn get_current_normalized_pivot(inputs: &[NodeInput]) -> DVec2 {
|
||||
if let Some(&TaggedValue::DVec2(pivot)) = inputs[5].as_value() { pivot } else { DVec2::splat(0.5) }
|
||||
}
|
||||
|
||||
/// Expand a bounds to avoid div zero errors
|
||||
fn clamp_bounds(bounds_min: DVec2, mut bounds_max: DVec2) -> [DVec2; 2] {
|
||||
let bounds_size = bounds_max - bounds_min;
|
||||
if bounds_size.x < 1e-10 {
|
||||
bounds_max.x = bounds_min.x + 1.;
|
||||
}
|
||||
if bounds_size.y < 1e-10 {
|
||||
bounds_max.y = bounds_min.y + 1.;
|
||||
}
|
||||
[bounds_min, bounds_max]
|
||||
}
|
||||
/// Returns corners of all subpaths
|
||||
fn subpath_bounds(subpaths: &[Subpath<PointId>]) -> [DVec2; 2] {
|
||||
subpaths
|
||||
.iter()
|
||||
.filter_map(|subpath| subpath.bounding_box())
|
||||
.reduce(|b1, b2| [b1[0].min(b2[0]), b1[1].max(b2[1])])
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Returns corners of all subpaths (but expanded to avoid division-by-zero errors)
|
||||
pub fn nonzero_subpath_bounds(subpaths: &[Subpath<PointId>]) -> [DVec2; 2] {
|
||||
let [bounds_min, bounds_max] = subpath_bounds(subpaths);
|
||||
clamp_bounds(bounds_min, bounds_max)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -16,11 +16,11 @@ use graph_craft::{ProtoNodeIdentifier, list};
|
||||
use graphene_std::brush::brush_stroke::BrushStroke;
|
||||
use graphene_std::raster::BlendMode;
|
||||
use graphene_std::raster_types::Image;
|
||||
use graphene_std::subpath::Subpath;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::style::{GradientForm, GradientHueDirection, GradientInterpolation, GradientSettings, GradientSpace, GradientSpread, PaintOrder, Stroke};
|
||||
use graphene_std::vector::{Gradient, GradientRamp, PointId, Vector, VectorModification, VectorModificationType};
|
||||
use graphene_std::vector::{Gradient, GradientRamp, Vector, VectorModification, VectorModificationType};
|
||||
use graphene_std::{Artboard, Color, Graphic};
|
||||
use kurbo::BezPath;
|
||||
|
||||
#[derive(PartialEq, Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum TransformIn {
|
||||
@@ -146,9 +146,9 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
path_id
|
||||
}
|
||||
|
||||
pub fn insert_vector(&mut self, subpaths: Vec<Subpath<PointId>>, layer: LayerNodeIdentifier, include_transform: bool, include_fill: bool, include_stroke: bool) {
|
||||
pub fn insert_vector(&mut self, bezpath: BezPath, layer: LayerNodeIdentifier, include_transform: bool, include_fill: bool, include_stroke: bool) {
|
||||
// Build a VectorModification that reproduces the geometry (same format the Pen tool uses)
|
||||
let vector = Vector::from_subpaths(subpaths, true);
|
||||
let vector = Vector::from_bezpath(bezpath);
|
||||
let modification = Box::new(VectorModification::create_from_vector(&vector));
|
||||
|
||||
let shape = resolve_network_node_type("Path")
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::Key;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::Key;
|
||||
use crate::messages::prelude::*;
|
||||
use glam::DVec2;
|
||||
|
||||
|
||||
@@ -4,8 +4,8 @@ use crate::consts::{
|
||||
VIEWPORT_ZOOM_TO_FIT_PADDING_SCALE_FACTOR,
|
||||
};
|
||||
use crate::messages::frontend::utility_types::MouseCursorIcon;
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::{Key, MouseMotion};
|
||||
use crate::messages::input_mapper::utility_types::input_mouse::ViewportPosition;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::{Key, MouseMotion};
|
||||
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;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::utility_types::Direction;
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::Key;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::Key;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{ImportOrExport, InputConnector, NodeTemplate, OutputConnector};
|
||||
|
||||
@@ -2429,7 +2429,7 @@ impl NodeGraphMessageHandler {
|
||||
if subgraph_path_names_length >= 2 {
|
||||
widgets.extend([
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
BreadcrumbTrailButtons::new(subgraph_path_names)
|
||||
BreadcrumbTrailButtons::new(subgraph_path_names.iter().map(|name| truncate_breadcrumb_label(name)).collect())
|
||||
.on_update(move |index| {
|
||||
DocumentMessage::ExitNestedNetwork {
|
||||
steps_back: subgraph_path_names_length - (*index as usize) - 1,
|
||||
|
||||
@@ -6,9 +6,9 @@ pub use crate::messages::portfolio::document::utility_types::text_metrics::text_
|
||||
use crate::messages::tool::common_functionality::shape_editor::{SelectedLayerState, ShapeState};
|
||||
use crate::messages::tool::tool_messages::tool_prelude::DocumentMessageHandler;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphene_std::subpath::{Bezier, BezierHandles};
|
||||
use graphene_std::vector::misc::ManipulatorPointId;
|
||||
use graphene_std::vector::misc::{BezierHandles, ManipulatorPointId, point_to_dvec2, segment_to_handles};
|
||||
use graphene_std::vector::{PointId, SegmentId, Vector};
|
||||
use kurbo::{Affine, ParamCurve, PathSeg};
|
||||
use std::collections::HashMap;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use wasm_bindgen::JsCast;
|
||||
@@ -59,7 +59,7 @@ pub fn selected_segments_for_layer(vector: &Vector, state: &SelectedLayerState)
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// Adding segments which are are connected to selected anchors
|
||||
for (segment_id, _bezier, start, end) in vector.segment_bezier_iter() {
|
||||
for (segment_id, _, start, end) in vector.segment_iter() {
|
||||
if selected_anchors.contains(&start) || selected_anchors.contains(&end) {
|
||||
selected_segments.push(segment_id);
|
||||
}
|
||||
@@ -67,23 +67,25 @@ pub fn selected_segments_for_layer(vector: &Vector, state: &SelectedLayerState)
|
||||
selected_segments
|
||||
}
|
||||
|
||||
fn overlay_bezier_handles(bezier: Bezier, segment_id: SegmentId, transform: DAffine2, is_selected: impl Fn(ManipulatorPointId) -> bool, overlay_context: &mut OverlayContext) {
|
||||
let bezier = bezier.apply_transformation(|point| transform.transform_point2(point));
|
||||
fn overlay_bezier_handles(segment: PathSeg, segment_id: SegmentId, transform: DAffine2, is_selected: impl Fn(ManipulatorPointId) -> bool, overlay_context: &mut OverlayContext) {
|
||||
let segment = Affine::new(transform.to_cols_array()) * segment;
|
||||
let segment_start = point_to_dvec2(segment.start());
|
||||
let segment_end = point_to_dvec2(segment.end());
|
||||
let not_under_anchor = |position: DVec2, anchor: DVec2| position.distance_squared(anchor) >= HIDE_HANDLE_DISTANCE * HIDE_HANDLE_DISTANCE;
|
||||
|
||||
match bezier.handles {
|
||||
BezierHandles::Quadratic { handle } if not_under_anchor(handle, bezier.start) && not_under_anchor(handle, bezier.end) => {
|
||||
overlay_context.line(handle, bezier.start, None, None);
|
||||
overlay_context.line(handle, bezier.end, None, None);
|
||||
match segment_to_handles(&segment) {
|
||||
BezierHandles::Quadratic { handle } if not_under_anchor(handle, segment_start) && not_under_anchor(handle, segment_end) => {
|
||||
overlay_context.line(handle, segment_start, None, None);
|
||||
overlay_context.line(handle, segment_end, None, None);
|
||||
overlay_context.manipulator_handle(handle, is_selected(ManipulatorPointId::PrimaryHandle(segment_id)), None);
|
||||
}
|
||||
BezierHandles::Cubic { handle_start, handle_end } => {
|
||||
if not_under_anchor(handle_start, bezier.start) {
|
||||
overlay_context.line(handle_start, bezier.start, None, None);
|
||||
if not_under_anchor(handle_start, segment_start) {
|
||||
overlay_context.line(handle_start, segment_start, None, None);
|
||||
overlay_context.manipulator_handle(handle_start, is_selected(ManipulatorPointId::PrimaryHandle(segment_id)), None);
|
||||
}
|
||||
if not_under_anchor(handle_end, bezier.end) {
|
||||
overlay_context.line(handle_end, bezier.end, None, None);
|
||||
if not_under_anchor(handle_end, segment_end) {
|
||||
overlay_context.line(handle_end, segment_end, None, None);
|
||||
overlay_context.manipulator_handle(handle_end, is_selected(ManipulatorPointId::EndHandle(segment_id)), None);
|
||||
}
|
||||
}
|
||||
@@ -92,7 +94,7 @@ fn overlay_bezier_handles(bezier: Bezier, segment_id: SegmentId, transform: DAff
|
||||
}
|
||||
|
||||
fn overlay_bezier_handle_specific_point(
|
||||
bezier: Bezier,
|
||||
segment: PathSeg,
|
||||
segment_id: SegmentId,
|
||||
(start, end): (PointId, PointId),
|
||||
point_to_render: PointId,
|
||||
@@ -100,24 +102,24 @@ fn overlay_bezier_handle_specific_point(
|
||||
is_selected: impl Fn(ManipulatorPointId) -> bool,
|
||||
overlay_context: &mut OverlayContext,
|
||||
) {
|
||||
let bezier = bezier.apply_transformation(|point| transform.transform_point2(point));
|
||||
let segment = Affine::new(transform.to_cols_array()) * segment;
|
||||
let segment_start = point_to_dvec2(segment.start());
|
||||
let segment_end = point_to_dvec2(segment.end());
|
||||
let not_under_anchor = |position: DVec2, anchor: DVec2| position.distance_squared(anchor) >= HIDE_HANDLE_DISTANCE * HIDE_HANDLE_DISTANCE;
|
||||
|
||||
match bezier.handles {
|
||||
BezierHandles::Quadratic { handle } => {
|
||||
if not_under_anchor(handle, bezier.start) && not_under_anchor(handle, bezier.end) {
|
||||
let end = if start == point_to_render { bezier.start } else { bezier.end };
|
||||
overlay_context.line(handle, end, None, None);
|
||||
overlay_context.manipulator_handle(handle, is_selected(ManipulatorPointId::PrimaryHandle(segment_id)), None);
|
||||
}
|
||||
match segment_to_handles(&segment) {
|
||||
BezierHandles::Quadratic { handle } if not_under_anchor(handle, segment_start) && not_under_anchor(handle, segment_end) => {
|
||||
let anchor = if start == point_to_render { segment_start } else { segment_end };
|
||||
overlay_context.line(handle, anchor, None, None);
|
||||
overlay_context.manipulator_handle(handle, is_selected(ManipulatorPointId::PrimaryHandle(segment_id)), None);
|
||||
}
|
||||
BezierHandles::Cubic { handle_start, handle_end } => {
|
||||
if not_under_anchor(handle_start, bezier.start) && (point_to_render == start) {
|
||||
overlay_context.line(handle_start, bezier.start, None, None);
|
||||
if not_under_anchor(handle_start, segment_start) && (point_to_render == start) {
|
||||
overlay_context.line(handle_start, segment_start, None, None);
|
||||
overlay_context.manipulator_handle(handle_start, is_selected(ManipulatorPointId::PrimaryHandle(segment_id)), None);
|
||||
}
|
||||
if not_under_anchor(handle_end, bezier.end) && (point_to_render == end) {
|
||||
overlay_context.line(handle_end, bezier.end, None, None);
|
||||
if not_under_anchor(handle_end, segment_end) && (point_to_render == end) {
|
||||
overlay_context.line(handle_end, segment_end, None, None);
|
||||
overlay_context.manipulator_handle(handle_end, is_selected(ManipulatorPointId::EndHandle(segment_id)), None);
|
||||
}
|
||||
}
|
||||
@@ -152,23 +154,23 @@ pub fn path_overlays(document: &DocumentMessageHandler, draw_handles: DrawHandle
|
||||
|
||||
match draw_handles {
|
||||
DrawHandles::All => {
|
||||
vector.segment_bezier_iter().for_each(|(segment_id, bezier, _start, _end)| {
|
||||
overlay_bezier_handles(bezier, segment_id, transform, is_selected, overlay_context);
|
||||
vector.segment_iter().for_each(|(segment_id, segment, _start, _end)| {
|
||||
overlay_bezier_handles(segment, segment_id, transform, is_selected, overlay_context);
|
||||
});
|
||||
}
|
||||
DrawHandles::SelectedAnchors(ref selected_segments) => {
|
||||
let Some(focused_segments) = selected_segments.get(&layer) else { continue };
|
||||
|
||||
vector
|
||||
.segment_bezier_iter()
|
||||
.segment_iter()
|
||||
.filter(|(segment_id, ..)| focused_segments.contains(segment_id))
|
||||
.for_each(|(segment_id, bezier, _start, _end)| {
|
||||
overlay_bezier_handles(bezier, segment_id, transform, is_selected, overlay_context);
|
||||
.for_each(|(segment_id, segment, _start, _end)| {
|
||||
overlay_bezier_handles(segment, segment_id, transform, is_selected, overlay_context);
|
||||
});
|
||||
|
||||
for (segment_id, bezier, start, end) in vector.segment_bezier_iter() {
|
||||
for (segment_id, segment, start, end) in vector.segment_iter() {
|
||||
if let Some((corresponding_anchor, _)) = opposite_handles_data.iter().find(|(_, adj_segment_id)| adj_segment_id == &segment_id) {
|
||||
overlay_bezier_handle_specific_point(bezier, segment_id, (start, end), *corresponding_anchor, transform, is_selected, overlay_context);
|
||||
overlay_bezier_handle_specific_point(segment, segment_id, (start, end), *corresponding_anchor, transform, is_selected, overlay_context);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -176,14 +178,14 @@ pub fn path_overlays(document: &DocumentMessageHandler, draw_handles: DrawHandle
|
||||
let Some(segment_endpoints) = segment_endpoints_by_layer.get(&layer) else { continue };
|
||||
|
||||
vector
|
||||
.segment_bezier_iter()
|
||||
.segment_iter()
|
||||
.filter(|(segment_id, ..)| segment_endpoints.contains_key(segment_id))
|
||||
.for_each(|(segment_id, bezier, start, end)| {
|
||||
.for_each(|(segment_id, segment, start, end)| {
|
||||
if segment_endpoints.get(&segment_id).unwrap().len() == 1 {
|
||||
let point_to_render = segment_endpoints.get(&segment_id).unwrap()[0];
|
||||
overlay_bezier_handle_specific_point(bezier, segment_id, (start, end), point_to_render, transform, is_selected, overlay_context);
|
||||
overlay_bezier_handle_specific_point(segment, segment_id, (start, end), point_to_render, transform, is_selected, overlay_context);
|
||||
} else {
|
||||
overlay_bezier_handles(bezier, segment_id, transform, is_selected, overlay_context);
|
||||
overlay_bezier_handles(segment, segment_id, transform, is_selected, overlay_context);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -15,7 +15,6 @@ use glam::{DAffine2, DVec2};
|
||||
use graphene_std::ATTR_TRANSFORM;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::math::quad::Quad;
|
||||
use graphene_std::subpath::{self, Subpath};
|
||||
use graphene_std::text::{TextAlign, TextContext, TypesettingConfig};
|
||||
use graphene_std::vector::click_target::ClickTargetType;
|
||||
use graphene_std::vector::misc::point_to_dvec2;
|
||||
@@ -404,14 +403,14 @@ impl OverlayContext {
|
||||
|
||||
/// Fills the area inside the path. Assumes `color` is in gamma space.
|
||||
/// Used by the Pen tool to show the path being closed.
|
||||
pub fn fill_path(&mut self, subpaths: impl Iterator<Item = impl Borrow<Subpath<PointId>>>, transform: DAffine2, color: &str) {
|
||||
self.internal().fill_path(subpaths, transform, color);
|
||||
pub fn fill_path(&mut self, bezpath: &BezPath, transform: DAffine2, color: &str) {
|
||||
self.internal().fill_path(bezpath, transform, color);
|
||||
}
|
||||
|
||||
/// Fills the area inside the path with a pattern. Assumes `color` is an sRGB hex string.
|
||||
/// Used by the fill tool to show the area to be filled.
|
||||
pub fn fill_path_pattern(&mut self, subpaths: impl Iterator<Item = impl Borrow<Subpath<PointId>>>, transform: DAffine2, color: &str) {
|
||||
self.internal().fill_path_pattern(subpaths, transform, color);
|
||||
pub fn fill_path_pattern(&mut self, bezpath: &BezPath, transform: DAffine2, color: &str) {
|
||||
self.internal().fill_path_pattern(bezpath, transform, color);
|
||||
}
|
||||
|
||||
pub fn text(&self, text: &str, font_color: &str, background_color: Option<&str>, transform: DAffine2, padding: f64, pivot: [Pivot; 2]) {
|
||||
@@ -978,49 +977,25 @@ impl OverlayContextInternal {
|
||||
path.push(bezier.as_path_el());
|
||||
}
|
||||
|
||||
fn push_path(&mut self, subpaths: impl Iterator<Item = impl Borrow<Subpath<PointId>>>, transform: DAffine2) -> BezPath {
|
||||
fn push_path(&mut self, bezpath: &BezPath, transform: DAffine2) -> BezPath {
|
||||
let mut path = BezPath::new();
|
||||
|
||||
for subpath in subpaths {
|
||||
let subpath = subpath.borrow();
|
||||
let mut curves = subpath.iter().peekable();
|
||||
let snap_start = |context: &Self, point: kurbo::Point| {
|
||||
let snapped = context.snap_to_physical_pixel(transform.transform_point2(point_to_dvec2(point)));
|
||||
kurbo::Point::new(snapped.x, snapped.y)
|
||||
};
|
||||
let snap_center = |context: &Self, point: kurbo::Point| {
|
||||
let snapped = context.snap_to_physical_pixel_center(transform.transform_point2(point_to_dvec2(point)));
|
||||
kurbo::Point::new(snapped.x, snapped.y)
|
||||
};
|
||||
|
||||
let Some(first) = curves.peek() else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let start_point = transform.transform_point2(point_to_dvec2(first.start()));
|
||||
let start_point = self.snap_to_physical_pixel(start_point);
|
||||
path.move_to(kurbo::Point::new(start_point.x, start_point.y));
|
||||
|
||||
for curve in curves {
|
||||
match curve {
|
||||
PathSeg::Line(line) => {
|
||||
let a = transform.transform_point2(point_to_dvec2(line.p1));
|
||||
let a = self.snap_to_physical_pixel_center(a);
|
||||
path.line_to(kurbo::Point::new(a.x, a.y));
|
||||
}
|
||||
PathSeg::Quad(quad_bez) => {
|
||||
let a = transform.transform_point2(point_to_dvec2(quad_bez.p1));
|
||||
let b = transform.transform_point2(point_to_dvec2(quad_bez.p2));
|
||||
let a = self.snap_to_physical_pixel_center(a);
|
||||
let b = self.snap_to_physical_pixel_center(b);
|
||||
path.quad_to(kurbo::Point::new(a.x, a.y), kurbo::Point::new(b.x, b.y));
|
||||
}
|
||||
PathSeg::Cubic(cubic_bez) => {
|
||||
let a = transform.transform_point2(point_to_dvec2(cubic_bez.p1));
|
||||
let b = transform.transform_point2(point_to_dvec2(cubic_bez.p2));
|
||||
let c = transform.transform_point2(point_to_dvec2(cubic_bez.p3));
|
||||
let a = self.snap_to_physical_pixel_center(a);
|
||||
let b = self.snap_to_physical_pixel_center(b);
|
||||
let c = self.snap_to_physical_pixel_center(c);
|
||||
path.curve_to(kurbo::Point::new(a.x, a.y), kurbo::Point::new(b.x, b.y), kurbo::Point::new(c.x, c.y));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if subpath.closed() {
|
||||
path.close_path();
|
||||
for element in bezpath.elements() {
|
||||
match *element {
|
||||
kurbo::PathEl::MoveTo(point) => path.move_to(snap_start(self, point)),
|
||||
kurbo::PathEl::LineTo(point) => path.line_to(snap_center(self, point)),
|
||||
kurbo::PathEl::QuadTo(a, b) => path.quad_to(snap_center(self, a), snap_center(self, b)),
|
||||
kurbo::PathEl::CurveTo(a, b, c) => path.curve_to(snap_center(self, a), snap_center(self, b), snap_center(self, c)),
|
||||
kurbo::PathEl::ClosePath => path.close_path(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1029,20 +1004,19 @@ impl OverlayContextInternal {
|
||||
|
||||
/// Used by the Select tool to outline a path or a free point when selected or hovered.
|
||||
fn outline(&mut self, target_types: impl Iterator<Item = impl Borrow<ClickTargetType>>, transform: DAffine2, color: Option<&str>) {
|
||||
let mut subpaths: Vec<subpath::Subpath<PointId>> = vec![];
|
||||
let mut combined = BezPath::new();
|
||||
|
||||
for target_type in target_types {
|
||||
match target_type.borrow() {
|
||||
ClickTargetType::FreePoint(point) => {
|
||||
self.manipulator_anchor(transform.transform_point2(point.position), false, None);
|
||||
}
|
||||
ClickTargetType::Subpath(subpath) => subpaths.push(subpath.clone()),
|
||||
ClickTargetType::CompoundPath(compound) => subpaths.extend(compound.iter().cloned()),
|
||||
ClickTargetType::Path(bezpath) => combined.extend(bezpath.elements().iter().copied()),
|
||||
}
|
||||
}
|
||||
|
||||
if !subpaths.is_empty() {
|
||||
let path = self.push_path(subpaths.iter(), transform);
|
||||
if !combined.is_empty() {
|
||||
let path = self.push_path(&combined, transform);
|
||||
let color = color.unwrap_or(COLOR_OVERLAY_BLUE);
|
||||
|
||||
self.scene.stroke(&kurbo::Stroke::new(1.), self.get_transform(), Self::parse_color(color), None, &path);
|
||||
@@ -1051,15 +1025,15 @@ impl OverlayContextInternal {
|
||||
|
||||
/// Fills the area inside the path. Assumes `color` is in gamma space.
|
||||
/// Used by the Pen tool to show the path being closed.
|
||||
fn fill_path(&mut self, subpaths: impl Iterator<Item = impl Borrow<Subpath<PointId>>>, transform: DAffine2, color: &str) {
|
||||
let path = self.push_path(subpaths, transform);
|
||||
fn fill_path(&mut self, bezpath: &BezPath, transform: DAffine2, color: &str) {
|
||||
let path = self.push_path(bezpath, transform);
|
||||
|
||||
self.scene.fill(peniko::Fill::NonZero, self.get_transform(), Self::parse_color(color), None, &path);
|
||||
}
|
||||
|
||||
/// Fills the area inside the path with a pattern. Assumes `color` is an sRGB hex string.
|
||||
/// Used by the fill tool to show the area to be filled.
|
||||
fn fill_path_pattern(&mut self, subpaths: impl Iterator<Item = impl Borrow<Subpath<PointId>>>, transform: DAffine2, color: &str) {
|
||||
fn fill_path_pattern(&mut self, bezpath: &BezPath, transform: DAffine2, color: &str) {
|
||||
const PATTERN_WIDTH: u32 = 4;
|
||||
const PATTERN_HEIGHT: u32 = 4;
|
||||
|
||||
@@ -1096,7 +1070,7 @@ impl OverlayContextInternal {
|
||||
},
|
||||
};
|
||||
|
||||
let path = self.push_path(subpaths, transform);
|
||||
let path = self.push_path(bezpath, transform);
|
||||
let brush = peniko::Brush::Image(image);
|
||||
|
||||
self.scene.fill(peniko::Fill::NonZero, self.get_transform(), &brush, None, &path);
|
||||
|
||||
@@ -13,11 +13,10 @@ use core::borrow::Borrow;
|
||||
use core::f64::consts::{FRAC_PI_2, PI, TAU};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphene_std::math::quad::Quad;
|
||||
use graphene_std::subpath::Subpath;
|
||||
use graphene_std::vector::click_target::ClickTargetType;
|
||||
use graphene_std::vector::misc::{dvec2_to_point, point_to_dvec2};
|
||||
use graphene_std::vector::{PointId, SegmentId, Vector};
|
||||
use kurbo::{self, Affine, CubicBez, ParamCurve, PathSeg};
|
||||
use kurbo::{self, Affine, BezPath, CubicBez, ParamCurve, PathSeg};
|
||||
use std::collections::HashMap;
|
||||
use wasm_bindgen::{JsCast, JsValue};
|
||||
use web_sys::{OffscreenCanvas, OffscreenCanvasRenderingContext2d};
|
||||
@@ -931,50 +930,33 @@ impl OverlayContext {
|
||||
self.end_dpi_aware_transform();
|
||||
}
|
||||
|
||||
fn push_path(&mut self, subpaths: impl Iterator<Item = impl Borrow<Subpath<PointId>>>, transform: DAffine2) {
|
||||
fn push_path(&mut self, bezpath: &BezPath, transform: DAffine2) {
|
||||
self.start_dpi_aware_transform();
|
||||
|
||||
self.render_context.begin_path();
|
||||
for subpath in subpaths {
|
||||
let subpath = subpath.borrow();
|
||||
let mut curves = subpath.iter().peekable();
|
||||
|
||||
let Some(&first) = curves.peek() else {
|
||||
continue;
|
||||
};
|
||||
let snap_start = |context: &Self, point: kurbo::Point| context.snap_to_physical_pixel(transform.transform_point2(point_to_dvec2(point)));
|
||||
let snap_center = |context: &Self, point: kurbo::Point| context.snap_to_physical_pixel_center(transform.transform_point2(point_to_dvec2(point)));
|
||||
|
||||
let start_point = transform.transform_point2(point_to_dvec2(first.start()));
|
||||
let start_point = self.snap_to_physical_pixel(start_point);
|
||||
self.render_context.move_to(start_point.x, start_point.y);
|
||||
|
||||
for curve in curves {
|
||||
match curve {
|
||||
PathSeg::Line(line) => {
|
||||
let a = transform.transform_point2(point_to_dvec2(line.p1));
|
||||
let a = self.snap_to_physical_pixel_center(a);
|
||||
self.render_context.line_to(a.x, a.y);
|
||||
}
|
||||
PathSeg::Quad(quad_bez) => {
|
||||
let a = transform.transform_point2(point_to_dvec2(quad_bez.p1));
|
||||
let b = transform.transform_point2(point_to_dvec2(quad_bez.p2));
|
||||
let a = self.snap_to_physical_pixel_center(a);
|
||||
let b = self.snap_to_physical_pixel_center(b);
|
||||
self.render_context.quadratic_curve_to(a.x, a.y, b.x, b.y);
|
||||
}
|
||||
PathSeg::Cubic(cubic_bez) => {
|
||||
let a = transform.transform_point2(point_to_dvec2(cubic_bez.p1));
|
||||
let b = transform.transform_point2(point_to_dvec2(cubic_bez.p2));
|
||||
let c = transform.transform_point2(point_to_dvec2(cubic_bez.p3));
|
||||
let a = self.snap_to_physical_pixel_center(a);
|
||||
let b = self.snap_to_physical_pixel_center(b);
|
||||
let c = self.snap_to_physical_pixel_center(c);
|
||||
self.render_context.bezier_curve_to(a.x, a.y, b.x, b.y, c.x, c.y);
|
||||
}
|
||||
for element in bezpath.elements() {
|
||||
match *element {
|
||||
kurbo::PathEl::MoveTo(point) => {
|
||||
let point = snap_start(self, point);
|
||||
self.render_context.move_to(point.x, point.y);
|
||||
}
|
||||
}
|
||||
|
||||
if subpath.closed() {
|
||||
self.render_context.close_path();
|
||||
kurbo::PathEl::LineTo(point) => {
|
||||
let point = snap_center(self, point);
|
||||
self.render_context.line_to(point.x, point.y);
|
||||
}
|
||||
kurbo::PathEl::QuadTo(a, b) => {
|
||||
let (a, b) = (snap_center(self, a), snap_center(self, b));
|
||||
self.render_context.quadratic_curve_to(a.x, a.y, b.x, b.y);
|
||||
}
|
||||
kurbo::PathEl::CurveTo(a, b, c) => {
|
||||
let (a, b, c) = (snap_center(self, a), snap_center(self, b), snap_center(self, c));
|
||||
self.render_context.bezier_curve_to(a.x, a.y, b.x, b.y, c.x, c.y);
|
||||
}
|
||||
kurbo::PathEl::ClosePath => self.render_context.close_path(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -983,18 +965,17 @@ impl OverlayContext {
|
||||
|
||||
/// Used by the Select tool to outline a path or a free point when selected or hovered.
|
||||
pub fn outline(&mut self, target_types: impl Iterator<Item = impl Borrow<ClickTargetType>>, transform: DAffine2, color: Option<&str>) {
|
||||
let mut subpaths: Vec<Subpath<PointId>> = vec![];
|
||||
let mut combined = BezPath::new();
|
||||
|
||||
target_types.for_each(|target_type| match target_type.borrow() {
|
||||
ClickTargetType::FreePoint(point) => {
|
||||
self.manipulator_anchor(transform.transform_point2(point.position), false, None);
|
||||
}
|
||||
ClickTargetType::Subpath(subpath) => subpaths.push(subpath.clone()),
|
||||
ClickTargetType::CompoundPath(compound) => subpaths.extend(compound.iter().cloned()),
|
||||
ClickTargetType::Path(bezpath) => combined.extend(bezpath.elements().iter().copied()),
|
||||
});
|
||||
|
||||
if !subpaths.is_empty() {
|
||||
self.push_path(subpaths.iter(), transform);
|
||||
if !combined.is_empty() {
|
||||
self.push_path(&combined, transform);
|
||||
|
||||
let color = color.unwrap_or(COLOR_OVERLAY_BLUE);
|
||||
self.render_context.set_stroke_style_str(color);
|
||||
@@ -1005,8 +986,8 @@ impl OverlayContext {
|
||||
|
||||
/// Fills the area inside the path. Assumes `color` is in gamma space.
|
||||
/// Used by the Pen tool to show the path being closed.
|
||||
pub fn fill_path(&mut self, subpaths: impl Iterator<Item = impl Borrow<Subpath<PointId>>>, transform: DAffine2, color: &str) {
|
||||
self.push_path(subpaths, transform);
|
||||
pub fn fill_path(&mut self, bezpath: &BezPath, transform: DAffine2, color: &str) {
|
||||
self.push_path(bezpath, transform);
|
||||
|
||||
self.render_context.set_fill_style_str(color);
|
||||
self.render_context.fill();
|
||||
@@ -1014,7 +995,7 @@ impl OverlayContext {
|
||||
|
||||
/// Fills the area inside the path with a pattern. Assumes `color` is an sRGB hex string.
|
||||
/// Used by the fill tool to show the area to be filled.
|
||||
pub fn fill_path_pattern(&mut self, subpaths: impl Iterator<Item = impl Borrow<Subpath<PointId>>>, transform: DAffine2, color: &str) {
|
||||
pub fn fill_path_pattern(&mut self, bezpath: &BezPath, transform: DAffine2, color: &str) {
|
||||
const PATTERN_WIDTH: usize = 4;
|
||||
const PATTERN_HEIGHT: usize = 4;
|
||||
|
||||
@@ -1047,7 +1028,7 @@ impl OverlayContext {
|
||||
pattern_context.put_image_data(&image_data, 0, 0).unwrap();
|
||||
let pattern = self.render_context.create_pattern_with_offscreen_canvas(&pattern_canvas, "repeat").unwrap().unwrap();
|
||||
|
||||
self.push_path(subpaths, transform);
|
||||
self.push_path(bezpath, transform);
|
||||
|
||||
self.render_context.set_fill_style_canvas_pattern(&pattern);
|
||||
self.render_context.fill();
|
||||
|
||||
@@ -12,6 +12,7 @@ use url::Url;
|
||||
pub struct ResourceMessageContext<'a> {
|
||||
pub document_id: DocumentId,
|
||||
pub fonts: &'a FontsMessageHandler,
|
||||
pub resource_storage: &'a ResourceStorageMessageHandler,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Default, serde::Serialize, ExtractField)]
|
||||
@@ -25,7 +26,7 @@ pub struct ResourceMessageHandler {
|
||||
#[message_handler_data]
|
||||
impl MessageHandler<ResourceMessage, ResourceMessageContext<'_>> for ResourceMessageHandler {
|
||||
fn process_message(&mut self, message: ResourceMessage, responses: &mut VecDeque<Message>, context: ResourceMessageContext) {
|
||||
let ResourceMessageContext { document_id, fonts } = context;
|
||||
let ResourceMessageContext { document_id, fonts, resource_storage } = context;
|
||||
|
||||
match message {
|
||||
ResourceMessage::StoreEmbedded { resource_id, data } => {
|
||||
@@ -48,8 +49,16 @@ impl MessageHandler<ResourceMessage, ResourceMessageContext<'_>> for ResourceMes
|
||||
responses.add(ResourceMessage::Resolve { resource_id });
|
||||
}
|
||||
ResourceMessage::ResolveAll => {
|
||||
let unresolved_ids: Vec<ResourceId> = self.registry.unresolved().map(|info| info.id).collect();
|
||||
for id in unresolved_ids {
|
||||
// A resource keeps its hash when storage evicts its data, so only a fetchable source can repair it
|
||||
let refetchable = self
|
||||
.registry
|
||||
.resolved()
|
||||
.filter(|info| info.hash.is_some_and(|hash| !resource_storage.contains(hash)))
|
||||
.filter(|info| info.sources.iter().any(|source| matches!(source, DataSource::Url(_) | DataSource::Font { .. })))
|
||||
.map(|info| info.id);
|
||||
let ids: Vec<ResourceId> = self.registry.unresolved().map(|info| info.id).chain(refetchable).collect();
|
||||
|
||||
for id in ids {
|
||||
if self.pending_resolves.contains(&id) {
|
||||
continue;
|
||||
}
|
||||
@@ -65,7 +74,9 @@ impl MessageHandler<ResourceMessage, ResourceMessageContext<'_>> for ResourceMes
|
||||
log::error!("Resolve for {resource_id}: no registry entry");
|
||||
return;
|
||||
};
|
||||
if info.hash.is_some() {
|
||||
// This hash names the very data that is missing, so it cannot stand in for fetching that data
|
||||
let data_missing = info.hash.is_some_and(|hash| !resource_storage.contains(hash));
|
||||
if info.hash.is_some() && !data_missing {
|
||||
log::warn!("Resource {resource_id} already resolved");
|
||||
return;
|
||||
}
|
||||
@@ -78,7 +89,7 @@ impl MessageHandler<ResourceMessage, ResourceMessageContext<'_>> for ResourceMes
|
||||
.sources
|
||||
.iter()
|
||||
.map(|source| match source {
|
||||
DataSource::Font { family, style } => {
|
||||
DataSource::Font { family, style } if !data_missing => {
|
||||
let font = match style {
|
||||
Some(style) => Font::new(family.clone(), style.clone()),
|
||||
None => Font::new_with_default_style(family.clone()),
|
||||
@@ -214,16 +225,20 @@ impl ResourceMessageHandler {
|
||||
.resolved()
|
||||
.filter(|info| info.sources.contains(&DataSource::Embedded))
|
||||
.filter_map(|info| {
|
||||
if let Some(hash) = info.hash {
|
||||
let resource = resources_load_handle.load(*hash);
|
||||
Some(async move { resource.await.map(|resource| (*hash, resource)) })
|
||||
} else {
|
||||
None
|
||||
}
|
||||
let (id, hash) = (info.id, *info.hash?);
|
||||
let resource = resources_load_handle.load(hash);
|
||||
Some(async move { (id, hash, resource.await) })
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
self.embedded = EmbeddedResources::from_iter(futures::future::join_all(embedded).await.into_iter().flatten());
|
||||
let loaded = futures::future::join_all(embedded).await;
|
||||
|
||||
// Saving without these bytes writes a document whose registry claims to carry them
|
||||
for (id, hash, _) in loaded.iter().filter(|(_, _, resource)| resource.is_none()) {
|
||||
log::error!("Resource {id} ({hash}) is marked as embedded but its data is missing from storage, so the saved document will not contain it");
|
||||
}
|
||||
|
||||
self.embedded = EmbeddedResources::from_iter(loaded.into_iter().filter_map(|(_, hash, resource)| resource.map(|resource| (hash, resource))));
|
||||
}
|
||||
|
||||
pub fn collect_garbage(&mut self, used: &[ResourceId]) {
|
||||
@@ -297,3 +312,65 @@ impl<'de> serde::Deserialize<'de> for ResourceMessageHandler {
|
||||
deserializer.deserialize_map(EmbeddedResourcesVisitor { human_readable })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use graph_craft::application_io::resource::ResourceStorage;
|
||||
|
||||
/// Storage can lose a resource's data while the document keeps the hash naming it, which leaves the graph
|
||||
/// pointing at bytes that are gone. Only sources that can be fetched again are worth re-resolving.
|
||||
#[test]
|
||||
fn resolve_all_refetches_resources_whose_data_is_missing() {
|
||||
let mut handler = ResourceMessageHandler::default();
|
||||
let storage = ResourceStorageMessageHandler::default();
|
||||
|
||||
// Present: its bytes are in storage, so it is already usable
|
||||
let present = ResourceId::new();
|
||||
let present_hash = storage.resources_mut().store(b"stored font bytes");
|
||||
handler.registry.resolve(&present, present_hash);
|
||||
handler.registry.push_source_back(&present, DataSource::Embedded);
|
||||
handler.registry.push_source_back(
|
||||
&present,
|
||||
DataSource::Font {
|
||||
family: "Lato".into(),
|
||||
style: Some("Regular (400)".into()),
|
||||
},
|
||||
);
|
||||
|
||||
// Recoverable: its bytes are gone, but the font it came from can be downloaded again
|
||||
let recoverable = ResourceId::new();
|
||||
handler.registry.resolve(&recoverable, ResourceHash::from(b"evicted font bytes".as_slice()));
|
||||
handler.registry.push_source_back(&recoverable, DataSource::Embedded);
|
||||
handler.registry.push_source_back(
|
||||
&recoverable,
|
||||
DataSource::Font {
|
||||
family: "Lato".into(),
|
||||
style: Some("Black (900)".into()),
|
||||
},
|
||||
);
|
||||
|
||||
// Unrecoverable: its bytes are gone and nothing records where to fetch them from
|
||||
let unrecoverable = ResourceId::new();
|
||||
handler.registry.resolve(&unrecoverable, ResourceHash::from(b"evicted image bytes".as_slice()));
|
||||
handler.registry.push_source_back(&unrecoverable, DataSource::Embedded);
|
||||
|
||||
let mut responses = VecDeque::new();
|
||||
let fonts = FontsMessageHandler::default();
|
||||
handler.process_message(
|
||||
ResourceMessage::ResolveAll,
|
||||
&mut responses,
|
||||
ResourceMessageContext {
|
||||
document_id: DocumentId(0),
|
||||
fonts: &fonts,
|
||||
resource_storage: &storage,
|
||||
},
|
||||
);
|
||||
|
||||
let resolve_requested = |id: ResourceId| responses.contains(&Message::from(ResourceMessage::Resolve { resource_id: id }));
|
||||
|
||||
assert!(resolve_requested(recoverable), "a missing resource with a font source should be fetched again");
|
||||
assert!(!resolve_requested(present), "a resource whose data is in storage should be left alone");
|
||||
assert!(!resolve_requested(unrecoverable), "a missing resource with no fetchable source has nowhere to fetch from");
|
||||
}
|
||||
}
|
||||
@@ -8,10 +8,10 @@ use glam::{DAffine2, DVec2};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::Appearance;
|
||||
use graphene_std::math::quad::Quad;
|
||||
use graphene_std::subpath;
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::vector::click_target::{ClickTarget, ClickTargetType};
|
||||
use graphene_std::vector::{PointId, Vector};
|
||||
use kurbo::{Affine, BezPath};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::num::NonZeroU64;
|
||||
use std::sync::Arc;
|
||||
@@ -188,11 +188,13 @@ impl DocumentMetadata {
|
||||
self.visual_targets(layer)?
|
||||
.iter()
|
||||
.filter_map(|click_target| match click_target.target_type() {
|
||||
ClickTargetType::Subpath(subpath) => subpath.loose_bounding_box_with_transform(transform),
|
||||
ClickTargetType::CompoundPath(subpaths) => subpaths
|
||||
.iter()
|
||||
.filter_map(|subpath| subpath.loose_bounding_box_with_transform(transform))
|
||||
.reduce(|[a_min, a_max], [b_min, b_max]| [a_min.min(b_min), a_max.max(b_max)]),
|
||||
ClickTargetType::Path(path) => {
|
||||
let mut transformed = path.clone();
|
||||
transformed.apply_affine(Affine::new(transform.to_cols_array()));
|
||||
|
||||
let control_box = transformed.control_box();
|
||||
(!transformed.is_empty()).then(|| [DVec2::new(control_box.min_x(), control_box.min_y()), DVec2::new(control_box.max_x(), control_box.max_y())])
|
||||
}
|
||||
ClickTargetType::FreePoint(_) => click_target.bounding_box_with_transform(transform),
|
||||
})
|
||||
.reduce(Quad::combine_bounds)
|
||||
@@ -251,11 +253,10 @@ impl DocumentMetadata {
|
||||
self.all_layers().filter_map(|layer| self.bounding_box_viewport(layer)).reduce(Quad::combine_bounds)
|
||||
}
|
||||
|
||||
pub fn layer_outline(&self, layer: LayerNodeIdentifier) -> impl Iterator<Item = &subpath::Subpath<PointId>> {
|
||||
self.visual_targets(layer).unwrap_or(&[]).iter().flat_map(|target| match target.target_type() {
|
||||
ClickTargetType::Subpath(subpath) => std::slice::from_ref(subpath),
|
||||
ClickTargetType::CompoundPath(subpaths) => subpaths.as_slice(),
|
||||
ClickTargetType::FreePoint(_) => &[],
|
||||
pub fn layer_outline(&self, layer: LayerNodeIdentifier) -> impl Iterator<Item = &BezPath> {
|
||||
self.visual_targets(layer).unwrap_or(&[]).iter().filter_map(|target| match target.target_type() {
|
||||
ClickTargetType::Path(path) => Some(path),
|
||||
ClickTargetType::FreePoint(_) => None,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -43,10 +43,9 @@ use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, No
|
||||
use graphene_std::Appearance;
|
||||
use graphene_std::ContextDependencies;
|
||||
use graphene_std::math::quad::Quad;
|
||||
use graphene_std::subpath::Subpath;
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphene_std::vector::click_target::{ClickTarget, ClickTargetType, FreePoint};
|
||||
use graphene_std::vector::{PointId, Vector, VectorModificationType};
|
||||
use graphene_std::vector::{Vector, VectorModificationType};
|
||||
use kurbo::BezPath;
|
||||
use memo_network::MemoNetwork;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -397,12 +397,12 @@ impl NodeNetworkInterface {
|
||||
|
||||
if *import_index == 0 {
|
||||
let remove_import_center = reorder_import_center + DVec2::new(-4., 0.);
|
||||
let remove_import = ClickTarget::new_with_subpath(Subpath::new_rectangle(remove_import_center - DVec2::new(8., 8.), remove_import_center + DVec2::new(8., 8.)), 0.);
|
||||
let remove_import = ClickTarget::new_with_path(rectangle_path(remove_import_center - DVec2::new(8., 8.), remove_import_center + DVec2::new(8., 8.)), 0.);
|
||||
remove_imports_exports.insert_custom_output_port(*import_index, remove_import);
|
||||
} else {
|
||||
let remove_import_center = reorder_import_center + DVec2::new(-12., 0.);
|
||||
let reorder_import = ClickTarget::new_with_subpath(Subpath::new_rectangle(reorder_import_center - DVec2::new(3., 4.), reorder_import_center + DVec2::new(3., 4.)), 0.);
|
||||
let remove_import = ClickTarget::new_with_subpath(Subpath::new_rectangle(remove_import_center - DVec2::new(8., 8.), remove_import_center + DVec2::new(8., 8.)), 0.);
|
||||
let reorder_import = ClickTarget::new_with_path(rectangle_path(reorder_import_center - DVec2::new(3., 4.), reorder_import_center + DVec2::new(3., 4.)), 0.);
|
||||
let remove_import = ClickTarget::new_with_path(rectangle_path(remove_import_center - DVec2::new(8., 8.), remove_import_center + DVec2::new(8., 8.)), 0.);
|
||||
reorder_imports_exports.insert_custom_output_port(*import_index, reorder_import);
|
||||
remove_imports_exports.insert_custom_output_port(*import_index, remove_import);
|
||||
}
|
||||
@@ -417,12 +417,12 @@ impl NodeNetworkInterface {
|
||||
|
||||
if *export_index == 0 {
|
||||
let remove_export_center = reorder_export_center + DVec2::new(4., 0.);
|
||||
let remove_export = ClickTarget::new_with_subpath(Subpath::new_rectangle(remove_export_center - DVec2::new(8., 8.), remove_export_center + DVec2::new(8., 8.)), 0.);
|
||||
let remove_export = ClickTarget::new_with_path(rectangle_path(remove_export_center - DVec2::new(8., 8.), remove_export_center + DVec2::new(8., 8.)), 0.);
|
||||
remove_imports_exports.insert_custom_input_port(*export_index, remove_export);
|
||||
} else {
|
||||
let remove_export_center = reorder_export_center + DVec2::new(12., 0.);
|
||||
let reorder_export = ClickTarget::new_with_subpath(Subpath::new_rectangle(reorder_export_center - DVec2::new(3., 4.), reorder_export_center + DVec2::new(3., 4.)), 0.);
|
||||
let remove_export = ClickTarget::new_with_subpath(Subpath::new_rectangle(remove_export_center - DVec2::new(8., 8.), remove_export_center + DVec2::new(8., 8.)), 0.);
|
||||
let reorder_export = ClickTarget::new_with_path(rectangle_path(reorder_export_center - DVec2::new(3., 4.), reorder_export_center + DVec2::new(3., 4.)), 0.);
|
||||
let remove_export = ClickTarget::new_with_path(rectangle_path(remove_export_center - DVec2::new(8., 8.), remove_export_center + DVec2::new(8., 8.)), 0.);
|
||||
reorder_imports_exports.insert_custom_input_port(*export_index, reorder_export);
|
||||
remove_imports_exports.insert_custom_input_port(*export_index, remove_export);
|
||||
}
|
||||
@@ -1001,8 +1001,8 @@ impl NodeNetworkInterface {
|
||||
let node_click_target_bottom_right = node_click_target_top_left + DVec2::new(width as f64, height as f64);
|
||||
|
||||
let radius = 3.;
|
||||
let subpath = Subpath::new_rounded_rectangle(node_click_target_top_left, node_click_target_bottom_right, [radius; 4]);
|
||||
let node_click_target = ClickTarget::new_with_subpath(subpath, 0.);
|
||||
let path = rounded_rectangle_path(node_click_target_top_left, node_click_target_bottom_right, [radius; 4]);
|
||||
let node_click_target = ClickTarget::new_with_path(path, 0.);
|
||||
|
||||
DocumentNodeClickTargets {
|
||||
node_click_target,
|
||||
@@ -1032,22 +1032,22 @@ impl NodeNetworkInterface {
|
||||
|
||||
// Update visibility button click target
|
||||
let visibility_offset = node_top_left + DVec2::new(width as f64, LAYER_VERTICAL_CENTER);
|
||||
let subpath = Subpath::new_rounded_rectangle(
|
||||
let path = rounded_rectangle_path(
|
||||
DVec2::new(-ICON_HALF_EXTENT, -ICON_HALF_EXTENT) + visibility_offset,
|
||||
DVec2::new(ICON_HALF_EXTENT, ICON_HALF_EXTENT) + visibility_offset,
|
||||
[3.; 4],
|
||||
);
|
||||
let visibility_click_target = ClickTarget::new_with_subpath(subpath, 0.);
|
||||
let visibility_click_target = ClickTarget::new_with_path(path, 0.);
|
||||
|
||||
// Update lock button click target, positioned one grid unit to the left of the visibility button (only when locked)
|
||||
let lock_click_target = if locked {
|
||||
let lock_offset = node_top_left + DVec2::new(width as f64 - GRID_SIZE as f64, LAYER_VERTICAL_CENTER);
|
||||
let subpath = Subpath::new_rounded_rectangle(
|
||||
let path = rounded_rectangle_path(
|
||||
DVec2::new(-ICON_HALF_EXTENT, -ICON_HALF_EXTENT) + lock_offset,
|
||||
DVec2::new(ICON_HALF_EXTENT, ICON_HALF_EXTENT) + lock_offset,
|
||||
[3.; 4],
|
||||
);
|
||||
Some(ClickTarget::new_with_subpath(subpath, 0.))
|
||||
Some(ClickTarget::new_with_path(path, 0.))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
@@ -1057,12 +1057,12 @@ impl NodeNetworkInterface {
|
||||
const GRIP_WIDTH: f64 = 8.;
|
||||
let icons_width = if locked { GRID_SIZE as f64 } else { 0. };
|
||||
let grip_offset_right_edge = node_top_left + DVec2::new(width as f64 - ICON_HALF_EXTENT - icons_width, LAYER_VERTICAL_CENTER);
|
||||
let subpath = Subpath::new_rounded_rectangle(
|
||||
let path = rounded_rectangle_path(
|
||||
DVec2::new(-GRIP_WIDTH, -ICON_HALF_EXTENT) + grip_offset_right_edge,
|
||||
DVec2::new(0., ICON_HALF_EXTENT) + grip_offset_right_edge,
|
||||
[0.; 4],
|
||||
);
|
||||
let grip_click_target = ClickTarget::new_with_subpath(subpath, 0.);
|
||||
let grip_click_target = ClickTarget::new_with_path(path, 0.);
|
||||
|
||||
// Update display-name text click target, used to detect double-click rename. Sized to the text bounds
|
||||
// (not the surrounding `.details` area) so the rest of the layer still drills into the subgraph on double-click.
|
||||
@@ -1091,8 +1091,8 @@ impl NodeNetworkInterface {
|
||||
// The 1-grid-tall name strip is centered vertically in the 2-grid-tall layer.
|
||||
let name_top = node_top_left.y + HALF_GRID_SIZE as f64;
|
||||
let name_bottom = node_top_left.y + GRID_SIZE as f64 + HALF_GRID_SIZE as f64;
|
||||
let subpath = Subpath::new_rounded_rectangle(DVec2::new(name_left, name_top), DVec2::new(name_right, name_bottom), [3.; 4]);
|
||||
Some(ClickTarget::new_with_subpath(subpath, 0.))
|
||||
let path = rounded_rectangle_path(DVec2::new(name_left, name_top), DVec2::new(name_right, name_bottom), [3.; 4]);
|
||||
Some(ClickTarget::new_with_path(path, 0.))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
@@ -1104,8 +1104,8 @@ impl NodeNetworkInterface {
|
||||
let node_bottom_right = node_top_left + DVec2::new(width as f64, height as f64);
|
||||
let chain_top_left = node_top_left - DVec2::new((chain_width_grid_spaces * GRID_SIZE) as f64, 0.);
|
||||
const CORNER_RADIUS: f64 = 10.;
|
||||
let subpath = Subpath::new_rounded_rectangle(chain_top_left, node_bottom_right, [CORNER_RADIUS; 4]);
|
||||
let node_click_target = ClickTarget::new_with_subpath(subpath, 0.);
|
||||
let path = rounded_rectangle_path(chain_top_left, node_bottom_right, [CORNER_RADIUS; 4]);
|
||||
let node_click_target = ClickTarget::new_with_path(path, 0.);
|
||||
|
||||
DocumentNodeClickTargets {
|
||||
node_click_target,
|
||||
|
||||
+17
-18
@@ -33,8 +33,8 @@ impl NodeNetworkInterface {
|
||||
let nodes = network_metadata.persistent_metadata.node_metadata.keys().copied().collect::<Vec<_>>();
|
||||
self.with_import_export_ports(network_path, |import_export_click_targets| {
|
||||
for port in import_export_click_targets.click_targets() {
|
||||
if let ClickTargetType::Subpath(subpath) = port.target_type() {
|
||||
connector_click_targets.push(subpath.to_bezpath().to_svg());
|
||||
if let ClickTargetType::Path(path) = port.target_type() {
|
||||
connector_click_targets.push(path.to_svg());
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -42,29 +42,29 @@ impl NodeNetworkInterface {
|
||||
self.with_node_click_targets(&node_id, network_path, |node_click_targets| {
|
||||
let mut node_path = String::new();
|
||||
|
||||
if let ClickTargetType::Subpath(subpath) = node_click_targets.node_click_target.target_type() {
|
||||
node_path.push_str(subpath.to_bezpath().to_svg().as_str())
|
||||
if let ClickTargetType::Path(path) = node_click_targets.node_click_target.target_type() {
|
||||
node_path.push_str(path.to_svg().as_str())
|
||||
}
|
||||
all_node_click_targets.push((node_id, node_path));
|
||||
for port in node_click_targets.port_click_targets.click_targets() {
|
||||
if let ClickTargetType::Subpath(subpath) = port.target_type() {
|
||||
connector_click_targets.push(subpath.to_bezpath().to_svg());
|
||||
if let ClickTargetType::Path(path) = port.target_type() {
|
||||
connector_click_targets.push(path.to_svg());
|
||||
}
|
||||
}
|
||||
if let NodeTypeClickTargets::Layer(layer_metadata) = &node_click_targets.node_type_metadata {
|
||||
// Visibility button (eye icon)
|
||||
if let ClickTargetType::Subpath(subpath) = layer_metadata.visibility_click_target.target_type() {
|
||||
icon_click_targets.push(subpath.to_bezpath().to_svg());
|
||||
if let ClickTargetType::Path(path) = layer_metadata.visibility_click_target.target_type() {
|
||||
icon_click_targets.push(path.to_svg());
|
||||
}
|
||||
// Lock button (padlock icon), only when the layer is locked
|
||||
if let Some(lock_click_target) = &layer_metadata.lock_click_target
|
||||
&& let ClickTargetType::Subpath(subpath) = lock_click_target.target_type()
|
||||
&& let ClickTargetType::Path(path) = lock_click_target.target_type()
|
||||
{
|
||||
icon_click_targets.push(subpath.to_bezpath().to_svg());
|
||||
icon_click_targets.push(path.to_svg());
|
||||
}
|
||||
// Drag grip (dotted symbol)
|
||||
if let ClickTargetType::Subpath(subpath) = layer_metadata.grip_click_target.target_type() {
|
||||
icon_click_targets.push(subpath.to_bezpath().to_svg());
|
||||
if let ClickTargetType::Path(path) = layer_metadata.grip_click_target.target_type() {
|
||||
icon_click_targets.push(path.to_svg());
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -80,8 +80,7 @@ impl NodeNetworkInterface {
|
||||
});
|
||||
|
||||
let bounds = self.all_nodes_bounding_box(network_path).unwrap_or([DVec2::ZERO, DVec2::ZERO]);
|
||||
let rect = Subpath::<PointId>::new_rectangle(bounds[0], bounds[1]);
|
||||
let all_nodes_bounding_box = rect.to_bezpath().to_svg();
|
||||
let all_nodes_bounding_box = rectangle_path(bounds[0], bounds[1]).to_svg();
|
||||
|
||||
let mut modify_import_export = Vec::new();
|
||||
self.with_modify_import_export(network_path, |modify_import_export_click_targets| {
|
||||
@@ -90,8 +89,8 @@ impl NodeNetworkInterface {
|
||||
.click_targets()
|
||||
.chain(modify_import_export_click_targets.reorder_imports_exports.click_targets())
|
||||
{
|
||||
if let ClickTargetType::Subpath(subpath) = click_target.target_type() {
|
||||
modify_import_export.push(subpath.to_bezpath().to_svg());
|
||||
if let ClickTargetType::Path(path) = click_target.target_type() {
|
||||
modify_import_export.push(path.to_svg());
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -342,8 +341,8 @@ impl NodeNetworkInterface {
|
||||
return None;
|
||||
};
|
||||
|
||||
let bounding_box_subpath = Subpath::<PointId>::new_rectangle(bounds[0], bounds[1]);
|
||||
bounding_box_subpath.bounding_box_with_transform(network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport)
|
||||
let node_graph_to_viewport = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport;
|
||||
Some((node_graph_to_viewport * Quad::from_box(bounds)).bounding_box())
|
||||
}
|
||||
|
||||
pub fn collect_layer_widths(&self, network_path: &[NodeId]) -> (HashMap<NodeId, u32>, HashMap<NodeId, u32>, HashMap<NodeId, bool>) {
|
||||
|
||||
@@ -38,9 +38,12 @@ impl NodeNetworkInterface {
|
||||
let vector = self.upstream_path_node_vector(layer)?;
|
||||
|
||||
let mut targets = Vec::new();
|
||||
let subpaths: Vec<Subpath<PointId>> = vector.stroke_bezier_paths().collect();
|
||||
if !subpaths.is_empty() {
|
||||
targets.push(ClickTargetType::CompoundPath(subpaths));
|
||||
let mut combined = BezPath::new();
|
||||
for bezpath in vector.stroke_bezpath_iter() {
|
||||
combined.extend(bezpath.elements().iter().copied());
|
||||
}
|
||||
if !combined.is_empty() {
|
||||
targets.push(ClickTargetType::Path(combined));
|
||||
}
|
||||
|
||||
for &point_id in vector.point_domain.ids() {
|
||||
|
||||
@@ -1,5 +1,33 @@
|
||||
use super::*;
|
||||
use graphene_std::ParameterRef;
|
||||
use graphene_std::vector::misc::dvec2_to_point;
|
||||
use kurbo::{DEFAULT_ACCURACY, Shape};
|
||||
|
||||
/// Axis-aligned rectangle spanning the two opposite corners, used for node graph chrome click targets.
|
||||
pub fn rectangle_path(corner1: DVec2, corner2: DVec2) -> BezPath {
|
||||
kurbo::Rect::from_points(dvec2_to_point(corner1), dvec2_to_point(corner2)).to_path(DEFAULT_ACCURACY)
|
||||
}
|
||||
|
||||
/// Same as [`rectangle_path`] but with per-corner radii ordered top left, top right, bottom right, bottom left.
|
||||
pub fn rounded_rectangle_path(corner1: DVec2, corner2: DVec2, radii: [f64; 4]) -> BezPath {
|
||||
let rect = kurbo::Rect::from_points(dvec2_to_point(corner1), dvec2_to_point(corner2));
|
||||
if radii.iter().all(|radius| *radius == 0.) {
|
||||
return rect.to_path(DEFAULT_ACCURACY);
|
||||
}
|
||||
|
||||
let [top_left, top_right, bottom_right, bottom_left] = radii;
|
||||
kurbo::RoundedRect::from_rect(rect, kurbo::RoundedRectRadii::new(top_left, top_right, bottom_right, bottom_left)).to_path(DEFAULT_ACCURACY)
|
||||
}
|
||||
|
||||
/// Ellipse inscribed in the box spanning the two opposite corners.
|
||||
pub fn ellipse_path(corner1: DVec2, corner2: DVec2) -> BezPath {
|
||||
let rect = kurbo::Rect::from_points(dvec2_to_point(corner1), dvec2_to_point(corner2));
|
||||
let mut path = kurbo::Ellipse::new(rect.center(), (rect.width() / 2., rect.height() / 2.), 0.).to_path(DEFAULT_ACCURACY);
|
||||
|
||||
// Kurbo emits the ellipse as an unclosed 360 degree arc, but hit testing only fills explicitly closed contours
|
||||
path.close_path();
|
||||
path
|
||||
}
|
||||
|
||||
#[derive(PartialEq)]
|
||||
pub enum FlowType {
|
||||
@@ -227,8 +255,8 @@ impl Ports {
|
||||
}
|
||||
|
||||
pub(crate) fn insert_input_port_at_center(&mut self, input_index: usize, center: DVec2) {
|
||||
let subpath = Subpath::new_ellipse(center - DVec2::new(8., 8.), center + DVec2::new(8., 8.));
|
||||
self.insert_custom_input_port(input_index, ClickTarget::new_with_subpath(subpath, 0.));
|
||||
let path = ellipse_path(center - DVec2::new(8., 8.), center + DVec2::new(8., 8.));
|
||||
self.insert_custom_input_port(input_index, ClickTarget::new_with_path(path, 0.));
|
||||
}
|
||||
|
||||
pub(crate) fn insert_custom_input_port(&mut self, input_index: usize, click_target: ClickTarget) {
|
||||
@@ -236,8 +264,8 @@ impl Ports {
|
||||
}
|
||||
|
||||
pub(crate) fn insert_output_port_at_center(&mut self, output_index: usize, center: DVec2) {
|
||||
let subpath = Subpath::new_ellipse(center - DVec2::new(8., 8.), center + DVec2::new(8., 8.));
|
||||
self.insert_custom_output_port(output_index, ClickTarget::new_with_subpath(subpath, 0.));
|
||||
let path = ellipse_path(center - DVec2::new(8., 8.), center + DVec2::new(8., 8.));
|
||||
self.insert_custom_output_port(output_index, ClickTarget::new_with_path(path, 0.));
|
||||
}
|
||||
|
||||
pub(crate) fn insert_custom_output_port(&mut self, output_index: usize, click_target: ClickTarget) {
|
||||
@@ -864,3 +892,23 @@ pub(crate) fn collect_input_resource(input: &NodeInput, out: &mut HashSet<Resour
|
||||
out.insert(*id);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn port_click_targets_are_clickable_at_their_center() {
|
||||
let center = DVec2::new(100., 50.);
|
||||
let mut ports = Ports::new();
|
||||
ports.insert_input_port_at_center(0, center);
|
||||
ports.insert_output_port_at_center(0, center + DVec2::new(200., 0.));
|
||||
|
||||
assert_eq!(ports.clicked_input_port_from_point(center), Some(0));
|
||||
assert_eq!(ports.clicked_input_port_from_point(center + DVec2::new(5., 5.)), Some(0));
|
||||
assert_eq!(ports.clicked_input_port_from_point(center + DVec2::new(20., 0.)), None);
|
||||
|
||||
assert_eq!(ports.clicked_output_port_from_point(center + DVec2::new(200., 0.)), Some(0));
|
||||
assert_eq!(ports.clicked_output_port_from_point(center), None);
|
||||
}
|
||||
}
|
||||
@@ -93,7 +93,7 @@ impl OriginalTransforms {
|
||||
|
||||
let mut selected_points = selected_points.clone();
|
||||
|
||||
for (segment_id, _, start, end) in vector.segment_bezier_iter() {
|
||||
for (segment_id, _, start, end) in vector.segment_iter() {
|
||||
if selected_segments.contains(&segment_id) {
|
||||
selected_points.insert(ManipulatorPointId::Anchor(start));
|
||||
selected_points.insert(ManipulatorPointId::Anchor(end));
|
||||
@@ -392,7 +392,7 @@ impl TransformOperation {
|
||||
}
|
||||
|
||||
pub fn hints(&self, responses: &mut VecDeque<Message>, local: bool) {
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::{Key, MouseMotion};
|
||||
use crate::messages::input_mapper::utility_types::keyboard::{Key, MouseMotion};
|
||||
use crate::messages::tool::utility_types::{HintData, HintGroup, HintInfo};
|
||||
|
||||
let mut input_hints = Vec::new();
|
||||
|
||||
@@ -479,7 +479,7 @@ fn straight_wire_to_bezpath(locations: Vec<IVec2>) -> BezPath {
|
||||
if locations.len() == 2 {
|
||||
let p1 = to_point(locations[0]);
|
||||
let p2 = to_point(locations[1]);
|
||||
Line::new(p1, p2).to_path(DEFAULT_ACCURACY);
|
||||
return Line::new(p1, p2).to_path(DEFAULT_ACCURACY);
|
||||
}
|
||||
|
||||
let corner_radius = 10;
|
||||
|
||||
@@ -1979,79 +1979,38 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
}
|
||||
}
|
||||
|
||||
// Upgrade Text node to include line height and character spacing, which were previously hardcoded to 1, from https://github.com/GraphiteEditor/Graphite/pull/2016
|
||||
if reference == DefinitionIdentifier::ProtoNode(ProtoNodeIdentifier::new("graphene_std::text::TextNode")) && inputs_count == 8 {
|
||||
// Every Text node era before alignment only appended inputs, so each is a prefix of the 11-input layout.
|
||||
// Alignment (#2920) is the exception: it landed at index 9 and pushed Per-Glyph Instances out to 10.
|
||||
if reference == DefinitionIdentifier::ProtoNode(ProtoNodeIdentifier::new("graphene_std::text::TextNode")) && (4..=10).contains(&inputs_count) {
|
||||
let mut template: NodeTemplate = legacy_text_node_template()?;
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut template);
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut template)?;
|
||||
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), old_inputs[1].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 2), old_inputs[2].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 3), old_inputs[3].clone(), network_path);
|
||||
document.network_interface.set_input(
|
||||
&InputConnector::node_at_index(*node_id, 4),
|
||||
if inputs_count == 6 {
|
||||
old_inputs[4].clone()
|
||||
} else {
|
||||
NodeInput::value(TaggedValue::F64(TypesettingConfig::default().line_height_ratio), false)
|
||||
},
|
||||
network_path,
|
||||
);
|
||||
document.network_interface.set_input(
|
||||
&InputConnector::node_at_index(*node_id, 5),
|
||||
if inputs_count == 6 {
|
||||
old_inputs[5].clone()
|
||||
} else {
|
||||
NodeInput::value(TaggedValue::F64(TypesettingConfig::default().letter_spacing), false)
|
||||
},
|
||||
network_path,
|
||||
);
|
||||
document.network_interface.set_input(
|
||||
&InputConnector::node_at_index(*node_id, 6),
|
||||
if inputs_count >= 7 {
|
||||
old_inputs[6].clone()
|
||||
} else {
|
||||
NodeInput::value(TaggedValue::F64(TypesettingConfig::default().max_width.unwrap_or_default()), false)
|
||||
},
|
||||
network_path,
|
||||
);
|
||||
document.network_interface.set_input(
|
||||
&InputConnector::node_at_index(*node_id, 7),
|
||||
if inputs_count >= 8 {
|
||||
old_inputs[7].clone()
|
||||
} else {
|
||||
NodeInput::value(TaggedValue::F64(TypesettingConfig::default().max_width.unwrap_or_default()), false)
|
||||
},
|
||||
network_path,
|
||||
);
|
||||
document.network_interface.set_input(
|
||||
&InputConnector::node_at_index(*node_id, 8),
|
||||
if inputs_count >= 9 {
|
||||
old_inputs[8].clone()
|
||||
} else {
|
||||
NodeInput::value(TaggedValue::F64(TypesettingConfig::default().letter_tilt), false)
|
||||
},
|
||||
network_path,
|
||||
);
|
||||
document.network_interface.set_input(
|
||||
&InputConnector::node_at_index(*node_id, 9),
|
||||
if inputs_count >= 10 {
|
||||
old_inputs[9].clone()
|
||||
} else {
|
||||
NodeInput::value(TaggedValue::TextAlign(TextAlign::default()), false)
|
||||
},
|
||||
network_path,
|
||||
);
|
||||
document.network_interface.set_input(
|
||||
&InputConnector::node_at_index(*node_id, 10),
|
||||
if inputs_count >= 11 {
|
||||
old_inputs[10].clone()
|
||||
} else {
|
||||
NodeInput::value(TaggedValue::Bool(false), false)
|
||||
},
|
||||
network_path,
|
||||
);
|
||||
// Line height and character spacing were hardcoded to 1 in the era before they became inputs
|
||||
let hardcoded_to_one = || NodeInput::value(TaggedValue::F64(1.), false);
|
||||
// Zero is how an absent `Option<f64>` maximum reads to the split below
|
||||
let unset_maximum = || NodeInput::value(TaggedValue::F64(0.), false);
|
||||
|
||||
let upgraded_inputs = [
|
||||
old_inputs[0].clone(),
|
||||
old_inputs[1].clone(),
|
||||
old_inputs[2].clone(),
|
||||
old_inputs[3].clone(),
|
||||
old_inputs.get(4).cloned().unwrap_or_else(hardcoded_to_one),
|
||||
old_inputs.get(5).cloned().unwrap_or_else(hardcoded_to_one),
|
||||
old_inputs.get(6).cloned().unwrap_or_else(unset_maximum),
|
||||
old_inputs.get(7).cloned().unwrap_or_else(unset_maximum),
|
||||
old_inputs
|
||||
.get(8)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| NodeInput::value(TaggedValue::F64(TypesettingConfig::default().letter_tilt), false)),
|
||||
NodeInput::value(TaggedValue::TextAlign(TextAlign::default()), false),
|
||||
old_inputs.get(9).cloned().unwrap_or_else(|| NodeInput::value(TaggedValue::Bool(false), false)),
|
||||
];
|
||||
for (index, input) in upgraded_inputs.into_iter().enumerate() {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input, network_path);
|
||||
}
|
||||
|
||||
inputs_count = 11
|
||||
}
|
||||
|
||||
@@ -2068,31 +2027,26 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, i), old_inputs[i].clone(), network_path);
|
||||
}
|
||||
|
||||
// The old `Option<f64>` maximum becomes a bool plus a value, with zero standing in for the absent option.
|
||||
// A wired maximum has no value to read, so it keeps its connection and counts as present.
|
||||
let split_maximum = |input: &NodeInput| match input.as_value() {
|
||||
Some(&TaggedValue::F64(maximum)) => (maximum != 0., NodeInput::value(TaggedValue::F64(if maximum == 0. { 100. } else { maximum }), false)),
|
||||
_ => (true, input.clone()),
|
||||
};
|
||||
|
||||
// Max Width
|
||||
let Some(&TaggedValue::F64(old_max_width)) = old_inputs[6].as_value() else { return None };
|
||||
document.network_interface.set_input(
|
||||
&InputConnector::node_at_index(*node_id, 6),
|
||||
NodeInput::value(TaggedValue::Bool(old_max_width != 0.), false),
|
||||
network_path,
|
||||
);
|
||||
document.network_interface.set_input(
|
||||
&InputConnector::node_at_index(*node_id, 7),
|
||||
NodeInput::value(TaggedValue::F64(if old_max_width == 0. { 100. } else { old_max_width }), false),
|
||||
network_path,
|
||||
);
|
||||
let (has_max_width, max_width) = split_maximum(&old_inputs[6]);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 6), NodeInput::value(TaggedValue::Bool(has_max_width), false), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 7), max_width, network_path);
|
||||
|
||||
// Max Height
|
||||
let Some(&TaggedValue::F64(old_max_height)) = old_inputs[7].as_value() else { return None };
|
||||
document.network_interface.set_input(
|
||||
&InputConnector::node_at_index(*node_id, 8),
|
||||
NodeInput::value(TaggedValue::Bool(old_max_height != 0.), false),
|
||||
network_path,
|
||||
);
|
||||
document.network_interface.set_input(
|
||||
&InputConnector::node_at_index(*node_id, 9),
|
||||
NodeInput::value(TaggedValue::F64(if old_max_height == 0. { 100. } else { old_max_height }), false),
|
||||
network_path,
|
||||
);
|
||||
let (has_max_height, max_height) = split_maximum(&old_inputs[7]);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 8), NodeInput::value(TaggedValue::Bool(has_max_height), false), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 9), max_height, network_path);
|
||||
|
||||
// Copy over old inputs
|
||||
#[allow(clippy::needless_range_loop)]
|
||||
@@ -2441,6 +2395,39 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
document.network_interface.add_import(TaggedValue::U32(0), false, 1, "Loop Level", "TODO", &node_path);
|
||||
}
|
||||
|
||||
// Drop the placeholder primary input the "Read Vector" node used to carry, since it reads its value from the context
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::context::read_vector::IDENTIFIER) && inputs_count > 0 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
}
|
||||
|
||||
// The "Dot Product" node gained a "Normalize" toggle, which older nodes predate by always taking the raw dot product
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::dot_product::IDENTIFIER) && inputs_count == 2 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
|
||||
for (index, input) in old_inputs.iter().take(2).enumerate() {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input.clone(), network_path);
|
||||
}
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 2), NodeInput::value(TaggedValue::Bool(false), false), network_path);
|
||||
}
|
||||
|
||||
// The "Query JSON" node succeeded "JSON Get", whose object lookups always returned their strings unquoted
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::text_nodes::json::query_json::IDENTIFIER) && inputs_count == 2 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
|
||||
for (index, input) in old_inputs.iter().take(2).enumerate() {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input.clone(), network_path);
|
||||
}
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 2), NodeInput::value(TaggedValue::Bool(true), false), network_path);
|
||||
}
|
||||
|
||||
// Upgrade the "Animation" node to add the "Rate" input
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::animation::animation_time::IDENTIFIER) && inputs_count < 2 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
@@ -2883,19 +2870,39 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
/// definition by its old reference name, swaps it to a still-supported implementation, and preserves the user's inputs.
|
||||
/// After this runs, the node's reference resolves cleanly so the rest of `migrate_node` proceeds normally.
|
||||
fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId], document: &mut DocumentMessageHandler) -> Option<()> {
|
||||
// Collapse the legacy "Sample Polyline" wrapper network into the standalone `sample_polyline` proto node.
|
||||
// The proto node now computes per-bezpath segment lengths inline, so the wrapper's separate `subpath_segment_lengths`
|
||||
// and `Memoize` nodes are no longer needed. The 7 user-facing inputs are positionally identical between the
|
||||
// old wrapper and the new proto node.
|
||||
if let Some(DefinitionIdentifier::Network(name)) = document.network_interface.reference(node_id, network_path)
|
||||
&& name == "Sample Polyline"
|
||||
&& node.inputs.len() == 7
|
||||
// Collapse the legacy "Sample Points" and "Sample Polyline" wrapper networks into the standalone `sample_polyline`
|
||||
// proto node, which now computes per-bezpath segment lengths inline instead of through the wrapper's helper nodes.
|
||||
// The oldest documents lose their stored reference on load, so the wrapper is recognized by the nodes it encloses.
|
||||
let wrapper_inputs = match &node.implementation {
|
||||
DocumentNodeImplementation::Network(inner) => {
|
||||
let helpers = [graphene_std::ops::passthrough::IDENTIFIER, graphene_std::memo::memoize::IDENTIFIER];
|
||||
let mut sample_nodes = 0;
|
||||
let only_helpers = inner.nodes.values().all(|inner_node| match &inner_node.implementation {
|
||||
DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::vector::sample_polyline::IDENTIFIER => {
|
||||
sample_nodes += 1;
|
||||
true
|
||||
}
|
||||
DocumentNodeImplementation::ProtoNode(identifier) => helpers.contains(identifier),
|
||||
_ => false,
|
||||
});
|
||||
(only_helpers && sample_nodes == 1).then_some(node.inputs.len())
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if let Some(wrapper_inputs) = wrapper_inputs
|
||||
&& (wrapper_inputs == 5 || wrapper_inputs == 7)
|
||||
{
|
||||
let mut node_template = resolve_proto_node_type(graphene_std::vector::sample_polyline::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)?;
|
||||
for (index, input) in old_inputs.iter().take(7).enumerate() {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input.clone(), network_path);
|
||||
|
||||
// The 5-input era predates the separation/quantity choice, so its lone spacing distance becomes the separation
|
||||
let upgraded_inputs: Vec<(usize, NodeInput)> = match wrapper_inputs {
|
||||
5 => [0, 2, 4, 5, 6].into_iter().zip(old_inputs.iter().cloned()).collect(),
|
||||
_ => old_inputs.iter().take(7).cloned().enumerate().collect(),
|
||||
};
|
||||
for (index, input) in upgraded_inputs {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input, network_path);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2984,6 +2991,93 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
// The Text node produced geometry until it became a string source, so every shape it ever had must reach the
|
||||
// current one and gain the converter that turns its string back into geometry
|
||||
#[test]
|
||||
fn every_legacy_text_shape_gains_its_geometry_converter() {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
|
||||
use graphene_std::NodeParameter;
|
||||
use graphene_std::text::Font;
|
||||
|
||||
// Each era only appended to the one before it, so the shorter shapes are prefixes of this longest pre-alignment one
|
||||
let legacy_inputs = [
|
||||
NodeInput::scope("editor-api"),
|
||||
NodeInput::value(TaggedValue::String("Lorem".into()), false),
|
||||
NodeInput::value(TaggedValue::Font(Font::new("Lato".to_string(), "Regular (400)".to_string())), false),
|
||||
NodeInput::value(TaggedValue::F64(48.), false),
|
||||
NodeInput::value(TaggedValue::F64(1.5), false),
|
||||
NodeInput::value(TaggedValue::F64(2.), false),
|
||||
NodeInput::value(TaggedValue::F64(0.), false),
|
||||
NodeInput::value(TaggedValue::F64(0.), false),
|
||||
NodeInput::value(TaggedValue::F64(10.), false),
|
||||
NodeInput::value(TaggedValue::Bool(false), false),
|
||||
];
|
||||
|
||||
for shape in [4, 6, 8, 9, 10] {
|
||||
let (text_id, consumer_id) = (NodeId(1), NodeId(2));
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
document.network_interface.insert_node(
|
||||
text_id,
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_std::text::TextNode")),
|
||||
inputs: legacy_inputs[..shape].to_vec(),
|
||||
..Default::default()
|
||||
},
|
||||
&[],
|
||||
);
|
||||
document.network_interface.insert_node(
|
||||
consumer_id,
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false)],
|
||||
..Default::default()
|
||||
},
|
||||
&[],
|
||||
);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(consumer_id, 0), NodeInput::node(text_id, 0), &[]);
|
||||
|
||||
document_migration_upgrades(&mut document, false);
|
||||
|
||||
let network = document.network_interface.document_network();
|
||||
let text_node = network.nodes.get(&text_id).expect("the upgraded text node should keep its ID");
|
||||
assert_eq!(text_node.inputs.len(), 12, "a {shape}-input text node should reach the current shape");
|
||||
|
||||
// The converter is a new node, so it is found by identity rather than by ID
|
||||
let converter = network
|
||||
.nodes
|
||||
.iter()
|
||||
.find(|(_, node)| matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::text::text_to_vector::IDENTIFIER))
|
||||
.map(|(converter_id, _)| *converter_id)
|
||||
.unwrap_or_else(|| panic!("a {shape}-input text node should gain a string converter"));
|
||||
assert_eq!(
|
||||
network.nodes[&consumer_id].inputs.first(),
|
||||
Some(&NodeInput::node(converter, 0)),
|
||||
"the converter should be spliced onto the wire leaving a {shape}-input text node"
|
||||
);
|
||||
|
||||
let input_value = |index: usize| text_node.inputs.get(index).and_then(|input| input.as_value()).cloned();
|
||||
assert_eq!(input_value(graphene_std::text::text::SizeInput::INDEX), Some(TaggedValue::F64(48.)), "shape {shape} lost its size");
|
||||
if shape >= 6 {
|
||||
assert_eq!(
|
||||
input_value(graphene_std::text::text::LineHeightInput::INDEX),
|
||||
Some(TaggedValue::F64(1.5)),
|
||||
"shape {shape} lost its line height"
|
||||
);
|
||||
assert_eq!(
|
||||
input_value(graphene_std::text::text::LetterSpacingInput::INDEX),
|
||||
Some(TaggedValue::F64(2.)),
|
||||
"shape {shape} lost its letter spacing"
|
||||
);
|
||||
}
|
||||
if shape >= 9 {
|
||||
assert_eq!(
|
||||
input_value(graphene_std::text::text::LetterTiltInput::INDEX),
|
||||
Some(TaggedValue::F64(10.)),
|
||||
"shape {shape} lost its letter tilt"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_no_duplicate_node_replacements() {
|
||||
let mut hashmap = HashMap::<ProtoNodeIdentifier, u32>::new();
|
||||
|
||||
@@ -6,7 +6,7 @@ use crate::consts::{DEFAULT_DOCUMENT_NAME, FILE_EXTENSION, GDD_FILE_EXTENSION};
|
||||
use crate::messages::animation::TimingInformation;
|
||||
use crate::messages::dialog::simple_dialogs;
|
||||
use crate::messages::frontend::utility_types::{DocumentInfo, PersistedState};
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::Key;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::Key;
|
||||
use crate::messages::input_mapper::utility_types::macros::{action_shortcut, action_shortcut_manual};
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::DocumentMessageContext;
|
||||
|
||||
@@ -48,6 +48,11 @@ impl ResourceStorageMessageHandler {
|
||||
inner: self.storage.clone().expect("Resource storage not initialized"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the resource's data is held in storage, assuming it is until storage is initialized.
|
||||
pub fn contains(&self, hash: &ResourceHash) -> bool {
|
||||
self.storage.as_ref().is_none_or(|storage| storage.contains(hash))
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for ResourceStorageMessageHandler {
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@ use crate::messages::tool::common_functionality::shapes::spiral_shape::calculate
|
||||
use glam::DVec2;
|
||||
use graph_craft::document::NodeInput;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::subpath::{calculate_growth_factor, spiral_point};
|
||||
use graphene_std::vector::algorithms::shapes::{calculate_growth_factor, spiral_point};
|
||||
use graphene_std::vector::misc::SpiralType;
|
||||
use std::collections::VecDeque;
|
||||
use std::f64::consts::TAU;
|
||||
|
||||
@@ -10,7 +10,6 @@ use graph_craft::document::{DocumentNode, NodeId, NodeInput};
|
||||
use graphene_std::Color;
|
||||
use graphene_std::raster::BlendMode;
|
||||
use graphene_std::raster_types::Image;
|
||||
use graphene_std::subpath::Subpath;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::misc::ManipulatorPointId;
|
||||
use graphene_std::vector::style::{FillChoice, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin, initial_gradient_transform_for_bounding_box};
|
||||
@@ -169,7 +168,7 @@ pub fn merge_points(document: &DocumentMessageHandler, layer: LayerNodeIdentifie
|
||||
let transform = document.metadata().transform_to_document(layer);
|
||||
let Some(vector) = document.network_interface.compute_modified_vector(layer) else { return };
|
||||
|
||||
let segment = vector.segment_bezier_iter().find(|(_, _, start, end)| *end == second_endpont || *start == second_endpont);
|
||||
let segment = vector.segment_iter().find(|(_, _, start, end)| *end == second_endpont || *start == second_endpont);
|
||||
let Some((segment, _, mut segment_start_point, mut segment_end_point)) = segment else {
|
||||
log::error!("Could not get the segment for second_endpoint.");
|
||||
return;
|
||||
@@ -207,15 +206,6 @@ pub fn merge_points(document: &DocumentMessageHandler, layer: LayerNodeIdentifie
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
}
|
||||
|
||||
/// Create a new vector layer.
|
||||
pub fn new_vector_layer(subpaths: Vec<Subpath<PointId>>, id: NodeId, parent: LayerNodeIdentifier, responses: &mut VecDeque<Message>) -> LayerNodeIdentifier {
|
||||
let insert_index = 0;
|
||||
responses.add(GraphOperationMessage::NewVectorLayer { id, subpaths, parent, insert_index });
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![id] });
|
||||
|
||||
LayerNodeIdentifier::new_unchecked(id)
|
||||
}
|
||||
|
||||
/// Create a new bitmap layer.
|
||||
pub fn new_image_layer(image: Image<Color>, id: NodeId, parent: LayerNodeIdentifier, responses: &mut VecDeque<Message>) -> LayerNodeIdentifier {
|
||||
let insert_index = 0;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::Key;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::Key;
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
@@ -12,10 +12,9 @@ use crate::messages::tool::common_functionality::snapping::SnapTypeConfiguration
|
||||
use crate::messages::tool::common_functionality::utility_functions::is_visible_point;
|
||||
use crate::messages::tool::tool_messages::path_tool::{PathOverlayMode, PointSelectState};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphene_std::subpath::{BezierHandles, Subpath};
|
||||
use graphene_std::subpath::{PathSegPoints, pathseg_points};
|
||||
use graphene_std::vector::algorithms::bezpath_algorithms::pathseg_compute_lookup_table;
|
||||
use graphene_std::vector::misc::{HandleId, ManipulatorPointId, dvec2_to_point, point_to_dvec2};
|
||||
use graphene_std::vector::algorithms::shapes::polyline_bezpath;
|
||||
use graphene_std::vector::misc::{BezierHandles, HandleId, ManipulatorPointId, PathSegPoints, bezpath_from_manipulator_groups, dvec2_to_point, pathseg_points, point_to_dvec2, segment_to_handles};
|
||||
use graphene_std::vector::{HandleExt, PointId, SegmentId, Vector, VectorModificationType};
|
||||
use kurbo::{Affine, DEFAULT_ACCURACY, Line, ParamCurve, ParamCurveNearest, PathSeg, Rect, Shape};
|
||||
use std::f64::consts::TAU;
|
||||
@@ -251,7 +250,7 @@ impl ClosestSegment {
|
||||
// Transform to viewport space
|
||||
let transform = document_metadata.transform_to_viewport_if_feeds(self.layer, network_interface);
|
||||
|
||||
// Split the Bezier at the parameter `t`
|
||||
// Split the segment at the parameter `t`
|
||||
let first = self.bezier.subsegment(0_f64..self.t);
|
||||
let second = self.bezier.subsegment(self.t..1.);
|
||||
|
||||
@@ -750,9 +749,9 @@ impl ShapeState {
|
||||
|
||||
let mut selected_stack = Vec::new();
|
||||
// Find all subpaths that have been clicked
|
||||
for stroke in vector.stroke_bezier_paths() {
|
||||
if stroke.contains_point(layer_mouse)
|
||||
&& let Some(first) = stroke.manipulator_groups().first()
|
||||
for (groups, closed) in vector.stroke_manipulator_groups() {
|
||||
if bezpath_from_manipulator_groups(&groups, closed).contains(dvec2_to_point(layer_mouse))
|
||||
&& let Some(first) = groups.first()
|
||||
{
|
||||
selected_stack.push(first.id);
|
||||
}
|
||||
@@ -788,7 +787,7 @@ impl ShapeState {
|
||||
}
|
||||
|
||||
if segments {
|
||||
for (id, _, start, end) in vector.segment_bezier_iter() {
|
||||
for (id, _, start, end) in vector.segment_iter() {
|
||||
if connected_points.contains(&start) || connected_points.contains(&end) {
|
||||
state.select_segment(id);
|
||||
}
|
||||
@@ -950,14 +949,14 @@ impl ShapeState {
|
||||
|
||||
// Move the other handle for a quadratic bezier
|
||||
for segment in vector.end_connected(point) {
|
||||
let Some((start, _end, bezier)) = vector.segment_points_from_id(segment) else { continue };
|
||||
let Some((start, _end, path_segment)) = vector.segment_points_from_id(segment) else { continue };
|
||||
|
||||
if let BezierHandles::Quadratic { handle } = bezier.handles {
|
||||
if let BezierHandles::Quadratic { handle } = segment_to_handles(&path_segment) {
|
||||
if selected.is_some_and(|selected| selected.is_point_selected(ManipulatorPointId::Anchor(start))) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let relative_position = handle - bezier.start + delta;
|
||||
let relative_position = handle - point_to_dvec2(path_segment.start()) + delta;
|
||||
let modification_type = VectorModificationType::SetPrimaryHandle { segment, relative_position };
|
||||
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
@@ -1284,7 +1283,7 @@ impl ShapeState {
|
||||
// Make a new set of anchor points which needs to be moved
|
||||
let mut affected_points = state.selected_points.clone();
|
||||
|
||||
for (segment_id, _, start, end) in vector.segment_bezier_iter() {
|
||||
for (segment_id, _, start, end) in vector.segment_iter() {
|
||||
if state.is_segment_selected(segment_id) {
|
||||
affected_points.insert(ManipulatorPointId::Anchor(start));
|
||||
affected_points.insert(ManipulatorPointId::Anchor(end));
|
||||
@@ -1570,7 +1569,7 @@ impl ShapeState {
|
||||
for (&layer, state) in &self.selected_shape_state {
|
||||
let Some(vector) = document.network_interface.compute_modified_vector(layer) else { continue };
|
||||
|
||||
for (segment, _, start, end) in vector.segment_bezier_iter() {
|
||||
for (segment, _, start, end) in vector.segment_iter() {
|
||||
if state.selected_segments.contains(&segment) {
|
||||
if start_transaction && !transaction_started {
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
@@ -1785,20 +1784,23 @@ impl ShapeState {
|
||||
let viewspace = network_interface.document_metadata().transform_to_viewport_if_feeds(layer, network_interface);
|
||||
|
||||
// Handles
|
||||
for (segment_id, bezier, _, _) in vector.segment_bezier_iter() {
|
||||
let bezier = bezier.apply_transformation(|point| viewspace.transform_point2(point));
|
||||
for (segment_id, segment, _, _) in vector.segment_iter() {
|
||||
let segment = Affine::new(viewspace.to_cols_array()) * segment;
|
||||
let handles = segment_to_handles(&segment);
|
||||
let segment_start = point_to_dvec2(segment.start());
|
||||
let segment_end = point_to_dvec2(segment.end());
|
||||
let valid = |handle: DVec2, control: DVec2| handle.distance_squared(control) > crate::consts::HIDE_HANDLE_DISTANCE.powi(2);
|
||||
|
||||
if let Some(primary_handle) = bezier.handle_start()
|
||||
&& valid(primary_handle, bezier.start)
|
||||
&& (bezier.handle_end().is_some() || valid(primary_handle, bezier.end))
|
||||
if let Some(primary_handle) = handles.start()
|
||||
&& valid(primary_handle, segment_start)
|
||||
&& (handles.end().is_some() || valid(primary_handle, segment_end))
|
||||
&& primary_handle.distance_squared(pos) <= closest_distance_squared
|
||||
{
|
||||
closest_distance_squared = primary_handle.distance_squared(pos);
|
||||
manipulator_point = Some(ManipulatorPointId::PrimaryHandle(segment_id));
|
||||
}
|
||||
if let Some(end_handle) = bezier.handle_end()
|
||||
&& valid(end_handle, bezier.end)
|
||||
if let Some(end_handle) = handles.end()
|
||||
&& valid(end_handle, segment_end)
|
||||
&& end_handle.distance_squared(pos) <= closest_distance_squared
|
||||
{
|
||||
closest_distance_squared = end_handle.distance_squared(pos);
|
||||
@@ -2071,9 +2073,9 @@ impl ShapeState {
|
||||
self.convert_manipulator_handles_to_colinear(&vector, point_id, responses, layer);
|
||||
} else {
|
||||
for handle in vector.all_connected(point_id) {
|
||||
let Some(bezier) = vector.segment_from_id(handle.segment) else { continue };
|
||||
let Some(path_segment) = vector.segment_from_id(handle.segment) else { continue };
|
||||
|
||||
match bezier.handles {
|
||||
match segment_to_handles(&path_segment) {
|
||||
BezierHandles::Linear => {}
|
||||
BezierHandles::Quadratic { .. } => {
|
||||
let segment = handle.segment;
|
||||
@@ -2173,7 +2175,7 @@ impl ShapeState {
|
||||
let Some(vector) = network_interface.compute_modified_vector(layer) else { continue };
|
||||
if !select_points && select_segments {
|
||||
vector
|
||||
.segment_bezier_iter()
|
||||
.segment_iter()
|
||||
.filter(|(segment, _, _, _)| segments.contains(segment))
|
||||
.for_each(|(_, _, start, end)| match selection_change {
|
||||
SelectionChange::Shrink => {
|
||||
@@ -2220,12 +2222,11 @@ impl ShapeState {
|
||||
assert!(vector.point_domain.ids().contains(&end));
|
||||
}
|
||||
|
||||
let polygon_subpath = if let SelectionShape::Lasso(polygon) = selection_shape {
|
||||
let polygon_bezpath = if let SelectionShape::Lasso(polygon) = selection_shape {
|
||||
if polygon.len() < 2 {
|
||||
return (points_inside, segments_inside);
|
||||
}
|
||||
let polygon: Subpath<PointId> = Subpath::from_anchors(polygon.to_vec(), true);
|
||||
Some(polygon)
|
||||
Some(polyline_bezpath(polygon.iter().copied(), true))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
@@ -2253,13 +2254,13 @@ impl ShapeState {
|
||||
}
|
||||
}
|
||||
SelectionShape::Lasso(_) => {
|
||||
let polygon = polygon_subpath.as_ref().expect("If `selection_shape` is a polygon then subpath is constructed beforehand.");
|
||||
let polygon = polygon_bezpath.as_ref().expect("If `selection_shape` is a polygon then its path is constructed beforehand.");
|
||||
|
||||
// Sample 10 points on the bezier and check if all or some lie inside the polygon
|
||||
let points = pathseg_compute_lookup_table(segment, Some(10), false);
|
||||
match selection_mode {
|
||||
SelectionMode::Enclosed => points.map(|p| transform.transform_point2(p)).all(|p| polygon.contains_point(p)),
|
||||
_ => points.map(|p| transform.transform_point2(p)).any(|p| polygon.contains_point(p)),
|
||||
SelectionMode::Enclosed => points.map(|p| transform.transform_point2(p)).all(|p| polygon.contains(dvec2_to_point(p))),
|
||||
_ => points.map(|p| transform.transform_point2(p)).any(|p| polygon.contains(dvec2_to_point(p))),
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -2278,10 +2279,10 @@ impl ShapeState {
|
||||
|
||||
let select = match selection_shape {
|
||||
SelectionShape::Box(rect) => rect.contains(dvec2_to_point(transformed_position)),
|
||||
SelectionShape::Lasso(_) => polygon_subpath
|
||||
SelectionShape::Lasso(_) => polygon_bezpath
|
||||
.as_ref()
|
||||
.expect("If `selection_shape` is a polygon then subpath is constructed beforehand.")
|
||||
.contains_point(transformed_position),
|
||||
.expect("If `selection_shape` is a polygon then its path is constructed beforehand.")
|
||||
.contains(dvec2_to_point(transformed_position)),
|
||||
};
|
||||
|
||||
if select && select_points {
|
||||
@@ -2303,10 +2304,10 @@ impl ShapeState {
|
||||
|
||||
let select = match selection_shape {
|
||||
SelectionShape::Box(rect) => rect.contains(dvec2_to_point(transformed_position)),
|
||||
SelectionShape::Lasso(_) => polygon_subpath
|
||||
SelectionShape::Lasso(_) => polygon_bezpath
|
||||
.as_ref()
|
||||
.expect("If `selection_shape` is a polygon then subpath is constructed beforehand.")
|
||||
.contains_point(transformed_position),
|
||||
.expect("If `selection_shape` is a polygon then its path is constructed beforehand.")
|
||||
.contains(dvec2_to_point(transformed_position)),
|
||||
};
|
||||
|
||||
if select && select_points {
|
||||
|
||||
@@ -16,7 +16,8 @@ use crate::messages::tool::utility_types::*;
|
||||
use glam::{DAffine2, DMat2, DVec2};
|
||||
use graph_craft::document::NodeInput;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::subpath::{self, Subpath};
|
||||
use graphene_std::math::float_noise::round_away_float_noise;
|
||||
use graphene_std::vector::algorithms::shapes::{arc_bezpath, regular_polygon_bezpath, star_polygon_bezpath};
|
||||
use graphene_std::vector::click_target::ClickTargetType;
|
||||
use graphene_std::vector::misc::{ArcType, GridType, SpiralType, dvec2_to_point};
|
||||
use kurbo::{BezPath, PathEl, Shape};
|
||||
@@ -442,12 +443,9 @@ pub fn star_outline(layer: Option<LayerNodeIdentifier>, document: &DocumentMessa
|
||||
let viewport = document.metadata().transform_to_viewport(layer);
|
||||
|
||||
let points = sides as u64;
|
||||
let diameter: f64 = radius1 * 2.;
|
||||
let inner_diameter = radius2 * 2.;
|
||||
let targets: Vec<ClickTargetType> = vec![ClickTargetType::Path(star_polygon_bezpath(DVec2::ZERO, points, radius1, radius2))];
|
||||
|
||||
let subpath: Vec<ClickTargetType> = vec![ClickTargetType::Subpath(Subpath::new_star_polygon(DVec2::splat(-diameter), points, diameter, inner_diameter))];
|
||||
|
||||
overlay_context.outline(subpath.iter(), viewport, None);
|
||||
overlay_context.outline(targets.iter(), viewport, None);
|
||||
}
|
||||
|
||||
/// Outlines the geometric shape made by polygon-node
|
||||
@@ -460,11 +458,9 @@ pub fn polygon_outline(layer: Option<LayerNodeIdentifier>, document: &DocumentMe
|
||||
let viewport = document.metadata().transform_to_viewport(layer);
|
||||
|
||||
let points = sides as u64;
|
||||
let radius: f64 = radius * 2.;
|
||||
let targets: Vec<ClickTargetType> = vec![ClickTargetType::Path(regular_polygon_bezpath(DVec2::ZERO, points, radius))];
|
||||
|
||||
let subpath: Vec<ClickTargetType> = vec![ClickTargetType::Subpath(Subpath::new_regular_polygon(DVec2::splat(-radius), points, radius))];
|
||||
|
||||
overlay_context.outline(subpath.iter(), viewport, None);
|
||||
overlay_context.outline(targets.iter(), viewport, None);
|
||||
}
|
||||
|
||||
/// Outlines the geometric shape made by an Arc node
|
||||
@@ -475,19 +471,11 @@ pub fn arc_outline(layer: Option<LayerNodeIdentifier>, document: &DocumentMessag
|
||||
return;
|
||||
};
|
||||
|
||||
let subpath: Vec<ClickTargetType> = vec![ClickTargetType::Subpath(Subpath::new_arc(
|
||||
radius,
|
||||
start_angle / 360. * std::f64::consts::TAU,
|
||||
sweep_angle / 360. * std::f64::consts::TAU,
|
||||
match arc_type {
|
||||
ArcType::Open => subpath::ArcType::Open,
|
||||
ArcType::Closed => subpath::ArcType::Closed,
|
||||
ArcType::PieSlice => subpath::ArcType::PieSlice,
|
||||
},
|
||||
))];
|
||||
let arc = arc_bezpath(radius, start_angle / 360. * std::f64::consts::TAU, sweep_angle / 360. * std::f64::consts::TAU, arc_type);
|
||||
let targets: Vec<ClickTargetType> = vec![ClickTargetType::Path(arc)];
|
||||
let viewport = document.metadata().transform_to_viewport(layer);
|
||||
|
||||
overlay_context.outline(subpath.iter(), viewport, None);
|
||||
overlay_context.outline(targets.iter(), viewport, None);
|
||||
}
|
||||
|
||||
/// Check if the the cursor is inside the geometric star shape made by the Star node without any upstream node modifications
|
||||
@@ -583,26 +571,6 @@ pub fn format_rounded(value: f64, precision: usize) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Recovers the intended number from floating point imprecision noise when that can be done reliably, e.g. 0.30000000000000004 -> 0.3.
|
||||
/// Rounding to each significant digit count from 1 to 12, the first candidate within a relative 1e-13 of the original is accepted.
|
||||
/// Actual high-precision values (like 0.3333333333333333) never pass the tolerance and are returned unchanged.
|
||||
pub fn round_away_float_noise(value: f64) -> f64 {
|
||||
if value == 0. || !value.is_finite() {
|
||||
return if value == 0. { 0. } else { value };
|
||||
}
|
||||
|
||||
let exponent = value.abs().log10().floor() as i32;
|
||||
for significant_digits in 1..=12 {
|
||||
let scale = 10_f64.powi(significant_digits - 1 - exponent);
|
||||
let rounded = (value * scale).round() / scale;
|
||||
if ((rounded - value) / value).abs() < 1e-13 {
|
||||
return rounded;
|
||||
}
|
||||
}
|
||||
|
||||
value
|
||||
}
|
||||
|
||||
/// Gives the approximated angle to display in degrees, given an angle in degrees.
|
||||
pub fn calculate_display_angle(angle: f64) -> f64 {
|
||||
if angle.is_sign_positive() {
|
||||
@@ -647,37 +615,6 @@ pub fn extract_grid_parameters(layer: LayerNodeIdentifier, document: &DocumentMe
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn round_away_float_noise_snaps_noisy_values() {
|
||||
assert_eq!(round_away_float_noise(0.1 + 0.2), 0.3);
|
||||
assert_eq!(round_away_float_noise(0.3000000000000012), 0.3);
|
||||
assert_eq!(round_away_float_noise(2.99999999999993), 3.);
|
||||
assert_eq!(round_away_float_noise(45.00000000000001), 45.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_away_float_noise_keeps_honest_values() {
|
||||
assert_eq!(round_away_float_noise(1. / 3.), 1. / 3.);
|
||||
assert_eq!(round_away_float_noise(0.2394023940209349), 0.2394023940209349);
|
||||
assert_eq!(round_away_float_noise(0.25), 0.25);
|
||||
assert_eq!(round_away_float_noise(-17.5), -17.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_away_float_noise_keeps_deliberate_values_with_zero_runs() {
|
||||
assert_eq!(round_away_float_noise(0.30000005), 0.30000005);
|
||||
assert_eq!(round_away_float_noise(0.3000000000001), 0.3000000000001);
|
||||
assert_eq!(round_away_float_noise(1.00000001), 1.00000001);
|
||||
assert_eq!(round_away_float_noise(2.9999993), 2.9999993);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_away_float_noise_normalizes_zero() {
|
||||
let result = round_away_float_noise(-0.);
|
||||
assert_eq!(result, 0.);
|
||||
assert!(result.is_sign_positive());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_rounded_trims_trailing_zeros_when_exact() {
|
||||
assert_eq!(format_rounded(0.25, 2), "0.25");
|
||||
|
||||
@@ -14,7 +14,7 @@ use crate::messages::tool::tool_messages::tool_prelude::*;
|
||||
use glam::DAffine2;
|
||||
use graph_craft::document::NodeInput;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::subpath::{calculate_growth_factor, spiral_point};
|
||||
use graphene_std::vector::algorithms::shapes::{calculate_growth_factor, spiral_point};
|
||||
use graphene_std::vector::misc::SpiralType;
|
||||
use std::collections::VecDeque;
|
||||
|
||||
|
||||
@@ -6,14 +6,12 @@ use crate::messages::prelude::*;
|
||||
use glam::{DAffine2, DVec2, FloatExt};
|
||||
use graphene_std::math::math_ext::QuadExt;
|
||||
use graphene_std::renderer::Quad;
|
||||
use graphene_std::subpath::pathseg_points;
|
||||
use graphene_std::subpath::{Identifier, ManipulatorGroup, Subpath};
|
||||
use graphene_std::vector::PointId;
|
||||
use graphene_std::vector::algorithms::bezpath_algorithms::{pathseg_normals_to_point, pathseg_tangents_to_point};
|
||||
use graphene_std::vector::algorithms::intersection::filtered_segment_intersections;
|
||||
use graphene_std::vector::misc::dvec2_to_point;
|
||||
use graphene_std::vector::misc::point_to_dvec2;
|
||||
use kurbo::{Affine, ParamCurve, PathSeg};
|
||||
use graphene_std::vector::algorithms::shapes::{ellipse_bezpath, line_bezpath};
|
||||
use graphene_std::vector::misc::{ManipulatorGroup, bezpath_from_manipulator_groups, dvec2_to_point, pathseg_points, point_to_dvec2};
|
||||
use kurbo::{Affine, BezPath, ParamCurve, PathEl, PathSeg};
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct LayerSnapper {
|
||||
@@ -47,7 +45,7 @@ impl LayerSnapper {
|
||||
self.paths_to_snap.push(SnapCandidatePath {
|
||||
document_curve,
|
||||
layer,
|
||||
start: PointId::new(),
|
||||
start: PointId::generate(),
|
||||
target,
|
||||
bounds: Some(bounds),
|
||||
});
|
||||
@@ -74,26 +72,20 @@ impl LayerSnapper {
|
||||
}
|
||||
|
||||
if document.snapping_state.target_enabled(SnapTarget::Path(PathSnapTarget::IntersectionPoint)) || document.snapping_state.target_enabled(SnapTarget::Path(PathSnapTarget::AlongPath)) {
|
||||
let mut push_candidates = |subpath: &Subpath<PointId>, transform: DAffine2| {
|
||||
for (start_index, curve) in subpath.iter().enumerate() {
|
||||
let document_curve = Affine::new(transform.to_cols_array()) * curve;
|
||||
let start = subpath.manipulator_groups()[start_index].id;
|
||||
if snap_data.ignore_manipulator(layer, start) || snap_data.ignore_manipulator(layer, subpath.manipulator_groups()[(start_index + 1) % subpath.len()].id) {
|
||||
continue;
|
||||
// Post-solidified outline (the layer's recorded geometry). Its anchors carry no point IDs,
|
||||
// so while this layer's manipulators are being dragged the whole outline is skipped instead of filtering per manipulator.
|
||||
if !snap_data.ignore_bounds(layer) {
|
||||
for bezpath in document.metadata().layer_outline(layer) {
|
||||
for curve in bezpath.segments() {
|
||||
self.paths_to_snap.push(SnapCandidatePath {
|
||||
document_curve: Affine::new(transform.to_cols_array()) * curve,
|
||||
layer,
|
||||
start: PointId::generate(),
|
||||
target: SnapTarget::Path(PathSnapTarget::AlongPath),
|
||||
bounds: None,
|
||||
});
|
||||
}
|
||||
self.paths_to_snap.push(SnapCandidatePath {
|
||||
document_curve,
|
||||
layer,
|
||||
start,
|
||||
target: SnapTarget::Path(PathSnapTarget::AlongPath),
|
||||
bounds: None,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Post-solidified outline (the layer's recorded geometry)
|
||||
for subpath in document.metadata().layer_outline(layer) {
|
||||
push_candidates(subpath, transform);
|
||||
}
|
||||
|
||||
// Pre-solidified centerline (the Path tool's view) when an upstream Path node exists,
|
||||
@@ -101,8 +93,22 @@ impl LayerSnapper {
|
||||
if let Some(vector) = document.network_interface.upstream_path_node_vector(layer) {
|
||||
let path_aware_transform = document.metadata().transform_to_document_if_feeds(layer, &document.network_interface);
|
||||
if path_aware_transform.is_finite() {
|
||||
for subpath in vector.stroke_bezier_paths() {
|
||||
push_candidates(&subpath, path_aware_transform);
|
||||
for (groups, closed) in vector.stroke_manipulator_groups() {
|
||||
let bezpath = bezpath_from_manipulator_groups(&groups, closed);
|
||||
for (start_index, curve) in bezpath.segments().enumerate() {
|
||||
let start = groups[start_index].id;
|
||||
let end = groups[(start_index + 1) % groups.len()].id;
|
||||
if snap_data.ignore_manipulator(layer, start) || snap_data.ignore_manipulator(layer, end) {
|
||||
continue;
|
||||
}
|
||||
self.paths_to_snap.push(SnapCandidatePath {
|
||||
document_curve: Affine::new(path_aware_transform.to_cols_array()) * curve,
|
||||
layer,
|
||||
start,
|
||||
target: SnapTarget::Path(PathSnapTarget::AlongPath),
|
||||
bounds: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -156,17 +162,17 @@ impl LayerSnapper {
|
||||
|
||||
let tolerance = snap_tolerance(document);
|
||||
let constraint_path = if let SnapConstraint::Circle { center, radius } = constraint {
|
||||
Subpath::new_ellipse(center - DVec2::splat(radius), center + DVec2::splat(radius))
|
||||
ellipse_bezpath(center - DVec2::splat(radius), center + DVec2::splat(radius))
|
||||
} else {
|
||||
let constrained_point = constraint.projection(point.document_point);
|
||||
let direction = constraint.direction().normalize_or_zero();
|
||||
let start = constrained_point - tolerance * direction;
|
||||
let end = constrained_point + tolerance * direction;
|
||||
Subpath::<PointId>::new_line(start, end)
|
||||
line_bezpath(start, end)
|
||||
};
|
||||
|
||||
for path in &self.paths_to_snap {
|
||||
for constraint_path in constraint_path.iter() {
|
||||
for constraint_path in constraint_path.segments() {
|
||||
for time in filtered_segment_intersections(path.document_curve, constraint_path, None, None) {
|
||||
let snapped_point_document = point_to_dvec2(path.document_curve.eval(time));
|
||||
|
||||
@@ -548,13 +554,14 @@ fn handle_not_under(to_document: DAffine2) -> impl Fn(&DVec2) -> bool {
|
||||
move |&offset: &DVec2| to_document.transform_vector2(offset).length_squared() >= HIDE_HANDLE_DISTANCE * HIDE_HANDLE_DISTANCE
|
||||
}
|
||||
|
||||
fn subpath_anchor_snap_points(layer: LayerNodeIdentifier, subpath: &Subpath<PointId>, snap_data: &SnapData, points: &mut Vec<SnapCandidatePoint>, to_document: DAffine2) {
|
||||
fn manipulator_groups_anchor_snap_points(layer: LayerNodeIdentifier, groups: &[ManipulatorGroup], closed: bool, snap_data: &SnapData, points: &mut Vec<SnapCandidatePoint>, to_document: DAffine2) {
|
||||
let document = snap_data.document;
|
||||
let bezpath = bezpath_from_manipulator_groups(groups, closed);
|
||||
|
||||
// Midpoints of linear segments
|
||||
if document.snapping_state.target_enabled(SnapTarget::Path(PathSnapTarget::LineMidpoint)) {
|
||||
for (index, curve) in subpath.iter().enumerate() {
|
||||
if snap_data.ignore_manipulator(layer, subpath.manipulator_groups()[index].id) || snap_data.ignore_manipulator(layer, subpath.manipulator_groups()[(index + 1) % subpath.len()].id) {
|
||||
for (index, curve) in bezpath.segments().enumerate() {
|
||||
if snap_data.ignore_manipulator(layer, groups[index].id) || snap_data.ignore_manipulator(layer, groups[(index + 1) % groups.len()].id) {
|
||||
continue;
|
||||
}
|
||||
if points.len() >= crate::consts::MAX_LAYER_SNAP_POINTS {
|
||||
@@ -576,7 +583,7 @@ fn subpath_anchor_snap_points(layer: LayerNodeIdentifier, subpath: &Subpath<Poin
|
||||
}
|
||||
|
||||
// Anchors
|
||||
for (index, manipulators) in subpath.manipulator_groups().iter().enumerate() {
|
||||
for (index, manipulators) in groups.iter().enumerate() {
|
||||
if snap_data.ignore_manipulator(layer, manipulators.id) {
|
||||
continue;
|
||||
}
|
||||
@@ -585,7 +592,7 @@ fn subpath_anchor_snap_points(layer: LayerNodeIdentifier, subpath: &Subpath<Poin
|
||||
return;
|
||||
}
|
||||
|
||||
let colinear = are_manipulator_handles_colinear(manipulators, to_document, subpath, index);
|
||||
let colinear = are_manipulator_handles_colinear(manipulators, to_document, closed, index, groups.len());
|
||||
|
||||
// Colinear handles
|
||||
if colinear && document.snapping_state.target_enabled(SnapTarget::Path(PathSnapTarget::AnchorPointWithColinearHandles)) {
|
||||
@@ -608,11 +615,101 @@ fn subpath_anchor_snap_points(layer: LayerNodeIdentifier, subpath: &Subpath<Poin
|
||||
}
|
||||
}
|
||||
|
||||
pub fn are_manipulator_handles_colinear(manipulators: &ManipulatorGroup<PointId>, to_document: DAffine2, subpath: &Subpath<PointId>, index: usize) -> bool {
|
||||
fn bezpath_anchor_snap_points(layer: LayerNodeIdentifier, bezpath: &BezPath, snap_data: &SnapData, points: &mut Vec<SnapCandidatePoint>, to_document: DAffine2) {
|
||||
let document = snap_data.document;
|
||||
|
||||
// Split the path into contours so endpoint and wraparound handling stays per-subpath
|
||||
let mut contours = Vec::new();
|
||||
let mut current = BezPath::new();
|
||||
for element in bezpath.elements() {
|
||||
if matches!(element, PathEl::MoveTo(_)) && !current.elements().is_empty() {
|
||||
contours.push(std::mem::take(&mut current));
|
||||
}
|
||||
current.push(*element);
|
||||
}
|
||||
if !current.elements().is_empty() {
|
||||
contours.push(current);
|
||||
}
|
||||
|
||||
for contour in contours {
|
||||
let closed = matches!(contour.elements().last(), Some(PathEl::ClosePath));
|
||||
let segments: Vec<PathSeg> = contour.segments().collect();
|
||||
if segments.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Midpoints of linear segments
|
||||
if document.snapping_state.target_enabled(SnapTarget::Path(PathSnapTarget::LineMidpoint)) {
|
||||
for &segment in &segments {
|
||||
if points.len() >= crate::consts::MAX_LAYER_SNAP_POINTS {
|
||||
return;
|
||||
}
|
||||
|
||||
let curve = pathseg_points(segment);
|
||||
let in_handle = curve.p1.map(|handle| handle - curve.p0).filter(handle_not_under(to_document));
|
||||
let out_handle = curve.p2.map(|handle| handle - curve.p3).filter(handle_not_under(to_document));
|
||||
if in_handle.is_none() && out_handle.is_none() {
|
||||
points.push(SnapCandidatePoint::new(
|
||||
to_document.transform_point2(curve.p0 * 0.5 + curve.p3 * 0.5),
|
||||
SnapSource::Path(PathSnapSource::LineMidpoint),
|
||||
SnapTarget::Path(PathSnapTarget::LineMidpoint),
|
||||
Some(layer),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Anchors
|
||||
let anchor_count = segments.len() + if closed { 0 } else { 1 };
|
||||
for index in 0..anchor_count {
|
||||
if points.len() >= crate::consts::MAX_LAYER_SNAP_POINTS {
|
||||
return;
|
||||
}
|
||||
|
||||
let anchor = if index < segments.len() {
|
||||
pathseg_points(segments[index]).p0
|
||||
} else {
|
||||
pathseg_points(segments[index - 1]).p3
|
||||
};
|
||||
|
||||
let in_handle = if index > 0 {
|
||||
pathseg_points(segments[index - 1]).p2
|
||||
} else if closed {
|
||||
pathseg_points(segments[segments.len() - 1]).p2
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let out_handle = if index < segments.len() { pathseg_points(segments[index]).p1 } else { None };
|
||||
|
||||
let handle_in = in_handle.map(|handle| anchor - handle).filter(handle_not_under(to_document));
|
||||
let handle_out = out_handle.map(|handle| handle - anchor).filter(handle_not_under(to_document));
|
||||
let anchor_is_endpoint = !closed && (index == 0 || index == anchor_count - 1);
|
||||
let colinear = !anchor_is_endpoint && handle_in.is_some_and(|handle_in| handle_out.is_some_and(|handle_out| handle_in.angle_to(handle_out) < 1e-5));
|
||||
|
||||
if colinear && document.snapping_state.target_enabled(SnapTarget::Path(PathSnapTarget::AnchorPointWithColinearHandles)) {
|
||||
points.push(SnapCandidatePoint::new(
|
||||
to_document.transform_point2(anchor),
|
||||
SnapSource::Path(PathSnapSource::AnchorPointWithColinearHandles),
|
||||
SnapTarget::Path(PathSnapTarget::AnchorPointWithColinearHandles),
|
||||
Some(layer),
|
||||
));
|
||||
} else if !colinear && document.snapping_state.target_enabled(SnapTarget::Path(PathSnapTarget::AnchorPointWithFreeHandles)) {
|
||||
points.push(SnapCandidatePoint::new(
|
||||
to_document.transform_point2(anchor),
|
||||
SnapSource::Path(PathSnapSource::AnchorPointWithFreeHandles),
|
||||
SnapTarget::Path(PathSnapTarget::AnchorPointWithFreeHandles),
|
||||
Some(layer),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn are_manipulator_handles_colinear(manipulators: &ManipulatorGroup, to_document: DAffine2, closed: bool, index: usize, count: usize) -> bool {
|
||||
let anchor = manipulators.anchor;
|
||||
let handle_in = manipulators.in_handle.map(|handle| anchor - handle).filter(handle_not_under(to_document));
|
||||
let handle_out = manipulators.out_handle.map(|handle| handle - anchor).filter(handle_not_under(to_document));
|
||||
let anchor_is_endpoint = !subpath.closed() && (index == 0 || index == subpath.len() - 1);
|
||||
let anchor_is_endpoint = !closed && (index == 0 || index == count - 1);
|
||||
|
||||
// Unless this is an endpoint, check if both handles are colinear (within an angular epsilon)
|
||||
!anchor_is_endpoint && handle_in.is_some_and(|handle_in| handle_out.is_some_and(|handle_out| handle_in.angle_to(handle_out) < 1e-5))
|
||||
@@ -633,11 +730,11 @@ pub fn get_layer_snap_points(layer: LayerNodeIdentifier, snap_data: &SnapData, p
|
||||
get_layer_snap_points(child, snap_data, points);
|
||||
}
|
||||
} else {
|
||||
// Post-solidified outline (the layer's recorded geometry)
|
||||
if document.metadata().layer_outline(layer).next().is_some() {
|
||||
// Post-solidified outline (the layer's recorded geometry), skipped wholesale while this layer's manipulators are being dragged since the outline carries no point IDs
|
||||
if !snap_data.ignore_bounds(layer) {
|
||||
let to_document = document.metadata().transform_to_document(layer);
|
||||
for subpath in document.metadata().layer_outline(layer) {
|
||||
subpath_anchor_snap_points(layer, subpath, snap_data, points, to_document);
|
||||
for bezpath in document.metadata().layer_outline(layer) {
|
||||
bezpath_anchor_snap_points(layer, bezpath, snap_data, points, to_document);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -646,8 +743,8 @@ pub fn get_layer_snap_points(layer: LayerNodeIdentifier, snap_data: &SnapData, p
|
||||
// matching what the Path tool's overlay shows
|
||||
if let Some(vector) = document.network_interface.upstream_path_node_vector(layer) {
|
||||
let to_document = document.metadata().transform_to_document_if_feeds(layer, &document.network_interface);
|
||||
for subpath in vector.stroke_bezier_paths() {
|
||||
subpath_anchor_snap_points(layer, &subpath, snap_data, points, to_document);
|
||||
for (groups, closed) in vector.stroke_manipulator_groups() {
|
||||
manipulator_groups_anchor_snap_points(layer, &groups, closed, snap_data, points, to_document);
|
||||
}
|
||||
|
||||
if document.snapping_state.target_enabled(SnapTarget::Path(PathSnapTarget::AnchorPointWithFreeHandles)) {
|
||||
|
||||
@@ -13,11 +13,10 @@ use crate::messages::tool::utility_types::ToolType;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::renderer::Quad;
|
||||
use graphene_std::subpath::{Bezier, BezierHandles};
|
||||
use graphene_std::vector::algorithms::bezpath_algorithms::pathseg_compute_lookup_table;
|
||||
use graphene_std::vector::misc::{HandleId, ManipulatorPointId, dvec2_to_point};
|
||||
use graphene_std::vector::{HandleExt, PointId, SegmentId, Vector, VectorModification, VectorModificationType};
|
||||
use kurbo::{CubicBez, DEFAULT_ACCURACY, Line, ParamCurve, PathSeg, Point, QuadBez, Shape};
|
||||
use kurbo::{CubicBez, DEFAULT_ACCURACY, ParamCurve, PathSeg, Point, Shape};
|
||||
|
||||
/// Determines if a path should be extended. Goal in viewport space. Returns the path and if it is extending from the start, if applicable.
|
||||
pub fn should_extend(document: &DocumentMessageHandler, goal: DVec2, tolerance: f64, layers: impl Iterator<Item = LayerNodeIdentifier>) -> Option<(LayerNodeIdentifier, PointId, DVec2)> {
|
||||
@@ -196,51 +195,6 @@ pub fn is_visible_point(
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_intersecting(bezier: Bezier, quad: [DVec2; 2], transform: DAffine2) -> bool {
|
||||
let to_layerspace = transform.inverse();
|
||||
let quad = [to_layerspace.transform_point2(quad[0]), to_layerspace.transform_point2(quad[1])];
|
||||
let start = Point::new(bezier.start.x, bezier.start.y);
|
||||
let end = Point::new(bezier.end.x, bezier.end.y);
|
||||
let segment = match bezier.handles {
|
||||
BezierHandles::Cubic { handle_start, handle_end } => {
|
||||
let p1 = Point::new(handle_start.x, handle_start.y);
|
||||
let p2 = Point::new(handle_end.x, handle_end.y);
|
||||
PathSeg::Cubic(CubicBez::new(start, p1, p2, end))
|
||||
}
|
||||
BezierHandles::Quadratic { handle } => {
|
||||
let p1 = Point::new(handle.x, handle.y);
|
||||
PathSeg::Quad(QuadBez::new(start, p1, end))
|
||||
}
|
||||
BezierHandles::Linear => PathSeg::Line(Line::new(start, end)),
|
||||
};
|
||||
|
||||
// Create a list of all the sides
|
||||
let sides = [
|
||||
Line::new((quad[0].x, quad[0].y), (quad[1].x, quad[0].y)),
|
||||
Line::new((quad[0].x, quad[0].y), (quad[0].x, quad[1].y)),
|
||||
Line::new((quad[1].x, quad[1].y), (quad[1].x, quad[0].y)),
|
||||
Line::new((quad[1].x, quad[1].y), (quad[0].x, quad[1].y)),
|
||||
];
|
||||
|
||||
let mut is_intersecting = false;
|
||||
for line in sides {
|
||||
let intersections = segment.intersect_line(line);
|
||||
let mut intersects = false;
|
||||
for intersection in intersections {
|
||||
if intersection.line_t <= 1. && intersection.line_t >= 0. && intersection.segment_t <= 1. && intersection.segment_t >= 0. {
|
||||
// There is a valid intersection point
|
||||
intersects = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if intersects {
|
||||
is_intersecting = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
is_intersecting
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn resize_bounds(
|
||||
document: &DocumentMessageHandler,
|
||||
|
||||
@@ -6,9 +6,9 @@ use crate::messages::tool::common_functionality::color_selector::solid;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::{NodeGraphLayer, get_upstream_color_value_node_id, gradient_chain_target_input, replaceable_paint_chain};
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::raster::color::Color;
|
||||
use graphene_std::subpath::Subpath;
|
||||
use graphene_std::vector::PointId;
|
||||
use graphene_std::vector::misc::dvec2_to_point;
|
||||
use graphene_std::vector::style::FillChoice;
|
||||
use kurbo::{BezPath, DEFAULT_ACCURACY, Rect, Shape};
|
||||
|
||||
#[derive(Default, ExtractField)]
|
||||
pub struct FillTool {
|
||||
@@ -150,9 +150,13 @@ impl Fsm for FillToolFsmState {
|
||||
|
||||
if paints_whole_expanse(layer, &document.network_interface) {
|
||||
let expanse = whole_expanse_rect(layer, document, overlay_context.viewport.size().into_dvec2());
|
||||
overlay_context.fill_path_pattern(std::iter::once(expanse), DAffine2::IDENTITY, &color_hex);
|
||||
overlay_context.fill_path_pattern(&expanse, DAffine2::IDENTITY, &color_hex);
|
||||
} else {
|
||||
overlay_context.fill_path_pattern(document.metadata().layer_outline(layer), document.metadata().transform_to_viewport(layer), &color_hex);
|
||||
let mut outline = BezPath::new();
|
||||
for path in document.metadata().layer_outline(layer) {
|
||||
outline.extend(path.elements().iter().copied());
|
||||
}
|
||||
overlay_context.fill_path_pattern(&outline, document.metadata().transform_to_viewport(layer), &color_hex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -244,15 +248,16 @@ fn paints_whole_expanse(layer: LayerNodeIdentifier, network_interface: &NodeNetw
|
||||
|
||||
/// The viewport-space area a whole-expanse color paints: the artboard containing the layer, since the color fills it,
|
||||
/// or else the visible viewport for a layer living outside any artboard.
|
||||
fn whole_expanse_rect(layer: LayerNodeIdentifier, document: &DocumentMessageHandler, viewport_size: DVec2) -> Subpath<PointId> {
|
||||
fn whole_expanse_rect(layer: LayerNodeIdentifier, document: &DocumentMessageHandler, viewport_size: DVec2) -> BezPath {
|
||||
let containing_artboard = layer
|
||||
.ancestors(document.metadata())
|
||||
.find(|&ancestor| ancestor != LayerNodeIdentifier::ROOT_PARENT && document.network_interface.is_artboard(&ancestor.to_node(), &[]));
|
||||
|
||||
match containing_artboard.and_then(|artboard| document.metadata().bounding_box_viewport(artboard)) {
|
||||
Some([min, max]) => Subpath::new_rectangle(min, max),
|
||||
None => Subpath::new_rectangle(DVec2::ZERO, viewport_size),
|
||||
}
|
||||
let [min, max] = containing_artboard
|
||||
.and_then(|artboard| document.metadata().bounding_box_viewport(artboard))
|
||||
.unwrap_or([DVec2::ZERO, viewport_size]);
|
||||
|
||||
Rect::from_points(dvec2_to_point(min), dvec2_to_point(max)).to_path(DEFAULT_ACCURACY)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -422,7 +422,7 @@ fn extend_path_with_next_segment(tool_data: &mut FreehandToolData, position: DVe
|
||||
|
||||
#[cfg(test)]
|
||||
mod test_freehand {
|
||||
use crate::messages::input_mapper::utility_types::input_mouse::{EditorMouseState, MouseKeys, ScrollDelta};
|
||||
use crate::messages::input_mapper::utility_types::pointer::{EditorPointerState, MouseKeys};
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::{NodeGraphLayer, get_stroke_width};
|
||||
use crate::messages::tool::common_functionality::stroke_options::StrokeOptionsUpdate;
|
||||
@@ -530,10 +530,10 @@ mod test_freehand {
|
||||
let last_initial_point = initial_points[initial_points.len() - 1];
|
||||
editor
|
||||
.mouseup(
|
||||
EditorMouseState {
|
||||
EditorPointerState {
|
||||
editor_position: last_initial_point,
|
||||
mouse_keys: MouseKeys::empty(),
|
||||
scroll_delta: ScrollDelta::default(),
|
||||
..Default::default()
|
||||
},
|
||||
ModifierKeys::empty(),
|
||||
)
|
||||
@@ -589,10 +589,10 @@ mod test_freehand {
|
||||
let last_extension_point = extension_points[extension_points.len() - 1];
|
||||
editor
|
||||
.mouseup(
|
||||
EditorMouseState {
|
||||
EditorPointerState {
|
||||
editor_position: last_extension_point,
|
||||
mouse_keys: MouseKeys::empty(),
|
||||
scroll_delta: ScrollDelta::default(),
|
||||
..Default::default()
|
||||
},
|
||||
ModifierKeys::empty(),
|
||||
)
|
||||
@@ -643,10 +643,10 @@ mod test_freehand {
|
||||
let last_initial_point = initial_points[initial_points.len() - 1];
|
||||
editor
|
||||
.mouseup(
|
||||
EditorMouseState {
|
||||
EditorPointerState {
|
||||
editor_position: last_initial_point,
|
||||
mouse_keys: MouseKeys::empty(),
|
||||
scroll_delta: ScrollDelta::default(),
|
||||
..Default::default()
|
||||
},
|
||||
ModifierKeys::empty(),
|
||||
)
|
||||
@@ -678,10 +678,10 @@ mod test_freehand {
|
||||
|
||||
editor
|
||||
.mousedown(
|
||||
EditorMouseState {
|
||||
EditorPointerState {
|
||||
editor_position: first_second_point,
|
||||
mouse_keys: MouseKeys::LEFT,
|
||||
scroll_delta: ScrollDelta::default(),
|
||||
..Default::default()
|
||||
},
|
||||
ModifierKeys::SHIFT,
|
||||
)
|
||||
@@ -694,10 +694,10 @@ mod test_freehand {
|
||||
let last_second_point = second_path_points[second_path_points.len() - 1];
|
||||
editor
|
||||
.mouseup(
|
||||
EditorMouseState {
|
||||
EditorPointerState {
|
||||
editor_position: last_second_point,
|
||||
mouse_keys: MouseKeys::empty(),
|
||||
scroll_delta: ScrollDelta::default(),
|
||||
..Default::default()
|
||||
},
|
||||
ModifierKeys::SHIFT,
|
||||
)
|
||||
@@ -767,10 +767,10 @@ mod test_freehand {
|
||||
let last_point = points[points.len() - 1];
|
||||
editor
|
||||
.mouseup(
|
||||
EditorMouseState {
|
||||
EditorPointerState {
|
||||
editor_position: last_point,
|
||||
mouse_keys: MouseKeys::empty(),
|
||||
scroll_delta: ScrollDelta::default(),
|
||||
..Default::default()
|
||||
},
|
||||
ModifierKeys::empty(),
|
||||
)
|
||||
|
||||
@@ -2051,8 +2051,7 @@ enum GradientDragHintState {
|
||||
mod test_gradient {
|
||||
use super::{gradient_to_viewport_transform, midpoint_diamonds, midpoint_ratio_at};
|
||||
use crate::consts::{GRADIENT_MIDPOINT_MAX, GRADIENT_MIDPOINT_MIN};
|
||||
use crate::messages::input_mapper::utility_types::input_mouse::EditorMouseState;
|
||||
use crate::messages::input_mapper::utility_types::input_mouse::ScrollDelta;
|
||||
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
|
||||
@@ -2525,10 +2524,10 @@ mod test_gradient {
|
||||
editor.move_mouse(end_pos.x, end_pos.y, ModifierKeys::empty(), MouseKeys::LEFT).await;
|
||||
editor
|
||||
.mouseup(
|
||||
EditorMouseState {
|
||||
EditorPointerState {
|
||||
editor_position: end_pos,
|
||||
mouse_keys: MouseKeys::empty(),
|
||||
scroll_delta: ScrollDelta::default(),
|
||||
..Default::default()
|
||||
},
|
||||
ModifierKeys::empty(),
|
||||
)
|
||||
@@ -2579,10 +2578,10 @@ mod test_gradient {
|
||||
let click_position = DVec2::new(25., 0.);
|
||||
editor
|
||||
.mousedown(
|
||||
EditorMouseState {
|
||||
EditorPointerState {
|
||||
editor_position: click_position,
|
||||
mouse_keys: MouseKeys::LEFT,
|
||||
scroll_delta: ScrollDelta::default(),
|
||||
..Default::default()
|
||||
},
|
||||
ModifierKeys::empty(),
|
||||
)
|
||||
@@ -2593,10 +2592,10 @@ mod test_gradient {
|
||||
|
||||
editor
|
||||
.mouseup(
|
||||
EditorMouseState {
|
||||
EditorPointerState {
|
||||
editor_position: drag_position,
|
||||
mouse_keys: MouseKeys::empty(),
|
||||
scroll_delta: ScrollDelta::default(),
|
||||
..Default::default()
|
||||
},
|
||||
ModifierKeys::empty(),
|
||||
)
|
||||
@@ -2658,10 +2657,10 @@ mod test_gradient {
|
||||
editor.left_mousedown(position2.x, position2.y, ModifierKeys::empty()).await;
|
||||
editor
|
||||
.mouseup(
|
||||
EditorMouseState {
|
||||
EditorPointerState {
|
||||
editor_position: position2,
|
||||
mouse_keys: MouseKeys::empty(),
|
||||
scroll_delta: ScrollDelta::default(),
|
||||
..Default::default()
|
||||
},
|
||||
ModifierKeys::empty(),
|
||||
)
|
||||
@@ -2907,10 +2906,10 @@ mod test_gradient {
|
||||
editor.move_mouse(new_viewport_end.x, new_viewport_end.y, ModifierKeys::empty(), MouseKeys::LEFT).await;
|
||||
editor
|
||||
.mouseup(
|
||||
EditorMouseState {
|
||||
EditorPointerState {
|
||||
editor_position: new_viewport_end,
|
||||
mouse_keys: MouseKeys::empty(),
|
||||
scroll_delta: ScrollDelta::default(),
|
||||
..Default::default()
|
||||
},
|
||||
ModifierKeys::empty(),
|
||||
)
|
||||
@@ -2984,10 +2983,10 @@ mod test_gradient {
|
||||
editor.move_mouse(new_viewport_end.x, new_viewport_end.y, ModifierKeys::empty(), MouseKeys::LEFT).await;
|
||||
editor
|
||||
.mouseup(
|
||||
EditorMouseState {
|
||||
EditorPointerState {
|
||||
editor_position: new_viewport_end,
|
||||
mouse_keys: MouseKeys::empty(),
|
||||
scroll_delta: ScrollDelta::default(),
|
||||
..Default::default()
|
||||
},
|
||||
ModifierKeys::empty(),
|
||||
)
|
||||
|
||||
@@ -14,7 +14,7 @@ pub mod text_tool;
|
||||
|
||||
pub mod tool_prelude {
|
||||
pub use crate::messages::frontend::utility_types::MouseCursorIcon;
|
||||
pub use crate::messages::input_mapper::utility_types::input_keyboard::{Key, MouseMotion};
|
||||
pub use crate::messages::input_mapper::utility_types::keyboard::{Key, MouseMotion};
|
||||
pub use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
pub use crate::messages::prelude::*;
|
||||
pub use crate::messages::tool::utility_types::{EventToMessageMap, Fsm, ToolActionMessageContext, ToolMetadata, ToolTransition, ToolType};
|
||||
|
||||
@@ -25,12 +25,12 @@ use crate::messages::tool::common_functionality::snapping::{SnapCache, SnapCandi
|
||||
use crate::messages::tool::common_functionality::utility_functions::{calculate_segment_angle, find_two_param_best_approximate, make_path_editable_is_allowed};
|
||||
use graphene_std::Color;
|
||||
use graphene_std::renderer::Quad;
|
||||
use graphene_std::subpath::pathseg_points;
|
||||
use graphene_std::transform::ReferencePoint;
|
||||
use graphene_std::uuid::NodeId;
|
||||
use graphene_std::vector::algorithms::util::pathseg_tangent;
|
||||
use graphene_std::vector::click_target::ClickTargetType;
|
||||
use graphene_std::vector::misc::{HandleId, ManipulatorPointId, dvec2_to_point, point_to_dvec2};
|
||||
use graphene_std::vector::misc::pathseg_points;
|
||||
use graphene_std::vector::misc::{HandleId, ManipulatorPointId, dvec2_to_point, point_to_dvec2, segment_to_handles};
|
||||
use graphene_std::vector::{HandleExt, NoHashBuilder, PointId, SegmentId, Vector, VectorModificationType};
|
||||
use kurbo::{DEFAULT_ACCURACY, ParamCurve, ParamCurveNearest, PathSeg, Rect};
|
||||
use std::vec;
|
||||
@@ -1647,7 +1647,7 @@ impl Fsm for PathToolFsmState {
|
||||
|
||||
let selected_state = shape_editor.selected_shape_state.entry(layer).or_default();
|
||||
|
||||
for (segment, _, start, end) in vector.segment_bezier_iter() {
|
||||
for (segment, _, start, end) in vector.segment_iter() {
|
||||
if selected_state.is_segment_selected(segment) {
|
||||
selected_state.select_point(ManipulatorPointId::Anchor(start));
|
||||
selected_state.select_point(ManipulatorPointId::Anchor(end));
|
||||
@@ -1700,7 +1700,7 @@ impl Fsm for PathToolFsmState {
|
||||
|
||||
let selected_state = shape_editor.selected_shape_state.entry(layer).or_default();
|
||||
|
||||
for (segment, _, start, end) in vector.segment_bezier_iter() {
|
||||
for (segment, _, start, end) in vector.segment_iter() {
|
||||
let first_selected = selected_state.is_point_selected(ManipulatorPointId::Anchor(start));
|
||||
let second_selected = selected_state.is_point_selected(ManipulatorPointId::Anchor(end));
|
||||
if first_selected && second_selected {
|
||||
@@ -1764,7 +1764,7 @@ impl Fsm for PathToolFsmState {
|
||||
// The points which are part of only one segment will be rendered
|
||||
let mut selected_segments_by_point: HashMap<PointId, Vec<SegmentId>> = HashMap::new();
|
||||
|
||||
for (segment_id, _bezier, start, end) in vector.segment_bezier_iter() {
|
||||
for (segment_id, _, start, end) in vector.segment_iter() {
|
||||
if focused_segments.contains(&segment_id) {
|
||||
selected_segments_by_point.entry(start).or_default().push(segment_id);
|
||||
selected_segments_by_point.entry(end).or_default().push(segment_id);
|
||||
@@ -2764,7 +2764,7 @@ impl Fsm for PathToolFsmState {
|
||||
|
||||
let mut selected_points_by_segment = HashSet::new();
|
||||
old_vector
|
||||
.segment_bezier_iter()
|
||||
.segment_iter()
|
||||
.filter(|(segment, _, _, _)| layer_selection_state.is_segment_selected(*segment))
|
||||
.for_each(|(_, _, start, end)| {
|
||||
selected_points_by_segment.insert(start);
|
||||
@@ -2781,7 +2781,7 @@ impl Fsm for PathToolFsmState {
|
||||
let find_index = |id: PointId| new_vector.point_domain.iter().enumerate().find(|(_, (point_id, _))| *point_id == id).map(|(index, _)| index);
|
||||
|
||||
// Add segments which have selected ends
|
||||
for ((segment_id, bezier, start, end), stroke) in old_vector.segment_bezier_iter().zip(old_vector.segment_domain.stroke().iter()) {
|
||||
for (segment_id, segment, start, end) in old_vector.segment_iter() {
|
||||
let both_ends_selected = layer_selection_state.is_point_selected(ManipulatorPointId::Anchor(start)) && layer_selection_state.is_point_selected(ManipulatorPointId::Anchor(end));
|
||||
|
||||
let segment_selected = layer_selection_state.is_segment_selected(segment_id);
|
||||
@@ -2791,7 +2791,7 @@ impl Fsm for PathToolFsmState {
|
||||
error!("Point does not exist in point domain");
|
||||
return PathToolFsmState::Ready;
|
||||
};
|
||||
new_vector.segment_domain.push(segment_id, start_index, end_index, bezier.handles, *stroke);
|
||||
new_vector.segment_domain.push(segment_id, start_index, end_index, segment_to_handles(&segment));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2945,7 +2945,7 @@ impl Fsm for PathToolFsmState {
|
||||
// Add all the selected points
|
||||
let mut selected_points_by_segment = HashSet::new();
|
||||
old_vector
|
||||
.segment_bezier_iter()
|
||||
.segment_iter()
|
||||
.filter(|(segment, _, _, _)| layer_selection_state.is_segment_selected(*segment))
|
||||
.for_each(|(_, _, start, end)| {
|
||||
selected_points_by_segment.insert(start);
|
||||
@@ -3398,7 +3398,7 @@ fn calculate_adjacent_anchor_tangent(currently_dragged_handle: ManipulatorPointI
|
||||
0 => {
|
||||
// Find non-shared segments
|
||||
let non_shared_segment: Vec<_> = vector
|
||||
.segment_bezier_iter()
|
||||
.segment_iter()
|
||||
.filter_map(|(segment_id, _, start, end)| {
|
||||
let touches_adjacent = start == adjacent_anchor || end == adjacent_anchor;
|
||||
let shares_with_dragged = start == dragged_handle_anchor || end == dragged_handle_anchor;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::tool_prelude::*;
|
||||
use crate::consts::{COLOR_OVERLAY_BLUE, COLOR_OVERLAY_BLUE_05, HIDE_HANDLE_DISTANCE, LINE_ROTATE_SNAP_ANGLE, SEGMENT_OVERLAY_SIZE};
|
||||
use crate::messages::input_mapper::utility_types::input_mouse::MouseKeys;
|
||||
use crate::messages::input_mapper::utility_types::pointer::MouseKeys;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type;
|
||||
use crate::messages::portfolio::document::overlays::utility_functions::path_overlays;
|
||||
use crate::messages::portfolio::document::overlays::utility_types::{DrawHandles, OverlayContext};
|
||||
@@ -18,11 +18,11 @@ use crate::messages::tool::common_functionality::stroke_options::{StrokeOptionsU
|
||||
use crate::messages::tool::common_functionality::utility_functions::{calculate_segment_angle, closest_point, should_extend};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::subpath::pathseg_points;
|
||||
use graphene_std::vector::misc::pathseg_points;
|
||||
use graphene_std::vector::misc::{HandleId, ManipulatorPointId, dvec2_to_point};
|
||||
use graphene_std::vector::style::FillChoice;
|
||||
use graphene_std::vector::{NoHashBuilder, PointId, SegmentId, StrokeId, Vector, VectorModificationType};
|
||||
use kurbo::{CubicBez, PathSeg};
|
||||
use graphene_std::vector::{NoHashBuilder, PointId, SegmentId, Vector, VectorModificationType};
|
||||
use kurbo::{BezPath, CubicBez, PathSeg};
|
||||
|
||||
#[derive(Default, ExtractField)]
|
||||
pub struct PenTool {
|
||||
@@ -1852,26 +1852,27 @@ impl Fsm for PenToolFsmState {
|
||||
// We have the point. Join the 2 vertices and check if any path is closed.
|
||||
if let Some(end) = closest_point {
|
||||
let segment_id = SegmentId::generate();
|
||||
vector.push(segment_id, start, end, (Some(handle_start), Some(handle_end)), StrokeId::ZERO);
|
||||
vector.push(segment_id, start, end, (Some(handle_start), Some(handle_end)));
|
||||
|
||||
let grouped_segments = vector.auto_join_paths();
|
||||
let closed_paths = grouped_segments.iter().filter(|path| path.is_closed() && path.contains(segment_id));
|
||||
|
||||
let subpaths: Vec<_> = closed_paths
|
||||
.filter_map(|path| {
|
||||
let segments = path.edges.iter().filter_map(|edge| {
|
||||
vector
|
||||
.segment_domain
|
||||
.iter()
|
||||
.find(|(id, _, _, _)| id == &edge.id)
|
||||
.map(|(_, start, end, bezier)| if start == edge.start { (bezier, start, end) } else { (bezier.reversed(), end, start) })
|
||||
});
|
||||
vector.subpath_from_segments_ignore_discontinuities(segments)
|
||||
})
|
||||
.collect();
|
||||
let mut fill_region = BezPath::new();
|
||||
for path in closed_paths {
|
||||
let segments = path.edges.iter().filter_map(|edge| {
|
||||
vector
|
||||
.segment_domain
|
||||
.iter()
|
||||
.find(|(id, _, _, _)| id == &edge.id)
|
||||
.map(|(_, start, end, bezier)| if start == edge.start { (bezier, start, end) } else { (bezier.reversed(), end, start) })
|
||||
});
|
||||
if let Some(bezpath) = vector.bezpath_from_segments_ignore_discontinuities(segments) {
|
||||
fill_region.extend(bezpath.elements().iter().copied());
|
||||
}
|
||||
}
|
||||
|
||||
let fill_color = COLOR_OVERLAY_BLUE_05;
|
||||
overlay_context.fill_path(subpaths.iter(), transform, fill_color);
|
||||
overlay_context.fill_path(&fill_region, transform, fill_color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use super::tool_prelude::*;
|
||||
use crate::consts::*;
|
||||
use crate::messages::input_mapper::utility_types::input_mouse::ViewportPosition;
|
||||
use crate::messages::input_mapper::utility_types::pointer::ViewportPosition;
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::{DocumentMetadata, LayerNodeIdentifier};
|
||||
@@ -28,8 +28,8 @@ use graph_craft::document::NodeId;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::renderer::Quad;
|
||||
use graphene_std::renderer::Rect;
|
||||
use graphene_std::subpath::Subpath;
|
||||
use graphene_std::transform::ReferencePoint;
|
||||
use graphene_std::vector::algorithms::shapes::polyline_bezpath;
|
||||
use graphene_std::vector::misc::BooleanOperation;
|
||||
use graphene_std::vector::style::FillChoice;
|
||||
use std::fmt;
|
||||
@@ -575,7 +575,7 @@ impl SelectToolData {
|
||||
if self.lasso_polygon.len() < 2 {
|
||||
return Vec::new();
|
||||
}
|
||||
let polygon = Subpath::from_anchors(self.lasso_polygon.clone(), true);
|
||||
let polygon = polyline_bezpath(self.lasso_polygon.iter().copied(), true);
|
||||
document.intersect_polygon_no_artboards(polygon, viewport).collect()
|
||||
}
|
||||
|
||||
@@ -583,7 +583,7 @@ impl SelectToolData {
|
||||
if self.lasso_polygon.len() < 2 {
|
||||
return false;
|
||||
}
|
||||
let polygon = Subpath::from_anchors(self.lasso_polygon.clone(), true);
|
||||
let polygon = polyline_bezpath(self.lasso_polygon.iter().copied(), true);
|
||||
document.is_layer_fully_inside_polygon(layer, viewport, polygon)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::tool_prelude::*;
|
||||
use crate::consts::{DRAG_THRESHOLD, PATH_JOIN_THRESHOLD, SNAP_POINT_TOLERANCE};
|
||||
use crate::messages::input_mapper::utility_types::input_mouse::MouseKeys;
|
||||
use crate::messages::input_mapper::utility_types::pointer::MouseKeys;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{resolve_network_node_type, resolve_proto_node_type};
|
||||
use crate::messages::portfolio::document::overlays::utility_functions::path_endpoint_overlays;
|
||||
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::Key;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::Key;
|
||||
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
|
||||
use crate::messages::portfolio::document::utility_types::transformation::TransformType;
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::consts::{ANGLE_MEASURE_RADIUS_FACTOR, ARC_MEASURE_RADIUS_FACTOR_RANGE, COLOR_OVERLAY_BLUE, COLOR_OVERLAY_GRAY, SLOWING_DIVISOR};
|
||||
use crate::messages::input_mapper::utility_types::input_mouse::{DocumentPosition, ViewportPosition};
|
||||
use crate::messages::input_mapper::utility_types::pointer::{DocumentPosition, ViewportPosition};
|
||||
use crate::messages::portfolio::document::overlays::utility_functions::text_width;
|
||||
use crate::messages::portfolio::document::overlays::utility_types::{OverlayProvider, Pivot};
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
@@ -162,7 +162,7 @@ impl MessageHandler<TransformLayerMessage, TransformLayerMessageContext<'_>> for
|
||||
let selected_segments = shape_editor.selected_segments().collect::<HashSet<_>>();
|
||||
let mut affected_points = shape_editor.selected_points().copied().collect::<Vec<_>>();
|
||||
|
||||
for (segment_id, _, start, end) in vector.segment_bezier_iter() {
|
||||
for (segment_id, _, start, end) in vector.segment_iter() {
|
||||
if selected_segments.contains(&segment_id) {
|
||||
affected_points.push(ManipulatorPointId::Anchor(start));
|
||||
affected_points.push(ManipulatorPointId::Anchor(end));
|
||||
|
||||
@@ -4,7 +4,7 @@ use super::common_functionality::shape_editor::ShapeState;
|
||||
use super::tool_messages::*;
|
||||
use crate::messages::broadcast::BroadcastMessage;
|
||||
use crate::messages::broadcast::event::EventMessage;
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::{Key, KeysGroup, LabeledKeyOrMouseMotion, LabeledShortcut, MouseMotion};
|
||||
use crate::messages::input_mapper::utility_types::keyboard::{Key, KeysGroup, LabeledKeyOrMouseMotion, LabeledShortcut, MouseMotion};
|
||||
use crate::messages::input_mapper::utility_types::macros::action_shortcut;
|
||||
use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
|
||||
+21
-21
@@ -1,6 +1,6 @@
|
||||
use crate::application::Editor;
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::ModifierKeys;
|
||||
use crate::messages::input_mapper::utility_types::input_mouse::{EditorMouseState, MouseKeys, ScrollDelta, ViewportPosition};
|
||||
use crate::messages::input_mapper::utility_types::keyboard::ModifierKeys;
|
||||
use crate::messages::input_mapper::utility_types::pointer::{EditorPointerState, MouseKeys, ViewportPosition};
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::tool_messages::tool_prelude::Key;
|
||||
@@ -105,7 +105,7 @@ impl EditorTestUtils {
|
||||
self.move_mouse(position.x, position.y, modifier_keys, MouseKeys::empty()).await;
|
||||
|
||||
self.mousedown(
|
||||
EditorMouseState {
|
||||
EditorPointerState {
|
||||
editor_position: position,
|
||||
mouse_keys: button,
|
||||
..Default::default()
|
||||
@@ -115,7 +115,7 @@ impl EditorTestUtils {
|
||||
.await;
|
||||
|
||||
self.mouseup(
|
||||
EditorMouseState {
|
||||
EditorPointerState {
|
||||
editor_position: position,
|
||||
..Default::default()
|
||||
},
|
||||
@@ -134,10 +134,10 @@ impl EditorTestUtils {
|
||||
self.move_mouse(x2, y2, modifier_keys, MouseKeys::LEFT).await;
|
||||
|
||||
self.mouseup(
|
||||
EditorMouseState {
|
||||
EditorPointerState {
|
||||
editor_position: (x2, y2).into(),
|
||||
mouse_keys: MouseKeys::empty(),
|
||||
scroll_delta: ScrollDelta::default(),
|
||||
..Default::default()
|
||||
},
|
||||
modifier_keys,
|
||||
)
|
||||
@@ -154,10 +154,10 @@ impl EditorTestUtils {
|
||||
self.move_mouse(100., 100., ModifierKeys::default(), MouseKeys::LEFT).await;
|
||||
|
||||
self.mousedown(
|
||||
EditorMouseState {
|
||||
EditorPointerState {
|
||||
editor_position: (100., 100.).into(),
|
||||
mouse_keys: MouseKeys::LEFT | MouseKeys::RIGHT,
|
||||
scroll_delta: ScrollDelta::default(),
|
||||
..Default::default()
|
||||
},
|
||||
ModifierKeys::default(),
|
||||
)
|
||||
@@ -173,7 +173,7 @@ impl EditorTestUtils {
|
||||
}
|
||||
|
||||
pub async fn move_mouse(&mut self, x: f64, y: f64, modifier_keys: ModifierKeys, mouse_keys: MouseKeys) {
|
||||
let editor_mouse_state = EditorMouseState {
|
||||
let editor_mouse_state = EditorPointerState {
|
||||
editor_position: ViewportPosition::new(x, y),
|
||||
mouse_keys,
|
||||
..Default::default()
|
||||
@@ -181,11 +181,11 @@ impl EditorTestUtils {
|
||||
self.input(InputPreprocessorMessage::PointerMove { editor_mouse_state, modifier_keys }).await;
|
||||
}
|
||||
|
||||
pub async fn mousedown(&mut self, editor_mouse_state: EditorMouseState, modifier_keys: ModifierKeys) {
|
||||
pub async fn mousedown(&mut self, editor_mouse_state: EditorPointerState, modifier_keys: ModifierKeys) {
|
||||
self.input(InputPreprocessorMessage::PointerDown { editor_mouse_state, modifier_keys }).await;
|
||||
}
|
||||
|
||||
pub async fn mouseup(&mut self, editor_mouse_state: EditorMouseState, modifier_keys: ModifierKeys) {
|
||||
pub async fn mouseup(&mut self, editor_mouse_state: EditorPointerState, modifier_keys: ModifierKeys) {
|
||||
self.handle_message(InputPreprocessorMessage::PointerUp { editor_mouse_state, modifier_keys }).await;
|
||||
}
|
||||
|
||||
@@ -198,10 +198,10 @@ impl EditorTestUtils {
|
||||
|
||||
pub async fn left_mousedown(&mut self, x: f64, y: f64, modifier_keys: ModifierKeys) {
|
||||
self.mousedown(
|
||||
EditorMouseState {
|
||||
EditorPointerState {
|
||||
editor_position: (x, y).into(),
|
||||
mouse_keys: MouseKeys::LEFT,
|
||||
scroll_delta: ScrollDelta::default(),
|
||||
..Default::default()
|
||||
},
|
||||
modifier_keys,
|
||||
)
|
||||
@@ -210,10 +210,10 @@ impl EditorTestUtils {
|
||||
|
||||
pub async fn left_mouseup(&mut self, x: f64, y: f64, modifier_keys: ModifierKeys) {
|
||||
self.mouseup(
|
||||
EditorMouseState {
|
||||
EditorPointerState {
|
||||
editor_position: (x, y).into(),
|
||||
mouse_keys: MouseKeys::empty(),
|
||||
scroll_delta: ScrollDelta::default(),
|
||||
..Default::default()
|
||||
},
|
||||
modifier_keys,
|
||||
)
|
||||
@@ -266,10 +266,10 @@ impl EditorTestUtils {
|
||||
|
||||
pub async fn double_click(&mut self, position: DVec2) {
|
||||
self.handle_message(InputPreprocessorMessage::DoubleClick {
|
||||
editor_mouse_state: EditorMouseState {
|
||||
editor_mouse_state: EditorPointerState {
|
||||
editor_position: position,
|
||||
mouse_keys: MouseKeys::LEFT,
|
||||
scroll_delta: ScrollDelta::default(),
|
||||
..Default::default()
|
||||
},
|
||||
modifier_keys: ModifierKeys::empty(),
|
||||
})
|
||||
@@ -290,10 +290,10 @@ impl EditorTestUtils {
|
||||
}
|
||||
|
||||
self.mouseup(
|
||||
EditorMouseState {
|
||||
EditorPointerState {
|
||||
editor_position: points[points.len() - 1],
|
||||
mouse_keys: MouseKeys::empty(),
|
||||
scroll_delta: ScrollDelta::default(),
|
||||
..Default::default()
|
||||
},
|
||||
modifier_keys,
|
||||
)
|
||||
@@ -352,8 +352,8 @@ pub mod test_prelude {
|
||||
pub use crate::application::Editor;
|
||||
pub use crate::float_eq;
|
||||
pub use crate::messages::clipboard::utility_types::ClipboardContentRaw;
|
||||
pub use crate::messages::input_mapper::utility_types::input_keyboard::{Key, ModifierKeys};
|
||||
pub use crate::messages::input_mapper::utility_types::input_mouse::MouseKeys;
|
||||
pub use crate::messages::input_mapper::utility_types::keyboard::{Key, ModifierKeys};
|
||||
pub use crate::messages::input_mapper::utility_types::pointer::MouseKeys;
|
||||
pub use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
pub use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
pub use crate::messages::prelude::*;
|
||||
|
||||
@@ -3,3 +3,4 @@ wrapper/pkg/
|
||||
wrapper/pkg-native/
|
||||
public/build/
|
||||
dist/
|
||||
node_modules.locked-*/
|
||||
@@ -12,31 +12,11 @@
|
||||
export let tooltipShortcut: ActionShortcut | undefined = undefined;
|
||||
// Callbacks
|
||||
export let action: (index: number) => void;
|
||||
|
||||
function truncate(label: string): string {
|
||||
let maxLength = 40;
|
||||
|
||||
if (label.length <= maxLength) return label;
|
||||
|
||||
let truncated = label;
|
||||
const hasQuotes = label.startsWith(`"`) && label.endsWith(`"`);
|
||||
|
||||
if (hasQuotes) {
|
||||
truncated = label.slice(1, -1);
|
||||
maxLength -= 2;
|
||||
}
|
||||
|
||||
truncated = truncated.slice(0, maxLength - 1) + "…";
|
||||
|
||||
if (hasQuotes) truncated = `"${truncated}"`;
|
||||
|
||||
return truncated;
|
||||
}
|
||||
</script>
|
||||
|
||||
<LayoutRow class="breadcrumb-trail-buttons" {tooltipLabel} {tooltipDescription} {tooltipShortcut}>
|
||||
{#each labels as label, index}
|
||||
<TextButton label={truncate(label)} emphasized={index === labels.length - 1} {disabled} action={() => !disabled && index !== labels.length - 1 && action(index)} />
|
||||
<TextButton {label} emphasized={index === labels.length - 1} {disabled} action={() => !disabled && index !== labels.length - 1 && action(index)} />
|
||||
{/each}
|
||||
</LayoutRow>
|
||||
|
||||
|
||||
@@ -205,6 +205,10 @@
|
||||
textarea {
|
||||
color: var(--color-8-uppergray);
|
||||
}
|
||||
|
||||
input {
|
||||
pointer-events: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -19,6 +19,8 @@
|
||||
export let italic = false;
|
||||
export let monospace = false;
|
||||
export let multiline = false;
|
||||
export let enquote = false;
|
||||
export let selectable = false;
|
||||
export let centerAlign = false;
|
||||
export let tableAlign = false;
|
||||
// Sizing
|
||||
@@ -76,6 +78,8 @@
|
||||
class:italic
|
||||
class:monospace
|
||||
class:multiline
|
||||
class:enquote
|
||||
class:selectable
|
||||
class:center-align={centerAlign}
|
||||
class:table-align={tableAlign}
|
||||
style:min-width={minWidthCharacters ? `${minWidthCharacters}ch` : minWidth > 0 ? `${minWidth}px` : undefined}
|
||||
@@ -125,6 +129,17 @@
|
||||
margin: 4px 0;
|
||||
}
|
||||
|
||||
&.enquote::before,
|
||||
&.enquote::after {
|
||||
content: '"';
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
&.selectable {
|
||||
user-select: text;
|
||||
cursor: text;
|
||||
}
|
||||
|
||||
&.center-align {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
@@ -128,6 +128,7 @@ export function onPointerMove(e: PointerEvent, editor: EditorWrapper, documentSt
|
||||
|
||||
export function onPointerDown(e: PointerEvent, editor: EditorWrapper, dialogStore: DialogStore) {
|
||||
potentiallyRestoreCanvasFocus(e);
|
||||
potentiallyClearTextSelection(e);
|
||||
|
||||
const inFloatingMenu = e.target instanceof Element && e.target.closest("[data-floating-menu-content]");
|
||||
const isTargetingCanvas = !inFloatingMenu && e.target instanceof Element && e.target.closest("[data-viewport], [data-viewport-container], [data-node-graph]");
|
||||
@@ -351,6 +352,20 @@ function targetIsTextField(target: EventTarget | HTMLElement | undefined): boole
|
||||
);
|
||||
}
|
||||
|
||||
function potentiallyClearTextSelection(e: PointerEvent) {
|
||||
const target = e.target instanceof Element ? e.target : undefined;
|
||||
if (target && (targetIsTextField(target) || window.getComputedStyle(target).userSelect !== "none")) return;
|
||||
|
||||
// A text control's selection lives in its shadow tree, which the document's `Selection` reports as collapsed and cannot clear, so each control holding one is collapsed through its own API
|
||||
const controls = window.document.querySelectorAll<HTMLInputElement | HTMLTextAreaElement>("textarea, input[type='text']");
|
||||
controls.forEach((control) => {
|
||||
const caret = control.selectionStart;
|
||||
if (typeof caret === "number" && caret !== control.selectionEnd) control.setSelectionRange(caret, caret);
|
||||
});
|
||||
|
||||
window.getSelection()?.removeAllRanges();
|
||||
}
|
||||
|
||||
function potentiallyRestoreCanvasFocus(e: Event) {
|
||||
const appElement = window.document.querySelector("[data-app-container]");
|
||||
const app = appElement instanceof HTMLElement ? appElement : undefined;
|
||||
|
||||
@@ -15,8 +15,8 @@ use wasm_bindgen::prelude::*;
|
||||
mod editor_commands {
|
||||
use crate::helpers::translate_key;
|
||||
use editor::messages::clipboard::utility_types::ClipboardContentRaw;
|
||||
use editor::messages::input_mapper::utility_types::input_keyboard::ModifierKeys;
|
||||
use editor::messages::input_mapper::utility_types::input_mouse::{EditorMouseState, ScrollDelta};
|
||||
use editor::messages::input_mapper::utility_types::keyboard::ModifierKeys;
|
||||
use editor::messages::input_mapper::utility_types::pointer::{EditorPointerState, ScrollDelta};
|
||||
use editor::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use editor::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use editor::messages::portfolio::document::utility_types::network_interface::ImportOrExport;
|
||||
@@ -300,14 +300,14 @@ mod editor_commands {
|
||||
|
||||
/// Mouse movement within the screenspace bounds of the viewport
|
||||
fn on_mouse_move(x: f64, y: f64, mouse_keys: u8, modifiers: u8) -> Message {
|
||||
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
|
||||
let editor_mouse_state = EditorPointerState::from_keys_and_editor_position(mouse_keys, (x, y).into());
|
||||
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
|
||||
InputPreprocessorMessage::PointerMove { editor_mouse_state, modifier_keys }.into()
|
||||
}
|
||||
|
||||
/// Mouse scrolling within the screenspace bounds of the viewport
|
||||
fn on_wheel_scroll(x: f64, y: f64, mouse_keys: u8, wheel_delta_x: f64, wheel_delta_y: f64, wheel_delta_z: f64, modifiers: u8) -> Message {
|
||||
let mut editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
|
||||
let mut editor_mouse_state = EditorPointerState::from_keys_and_editor_position(mouse_keys, (x, y).into());
|
||||
editor_mouse_state.scroll_delta = ScrollDelta::new(wheel_delta_x, wheel_delta_y, wheel_delta_z);
|
||||
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
|
||||
InputPreprocessorMessage::WheelScroll { editor_mouse_state, modifier_keys }.into()
|
||||
@@ -315,28 +315,28 @@ mod editor_commands {
|
||||
|
||||
/// A mouse button depressed within screenspace the bounds of the viewport
|
||||
fn on_mouse_down(x: f64, y: f64, mouse_keys: u8, modifiers: u8) -> Message {
|
||||
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
|
||||
let editor_mouse_state = EditorPointerState::from_keys_and_editor_position(mouse_keys, (x, y).into());
|
||||
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
|
||||
InputPreprocessorMessage::PointerDown { editor_mouse_state, modifier_keys }.into()
|
||||
}
|
||||
|
||||
/// A mouse button released
|
||||
fn on_mouse_up(x: f64, y: f64, mouse_keys: u8, modifiers: u8) -> Message {
|
||||
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
|
||||
let editor_mouse_state = EditorPointerState::from_keys_and_editor_position(mouse_keys, (x, y).into());
|
||||
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
|
||||
InputPreprocessorMessage::PointerUp { editor_mouse_state, modifier_keys }.into()
|
||||
}
|
||||
|
||||
/// Mouse shaken
|
||||
fn on_mouse_shake(x: f64, y: f64, mouse_keys: u8, modifiers: u8) -> Message {
|
||||
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
|
||||
let editor_mouse_state = EditorPointerState::from_keys_and_editor_position(mouse_keys, (x, y).into());
|
||||
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
|
||||
InputPreprocessorMessage::PointerShake { editor_mouse_state, modifier_keys }.into()
|
||||
}
|
||||
|
||||
/// Mouse double clicked
|
||||
fn on_double_click(x: f64, y: f64, mouse_keys: u8, modifiers: u8) -> Message {
|
||||
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
|
||||
let editor_mouse_state = EditorPointerState::from_keys_and_editor_position(mouse_keys, (x, y).into());
|
||||
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
|
||||
InputPreprocessorMessage::DoubleClick { editor_mouse_state, modifier_keys }.into()
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ use crate::native_communication::RasterizedImage;
|
||||
#[cfg(not(feature = "native"))]
|
||||
use editor::application::Editor;
|
||||
#[cfg(feature = "editor")]
|
||||
use editor::messages::input_mapper::utility_types::input_keyboard::Key;
|
||||
use editor::messages::input_mapper::utility_types::keyboard::Key;
|
||||
#[cfg(not(feature = "native"))]
|
||||
use editor::messages::prelude::*;
|
||||
use js_sys::{Object, Reflect};
|
||||
|
||||
@@ -153,6 +153,9 @@ async fn drain_queue(inner: Arc<Mutex<Inner>>) {
|
||||
Mutation::Write { hash, bytes } => {
|
||||
if let Err(error) = write_file(&directory, &hash, &bytes).await {
|
||||
log::error!("OPFS write for {hash} failed: {error:?}");
|
||||
|
||||
// Nothing reached disk, so leaving the hash listed would claim a file that later sessions cannot read
|
||||
inner.lock().unwrap().on_disk.remove(&hash);
|
||||
}
|
||||
}
|
||||
Mutation::Delete { hash } => {
|
||||
|
||||
@@ -390,7 +390,6 @@ macro_rules! tagged_value {
|
||||
Type::Generic(_) => None,
|
||||
Type::Concrete(concrete_type) => {
|
||||
let name = concrete_type.name.as_ref();
|
||||
// TODO: Add default implementations for types such as TaggedValue::Subpaths, and use the defaults here and in document_node_types
|
||||
// Tries using the default for the tagged value type. If it not implemented, then uses the default used in document_node_types. If it is not used there, then TaggedValue::None is returned.
|
||||
if name == std::any::type_name::<()>() { return Some(TaggedValue::None) }
|
||||
if name == std::any::type_name::<Gradient>() { return Some(TaggedValue::GradientRamp(GradientRamp::default())) }
|
||||
@@ -671,7 +670,6 @@ impl TaggedValue {
|
||||
Type::Concrete(concrete_type) => {
|
||||
let ty = concrete_type.id?;
|
||||
use std::any::TypeId;
|
||||
// TODO: Add default implementations for types such as TaggedValue::Subpaths, and use the defaults here and in document_node_types
|
||||
// Tries using the default for the tagged value type. If it not implemented, then uses the default used in document_node_types. If it is not used there, then TaggedValue::None is returned.
|
||||
let ty = match () {
|
||||
() if ty == TypeId::of::<()>() => TaggedValue::None,
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
use std::fmt::Write;
|
||||
|
||||
/// Recovers the intended number from floating point imprecision noise when that can be done reliably, e.g. 0.30000000000000004 -> 0.3.
|
||||
/// Rounding to each significant digit count from 1 to 12, the first candidate within a relative 1e-13 of the original is accepted.
|
||||
/// Actual high-precision values (like 0.3333333333333333) never pass the tolerance and are returned unchanged.
|
||||
/// f64 only, as f32 lacks precision to reliably distinguish between intentional digits and noise.
|
||||
pub fn round_away_float_noise(value: f64) -> f64 {
|
||||
if value == 0. || !value.is_finite() {
|
||||
return if value == 0. { 0. } else { value };
|
||||
}
|
||||
|
||||
// Candidates come from decimal formatting rather than scaling by a power of ten, which is inexact enough to invent
|
||||
// noise of its own: it turns 1e300 into 9.999999999999999e299 and 999999.9999999 into 999999.9999999999.
|
||||
// One buffer serves every candidate, since the digit counts are tried in turn.
|
||||
let mut buffer = String::with_capacity(32);
|
||||
for significant_digits in 1..=12 {
|
||||
buffer.clear();
|
||||
let _ = write!(buffer, "{value:.*e}", significant_digits - 1);
|
||||
|
||||
let Ok(rounded) = buffer.parse::<f64>() else { continue };
|
||||
if ((rounded - value) / value).abs() < 1e-13 {
|
||||
return rounded;
|
||||
}
|
||||
}
|
||||
|
||||
value
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn round_away_float_noise_snaps_noisy_values() {
|
||||
assert_eq!(round_away_float_noise(0.1 + 0.2), 0.3);
|
||||
assert_eq!(round_away_float_noise(0.3000000000000012), 0.3);
|
||||
assert_eq!(round_away_float_noise(2.99999999999993), 3.);
|
||||
assert_eq!(round_away_float_noise(45.00000000000001), 45.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_away_float_noise_keeps_honest_values() {
|
||||
assert_eq!(round_away_float_noise(1. / 3.), 1. / 3.);
|
||||
assert_eq!(round_away_float_noise(0.2394023940209349), 0.2394023940209349);
|
||||
assert_eq!(round_away_float_noise(0.25), 0.25);
|
||||
assert_eq!(round_away_float_noise(-17.5), -17.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_away_float_noise_keeps_deliberate_values_with_zero_runs() {
|
||||
assert_eq!(round_away_float_noise(0.30000005), 0.30000005);
|
||||
assert_eq!(round_away_float_noise(0.3000000000001), 0.3000000000001);
|
||||
assert_eq!(round_away_float_noise(1.00000001), 1.00000001);
|
||||
assert_eq!(round_away_float_noise(2.9999993), 2.9999993);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_away_float_noise_normalizes_zero() {
|
||||
let result = round_away_float_noise(-0.);
|
||||
assert_eq!(result, 0.);
|
||||
assert!(result.is_sign_positive());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_away_float_noise_keeps_extreme_magnitudes_exact() {
|
||||
assert_eq!(round_away_float_noise(1e300), 1e300);
|
||||
assert_eq!(round_away_float_noise(1.5e300), 1.5e300);
|
||||
assert_eq!(round_away_float_noise(1e-300), 1e-300);
|
||||
assert_eq!(round_away_float_noise(f64::MIN_POSITIVE), f64::MIN_POSITIVE);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
pub mod bbox;
|
||||
pub mod float_noise;
|
||||
pub mod polynomial;
|
||||
pub mod quad;
|
||||
pub mod rect;
|
||||
@@ -1,10 +1,9 @@
|
||||
use kurbo::PathSeg;
|
||||
use std::fmt::{self, Display, Formatter};
|
||||
use std::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign};
|
||||
use std::ops::{Mul, MulAssign};
|
||||
|
||||
/// A struct that represents a polynomial with a maximum degree of `N-1`.
|
||||
///
|
||||
/// It provides basic mathematical operations for polynomials like addition, multiplication, differentiation, integration, etc.
|
||||
/// It provides basic mathematical operations for polynomials like multiplication, differentiation, integration, etc.
|
||||
#[derive(Copy, Clone, Debug, PartialEq)]
|
||||
pub struct Polynomial<const N: usize> {
|
||||
coefficients: [f64; N],
|
||||
@@ -18,18 +17,6 @@ impl<const N: usize> Polynomial<N> {
|
||||
Polynomial { coefficients }
|
||||
}
|
||||
|
||||
/// Create a polynomial where all its coefficients are zero.
|
||||
pub fn zero() -> Polynomial<N> {
|
||||
Polynomial { coefficients: [0.; N] }
|
||||
}
|
||||
|
||||
/// Return an immutable reference to the coefficients.
|
||||
///
|
||||
/// The coefficient for nth degree is at the nth index in array. Therefore the order of coefficients are reversed than the usual order for writing polynomials mathematically.
|
||||
pub fn coefficients(&self) -> &[f64; N] {
|
||||
&self.coefficients
|
||||
}
|
||||
|
||||
/// Return a mutable reference to the coefficients.
|
||||
///
|
||||
/// The coefficient for nth degree is at the nth index in array. Therefore the order of coefficients are reversed than the usual order for writing polynomials mathematically.
|
||||
@@ -83,98 +70,6 @@ impl<const N: usize> Polynomial<N> {
|
||||
ans.derivative_mut();
|
||||
ans
|
||||
}
|
||||
|
||||
/// Computes the antiderivative at `C = 0`.
|
||||
///
|
||||
/// Returns `None` if the polynomial is not big enough to accommodate the extra degree.
|
||||
pub fn antiderivative(&self) -> Option<Polynomial<N>> {
|
||||
let mut ans = *self;
|
||||
ans.antiderivative_mut()?;
|
||||
Some(ans)
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize> Default for Polynomial<N> {
|
||||
fn default() -> Self {
|
||||
Self::zero()
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize> Display for Polynomial<N> {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||
let mut first = true;
|
||||
for (index, coefficient) in self.coefficients.iter().enumerate().rev().filter(|&(_, &coefficient)| coefficient != 0.) {
|
||||
if first {
|
||||
first = false;
|
||||
} else {
|
||||
f.write_str(" + ")?
|
||||
}
|
||||
|
||||
coefficient.fmt(f)?;
|
||||
if index == 0 {
|
||||
continue;
|
||||
}
|
||||
f.write_str("x")?;
|
||||
if index == 1 {
|
||||
continue;
|
||||
}
|
||||
f.write_str("^")?;
|
||||
index.fmt(f)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize> AddAssign<&Polynomial<N>> for Polynomial<N> {
|
||||
fn add_assign(&mut self, rhs: &Polynomial<N>) {
|
||||
self.coefficients.iter_mut().zip(rhs.coefficients.iter()).for_each(|(a, b)| *a += b);
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize> Add for &Polynomial<N> {
|
||||
type Output = Polynomial<N>;
|
||||
|
||||
fn add(self, other: &Polynomial<N>) -> Polynomial<N> {
|
||||
let mut output = *self;
|
||||
output += other;
|
||||
output
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize> Neg for &Polynomial<N> {
|
||||
type Output = Polynomial<N>;
|
||||
|
||||
fn neg(self) -> Polynomial<N> {
|
||||
let mut output = *self;
|
||||
output.coefficients.iter_mut().for_each(|x| *x = -*x);
|
||||
output
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize> Neg for Polynomial<N> {
|
||||
type Output = Polynomial<N>;
|
||||
|
||||
fn neg(mut self) -> Polynomial<N> {
|
||||
self.coefficients.iter_mut().for_each(|x| *x = -*x);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize> SubAssign<&Polynomial<N>> for Polynomial<N> {
|
||||
fn sub_assign(&mut self, rhs: &Polynomial<N>) {
|
||||
self.coefficients.iter_mut().zip(rhs.coefficients.iter()).for_each(|(a, b)| *a -= b);
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize> Sub for &Polynomial<N> {
|
||||
type Output = Polynomial<N>;
|
||||
|
||||
fn sub(self, other: &Polynomial<N>) -> Polynomial<N> {
|
||||
let mut output = *self;
|
||||
output -= other;
|
||||
output
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize> MulAssign<&Polynomial<N>> for Polynomial<N> {
|
||||
@@ -248,18 +143,6 @@ mod test {
|
||||
assert_eq!(p2.as_size::<2>(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn addition_and_subtaction() {
|
||||
let p1 = Polynomial::new([1., 2., 3.]);
|
||||
let p2 = Polynomial::new([4., 5., 6.]);
|
||||
|
||||
let addition = Polynomial::new([5., 7., 9.]);
|
||||
let subtraction = Polynomial::new([-3., -3., -3.]);
|
||||
|
||||
assert_eq!(&p1 + &p2, addition);
|
||||
assert_eq!(&p1 - &p2, subtraction);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multiplication() {
|
||||
let p1 = Polynomial::new([1., 2., 3.]).as_size().unwrap();
|
||||
@@ -278,15 +161,10 @@ mod test {
|
||||
assert_eq!(p.derivative(), p_deriv);
|
||||
|
||||
p.coefficients_mut()[0] = 0.;
|
||||
assert_eq!(p_deriv.antiderivative().unwrap(), p);
|
||||
let mut antiderivative = p_deriv;
|
||||
assert_eq!(antiderivative.antiderivative_mut(), Some(()));
|
||||
assert_eq!(antiderivative, p);
|
||||
|
||||
assert_eq!(p.antiderivative(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display() {
|
||||
let p = Polynomial::new([1., 2., 0., 3.]);
|
||||
|
||||
assert_eq!(format!("{p:.2}"), "3.00x^3 + 2.00x + 1.00");
|
||||
assert_eq!(p.antiderivative_mut(), None);
|
||||
}
|
||||
}
|
||||
@@ -36,13 +36,6 @@ impl Rect {
|
||||
bounds
|
||||
}
|
||||
|
||||
/// Get all the edges in the rect.
|
||||
#[must_use]
|
||||
pub fn edges(&self) -> [[DVec2; 2]; 4] {
|
||||
let corners = [self[0], DVec2::new(self[0].x, self[1].y), self[1], DVec2::new(self[1].y, self[0].x)];
|
||||
[[corners[0], corners[1]], [corners[1], corners[2]], [corners[2], corners[3]], [corners[3], corners[0]]]
|
||||
}
|
||||
|
||||
/// Gets the center of a rect
|
||||
#[must_use]
|
||||
pub fn center(&self) -> DVec2 {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use crate::Node;
|
||||
use crate::math::float_noise::round_away_float_noise;
|
||||
use crate::transform::Footprint;
|
||||
use glam::DVec2;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use std::future::Future;
|
||||
use std::marker::PhantomData;
|
||||
|
||||
@@ -45,11 +46,26 @@ pub trait Convert<T, C>: Sized {
|
||||
fn convert(self, footprint: Footprint, converter: C) -> impl Future<Output = T> + Send;
|
||||
}
|
||||
|
||||
impl<T: ToString + Send> Convert<String, ()> for T {
|
||||
/// Converts this type into a `String` using its `ToString` implementation.
|
||||
/// Implements the [`Convert`] trait for formatting a type into a `String` via [`ToString`].
|
||||
macro_rules! impl_convert_to_string {
|
||||
($($from:ty),* $(,)?) => {
|
||||
$(
|
||||
impl Convert<String, ()> for $from {
|
||||
#[inline]
|
||||
async fn convert(self, _: Footprint, _converter: ()) -> String {
|
||||
self.to_string()
|
||||
}
|
||||
}
|
||||
)*
|
||||
};
|
||||
}
|
||||
impl_convert_to_string!(f32, u32, u64, i32, i64, bool, DVec2, DAffine2);
|
||||
|
||||
// Denoised so 0.1 + 0.2 reaches the string as "0.3" rather than "0.30000000000000004"
|
||||
impl Convert<String, ()> for f64 {
|
||||
#[inline]
|
||||
async fn convert(self, _: Footprint, _converter: ()) -> String {
|
||||
self.to_string()
|
||||
round_away_float_noise(self).to_string()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ pub mod migrations {
|
||||
use core_types::Color;
|
||||
use dyn_any::DynAny;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use vector_types::vector::{PointDomain, RegionDomain, SegmentDomain, misc::HandleId, style::Stroke};
|
||||
use vector_types::vector::{PointDomain, SegmentDomain, misc::HandleId, style::Stroke};
|
||||
use vector_types::{GradientRamp, Vector, vector};
|
||||
|
||||
#[derive(Default, Debug, Clone, PartialEq, graphene_hash::CacheHash, DynAny, serde::Serialize, serde::Deserialize)]
|
||||
@@ -111,7 +111,6 @@ pub mod migrations {
|
||||
pub colinear_manipulators: Vec<[HandleId; 2]>,
|
||||
pub point_domain: PointDomain,
|
||||
pub segment_domain: SegmentDomain,
|
||||
pub region_domain: RegionDomain,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
@@ -142,7 +141,6 @@ pub mod migrations {
|
||||
colinear_manipulators: old.colinear_manipulators,
|
||||
point_domain: old.point_domain,
|
||||
segment_domain: old.segment_domain,
|
||||
region_domain: old.region_domain,
|
||||
}),
|
||||
VectorFormat::Vector(vector) => Some(vector),
|
||||
VectorFormat::List(list) => list.element.into_iter().next(),
|
||||
|
||||
@@ -1,47 +1,35 @@
|
||||
use glam::DVec2;
|
||||
use vector_types::subpath::{ManipulatorGroup, Subpath};
|
||||
use vector_types::vector::PointId;
|
||||
use kurbo::{BezPath, Point};
|
||||
|
||||
pub fn convert_usvg_path(path: &usvg::Path) -> Vec<Subpath<PointId>> {
|
||||
let mut subpaths = Vec::new();
|
||||
let mut manipulators_list = Vec::new();
|
||||
pub fn convert_usvg_path(path: &usvg::Path) -> BezPath {
|
||||
let mut bezpath = BezPath::new();
|
||||
|
||||
let mut points = path.data().points().iter();
|
||||
let to_vec = |p: &usvg::tiny_skia_path::Point| DVec2::new(p.x as f64, p.y as f64);
|
||||
let to_point = |p: &usvg::tiny_skia_path::Point| Point::new(p.x as f64, p.y as f64);
|
||||
|
||||
for verb in path.data().verbs() {
|
||||
match verb {
|
||||
usvg::tiny_skia_path::PathVerb::Move => {
|
||||
subpaths.push(Subpath::new(std::mem::take(&mut manipulators_list), false));
|
||||
let Some(start) = points.next().map(to_vec) else { continue };
|
||||
manipulators_list.push(ManipulatorGroup::new(start, Some(start), Some(start)));
|
||||
let Some(start) = points.next().map(to_point) else { continue };
|
||||
bezpath.move_to(start);
|
||||
}
|
||||
usvg::tiny_skia_path::PathVerb::Line => {
|
||||
let Some(end) = points.next().map(to_vec) else { continue };
|
||||
manipulators_list.push(ManipulatorGroup::new(end, Some(end), Some(end)));
|
||||
let Some(end) = points.next().map(to_point) else { continue };
|
||||
bezpath.line_to(end);
|
||||
}
|
||||
usvg::tiny_skia_path::PathVerb::Quad => {
|
||||
let Some(handle) = points.next().map(to_vec) else { continue };
|
||||
let Some(end) = points.next().map(to_vec) else { continue };
|
||||
if let Some(last) = manipulators_list.last_mut() {
|
||||
last.out_handle = Some(last.anchor + (2. / 3.) * (handle - last.anchor));
|
||||
}
|
||||
manipulators_list.push(ManipulatorGroup::new(end, Some(end + (2. / 3.) * (handle - end)), Some(end)));
|
||||
let Some(handle) = points.next().map(to_point) else { continue };
|
||||
let Some(end) = points.next().map(to_point) else { continue };
|
||||
bezpath.quad_to(handle, end);
|
||||
}
|
||||
usvg::tiny_skia_path::PathVerb::Cubic => {
|
||||
let Some(first_handle) = points.next().map(to_vec) else { continue };
|
||||
let Some(second_handle) = points.next().map(to_vec) else { continue };
|
||||
let Some(end) = points.next().map(to_vec) else { continue };
|
||||
if let Some(last) = manipulators_list.last_mut() {
|
||||
last.out_handle = Some(first_handle);
|
||||
}
|
||||
manipulators_list.push(ManipulatorGroup::new(end, Some(second_handle), Some(end)));
|
||||
}
|
||||
usvg::tiny_skia_path::PathVerb::Close => {
|
||||
subpaths.push(Subpath::new(std::mem::take(&mut manipulators_list), true));
|
||||
let Some(first_handle) = points.next().map(to_point) else { continue };
|
||||
let Some(second_handle) = points.next().map(to_point) else { continue };
|
||||
let Some(end) = points.next().map(to_point) else { continue };
|
||||
bezpath.curve_to(first_handle, second_handle, end);
|
||||
}
|
||||
usvg::tiny_skia_path::PathVerb::Close => bezpath.close_path(),
|
||||
}
|
||||
}
|
||||
subpaths.push(Subpath::new(manipulators_list, false));
|
||||
subpaths
|
||||
|
||||
bezpath
|
||||
}
|
||||
@@ -24,11 +24,11 @@ use graphene_hash::CacheHashWrapper;
|
||||
use graphene_resource::Resource;
|
||||
use graphic_types::raster_types::{BitmapMut, CPU, GPU, Image, Raster, Texture};
|
||||
use graphic_types::vector_types::gradient::{Gradient, GradientForm};
|
||||
use graphic_types::vector_types::subpath::Subpath;
|
||||
use graphic_types::vector_types::vector::click_target::{ClickTarget, FreePoint};
|
||||
use graphic_types::vector_types::vector::misc::dvec2_to_point;
|
||||
use graphic_types::vector_types::vector::style::{RenderMode, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use graphic_types::{Appearance, Artboard, Cover, Coverage, FillAndStroke, Graphic, Vector};
|
||||
use kurbo::{Affine, BezPath, Cap, Join, Shape, StrokeOpts};
|
||||
use kurbo::{Affine, BezPath, Cap, Join, PathEl, Shape, StrokeOpts};
|
||||
use num_traits::Zero;
|
||||
use skrifa::instance::{LocationRef, NormalizedCoord, Size};
|
||||
use skrifa::outline::{DrawSettings, OutlinePen};
|
||||
@@ -475,11 +475,9 @@ fn get_outline_styles(render_params: &RenderParams) -> (kurbo::Stroke, peniko::C
|
||||
}
|
||||
|
||||
fn draw_raster_outline(scene: &mut Scene, outline_transform: &DAffine2, render_params: &RenderParams) {
|
||||
use graphic_types::vector_types::vector::PointId;
|
||||
|
||||
let (outline_stroke, outline_color_peniko) = get_outline_styles(render_params);
|
||||
|
||||
let mut outline_path = Subpath::<PointId>::new_rectangle(DVec2::ZERO, DVec2::ONE).to_bezpath();
|
||||
let mut outline_path = rectangle_path(DVec2::ZERO, DVec2::ONE);
|
||||
outline_path.apply_affine(Affine::new(outline_transform.to_cols_array()));
|
||||
|
||||
scene.stroke(&outline_stroke, Affine::IDENTITY, outline_color_peniko, None, &outline_path);
|
||||
@@ -1361,8 +1359,9 @@ impl Render for List<Artboard> {
|
||||
let element_id = layer_path.iter_element_values().next_back().copied();
|
||||
|
||||
if let Some(element_id) = element_id {
|
||||
let subpath = Subpath::new_rectangle(DVec2::ZERO, dimensions);
|
||||
metadata.click_targets.insert(element_id, vec![ClickTarget::new_with_subpath(subpath, 0.).into()]);
|
||||
metadata
|
||||
.click_targets
|
||||
.insert(element_id, vec![ClickTarget::new_with_path(rectangle_path(DVec2::ZERO, dimensions), 0.).into()]);
|
||||
metadata.upstream_footprints.insert(element_id, footprint);
|
||||
metadata.local_transforms.insert(element_id, DAffine2::from_translation(location));
|
||||
if clip {
|
||||
@@ -1381,8 +1380,7 @@ impl Render for List<Artboard> {
|
||||
fn add_upstream_click_targets(&self, click_targets: &mut Vec<ClickTarget>, _inherited_appearance: Option<&Appearance>) {
|
||||
for index in 0..self.len() {
|
||||
let dimensions: DVec2 = self.attribute_cloned_or_default(ATTR_DIMENSIONS, index);
|
||||
let subpath_rectangle = Subpath::new_rectangle(DVec2::ZERO, dimensions);
|
||||
click_targets.push(ClickTarget::new_with_subpath(subpath_rectangle, 0.));
|
||||
click_targets.push(ClickTarget::new_with_path(rectangle_path(DVec2::ZERO, dimensions), 0.));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1485,7 +1483,7 @@ fn render_vector_shape_svg(item: ItemRef<'_, Vector>, vector: &Vector, render: &
|
||||
MaskType::Mask
|
||||
};
|
||||
|
||||
let path_is_closed = vector.stroke_bezier_paths().all(|path| path.closed());
|
||||
let path_is_closed = vector.stroke_bezpath_iter().all(|path| matches!(path.elements().last(), Some(PathEl::ClosePath)));
|
||||
let can_draw_aligned_stroke = path_is_closed
|
||||
&& stroke_params.as_ref().is_some_and(|stroke| stroke.has_renderable_stroke() && stroke.align.is_not_centered())
|
||||
&& stroke_paint.is_some_and(|graphic| !graphic.is_guaranteed_fully_transparent());
|
||||
@@ -1524,7 +1522,7 @@ fn render_vector_shape_svg(item: ItemRef<'_, Vector>, vector: &Vector, render: &
|
||||
});
|
||||
|
||||
if use_face_fill {
|
||||
for mut face_path in vector.construct_faces().filter(|face| face.area() >= 0.) {
|
||||
for mut face_path in vector.construct_faces() {
|
||||
face_path.apply_affine(Affine::new(applied_stroke_transform.to_cols_array()));
|
||||
let face_d = face_path.to_svg();
|
||||
|
||||
@@ -1614,10 +1612,6 @@ fn render_vector_shape_svg(item: ItemRef<'_, Vector>, vector: &Vector, render: &
|
||||
attributes.push_val(stroke_shape_attribute);
|
||||
attributes.push_val(stroke_attribute);
|
||||
|
||||
if vector.is_branching() && !use_face_fill {
|
||||
attributes.push("fill-rule", "evenodd");
|
||||
}
|
||||
|
||||
let opacity = (opacity_attr * if render_params.for_mask { 1. } else { opacity_fill_attr }) as f32;
|
||||
if opacity < 1. {
|
||||
attributes.push("opacity", opacity.to_string());
|
||||
@@ -1749,7 +1743,9 @@ fn render_vector_item_to_vello(
|
||||
// the function ignores the arg for Center align) and the `SrcIn`/`SrcOut` aligned-stroke branch further down.
|
||||
let stroke = stroke_params.as_ref();
|
||||
let stroke_fully_transparent = stroke_paint.is_none_or(|paint| paint.is_guaranteed_fully_transparent());
|
||||
let can_draw_aligned_stroke = !stroke_fully_transparent && stroke.is_some_and(|s| s.has_renderable_stroke() && s.align.is_not_centered()) && element.stroke_bezier_paths().all(|p| p.closed());
|
||||
let can_draw_aligned_stroke = !stroke_fully_transparent
|
||||
&& stroke.is_some_and(|s| s.has_renderable_stroke() && s.align.is_not_centered())
|
||||
&& element.stroke_bezpath_iter().all(|p| matches!(p.elements().last(), Some(PathEl::ClosePath)));
|
||||
|
||||
let opacity = (opacity_attr * if render_params.for_mask { 1. } else { opacity_fill_attr }) as f32;
|
||||
let needs_blend_layer = opacity < 1. || blend_mode_attr != BlendMode::default();
|
||||
@@ -1848,11 +1844,10 @@ fn render_vector_item_to_vello(
|
||||
};
|
||||
};
|
||||
|
||||
// Branching vectors without regions (e.g. mesh grids) need face-by-face fill rendering.
|
||||
let use_face_fill = element.use_face_fill();
|
||||
let do_fill = |scene: &mut Scene, context: &mut RenderContext| {
|
||||
if use_face_fill {
|
||||
for mut face_path in element.construct_faces().filter(|face| face.area() >= 0.) {
|
||||
for mut face_path in element.construct_faces() {
|
||||
face_path.apply_affine(Affine::new(applied_stroke_transform.to_cols_array()));
|
||||
let mut kurbo_path = kurbo::BezPath::new();
|
||||
for element in face_path {
|
||||
@@ -1860,8 +1855,6 @@ fn render_vector_item_to_vello(
|
||||
}
|
||||
do_fill_path(scene, context, &kurbo_path, peniko::Fill::NonZero);
|
||||
}
|
||||
} else if element.is_branching() {
|
||||
do_fill_path(scene, context, &path, peniko::Fill::EvenOdd);
|
||||
} else {
|
||||
do_fill_path(scene, context, &path, peniko::Fill::NonZero);
|
||||
}
|
||||
@@ -2210,20 +2203,20 @@ impl Render for List<Vector> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Build one `CompoundPath` (non-zero fill rule, so holes like the inside of an "O" work
|
||||
/// Build one multi-contour `Path` (non-zero fill rule, so holes like the inside of an "O" work
|
||||
/// correctly) plus one `FreePoint` per disconnected anchor, apply the transform, and append.
|
||||
fn extend_targets_from_vector(targets: &mut Vec<ClickTarget>, appearance: Option<&Appearance>, geometry: &Vector, transform: DAffine2) {
|
||||
// A coverage whose paint is `Graphic::None` exists but paints nothing, so it does not close subpaths for hit testing
|
||||
let filled = appearance.is_some_and(|appearance| appearance.has_painted_cover(Cover::Fill));
|
||||
|
||||
let mut subpaths: Vec<Subpath<_>> = geometry.stroke_bezier_paths().collect();
|
||||
let all_subpaths_closed = subpaths.iter().all(|subpath| subpath.closed());
|
||||
let mut bezpaths: Vec<BezPath> = geometry.stroke_bezpath_iter().filter(|bezpath| !bezpath.elements().is_empty()).collect();
|
||||
let all_contours_closed = bezpaths.iter().all(|bezpath| matches!(bezpath.elements().last(), Some(PathEl::ClosePath)));
|
||||
|
||||
// Inside/Outside-aligned strokes reach `weight` from the centerline rather than `weight / 2` per side,
|
||||
// so they need double the click inflation. Alignment is only honored by the renderer for fully-closed paths.
|
||||
let stroke_width = appearance.and_then(|appearance| appearance.first_coverage_of(Cover::Stroke)).map_or(0., |coverage| {
|
||||
let stroke = coverage.stroke_params();
|
||||
if stroke.align.is_not_centered() && all_subpaths_closed {
|
||||
if stroke.align.is_not_centered() && all_contours_closed {
|
||||
stroke.weight * 2.
|
||||
} else {
|
||||
stroke.weight
|
||||
@@ -2231,13 +2224,20 @@ fn extend_targets_from_vector(targets: &mut Vec<ClickTarget>, appearance: Option
|
||||
});
|
||||
|
||||
if filled {
|
||||
for subpath in &mut subpaths {
|
||||
subpath.set_closed(true);
|
||||
for bezpath in &mut bezpaths {
|
||||
if !matches!(bezpath.elements().last(), Some(PathEl::ClosePath)) {
|
||||
bezpath.close_path();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !subpaths.is_empty() {
|
||||
let mut click_target = ClickTarget::new_with_compound_path(subpaths, stroke_width);
|
||||
if !bezpaths.is_empty() {
|
||||
let mut combined_path = BezPath::new();
|
||||
for bezpath in bezpaths {
|
||||
combined_path.extend(bezpath);
|
||||
}
|
||||
|
||||
let mut click_target = ClickTarget::new_with_path(combined_path, stroke_width);
|
||||
click_target.apply_transform(transform);
|
||||
targets.push(click_target);
|
||||
}
|
||||
@@ -2412,9 +2412,9 @@ fn render_raster_cpu_item_to_vello(item: ItemRef<'_, Raster<CPU>>, scene: &mut S
|
||||
/// plus the first item's transform and any merged-layers snapshot when a first item exists.
|
||||
fn collect_raster_metadata<T>(first_row: Option<ItemRef<'_, T>>, metadata: &mut RenderMetadata, footprint: Footprint, element_id: Option<NodeId>) {
|
||||
let Some(element_id) = element_id else { return };
|
||||
let subpath = Subpath::new_rectangle(DVec2::ZERO, DVec2::ONE);
|
||||
|
||||
metadata.click_targets.insert(element_id, vec![ClickTarget::new_with_subpath(subpath, 0.).into()]);
|
||||
metadata
|
||||
.click_targets
|
||||
.insert(element_id, vec![ClickTarget::new_with_path(rectangle_path(DVec2::ZERO, DVec2::ONE), 0.).into()]);
|
||||
metadata.upstream_footprints.insert(element_id, footprint);
|
||||
// TODO: Find a way to handle more than one item of the `List<Raster<...>>`
|
||||
if let Some(item) = first_row {
|
||||
@@ -2437,10 +2437,10 @@ fn collect_raster_metadata<T>(first_row: Option<ItemRef<'_, T>>, metadata: &mut
|
||||
/// Adds the unit-square click target every raster item presents, placed by the item's transform.
|
||||
fn add_unit_square_click_target(transform: DAffine2, click_targets: &mut Vec<ClickTarget>) {
|
||||
// The unit square is the raster's own space, so its placement only exists in the item transform
|
||||
let mut subpath = Subpath::new_rectangle(DVec2::ZERO, DVec2::ONE);
|
||||
subpath.apply_transform(transform);
|
||||
let mut path = rectangle_path(DVec2::ZERO, DVec2::ONE);
|
||||
path.apply_affine(Affine::new(transform.to_cols_array()));
|
||||
|
||||
click_targets.push(ClickTarget::new_with_subpath(subpath, 0.));
|
||||
click_targets.push(ClickTarget::new_with_path(path, 0.));
|
||||
}
|
||||
|
||||
impl Render for List<Raster<CPU>> {
|
||||
@@ -2630,11 +2630,28 @@ fn render_color_item_to_vello(item: ItemRef<'_, Color>, scene: &mut Scene, rende
|
||||
}
|
||||
}
|
||||
|
||||
/// The closed rectangular path spanning the two opposite corners, used for the box-shaped click targets.
|
||||
fn rectangle_path(corner1: DVec2, corner2: DVec2) -> BezPath {
|
||||
kurbo::Rect::from_points(dvec2_to_point(corner1), dvec2_to_point(corner2)).to_path(kurbo::DEFAULT_ACCURACY)
|
||||
}
|
||||
|
||||
/// A gradient's control geometry in its local space: the unit circle a radial gradient's transform carries to its drawn ellipse, or the (0,0) to (1,0) gradient line for a linear one.
|
||||
fn gradient_control_outline(gradient_form: GradientForm) -> Subpath<graphic_types::vector_types::vector::PointId> {
|
||||
fn gradient_control_outline(gradient_form: GradientForm) -> BezPath {
|
||||
match gradient_form {
|
||||
GradientForm::Linear => Subpath::new_line(DVec2::ZERO, DVec2::X),
|
||||
GradientForm::Radial => Subpath::new_ellipse(DVec2::splat(-1.), DVec2::splat(1.)),
|
||||
GradientForm::Linear => BezPath::from_path_segments(std::iter::once(kurbo::PathSeg::Line(kurbo::Line::new(dvec2_to_point(DVec2::ZERO), dvec2_to_point(DVec2::X))))),
|
||||
GradientForm::Radial => {
|
||||
// Four-cubic kappa circle with anchors on the axes, so the tight bounding box is exactly the unit square
|
||||
// <https://en.wikipedia.org/wiki/Composite_B%C3%A9zier_curve#Using_four_curves>
|
||||
const KAPPA: f64 = 4. / 3. * (std::f64::consts::SQRT_2 - 1.);
|
||||
let mut path = BezPath::new();
|
||||
path.move_to((1., 0.));
|
||||
path.curve_to((1., KAPPA), (KAPPA, 1.), (0., 1.));
|
||||
path.curve_to((-KAPPA, 1.), (-1., KAPPA), (-1., 0.));
|
||||
path.curve_to((-1., -KAPPA), (-KAPPA, -1.), (0., -1.));
|
||||
path.curve_to((KAPPA, -1.), (1., -KAPPA), (1., 0.));
|
||||
path.close_path();
|
||||
path
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2867,7 +2884,7 @@ fn collect_gradient_items_metadata<'a>(items: impl Iterator<Item = ItemRef<'a, G
|
||||
// The first item's transform is the reference all targets bake against
|
||||
let item_zero_inverse = *item_zero_inverse.get_or_insert_with(|| if transform_is_invertible(item_transform) { item_transform.inverse() } else { DAffine2::IDENTITY });
|
||||
|
||||
let mut target = ClickTarget::new_with_subpath(gradient_control_outline(gradient_form), 0.);
|
||||
let mut target = ClickTarget::new_with_path(gradient_control_outline(gradient_form), 0.);
|
||||
target.apply_transform(item_zero_inverse * item_transform);
|
||||
let target = Arc::new(target);
|
||||
|
||||
@@ -2895,7 +2912,7 @@ fn add_gradient_item_click_targets(item: ItemRef<'_, Gradient>, click_targets: &
|
||||
}
|
||||
|
||||
let transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let mut target = ClickTarget::new_with_subpath(gradient_control_outline(gradient_form), 0.);
|
||||
let mut target = ClickTarget::new_with_path(gradient_control_outline(gradient_form), 0.);
|
||||
target.apply_transform(transform);
|
||||
click_targets.push(target);
|
||||
}
|
||||
@@ -2905,7 +2922,7 @@ fn add_gradient_item_outline_targets(item: ItemRef<'_, Gradient>, outlines: &mut
|
||||
let gradient_form: GradientForm = item.attribute_cloned_or_default(ATTR_GRADIENT_FORM);
|
||||
let transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
|
||||
let mut target = ClickTarget::new_with_subpath(gradient_control_outline(gradient_form), 0.);
|
||||
let mut target = ClickTarget::new_with_path(gradient_control_outline(gradient_form), 0.);
|
||||
target.apply_transform(transform);
|
||||
outlines.push(target);
|
||||
}
|
||||
@@ -3273,8 +3290,7 @@ fn collect_text_items_metadata<'a>(items: impl Iterator<Item = ItemRef<'a, Strin
|
||||
}
|
||||
|
||||
let Some((size, item_transform)) = text_item_size_and_transform(item) else { continue };
|
||||
let subpath = Subpath::new_rectangle(DVec2::ZERO, size);
|
||||
let mut target = ClickTarget::new_with_subpath(subpath, 0.);
|
||||
let mut target = ClickTarget::new_with_path(rectangle_path(DVec2::ZERO, size), 0.);
|
||||
target.apply_transform(item_zero_inverse * item_transform);
|
||||
accumulated_click_targets.entry(element_id).or_default().push(Arc::new(target));
|
||||
}
|
||||
@@ -3289,8 +3305,7 @@ fn collect_text_items_metadata<'a>(items: impl Iterator<Item = ItemRef<'a, Strin
|
||||
/// Collects one text item's laid-out rectangle as a click target.
|
||||
fn add_text_item_click_targets(item: ItemRef<'_, String>, click_targets: &mut Vec<ClickTarget>) {
|
||||
let Some((size, transform)) = text_item_size_and_transform(item) else { return };
|
||||
let subpath = Subpath::new_rectangle(DVec2::ZERO, size);
|
||||
let mut target = ClickTarget::new_with_subpath(subpath, 0.);
|
||||
let mut target = ClickTarget::new_with_path(rectangle_path(DVec2::ZERO, size), 0.);
|
||||
target.apply_transform(transform);
|
||||
click_targets.push(target);
|
||||
}
|
||||
|
||||
@@ -3,14 +3,12 @@ extern crate log;
|
||||
|
||||
pub mod gradient;
|
||||
pub mod math;
|
||||
pub mod subpath;
|
||||
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, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStop};
|
||||
pub use math::{QuadExt, RectExt};
|
||||
pub use subpath::Subpath;
|
||||
pub use math::QuadExt;
|
||||
pub use vector::Vector;
|
||||
pub use vector::reference_point::ReferencePoint;
|
||||
|
||||
|
||||
@@ -1,32 +1,13 @@
|
||||
use crate::subpath::Bezier;
|
||||
use crate::vector::misc::dvec2_to_point;
|
||||
use core_types::math::quad::Quad;
|
||||
use core_types::math::rect::Rect;
|
||||
use kurbo::{Line, PathSeg};
|
||||
|
||||
pub trait QuadExt {
|
||||
/// Get all the edges in the rect as linear bezier curves
|
||||
fn bezier_lines(&self) -> impl Iterator<Item = Bezier> + '_;
|
||||
fn to_lines(&self) -> impl Iterator<Item = PathSeg>;
|
||||
}
|
||||
|
||||
impl QuadExt for Quad {
|
||||
fn bezier_lines(&self) -> impl Iterator<Item = Bezier> + '_ {
|
||||
self.all_edges().into_iter().map(|[start, end]| Bezier::from_linear_dvec2(start, end))
|
||||
}
|
||||
|
||||
fn to_lines(&self) -> impl Iterator<Item = PathSeg> {
|
||||
self.all_edges().into_iter().map(|[start, end]| PathSeg::Line(Line::new(dvec2_to_point(start), dvec2_to_point(end))))
|
||||
}
|
||||
}
|
||||
|
||||
pub trait RectExt {
|
||||
/// Get all the edges in the quad as linear bezier curves
|
||||
fn bezier_lines(&self) -> impl Iterator<Item = Bezier> + '_;
|
||||
}
|
||||
|
||||
impl RectExt for Rect {
|
||||
fn bezier_lines(&self) -> impl Iterator<Item = Bezier> + '_ {
|
||||
self.edges().into_iter().map(|[start, end]| Bezier::from_linear_dvec2(start, end))
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
// Implementation constants
|
||||
|
||||
/// Constant used to determine if `f64`s are equivalent.
|
||||
pub const MAX_ABSOLUTE_DIFFERENCE: f64 = 1e-3;
|
||||
@@ -1,469 +0,0 @@
|
||||
use super::consts::*;
|
||||
use super::*;
|
||||
use crate::vector::misc::{SpiralType, point_to_dvec2};
|
||||
use glam::DVec2;
|
||||
use kurbo::PathSeg;
|
||||
use std::f64::consts::TAU;
|
||||
|
||||
pub struct PathSegPoints {
|
||||
pub p0: DVec2,
|
||||
pub p1: Option<DVec2>,
|
||||
pub p2: Option<DVec2>,
|
||||
pub p3: DVec2,
|
||||
}
|
||||
|
||||
impl PathSegPoints {
|
||||
pub fn new(p0: DVec2, p1: Option<DVec2>, p2: Option<DVec2>, p3: DVec2) -> Self {
|
||||
Self { p0, p1, p2, p3 }
|
||||
}
|
||||
}
|
||||
|
||||
pub fn pathseg_points(segment: PathSeg) -> PathSegPoints {
|
||||
match segment {
|
||||
PathSeg::Line(line) => PathSegPoints::new(point_to_dvec2(line.p0), None, None, point_to_dvec2(line.p1)),
|
||||
PathSeg::Quad(quad) => PathSegPoints::new(point_to_dvec2(quad.p0), None, Some(point_to_dvec2(quad.p1)), point_to_dvec2(quad.p2)),
|
||||
PathSeg::Cubic(cube) => PathSegPoints::new(point_to_dvec2(cube.p0), Some(point_to_dvec2(cube.p1)), Some(point_to_dvec2(cube.p2)), point_to_dvec2(cube.p3)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Functionality relating to core `Subpath` operations, such as constructors and `iter`.
|
||||
impl<PointId: Identifier> Subpath<PointId> {
|
||||
/// Create a new `Subpath` using a list of [ManipulatorGroup]s.
|
||||
/// A `Subpath` with less than 2 [ManipulatorGroup]s may not be closed.
|
||||
#[track_caller]
|
||||
pub fn new(manipulator_groups: Vec<ManipulatorGroup<PointId>>, closed: bool) -> Self {
|
||||
assert!(!closed || !manipulator_groups.is_empty(), "A closed Subpath must contain more than 0 ManipulatorGroups.");
|
||||
Self { manipulator_groups, closed }
|
||||
}
|
||||
|
||||
/// Create a `Subpath` consisting of 2 manipulator groups from a `Bezier`.
|
||||
pub fn from_bezier(segment: PathSeg) -> Self {
|
||||
let PathSegPoints { p0, p1, p2, p3 } = pathseg_points(segment);
|
||||
Subpath::new(vec![ManipulatorGroup::new(p0, None, p1), ManipulatorGroup::new(p3, p2, None)], false)
|
||||
}
|
||||
|
||||
/// Creates a subpath from a slice of [Bezier]. When two consecutive Beziers do not share an end and start point, this function
|
||||
/// resolves the discrepancy by simply taking the start-point of the second Bezier as the anchor of the Manipulator Group.
|
||||
pub fn from_beziers(beziers: &[PathSeg], closed: bool) -> Self {
|
||||
assert!(!closed || beziers.len() > 1, "A closed Subpath must contain at least 1 Bezier.");
|
||||
if beziers.is_empty() {
|
||||
return Subpath::new(vec![], closed);
|
||||
}
|
||||
|
||||
let beziers: Vec<_> = beziers.iter().map(|b| pathseg_points(*b)).collect();
|
||||
|
||||
let first = beziers.first().unwrap();
|
||||
let mut manipulator_groups = vec![ManipulatorGroup {
|
||||
anchor: first.p0,
|
||||
in_handle: None,
|
||||
out_handle: first.p1,
|
||||
id: PointId::new(),
|
||||
}];
|
||||
let mut inner_groups: Vec<ManipulatorGroup<PointId>> = beziers
|
||||
.windows(2)
|
||||
.map(|bezier_pair| ManipulatorGroup {
|
||||
anchor: bezier_pair[1].p0,
|
||||
in_handle: bezier_pair[0].p2,
|
||||
out_handle: bezier_pair[1].p1,
|
||||
id: PointId::new(),
|
||||
})
|
||||
.collect::<Vec<ManipulatorGroup<PointId>>>();
|
||||
manipulator_groups.append(&mut inner_groups);
|
||||
|
||||
let last = beziers.last().unwrap();
|
||||
if !closed {
|
||||
manipulator_groups.push(ManipulatorGroup {
|
||||
anchor: last.p3,
|
||||
in_handle: last.p2,
|
||||
out_handle: None,
|
||||
id: PointId::new(),
|
||||
});
|
||||
return Subpath::new(manipulator_groups, false);
|
||||
}
|
||||
|
||||
manipulator_groups[0].in_handle = last.p2;
|
||||
Subpath::new(manipulator_groups, true)
|
||||
}
|
||||
|
||||
/// Returns true if the `Subpath` contains no [ManipulatorGroup].
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.manipulator_groups.is_empty()
|
||||
}
|
||||
|
||||
/// Returns the number of [ManipulatorGroup]s contained within the `Subpath`.
|
||||
pub fn len(&self) -> usize {
|
||||
self.manipulator_groups.len()
|
||||
}
|
||||
|
||||
/// Returns the number of segments contained within the `Subpath`.
|
||||
pub fn len_segments(&self) -> usize {
|
||||
let mut number_of_curves = self.len();
|
||||
if !self.closed && number_of_curves > 0 {
|
||||
number_of_curves -= 1
|
||||
}
|
||||
number_of_curves
|
||||
}
|
||||
|
||||
/// Returns a copy of the bezier segment at the given segment index, if this segment exists.
|
||||
pub fn get_segment(&self, segment_index: usize) -> Option<PathSeg> {
|
||||
if segment_index >= self.len_segments() {
|
||||
return None;
|
||||
}
|
||||
Some(self[segment_index].to_bezier(&self[(segment_index + 1) % self.len()]))
|
||||
}
|
||||
|
||||
/// Returns an iterator of the [Bezier]s along the `Subpath`.
|
||||
pub fn iter(&self) -> SubpathIter<'_, PointId> {
|
||||
SubpathIter {
|
||||
subpath: self,
|
||||
index: 0,
|
||||
is_always_closed: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an iterator of the [Bezier]s along the `Subpath` always considering it as a closed subpath.
|
||||
pub fn iter_closed(&self) -> SubpathIter<'_, PointId> {
|
||||
SubpathIter {
|
||||
subpath: self,
|
||||
index: 0,
|
||||
is_always_closed: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a slice of the [ManipulatorGroup]s in the `Subpath`.
|
||||
pub fn manipulator_groups(&self) -> &[ManipulatorGroup<PointId>] {
|
||||
&self.manipulator_groups
|
||||
}
|
||||
|
||||
/// Returns a mutable reference to the [ManipulatorGroup]s in the `Subpath`.
|
||||
pub fn manipulator_groups_mut(&mut self) -> &mut Vec<ManipulatorGroup<PointId>> {
|
||||
&mut self.manipulator_groups
|
||||
}
|
||||
|
||||
/// Returns a vector of all the anchors (DVec2) for this `Subpath`.
|
||||
pub fn anchors(&self) -> Vec<DVec2> {
|
||||
self.manipulator_groups().iter().map(|group| group.anchor).collect()
|
||||
}
|
||||
|
||||
/// Returns if the Subpath is equivalent to a single point.
|
||||
pub fn is_point(&self) -> bool {
|
||||
if self.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let point = self.manipulator_groups[0].anchor;
|
||||
self.manipulator_groups
|
||||
.iter()
|
||||
.all(|manipulator_group| manipulator_group.anchor.abs_diff_eq(point, MAX_ABSOLUTE_DIFFERENCE))
|
||||
}
|
||||
|
||||
pub fn from_anchors(anchor_positions: impl IntoIterator<Item = DVec2>, closed: bool) -> Self {
|
||||
Self::new(anchor_positions.into_iter().map(|anchor| ManipulatorGroup::new_anchor(anchor)).collect(), closed)
|
||||
}
|
||||
|
||||
/// Constructs a rectangle with `corner1` and `corner2` as the two corners.
|
||||
pub fn new_rectangle(corner1: DVec2, corner2: DVec2) -> Self {
|
||||
Self::from_anchors([corner1, DVec2::new(corner2.x, corner1.y), corner2, DVec2::new(corner1.x, corner2.y)], true)
|
||||
}
|
||||
|
||||
/// Constructs a rounded rectangle with `corner1` and `corner2` as the two corners and `corner_radii` as the radii of the corners: `[top_left, top_right, bottom_right, bottom_left]`.
|
||||
pub fn new_rounded_rectangle(corner1: DVec2, corner2: DVec2, corner_radii: [f64; 4]) -> Self {
|
||||
if corner_radii.iter().all(|radii| radii.abs() < f64::EPSILON * 100.) {
|
||||
return Self::new_rectangle(corner1, corner2);
|
||||
}
|
||||
|
||||
use std::f64::consts::{FRAC_1_SQRT_2, PI};
|
||||
|
||||
let new_arc = |center: DVec2, corner: DVec2, radius: f64| -> Vec<ManipulatorGroup<PointId>> {
|
||||
let point1 = center + DVec2::from_angle(-PI * 0.25).rotate(corner - center) * FRAC_1_SQRT_2;
|
||||
let point2 = center + DVec2::from_angle(PI * 0.25).rotate(corner - center) * FRAC_1_SQRT_2;
|
||||
if radius == 0. {
|
||||
return vec![ManipulatorGroup::new_anchor(point1), ManipulatorGroup::new_anchor(point2)];
|
||||
}
|
||||
|
||||
// Constant from https://pomax.github.io/bezierinfo/#circles_cubic
|
||||
const HANDLE_OFFSET_FACTOR: f64 = 0.551784777779014;
|
||||
let handle_offset = radius * HANDLE_OFFSET_FACTOR;
|
||||
vec![
|
||||
ManipulatorGroup::new(point1, None, Some(point1 + handle_offset * (corner - point1).normalize())),
|
||||
ManipulatorGroup::new(point2, Some(point2 + handle_offset * (corner - point2).normalize()), None),
|
||||
]
|
||||
};
|
||||
Self::new(
|
||||
[
|
||||
new_arc(DVec2::new(corner1.x + corner_radii[0], corner1.y + corner_radii[0]), DVec2::new(corner1.x, corner1.y), corner_radii[0]),
|
||||
new_arc(DVec2::new(corner2.x - corner_radii[1], corner1.y + corner_radii[1]), DVec2::new(corner2.x, corner1.y), corner_radii[1]),
|
||||
new_arc(DVec2::new(corner2.x - corner_radii[2], corner2.y - corner_radii[2]), DVec2::new(corner2.x, corner2.y), corner_radii[2]),
|
||||
new_arc(DVec2::new(corner1.x + corner_radii[3], corner2.y - corner_radii[3]), DVec2::new(corner1.x, corner2.y), corner_radii[3]),
|
||||
]
|
||||
.concat(),
|
||||
true,
|
||||
)
|
||||
}
|
||||
|
||||
/// Constructs an ellipse with `corner1` and `corner2` as the two corners of the bounding box.
|
||||
pub fn new_ellipse(corner1: DVec2, corner2: DVec2) -> Self {
|
||||
let size = (corner1 - corner2).abs();
|
||||
let center = (corner1 + corner2) / 2.;
|
||||
let top = DVec2::new(center.x, corner1.y);
|
||||
let bottom = DVec2::new(center.x, corner2.y);
|
||||
let left = DVec2::new(corner1.x, center.y);
|
||||
let right = DVec2::new(corner2.x, center.y);
|
||||
|
||||
// Based on https://pomax.github.io/bezierinfo/#circles_cubic
|
||||
const HANDLE_OFFSET_FACTOR: f64 = 0.551784777779014;
|
||||
let handle_offset = size * HANDLE_OFFSET_FACTOR * 0.5;
|
||||
|
||||
let manipulator_groups = vec![
|
||||
ManipulatorGroup::new(top, Some(top - handle_offset * DVec2::X), Some(top + handle_offset * DVec2::X)),
|
||||
ManipulatorGroup::new(right, Some(right - handle_offset * DVec2::Y), Some(right + handle_offset * DVec2::Y)),
|
||||
ManipulatorGroup::new(bottom, Some(bottom + handle_offset * DVec2::X), Some(bottom - handle_offset * DVec2::X)),
|
||||
ManipulatorGroup::new(left, Some(left + handle_offset * DVec2::Y), Some(left - handle_offset * DVec2::Y)),
|
||||
];
|
||||
Self::new(manipulator_groups, true)
|
||||
}
|
||||
|
||||
/// Constructs an arc by a `radius`, `angle_start` and `angle_size`. Angles must be in radians. Slice option makes it look like pie or pacman.
|
||||
pub fn new_arc(radius: f64, start_angle: f64, sweep_angle: f64, arc_type: ArcType) -> Self {
|
||||
// Prevents glitches from numerical imprecision that have been observed during animation playback after about a minute
|
||||
let start_angle = start_angle % (std::f64::consts::TAU * 2.);
|
||||
let sweep_angle = sweep_angle % (std::f64::consts::TAU * 2.);
|
||||
|
||||
let original_start_angle = start_angle;
|
||||
let sweep_angle_sign = sweep_angle.signum();
|
||||
|
||||
let mut start_angle = 0.;
|
||||
let mut sweep_angle = sweep_angle.abs();
|
||||
|
||||
if ((sweep_angle / std::f64::consts::TAU).floor() as u32).is_multiple_of(2) {
|
||||
sweep_angle %= std::f64::consts::TAU;
|
||||
} else {
|
||||
start_angle = sweep_angle % std::f64::consts::TAU;
|
||||
sweep_angle = std::f64::consts::TAU - start_angle;
|
||||
}
|
||||
|
||||
sweep_angle *= sweep_angle_sign;
|
||||
start_angle *= sweep_angle_sign;
|
||||
start_angle += original_start_angle;
|
||||
|
||||
let closed = arc_type == ArcType::Closed;
|
||||
let slice = arc_type == ArcType::PieSlice;
|
||||
|
||||
let center = DVec2::new(0., 0.);
|
||||
let segments = (sweep_angle.abs() / (std::f64::consts::PI / 4.)).ceil().max(1.) as usize;
|
||||
let step = sweep_angle / segments as f64;
|
||||
let factor = 4. / 3. * (step / 2.).sin() / (1. + (step / 2.).cos());
|
||||
|
||||
let mut manipulator_groups = Vec::with_capacity(segments);
|
||||
let mut prev_in_handle = None;
|
||||
let mut prev_end = DVec2::new(0., 0.);
|
||||
|
||||
for i in 0..segments {
|
||||
let start_angle = start_angle + step * i as f64;
|
||||
let end_angle = start_angle + step;
|
||||
let start_vec = DVec2::from_angle(start_angle);
|
||||
let end_vec = DVec2::from_angle(end_angle);
|
||||
|
||||
let start = center + radius * start_vec;
|
||||
let end = center + radius * end_vec;
|
||||
|
||||
let handle_start = start + start_vec.perp() * radius * factor;
|
||||
let handle_end = end - end_vec.perp() * radius * factor;
|
||||
|
||||
manipulator_groups.push(ManipulatorGroup::new(start, prev_in_handle, Some(handle_start)));
|
||||
prev_in_handle = Some(handle_end);
|
||||
prev_end = end;
|
||||
}
|
||||
manipulator_groups.push(ManipulatorGroup::new(prev_end, prev_in_handle, None));
|
||||
|
||||
if slice {
|
||||
manipulator_groups.push(ManipulatorGroup::new(center, None, None));
|
||||
}
|
||||
|
||||
Self::new(manipulator_groups, closed || slice)
|
||||
}
|
||||
|
||||
/// Constructs a regular polygon (ngon). Based on `sides` and `radius`, which is the distance from the center to any vertex.
|
||||
pub fn new_regular_polygon(center: DVec2, sides: u64, radius: f64) -> Self {
|
||||
let sides = sides.max(3);
|
||||
let angle_increment = std::f64::consts::TAU / (sides as f64);
|
||||
let anchor_positions = (0..sides).map(|i| {
|
||||
let angle = (i as f64) * angle_increment - std::f64::consts::FRAC_PI_2;
|
||||
let center = center + DVec2::ONE * radius;
|
||||
DVec2::new(center.x + radius * f64::cos(angle), center.y + radius * f64::sin(angle)) * 0.5
|
||||
});
|
||||
Self::from_anchors(anchor_positions, true)
|
||||
}
|
||||
|
||||
/// Constructs a star polygon (n-star). See [new_regular_polygon], but with interspersed vertices at an `inner_radius`.
|
||||
pub fn new_star_polygon(center: DVec2, sides: u64, radius: f64, inner_radius: f64) -> Self {
|
||||
let sides = sides.max(2);
|
||||
let angle_increment = 0.5 * std::f64::consts::TAU / (sides as f64);
|
||||
let anchor_positions = (0..sides * 2).map(|i| {
|
||||
let angle = (i as f64) * angle_increment - std::f64::consts::FRAC_PI_2;
|
||||
let center = center + DVec2::ONE * radius;
|
||||
let r = if i % 2 == 0 { radius } else { inner_radius };
|
||||
DVec2::new(center.x + r * f64::cos(angle), center.y + r * f64::sin(angle)) * 0.5
|
||||
});
|
||||
Self::from_anchors(anchor_positions, true)
|
||||
}
|
||||
|
||||
/// Constructs a line from `p1` to `p2`
|
||||
pub fn new_line(p1: DVec2, p2: DVec2) -> Self {
|
||||
Self::from_anchors([p1, p2], false)
|
||||
}
|
||||
|
||||
/// Constructs an arrow shape from start and end points with parametric control over dimensions
|
||||
pub fn new_arrow(start: DVec2, end: DVec2, shaft_width: f64, head_width: f64, head_length: f64) -> Self {
|
||||
let delta = end - start;
|
||||
let length = delta.length();
|
||||
|
||||
if length < 1e-10 {
|
||||
// Degenerate case: return a point
|
||||
return Self::from_anchors([start], true);
|
||||
}
|
||||
|
||||
let direction = delta / length;
|
||||
let perpendicular = DVec2::new(-direction.y, direction.x);
|
||||
|
||||
let half_shaft = shaft_width * 0.5;
|
||||
let half_head = head_width * 0.5;
|
||||
let head_base_distance = (length - head_length).max(0.);
|
||||
let head_base = start + direction * head_base_distance;
|
||||
|
||||
// Arrow path starts at the tail, traces around the shape, and returns to the tail
|
||||
let anchors = [
|
||||
start, // Tail center (origin)
|
||||
start + perpendicular * half_shaft, // Tail top
|
||||
head_base + perpendicular * half_shaft, // Head base top (shaft)
|
||||
head_base + perpendicular * half_head, // Head base top (wide)
|
||||
end, // Tip
|
||||
head_base - perpendicular * half_head, // Head base bottom (wide)
|
||||
head_base - perpendicular * half_shaft, // Head base bottom (shaft)
|
||||
start - perpendicular * half_shaft, // Tail bottom
|
||||
];
|
||||
|
||||
Self::from_anchors(anchors, true)
|
||||
}
|
||||
|
||||
pub fn new_spiral(a: f64, outer_radius: f64, turns: f64, start_angle: f64, delta_theta: f64, spiral_type: SpiralType) -> Self {
|
||||
let mut manipulator_groups = Vec::new();
|
||||
let mut prev_in_handle = None;
|
||||
let theta_end = turns * std::f64::consts::TAU + start_angle;
|
||||
|
||||
let a = if spiral_type == SpiralType::Logarithmic { a.max(1e-10) } else { a };
|
||||
let b = calculate_growth_factor(a, turns, outer_radius, spiral_type);
|
||||
|
||||
let mut theta = start_angle;
|
||||
while theta < theta_end {
|
||||
let theta_next = f64::min(theta + delta_theta, theta_end);
|
||||
|
||||
let p0 = spiral_point(theta, a, b, spiral_type);
|
||||
let p3 = spiral_point(theta_next, a, b, spiral_type);
|
||||
let t0 = spiral_tangent(theta, a, b, spiral_type);
|
||||
let t1 = spiral_tangent(theta_next, a, b, spiral_type);
|
||||
|
||||
let arc_len = spiral_arc_length(theta, theta_next, a, b, spiral_type);
|
||||
let d = arc_len / 3.;
|
||||
|
||||
let p1 = p0 + d * t0;
|
||||
let p2 = p3 - d * t1;
|
||||
|
||||
manipulator_groups.push(ManipulatorGroup::new(p0, prev_in_handle, Some(p1)));
|
||||
prev_in_handle = Some(p2);
|
||||
|
||||
// If final segment, end with anchor at theta_end
|
||||
if (theta_next - theta_end).abs() < f64::EPSILON {
|
||||
manipulator_groups.push(ManipulatorGroup::new(p3, prev_in_handle, None));
|
||||
break;
|
||||
}
|
||||
|
||||
theta = theta_next;
|
||||
}
|
||||
|
||||
Self::new(manipulator_groups, false)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn calculate_growth_factor(a: f64, turns: f64, outer_radius: f64, spiral_type: SpiralType) -> f64 {
|
||||
match spiral_type {
|
||||
SpiralType::Archimedean => {
|
||||
let total_theta = turns * TAU;
|
||||
(outer_radius - a) / total_theta
|
||||
}
|
||||
SpiralType::Logarithmic => {
|
||||
let total_theta = turns * TAU;
|
||||
((outer_radius.abs() / a).ln()) / total_theta
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a point on the given spiral type at angle `theta`.
|
||||
pub fn spiral_point(theta: f64, a: f64, b: f64, spiral_type: SpiralType) -> DVec2 {
|
||||
match spiral_type {
|
||||
SpiralType::Archimedean => archimedean_spiral_point(theta, a, b),
|
||||
SpiralType::Logarithmic => log_spiral_point(theta, a, b),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the tangent direction at angle `theta` for the given spiral type.
|
||||
pub fn spiral_tangent(theta: f64, a: f64, b: f64, spiral_type: SpiralType) -> DVec2 {
|
||||
match spiral_type {
|
||||
SpiralType::Archimedean => archimedean_spiral_tangent(theta, a, b),
|
||||
SpiralType::Logarithmic => log_spiral_tangent(theta, a, b),
|
||||
}
|
||||
}
|
||||
|
||||
/// Computes arc length between two angles for the given spiral type.
|
||||
pub fn spiral_arc_length(theta_start: f64, theta_end: f64, a: f64, b: f64, spiral_type: SpiralType) -> f64 {
|
||||
match spiral_type {
|
||||
SpiralType::Archimedean => archimedean_spiral_arc_length(theta_start, theta_end, a, b),
|
||||
SpiralType::Logarithmic => log_spiral_arc_length(theta_start, theta_end, a, b),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a point on a logarithmic spiral at angle `theta`.
|
||||
pub fn log_spiral_point(theta: f64, a: f64, b: f64) -> DVec2 {
|
||||
let r = a * (b * theta).exp(); // a * e^(bθ)
|
||||
DVec2::new(r * theta.cos(), -r * theta.sin())
|
||||
}
|
||||
|
||||
/// Computes arc length along a logarithmic spiral between two angles.
|
||||
pub fn log_spiral_arc_length(theta_start: f64, theta_end: f64, a: f64, b: f64) -> f64 {
|
||||
let factor = (1. + b * b).sqrt();
|
||||
(a / b) * factor * ((b * theta_end).exp() - (b * theta_start).exp())
|
||||
}
|
||||
|
||||
/// Returns the tangent direction of a logarithmic spiral at angle `theta`.
|
||||
pub fn log_spiral_tangent(theta: f64, a: f64, b: f64) -> DVec2 {
|
||||
let r = a * (b * theta).exp();
|
||||
let dx = r * (b * theta.cos() - theta.sin());
|
||||
let dy = r * (b * theta.sin() + theta.cos());
|
||||
|
||||
DVec2::new(dx, -dy).normalize_or(DVec2::X)
|
||||
}
|
||||
|
||||
/// Returns a point on an Archimedean spiral at angle `theta`.
|
||||
pub fn archimedean_spiral_point(theta: f64, a: f64, b: f64) -> DVec2 {
|
||||
let r = a + b * theta;
|
||||
DVec2::new(r * theta.cos(), -r * theta.sin())
|
||||
}
|
||||
|
||||
/// Returns the tangent direction of an Archimedean spiral at angle `theta`.
|
||||
pub fn archimedean_spiral_tangent(theta: f64, a: f64, b: f64) -> DVec2 {
|
||||
let r = a + b * theta;
|
||||
let dx = b * theta.cos() - r * theta.sin();
|
||||
let dy = b * theta.sin() + r * theta.cos();
|
||||
DVec2::new(dx, -dy).normalize_or(DVec2::X)
|
||||
}
|
||||
|
||||
/// Computes arc length along an Archimedean spiral between two angles.
|
||||
pub fn archimedean_spiral_arc_length(theta_start: f64, theta_end: f64, a: f64, b: f64) -> f64 {
|
||||
archimedean_spiral_arc_length_origin(theta_end, a, b) - archimedean_spiral_arc_length_origin(theta_start, a, b)
|
||||
}
|
||||
|
||||
/// Computes arc length from origin to a point on Archimedean spiral at angle `theta`.
|
||||
pub fn archimedean_spiral_arc_length_origin(theta: f64, a: f64, b: f64) -> f64 {
|
||||
let r = a + b * theta;
|
||||
let sqrt_term = (r * r + b * b).sqrt();
|
||||
(r * sqrt_term + b * b * ((r + sqrt_term).ln())) / (2. * b)
|
||||
}
|
||||
@@ -1,128 +0,0 @@
|
||||
use super::consts::MAX_ABSOLUTE_DIFFERENCE;
|
||||
use super::*;
|
||||
use crate::vector::algorithms::bezpath_algorithms::pathseg_length_centroid_and_length;
|
||||
use crate::vector::algorithms::intersection::{filtered_all_segment_intersections, pathseg_self_intersections};
|
||||
use core_types::math::polynomial::pathseg_to_parametric_polynomial;
|
||||
use glam::DVec2;
|
||||
|
||||
impl<PointId: Identifier> Subpath<PointId> {
|
||||
/// Returns a list of `t` values that correspond to all the self intersection points of the subpath always considering it as a closed subpath. The index and `t` value of both will be returned that corresponds to a point.
|
||||
/// The points will be sorted based on their index and `t` repsectively.
|
||||
/// - `error` - For intersections with non-linear beziers, `error` defines the threshold for bounding boxes to be considered an intersection point.
|
||||
/// - `minimum_separation`: the minimum difference two adjacent `t`-values must have when comparing adjacent `t`-values in sorted order.
|
||||
///
|
||||
/// If the comparison condition is not satisfied, the function takes the larger `t`-value of the two
|
||||
///
|
||||
/// **NOTE**: if an intersection were to occur within an `error` distance away from an anchor point, the algorithm will filter that intersection out.
|
||||
pub fn all_self_intersections(&self, accuracy: Option<f64>, minimum_separation: Option<f64>) -> Vec<(usize, f64)> {
|
||||
let mut intersections_vec = Vec::new();
|
||||
let err = accuracy.unwrap_or(MAX_ABSOLUTE_DIFFERENCE);
|
||||
let num_curves = self.len();
|
||||
// TODO: optimization opportunity - this for-loop currently compares all intersections with all curve-segments in the subpath list
|
||||
self.iter_closed().enumerate().for_each(|(i, other)| {
|
||||
intersections_vec.extend(pathseg_self_intersections(other, accuracy, minimum_separation).iter().flat_map(|value| [(i, value.0), (i, value.1)]));
|
||||
self.iter_closed().enumerate().skip(i + 1).for_each(|(j, curve)| {
|
||||
intersections_vec.extend(
|
||||
filtered_all_segment_intersections(curve, other, accuracy, minimum_separation)
|
||||
.iter()
|
||||
.filter(|&value| (j != i + 1 || value.0 > err || (1. - value.1) > err) && (j != num_curves - 1 || i != 0 || value.1 > err || (1. - value.0) > err))
|
||||
.flat_map(|value| [(j, value.0), (i, value.1)]),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
intersections_vec.sort_by(|a, b| a.partial_cmp(b).unwrap());
|
||||
|
||||
intersections_vec
|
||||
}
|
||||
|
||||
/// Return the area centroid, together with the area, of the `Subpath` always considering it as a closed subpath. The area will always be a positive value.
|
||||
///
|
||||
/// The area centroid is the center of mass for the area of a solid shape's interior.
|
||||
/// An infinitely flat material forming the subpath's closed shape would balance at this point.
|
||||
///
|
||||
/// It will return `None` if no manipulator is present. If the area is less than `error`, it will return `Some((DVec2::NAN, 0.))`.
|
||||
///
|
||||
/// Because the calculation of area and centroid for self-intersecting path requires finding the intersections, the following parameters are used:
|
||||
/// - `error` - For intersections with non-linear beziers, `error` defines the threshold for bounding boxes to be considered an intersection point.
|
||||
/// - `minimum_separation` - the minimum difference two adjacent `t`-values must have when comparing adjacent `t`-values in sorted order.
|
||||
///
|
||||
/// If the comparison condition is not satisfied, the function takes the larger `t`-value of the two.
|
||||
///
|
||||
/// **NOTE**: if an intersection were to occur within an `error` distance away from an anchor point, the algorithm will filter that intersection out.
|
||||
pub fn area_centroid_and_area(&self, error: Option<f64>, minimum_separation: Option<f64>) -> Option<(DVec2, f64)> {
|
||||
let all_intersections = self.all_self_intersections(error, minimum_separation);
|
||||
let mut current_sign: f64 = 1.;
|
||||
|
||||
let (x_sum, y_sum, area) = self
|
||||
.iter_closed()
|
||||
.enumerate()
|
||||
.map(|(index, bezier)| {
|
||||
let (f_x, f_y) = pathseg_to_parametric_polynomial(bezier);
|
||||
let (f_x, f_y) = (f_x.as_size::<10>().unwrap(), f_y.as_size::<10>().unwrap());
|
||||
let f_y_prime = f_y.derivative();
|
||||
let f_x_prime = f_x.derivative();
|
||||
let f_xy = &f_x * &f_y;
|
||||
|
||||
let mut x_part = &f_xy * &f_x_prime;
|
||||
let mut y_part = &f_xy * &f_y_prime;
|
||||
let mut area_part = &f_x * &f_y_prime;
|
||||
x_part.antiderivative_mut();
|
||||
y_part.antiderivative_mut();
|
||||
area_part.antiderivative_mut();
|
||||
|
||||
let mut curve_sum_x = -current_sign * x_part.eval(0.);
|
||||
let mut curve_sum_y = -current_sign * y_part.eval(0.);
|
||||
let mut curve_sum_area = -current_sign * area_part.eval(0.);
|
||||
for (_, t) in all_intersections.iter().filter(|(i, _)| *i == index) {
|
||||
curve_sum_x += 2. * current_sign * x_part.eval(*t);
|
||||
curve_sum_y += 2. * current_sign * y_part.eval(*t);
|
||||
curve_sum_area += 2. * current_sign * area_part.eval(*t);
|
||||
current_sign *= -1.;
|
||||
}
|
||||
curve_sum_x += current_sign * x_part.eval(1.);
|
||||
curve_sum_y += current_sign * y_part.eval(1.);
|
||||
curve_sum_area += current_sign * area_part.eval(1.);
|
||||
|
||||
(-curve_sum_x, curve_sum_y, curve_sum_area)
|
||||
})
|
||||
.reduce(|(x1, y1, area1), (x2, y2, area2)| (x1 + x2, y1 + y2, area1 + area2))?;
|
||||
|
||||
if area.abs() < error.unwrap_or(MAX_ABSOLUTE_DIFFERENCE) {
|
||||
return Some((DVec2::NAN, 0.));
|
||||
}
|
||||
|
||||
Some((DVec2::new(x_sum / area, y_sum / area), area.abs()))
|
||||
}
|
||||
|
||||
/// Return the approximation of the length centroid, together with the length, of the `Subpath`.
|
||||
///
|
||||
/// The length centroid is the center of mass for the arc length of the solid shape's perimeter.
|
||||
/// An infinitely thin wire forming the subpath's closed shape would balance at this point.
|
||||
///
|
||||
/// It will return `None` if no manipulator is present.
|
||||
/// - `accuracy` is used to approximate the curve.
|
||||
/// - `always_closed` is to consider the subpath as closed always.
|
||||
pub fn length_centroid_and_length(&self, accuracy: Option<f64>, always_closed: bool) -> Option<(DVec2, f64)> {
|
||||
if always_closed { self.iter_closed() } else { self.iter() }
|
||||
.map(|bezier| pathseg_length_centroid_and_length(bezier, accuracy))
|
||||
.map(|(centroid, length)| (centroid * length, length))
|
||||
.reduce(|(centroid_part1, length1), (centroid_part2, length2)| (centroid_part1 + centroid_part2, length1 + length2))
|
||||
.map(|(centroid_part, length)| (centroid_part / length, length))
|
||||
.map(|(centroid_part, length)| (DVec2::new(centroid_part.x, centroid_part.y), length))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test_centroid {
|
||||
use crate::vector::PointId;
|
||||
|
||||
use super::*;
|
||||
#[test]
|
||||
fn centroid_rect() {
|
||||
let rect = Subpath::<PointId>::new_rectangle(DVec2::new(100., 100.), DVec2::new(300., 200.));
|
||||
let (center, area) = rect.area_centroid_and_area(Some(1e-3), Some(1e-3)).unwrap();
|
||||
assert_eq!(area, 200. * 100.);
|
||||
assert_eq!(center, DVec2::new(200., 150.))
|
||||
}
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
// use super::consts::MAX_ABSOLUTE_DIFFERENCE;
|
||||
// use super::utils::{SubpathTValue};
|
||||
use super::*;
|
||||
|
||||
impl<PointId: super::structs::Identifier> Subpath<PointId> {
|
||||
/// Get whether the subpath is closed.
|
||||
pub fn closed(&self) -> bool {
|
||||
self.closed
|
||||
}
|
||||
|
||||
/// Set whether the subpath is closed.
|
||||
pub fn set_closed(&mut self, new_closed: bool) {
|
||||
self.closed = new_closed;
|
||||
}
|
||||
|
||||
/// Access a [ManipulatorGroup] from a PointId.
|
||||
pub fn manipulator_from_id(&self, id: PointId) -> Option<&ManipulatorGroup<PointId>> {
|
||||
self.manipulator_groups.iter().find(|manipulator_group| manipulator_group.id == id)
|
||||
}
|
||||
|
||||
/// Access a mutable [ManipulatorGroup] from a PointId.
|
||||
pub fn manipulator_mut_from_id(&mut self, id: PointId) -> Option<&mut ManipulatorGroup<PointId>> {
|
||||
self.manipulator_groups.iter_mut().find(|manipulator_group| manipulator_group.id == id)
|
||||
}
|
||||
|
||||
/// Access the index of a [ManipulatorGroup] from a PointId.
|
||||
pub fn manipulator_index_from_id(&self, id: PointId) -> Option<usize> {
|
||||
self.manipulator_groups.iter().position(|manipulator_group| manipulator_group.id == id)
|
||||
}
|
||||
|
||||
/// Insert a manipulator group at an index.
|
||||
pub fn insert_manipulator_group(&mut self, index: usize, group: ManipulatorGroup<PointId>) {
|
||||
assert!(group.is_finite(), "Inserting non finite manipulator group");
|
||||
self.manipulator_groups.insert(index, group)
|
||||
}
|
||||
|
||||
/// Push a manipulator group to the end.
|
||||
pub fn push_manipulator_group(&mut self, group: ManipulatorGroup<PointId>) {
|
||||
assert!(group.is_finite(), "Pushing non finite manipulator group");
|
||||
self.manipulator_groups.push(group)
|
||||
}
|
||||
|
||||
/// Get a mutable reference to the last manipulator
|
||||
pub fn last_manipulator_group_mut(&mut self) -> Option<&mut ManipulatorGroup<PointId>> {
|
||||
self.manipulator_groups.last_mut()
|
||||
}
|
||||
|
||||
/// Remove a manipulator group at an index.
|
||||
pub fn remove_manipulator_group(&mut self, index: usize) -> ManipulatorGroup<PointId> {
|
||||
self.manipulator_groups.remove(index)
|
||||
}
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
mod consts;
|
||||
mod core;
|
||||
mod lookup;
|
||||
mod manipulators;
|
||||
mod solvers;
|
||||
mod structs;
|
||||
mod transform;
|
||||
|
||||
pub use core::*;
|
||||
use kurbo::PathSeg;
|
||||
use std::fmt::{Debug, Formatter, Result};
|
||||
use std::ops::{Index, IndexMut};
|
||||
pub use structs::*;
|
||||
|
||||
/// Structure used to represent a path composed of [Bezier] curves.
|
||||
#[derive(Clone, PartialEq, graphene_hash::CacheHash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct Subpath<PointId: Identifier> {
|
||||
manipulator_groups: Vec<ManipulatorGroup<PointId>>,
|
||||
pub closed: bool,
|
||||
}
|
||||
|
||||
/// Iteration structure for iterating across each curve of a `Subpath`, using an intermediate `Bezier` representation.
|
||||
pub struct SubpathIter<'a, PointId: Identifier> {
|
||||
index: usize,
|
||||
subpath: &'a Subpath<PointId>,
|
||||
is_always_closed: bool,
|
||||
}
|
||||
|
||||
impl<PointId: Identifier> Index<usize> for Subpath<PointId> {
|
||||
type Output = ManipulatorGroup<PointId>;
|
||||
|
||||
fn index(&self, index: usize) -> &Self::Output {
|
||||
assert!(index < self.len(), "Index out of bounds in trait Index of SubPath.");
|
||||
&self.manipulator_groups[index]
|
||||
}
|
||||
}
|
||||
|
||||
impl<PointId: Identifier> IndexMut<usize> for Subpath<PointId> {
|
||||
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
|
||||
assert!(index < self.len(), "Index out of bounds in trait IndexMut of SubPath.");
|
||||
&mut self.manipulator_groups[index]
|
||||
}
|
||||
}
|
||||
|
||||
impl<PointId: Identifier> Iterator for SubpathIter<'_, PointId> {
|
||||
type Item = PathSeg;
|
||||
|
||||
// Returns the Bezier representation of each `Subpath` segment, defined between a pair of adjacent manipulator points.
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if self.subpath.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let closed = if self.is_always_closed { true } else { self.subpath.closed };
|
||||
let len = self.subpath.len() - 1 + if closed { 1 } else { 0 };
|
||||
if self.index >= len {
|
||||
return None;
|
||||
}
|
||||
let start_index = self.index;
|
||||
let end_index = (self.index + 1) % self.subpath.len();
|
||||
self.index += 1;
|
||||
|
||||
Some(self.subpath[start_index].to_bezier(&self.subpath[end_index]))
|
||||
}
|
||||
}
|
||||
|
||||
impl<PointId: Identifier> Debug for Subpath<PointId> {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
|
||||
f.debug_struct("Subpath").field("closed", &self.closed).field("manipulator_groups", &self.manipulator_groups).finish()
|
||||
}
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
use crate::subpath::{Identifier, Subpath};
|
||||
use crate::vector::algorithms::bezpath_algorithms::bezpath_is_inside_bezpath;
|
||||
use crate::vector::misc::dvec2_to_point;
|
||||
use glam::DVec2;
|
||||
use kurbo::{Affine, BezPath, Shape};
|
||||
|
||||
impl<PointId: Identifier> Subpath<PointId> {
|
||||
pub fn contains_point(&self, point: DVec2) -> bool {
|
||||
self.to_bezpath().contains(dvec2_to_point(point))
|
||||
}
|
||||
|
||||
pub fn to_bezpath(&self) -> BezPath {
|
||||
let mut bezpath = kurbo::BezPath::new();
|
||||
let mut out_handle;
|
||||
|
||||
let Some(first) = self.manipulator_groups.first() else { return bezpath };
|
||||
bezpath.move_to(dvec2_to_point(first.anchor));
|
||||
out_handle = first.out_handle;
|
||||
|
||||
for manipulator in self.manipulator_groups.iter().skip(1) {
|
||||
match (out_handle, manipulator.in_handle) {
|
||||
(Some(handle_start), Some(handle_end)) => bezpath.curve_to(dvec2_to_point(handle_start), dvec2_to_point(handle_end), dvec2_to_point(manipulator.anchor)),
|
||||
(None, None) => bezpath.line_to(dvec2_to_point(manipulator.anchor)),
|
||||
(None, Some(handle)) => bezpath.quad_to(dvec2_to_point(handle), dvec2_to_point(manipulator.anchor)),
|
||||
(Some(handle), None) => bezpath.quad_to(dvec2_to_point(handle), dvec2_to_point(manipulator.anchor)),
|
||||
}
|
||||
out_handle = manipulator.out_handle;
|
||||
}
|
||||
|
||||
if self.closed {
|
||||
match (out_handle, first.in_handle) {
|
||||
(Some(handle_start), Some(handle_end)) => bezpath.curve_to(dvec2_to_point(handle_start), dvec2_to_point(handle_end), dvec2_to_point(first.anchor)),
|
||||
(None, None) => bezpath.line_to(dvec2_to_point(first.anchor)),
|
||||
(None, Some(handle)) => bezpath.quad_to(dvec2_to_point(handle), dvec2_to_point(first.anchor)),
|
||||
(Some(handle), None) => bezpath.quad_to(dvec2_to_point(handle), dvec2_to_point(first.anchor)),
|
||||
}
|
||||
bezpath.close_path();
|
||||
}
|
||||
bezpath
|
||||
}
|
||||
|
||||
/// Returns `true` if this subpath is completely inside the `other` subpath.
|
||||
pub fn is_inside_subpath(&self, other: &Subpath<PointId>, accuracy: Option<f64>, minimum_separation: Option<f64>) -> bool {
|
||||
bezpath_is_inside_bezpath(&self.to_bezpath(), &other.to_bezpath(), accuracy, minimum_separation)
|
||||
}
|
||||
|
||||
/// Return the min and max corners that represent the bounding box of the subpath. Return `None` if the subpath is empty.
|
||||
pub fn bounding_box(&self) -> Option<[DVec2; 2]> {
|
||||
self.iter()
|
||||
.map(|bezier| bezier.bounding_box())
|
||||
.map(|bbox| [DVec2::new(bbox.min_x(), bbox.min_y()), DVec2::new(bbox.max_x(), bbox.max_y())])
|
||||
.reduce(|bbox1, bbox2| [bbox1[0].min(bbox2[0]), bbox1[1].max(bbox2[1])])
|
||||
}
|
||||
|
||||
/// Return the min and max corners that represent the bounding box of the subpath, after a given affine transform.
|
||||
pub fn bounding_box_with_transform(&self, transform: glam::DAffine2) -> Option<[DVec2; 2]> {
|
||||
self.iter()
|
||||
.map(|bezier| (Affine::new(transform.to_cols_array()) * bezier).bounding_box())
|
||||
.map(|bbox| [DVec2::new(bbox.min_x(), bbox.min_y()), DVec2::new(bbox.max_x(), bbox.max_y())])
|
||||
.reduce(|bbox1, bbox2| [bbox1[0].min(bbox2[0]), bbox1[1].max(bbox2[1])])
|
||||
}
|
||||
|
||||
/// Return the min and max corners that represent the loose bounding box of the subpath (bounding box of all handles and anchors).
|
||||
pub fn loose_bounding_box(&self) -> Option<[DVec2; 2]> {
|
||||
self.manipulator_groups
|
||||
.iter()
|
||||
.flat_map(|group| [group.in_handle, group.out_handle, Some(group.anchor)])
|
||||
.flatten()
|
||||
.map(|pos| [pos, pos])
|
||||
.reduce(|bbox1, bbox2| [bbox1[0].min(bbox2[0]), bbox1[1].max(bbox2[1])])
|
||||
}
|
||||
|
||||
/// Return the min and max corners that represent the loose bounding box of the subpath, after a given affine transform.
|
||||
pub fn loose_bounding_box_with_transform(&self, transform: glam::DAffine2) -> Option<[DVec2; 2]> {
|
||||
self.manipulator_groups
|
||||
.iter()
|
||||
.flat_map(|group| [group.in_handle, group.out_handle, Some(group.anchor)])
|
||||
.flatten()
|
||||
.map(|pos| transform.transform_point2(pos))
|
||||
.map(|pos| [pos, pos])
|
||||
.reduce(|bbox1, bbox2| [bbox1[0].min(bbox2[0]), bbox1[1].max(bbox2[1])])
|
||||
}
|
||||
}
|
||||
@@ -1,384 +0,0 @@
|
||||
use crate::vector::algorithms::intersection::filtered_segment_intersections;
|
||||
use crate::vector::misc::{dvec2_to_point, handles_to_segment};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use kurbo::{CubicBez, Line, PathSeg, QuadBez, Shape};
|
||||
use std::fmt::{Debug, Formatter, Result};
|
||||
use std::hash::Hash;
|
||||
|
||||
/// An id type used for each [ManipulatorGroup].
|
||||
pub trait Identifier: Sized + Clone + PartialEq + Hash + graphene_hash::CacheHash + 'static {
|
||||
fn new() -> Self;
|
||||
}
|
||||
|
||||
/// Structure used to represent a single anchor with up to two optional associated handles along a `Subpath`
|
||||
#[derive(Copy, Clone, PartialEq, graphene_hash::CacheHash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct ManipulatorGroup<PointId: Identifier> {
|
||||
pub anchor: DVec2,
|
||||
pub in_handle: Option<DVec2>,
|
||||
pub out_handle: Option<DVec2>,
|
||||
pub id: PointId,
|
||||
}
|
||||
|
||||
impl<PointId: Identifier> Debug for ManipulatorGroup<PointId> {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
|
||||
f.debug_struct("ManipulatorGroup")
|
||||
.field("anchor", &self.anchor)
|
||||
.field("in_handle", &self.in_handle)
|
||||
.field("out_handle", &self.out_handle)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl<PointId: Identifier> ManipulatorGroup<PointId> {
|
||||
/// Construct a new manipulator group from an anchor, in handle and out handle
|
||||
pub fn new(anchor: DVec2, in_handle: Option<DVec2>, out_handle: Option<DVec2>) -> Self {
|
||||
let id = PointId::new();
|
||||
Self { anchor, in_handle, out_handle, id }
|
||||
}
|
||||
|
||||
/// Construct a new manipulator point with just an anchor position
|
||||
pub fn new_anchor(anchor: DVec2) -> Self {
|
||||
Self::new(anchor, None, None)
|
||||
}
|
||||
|
||||
/// Construct a new manipulator group from an anchor, in handle, out handle and an id
|
||||
pub fn new_with_id(anchor: DVec2, in_handle: Option<DVec2>, out_handle: Option<DVec2>, id: PointId) -> Self {
|
||||
Self { anchor, in_handle, out_handle, id }
|
||||
}
|
||||
|
||||
/// Construct a new manipulator point with just an anchor position and an id
|
||||
pub fn new_anchor_with_id(anchor: DVec2, id: PointId) -> Self {
|
||||
Self::new_with_id(anchor, Some(anchor), Some(anchor), id)
|
||||
}
|
||||
|
||||
/// Create a bezier curve that starts at the current manipulator group and finishes in the `end_group` manipulator group.
|
||||
pub fn to_bezier(&self, end_group: &ManipulatorGroup<PointId>) -> PathSeg {
|
||||
let start = self.anchor;
|
||||
let end = end_group.anchor;
|
||||
let out_handle = self.out_handle;
|
||||
let in_handle = end_group.in_handle;
|
||||
|
||||
match (out_handle, in_handle) {
|
||||
(Some(handle1), Some(handle2)) => PathSeg::Cubic(CubicBez::new(dvec2_to_point(start), dvec2_to_point(handle1), dvec2_to_point(handle2), dvec2_to_point(end))),
|
||||
(Some(handle), None) | (None, Some(handle)) => PathSeg::Quad(QuadBez::new(dvec2_to_point(start), dvec2_to_point(handle), dvec2_to_point(end))),
|
||||
(None, None) => PathSeg::Line(Line::new(dvec2_to_point(start), dvec2_to_point(end))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply a transformation to all of the [ManipulatorGroup] points
|
||||
pub fn apply_transform(&mut self, affine_transform: DAffine2) {
|
||||
self.anchor = affine_transform.transform_point2(self.anchor);
|
||||
self.in_handle = self.in_handle.map(|in_handle| affine_transform.transform_point2(in_handle));
|
||||
self.out_handle = self.out_handle.map(|out_handle| affine_transform.transform_point2(out_handle));
|
||||
}
|
||||
|
||||
/// Are all handles at finite positions
|
||||
pub fn is_finite(&self) -> bool {
|
||||
self.anchor.is_finite() && self.in_handle.is_none_or(|handle| handle.is_finite()) && self.out_handle.is_none_or(|handle| handle.is_finite())
|
||||
}
|
||||
|
||||
/// Reverse directions of handles
|
||||
pub fn flip(mut self) -> Self {
|
||||
std::mem::swap(&mut self.in_handle, &mut self.out_handle);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn has_in_handle(&self) -> bool {
|
||||
self.in_handle.map(|handle| Self::has_handle(self.anchor, handle)).unwrap_or(false)
|
||||
}
|
||||
|
||||
pub fn has_out_handle(&self) -> bool {
|
||||
self.out_handle.map(|handle| Self::has_handle(self.anchor, handle)).unwrap_or(false)
|
||||
}
|
||||
|
||||
fn has_handle(anchor: DVec2, handle: DVec2) -> bool {
|
||||
!((handle.x - anchor.x).abs() < f64::EPSILON && (handle.y - anchor.y).abs() < f64::EPSILON)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone)]
|
||||
pub enum AppendType {
|
||||
IgnoreStart,
|
||||
SmoothJoin(f64),
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Eq, PartialEq, Hash, graphene_hash::CacheHash)]
|
||||
pub enum ArcType {
|
||||
Open,
|
||||
Closed,
|
||||
PieSlice,
|
||||
}
|
||||
|
||||
/// Representation of the handle point(s) in a bezier segment.
|
||||
#[derive(Copy, Clone, PartialEq, Debug, graphene_hash::CacheHash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub enum BezierHandles {
|
||||
Linear,
|
||||
/// Handles for a quadratic curve.
|
||||
Quadratic {
|
||||
/// Point representing the location of the single handle.
|
||||
handle: DVec2,
|
||||
},
|
||||
/// Handles for a cubic curve.
|
||||
Cubic {
|
||||
/// Point representing the location of the handle associated to the start point.
|
||||
handle_start: DVec2,
|
||||
/// Point representing the location of the handle associated to the end point.
|
||||
handle_end: DVec2,
|
||||
},
|
||||
}
|
||||
|
||||
impl BezierHandles {
|
||||
pub fn is_cubic(&self) -> bool {
|
||||
matches!(self, Self::Cubic { .. })
|
||||
}
|
||||
|
||||
pub fn is_finite(&self) -> bool {
|
||||
match self {
|
||||
BezierHandles::Linear => true,
|
||||
BezierHandles::Quadratic { handle } => handle.is_finite(),
|
||||
BezierHandles::Cubic { handle_start, handle_end } => handle_start.is_finite() && handle_end.is_finite(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the coordinates of the bezier segment's first handle point. This represents the only handle in a quadratic segment.
|
||||
pub fn start(&self) -> Option<DVec2> {
|
||||
match *self {
|
||||
BezierHandles::Cubic { handle_start, .. } | BezierHandles::Quadratic { handle: handle_start } => Some(handle_start),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the coordinates of the second handle point. This will return `None` for a quadratic segment.
|
||||
pub fn end(&self) -> Option<DVec2> {
|
||||
match *self {
|
||||
BezierHandles::Cubic { handle_end, .. } => Some(handle_end),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn move_start(&mut self, delta: DVec2) {
|
||||
if let BezierHandles::Cubic { handle_start, .. } | BezierHandles::Quadratic { handle: handle_start } = self {
|
||||
*handle_start += delta
|
||||
}
|
||||
}
|
||||
|
||||
pub fn move_end(&mut self, delta: DVec2) {
|
||||
if let BezierHandles::Cubic { handle_end, .. } = self {
|
||||
*handle_end += delta
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a Bezier curve that results from applying the transformation function to each handle point in the Bezier.
|
||||
#[must_use]
|
||||
pub fn apply_transformation(&self, transformation_function: impl Fn(DVec2) -> DVec2) -> Self {
|
||||
match *self {
|
||||
BezierHandles::Linear => Self::Linear,
|
||||
BezierHandles::Quadratic { handle } => {
|
||||
let handle = transformation_function(handle);
|
||||
Self::Quadratic { handle }
|
||||
}
|
||||
BezierHandles::Cubic { handle_start, handle_end } => {
|
||||
let handle_start = transformation_function(handle_start);
|
||||
let handle_end = transformation_function(handle_end);
|
||||
Self::Cubic { handle_start, handle_end }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn reversed(self) -> Self {
|
||||
match self {
|
||||
BezierHandles::Cubic { handle_start, handle_end } => Self::Cubic {
|
||||
handle_start: handle_end,
|
||||
handle_end: handle_start,
|
||||
},
|
||||
_ => self,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Representation of a bezier curve with 2D points.
|
||||
#[derive(Copy, Clone, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct Bezier {
|
||||
/// Start point of the bezier curve.
|
||||
pub start: DVec2,
|
||||
/// End point of the bezier curve.
|
||||
pub end: DVec2,
|
||||
/// Handles of the bezier curve.
|
||||
pub handles: BezierHandles,
|
||||
}
|
||||
|
||||
impl Debug for Bezier {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
|
||||
let mut debug_struct = f.debug_struct("Bezier");
|
||||
let mut debug_struct_ref = debug_struct.field("start", &self.start);
|
||||
debug_struct_ref = match self.handles {
|
||||
BezierHandles::Linear => debug_struct_ref,
|
||||
BezierHandles::Quadratic { handle } => debug_struct_ref.field("handle", &handle),
|
||||
BezierHandles::Cubic { handle_start, handle_end } => debug_struct_ref.field("handle_start", &handle_start).field("handle_end", &handle_end),
|
||||
};
|
||||
debug_struct_ref.field("end", &self.end).finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// Functionality for the getters and setters of the various points in a Bezier
|
||||
impl Bezier {
|
||||
/// Set the coordinates of the start point.
|
||||
pub fn set_start(&mut self, s: DVec2) {
|
||||
self.start = s;
|
||||
}
|
||||
|
||||
/// Set the coordinates of the end point.
|
||||
pub fn set_end(&mut self, e: DVec2) {
|
||||
self.end = e;
|
||||
}
|
||||
|
||||
/// Set the coordinates of the first handle point. This represents the only handle in a quadratic segment. If used on a linear segment, it will be changed to a quadratic.
|
||||
pub fn set_handle_start(&mut self, h1: DVec2) {
|
||||
match self.handles {
|
||||
BezierHandles::Linear => {
|
||||
self.handles = BezierHandles::Quadratic { handle: h1 };
|
||||
}
|
||||
BezierHandles::Quadratic { ref mut handle } => {
|
||||
*handle = h1;
|
||||
}
|
||||
BezierHandles::Cubic { ref mut handle_start, .. } => {
|
||||
*handle_start = h1;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// Set the coordinates of the second handle point. This will convert both linear and quadratic segments into cubic ones. For a linear segment, the first handle will be set to the start point.
|
||||
pub fn set_handle_end(&mut self, h2: DVec2) {
|
||||
match self.handles {
|
||||
BezierHandles::Linear => {
|
||||
self.handles = BezierHandles::Cubic {
|
||||
handle_start: self.start,
|
||||
handle_end: h2,
|
||||
};
|
||||
}
|
||||
BezierHandles::Quadratic { handle } => {
|
||||
self.handles = BezierHandles::Cubic { handle_start: handle, handle_end: h2 };
|
||||
}
|
||||
BezierHandles::Cubic { ref mut handle_end, .. } => {
|
||||
*handle_end = h2;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// Get the coordinates of the bezier segment's start point.
|
||||
pub fn start(&self) -> DVec2 {
|
||||
self.start
|
||||
}
|
||||
|
||||
/// Get the coordinates of the bezier segment's end point.
|
||||
pub fn end(&self) -> DVec2 {
|
||||
self.end
|
||||
}
|
||||
|
||||
/// Get the coordinates of the bezier segment's first handle point. This represents the only handle in a quadratic segment.
|
||||
pub fn handle_start(&self) -> Option<DVec2> {
|
||||
self.handles.start()
|
||||
}
|
||||
|
||||
/// Get the coordinates of the second handle point. This will return `None` for a quadratic segment.
|
||||
pub fn handle_end(&self) -> Option<DVec2> {
|
||||
self.handles.end()
|
||||
}
|
||||
|
||||
/// Get an iterator over the coordinates of all points in a vector.
|
||||
/// - For a linear segment, the order of the points will be: `start`, `end`.
|
||||
/// - For a quadratic segment, the order of the points will be: `start`, `handle`, `end`.
|
||||
/// - For a cubic segment, the order of the points will be: `start`, `handle_start`, `handle_end`, `end`.
|
||||
pub fn get_points(&self) -> impl Iterator<Item = DVec2> + use<> {
|
||||
match self.handles {
|
||||
BezierHandles::Linear => [self.start, self.end, DVec2::ZERO, DVec2::ZERO].into_iter().take(2),
|
||||
BezierHandles::Quadratic { handle } => [self.start, handle, self.end, DVec2::ZERO].into_iter().take(3),
|
||||
BezierHandles::Cubic { handle_start, handle_end } => [self.start, handle_start, handle_end, self.end].into_iter().take(4),
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Consider removing this function
|
||||
/// Create a linear bezier using the provided coordinates as the start and end points.
|
||||
pub fn from_linear_coordinates(x1: f64, y1: f64, x2: f64, y2: f64) -> Self {
|
||||
Bezier {
|
||||
start: DVec2::new(x1, y1),
|
||||
handles: BezierHandles::Linear,
|
||||
end: DVec2::new(x2, y2),
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a linear bezier using the provided DVec2s as the start and end points.
|
||||
pub fn from_linear_dvec2(p1: DVec2, p2: DVec2) -> Self {
|
||||
Bezier {
|
||||
start: p1,
|
||||
handles: BezierHandles::Linear,
|
||||
end: p2,
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Consider removing this function
|
||||
/// Create a quadratic bezier using the provided coordinates as the start, handle, and end points.
|
||||
pub fn from_quadratic_coordinates(x1: f64, y1: f64, x2: f64, y2: f64, x3: f64, y3: f64) -> Self {
|
||||
Bezier {
|
||||
start: DVec2::new(x1, y1),
|
||||
handles: BezierHandles::Quadratic { handle: DVec2::new(x2, y2) },
|
||||
end: DVec2::new(x3, y3),
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a quadratic bezier using the provided DVec2s as the start, handle, and end points.
|
||||
pub fn from_quadratic_dvec2(p1: DVec2, p2: DVec2, p3: DVec2) -> Self {
|
||||
Bezier {
|
||||
start: p1,
|
||||
handles: BezierHandles::Quadratic { handle: p2 },
|
||||
end: p3,
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Consider removing this function
|
||||
/// Create a cubic bezier using the provided coordinates as the start, handles, and end points.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn from_cubic_coordinates(x1: f64, y1: f64, x2: f64, y2: f64, x3: f64, y3: f64, x4: f64, y4: f64) -> Self {
|
||||
Bezier {
|
||||
start: DVec2::new(x1, y1),
|
||||
handles: BezierHandles::Cubic {
|
||||
handle_start: DVec2::new(x2, y2),
|
||||
handle_end: DVec2::new(x3, y3),
|
||||
},
|
||||
end: DVec2::new(x4, y4),
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a cubic bezier using the provided DVec2s as the start, handles, and end points.
|
||||
pub fn from_cubic_dvec2(p1: DVec2, p2: DVec2, p3: DVec2, p4: DVec2) -> Self {
|
||||
Bezier {
|
||||
start: p1,
|
||||
handles: BezierHandles::Cubic { handle_start: p2, handle_end: p3 },
|
||||
end: p4,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a Bezier curve that results from applying the transformation function to each point in the Bezier.
|
||||
pub fn apply_transformation(&self, transformation_function: impl Fn(DVec2) -> DVec2) -> Bezier {
|
||||
Self {
|
||||
start: transformation_function(self.start),
|
||||
end: transformation_function(self.end),
|
||||
handles: self.handles.apply_transformation(transformation_function),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn intersections(&self, other: &Bezier, accuracy: Option<f64>, minimum_separation: Option<f64>) -> Vec<f64> {
|
||||
let this = handles_to_segment(self.start, self.handles, self.end);
|
||||
let other = handles_to_segment(other.start, other.handles, other.end);
|
||||
filtered_segment_intersections(this, other, accuracy, minimum_separation)
|
||||
}
|
||||
|
||||
pub fn winding(&self, point: DVec2) -> i32 {
|
||||
let this = handles_to_segment(self.start, self.handles, self.end);
|
||||
this.winding(dvec2_to_point(point))
|
||||
}
|
||||
}
|
||||
Loaded 100 of 130 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user