From efd7f3e97a27d22c82d6d89144b99bc619012599 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 29 Oct 2026 03:38:35 -0700 Subject: [PATCH 01/11] Blend: a pending pick starts over when the document's history changes The Blend tool kept its first pick, its clicked anchor and the blend it was adding to through edits made outside the tool. Picking A, recoloring other art and clicking B made a blend of A and B; undoing A's creation left the next click doing nothing. History::step names the current step by the serial numbers of the newest undo step and the next redo step. The session keeps the active document's uid and step from the tool's last pointer event and calls the new Tool::history_moved at the next pointer event, or before drawing overlays, when they differ. The tool's own edits are recorded after its actions; a selection tool lent by Cmd is not told. BlendTool clears its pick and chain there, as Escape does. A selection change keeps them. --- crates/engine/src/history.rs | 28 +++++++++- crates/engine/src/lib.rs | 4 ++ crates/engine/src/session/documents.rs | 1 + crates/engine/src/tests/blendopts.rs | 74 +++++++++++++++++++++++++- crates/engine/src/tooling.rs | 28 ++++++++++ crates/tools/src/lib.rs | 4 ++ crates/tools/src/meshblend.rs | 5 ++ 7 files changed, 141 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index ec53acd5ba..ee6adccc49 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -19,6 +19,14 @@ pub struct HistoryEntry { next: usize, /// The template and name `label` was made from ([`Session::edit_named`]). pub(crate) named: Option, + /// A number no other step takes ([`History::step`]). + serial: u64, +} + +/// The next [`HistoryEntry::serial`]: 1 for the first step made, so 0 never names a step. +fn next_serial() -> u64 { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) } /// A step name made by filling the `{name}` placeholder of a template with a name @@ -45,7 +53,7 @@ impl HistoryEntry { pub(crate) fn kept(label: String, doc: Arc, selection: Arc, next: &Document) -> Self { doc.drop_lookup_cache(); let (bytes, next_bytes) = doc.retained_bytes_each(next); - HistoryEntry { label, doc, selection, bytes, next_bytes, next: std::ptr::from_ref(next) as usize, named: None } + HistoryEntry { label, doc, selection, bytes, next_bytes, next: std::ptr::from_ref(next) as usize, named: None, serial: next_serial() } } /// The template and name the step's label was made from, while the label is still the one @@ -66,7 +74,16 @@ impl HistoryEntry { return Self::kept(label, doc, selection, now); } doc.drop_lookup_cache(); - HistoryEntry { label, doc, selection, bytes: costs.next_bytes, next_bytes: costs.bytes, next: Arc::as_ptr(now) as usize, named: None } + HistoryEntry { + label, + doc, + selection, + bytes: costs.next_bytes, + next_bytes: costs.bytes, + next: Arc::as_ptr(now) as usize, + named: None, + serial: next_serial(), + } } /// The figures [`HistoryEntry::turned`] reuses. @@ -111,6 +128,13 @@ impl History { self.undo.iter().chain(&self.redo).map(|e| e.bytes).sum() } + /// Which step the document is at: the newest undo step and the next redo step, by numbers no + /// other step takes (0 for none). Every new step, Undo and Redo changes it; an edit merged into + /// the newest step (an undo group) and a selection change do not. + pub fn step(&self) -> (u64, u64) { + (self.undo.last().map_or(0, |e| e.serial), self.redo.last().map_or(0, |e| e.serial)) + } + /// Let the oldest steps go while over the step limit or the memory budget: undo steps first /// (the oldest), then redo steps (the furthest ahead). pub fn trim(&mut self) { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 7f32ca9948..226c391d36 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -60,6 +60,10 @@ pub struct Session { /// While Cmd lends `tool` (a selection tool) for a drag: the tool it was lent to, which comes /// back as it was at the release ([`Session::pointer`]). pub(crate) lender: Option>, + /// The active document (its uid) and its [`History::step`] when the tool last handled a pointer + /// event or drew its overlays: when they differ at the next one, the tool is told first + /// ([`vectorcraft_tools::Tool::history_moved`]). None until the first. + pub(crate) tool_step: Option<(u64, (u64, u64))>, /// The selection tool chosen last (Selection, Direct Selection or Group Selection): the one Cmd /// lends the other tools. None until one is chosen. pub(crate) last_selection_tool: Option<&'static str>, diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 89d846330b..c073369aa8 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -31,6 +31,7 @@ impl Session { journal: Journal::default(), tool: vectorcraft_tools::create("selection"), lender: None, + tool_step: None, last_selection_tool: None, last_view: ViewInfo::default(), preview_memo: Default::default(), diff --git a/crates/engine/src/tests/blendopts.rs b/crates/engine/src/tests/blendopts.rs index 97f3560787..ec05893f8e 100644 --- a/crates/engine/src/tests/blendopts.rs +++ b/crates/engine/src/tests/blendopts.rs @@ -1,6 +1,6 @@ //! Blend Options (defaults with nothing selected, `object.blend.info`) and the Blend tool: //! start points from clicked anchors, adding keys to a blend instead of nesting it (M8.18), and -//! Escape dropping the first pick. +//! Escape, or an edit made outside the tool, dropping the first pick. use serde_json::{Value, json}; use vectorcraft_doc::live::{BlendOrientation, BlendSpacing, BlendSpec}; @@ -167,6 +167,78 @@ fn escape_drops_the_blend_tools_first_pick() { assert_eq!(spec(&s, g).0, vec![b, c], "a was not added"); } +#[test] +fn an_edit_or_undo_made_outside_the_blend_tool_drops_its_first_pick() { + for undo in [false, true] { + let mut s = session(); + let (a, b, c) = (rect(&mut s, 0.0, 0.0, 40.0), rect(&mut s, 200.0, 0.0, 40.0), rect(&mut s, 400.0, 0.0, 40.0)); + s.select_tool("blend", ViewInfo::default()).unwrap(); + let click = |s: &mut Session, x: f64, y: f64| s.pointer(&PointerEvent::new(PointerKind::Down, x, y), ViewInfo::default()).unwrap(); + // Undo takes away c, the object picked first; an edit recolors c, which is not picked. + click(&mut s, if undo { 420.0 } else { 20.0 }, 20.0); + assert!(!s.overlays(ViewInfo::default()).is_empty()); + if undo { + s.execute("edit.undo", &json!({})).unwrap(); + } else { + s.execute("paint.setFill", &json!({"ids": [c.0], "color": "#ff0000"})).unwrap(); + } + assert!(s.overlays(ViewInfo::default()).is_empty(), "undo {undo}: the pick is not marked"); + let (layers, depth) = (s.doc().unwrap().doc.layers.clone(), s.doc().unwrap().history.undo.len()); + click(&mut s, 220.0, 20.0); + assert_eq!(s.doc().unwrap().selection.objects, vec![b], "undo {undo}: b is picked first"); + assert_eq!((&s.doc().unwrap().doc.layers, s.doc().unwrap().history.undo.len()), (&layers, depth), "undo {undo}: the click changes no art"); + click(&mut s, if undo { 20.0 } else { 420.0 }, 20.0); + let g = s.doc().unwrap().selection.objects[0]; + assert_eq!(spec(&s, g).0, if undo { vec![a, b] } else { vec![b, c] }, "undo {undo}"); + } +} + +#[test] +fn removing_the_blend_the_blend_tool_adds_to_ends_adding() { + let mut s = session(); + let (a, b, c) = (rect(&mut s, 0.0, 0.0, 40.0), rect(&mut s, 200.0, 0.0, 40.0), rect(&mut s, 400.0, 0.0, 40.0)); + let (d, e) = (rect(&mut s, 0.0, 300.0, 40.0), rect(&mut s, 200.0, 300.0, 40.0)); + let other = id_of(&s.execute("object.blend.make", &json!({"ids": [d.0, e.0]})).unwrap()); + s.select_tool("blend", ViewInfo::default()).unwrap(); + let click = |s: &mut Session, x: f64, y: f64| s.pointer(&PointerEvent::new(PointerKind::Down, x, y), ViewInfo::default()).unwrap(); + click(&mut s, 20.0, 20.0); + click(&mut s, 220.0, 20.0); + let g = s.doc().unwrap().selection.objects[0]; + s.execute("edit.clear", &json!({"ids": [g.0]})).unwrap(); + sel(&mut s, &[other]); + click(&mut s, 420.0, 20.0); + assert_eq!(s.doc().unwrap().selection.objects, vec![c], "c is picked first"); + assert_eq!(spec(&s, other).0, vec![d, e], "c is not added to the selected blend"); + assert!([a, b, g].iter().all(|id| s.doc().unwrap().doc.node(*id).is_none()), "the blend went with its keys"); +} + +#[test] +fn a_selection_change_keeps_the_blend_tools_first_pick() { + for drag in [false, true] { + let mut s = session(); + let (a, b, c) = (rect(&mut s, 0.0, 0.0, 40.0), rect(&mut s, 200.0, 0.0, 40.0), rect(&mut s, 400.0, 0.0, 40.0)); + let view = ViewInfo::default(); + s.select_tool("blend", view).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 20.0, 20.0), view).unwrap(); + sel(&mut s, &[c]); + // Cmd lends the selection tool: a click on c selects it, a drag moves it (an edit). + let cmd = Mods { cmd: true, ..Mods::default() }; + let to = if drag { 440.0 } else { 420.0 }; + s.pointer(&PointerEvent::new(PointerKind::Down, 420.0, 20.0).with_mods(cmd), view).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, to, 20.0).with_mods(cmd), view).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, to, 20.0).with_mods(cmd), view).unwrap(); + assert_eq!(s.tool_id(), "blend"); + assert_eq!(s.overlays(view).is_empty(), drag, "drag {drag}"); + s.pointer(&PointerEvent::new(PointerKind::Down, 220.0, 20.0), view).unwrap(); + if drag { + assert_eq!(s.doc().unwrap().selection.objects, vec![b], "the drag dropped the pick"); + } else { + let g = s.doc().unwrap().selection.objects[0]; + assert_eq!(spec(&s, g).0, vec![a, b]); + } + } +} + #[test] fn start_points_round_trip_and_old_blends_load() { let mut s = session(); diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 81f8616a80..94d2d6742e 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -328,6 +328,25 @@ impl Session { self.tool_panic.take().map_or(Ok(()), Err) } + /// The active document (its uid) and its [`crate::History::step`]. + fn history_step(&self) -> Option<(u64, (u64, u64))> { + self.active().map(|d| (d.uid, d.history.step())) + } + + /// Tell the active tool when the history moved, or another document became active, since it + /// last handled a pointer event or was last told ([`vectorcraft_tools::Tool::history_moved`]). + /// A lent selection tool is not told. + fn tell_tool_history_moved(&mut self) { + if self.lender.is_some() { + return; + } + let now = self.history_step(); + if self.tool_step.is_some_and(|seen| Some(seen) != now) { + self.tool.history_moved(); + } + self.tool_step = now; + } + /// Feed a pointer event to the active tool. Returns requests for the UI. pub fn pointer(&mut self, ev: &PointerEvent, view: ViewInfo) -> Result> { self.last_view = view; @@ -341,7 +360,9 @@ impl Session { return r; } self.leave_draw_inside(ev, view)?; + self.tell_tool_history_moved(); let ev = &self.lend_selection_tool(ev); + let lent = self.lender.is_some(); let acts = self.with_tool_cx(view, |t, cx| t.pointer(cx, ev)); let r = self.take_tool_panic().and_then(|()| { // A gesture may change options (Alt-drag sizes a Liquify brush): keep them. @@ -350,6 +371,11 @@ impl Session { } self.apply_actions(acts) }); + // The tool's own edits do not move the history for it. A selection tool that Cmd lends + // edits for the lender, which hears of the edit at its next event. + if !lent { + self.tool_step = self.history_step(); + } if ev.kind == PointerKind::Up { self.give_back_tool(view)?; } @@ -553,6 +579,8 @@ impl Session { } pub fn overlays(&mut self, view: ViewInfo) -> Vec { + // The Blend tool's first pick is not marked after an edit that dropped it. + self.tell_tool_history_moved(); let mut v = self.with_tool_cx(view, |t, cx| t.overlays(cx)); // The Type tools draw the ports of selected type themselves. if !matches!(self.tool.id(), "type" | "areaType" | "typeOnPath" | "verticalType" | "verticalAreaType" | "verticalTypeOnPath") { diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index e55bb4069a..686e004081 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -224,6 +224,10 @@ pub trait Tool: Send { fn after_command(&mut self, _cx: &ToolContext) -> Vec { vec![] } + /// The undo history moved outside the tool (an edit, Undo or Redo the tool did not make), or + /// another document became active. The Blend tool drops its first pick and stops adding to the + /// blend it just made. + fn history_moved(&mut self) {} /// Time passes while the pointer button is held (`dt` seconds since the last tick, whether or /// not the pointer moved): tools that keep working while the brush holds still (Twirl, Pucker, /// Bloat) act on it. The host supplies the time, so tests and agents drive it exactly. diff --git a/crates/tools/src/meshblend.rs b/crates/tools/src/meshblend.rs index d6a46faf05..e881d54c41 100644 --- a/crates/tools/src/meshblend.rs +++ b/crates/tools/src/meshblend.rs @@ -148,6 +148,11 @@ impl Tool for BlendTool { (self.first, self.chained) = (None, false); vec![] } + /// An edit, Undo or Redo made outside the tool drops the object picked first and stops adding to + /// the blend just made, so the next click picks a new first object. + fn history_moved(&mut self) { + (self.first, self.chained) = (None, false); + } } #[derive(Default)] From 4b663906e9935b5b7fe97756cf3c0b31ea181aa1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 06:53:56 -0800 Subject: [PATCH 02/11] Blend: tests for a pick dropped by Redo and for the history step A Redo made outside the Blend tool drops its first pick, as an edit or an Undo does, and two picks with no edit between them blend. History::step changes with each new step, Undo and Redo, also when an Undo and a new edit leave as many steps as before, and stays the same for a selection change and for an edit merged into an undo group. --- crates/engine/src/tests/blendopts.rs | 43 +++++++++++++++++++------- crates/engine/src/tests/history_mem.rs | 37 ++++++++++++++++++++++ 2 files changed, 68 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/tests/blendopts.rs b/crates/engine/src/tests/blendopts.rs index 7332e18ec0..366a19241f 100644 --- a/crates/engine/src/tests/blendopts.rs +++ b/crates/engine/src/tests/blendopts.rs @@ -234,31 +234,50 @@ fn escape_drops_the_blend_tools_first_pick() { } #[test] -fn an_edit_or_undo_made_outside_the_blend_tool_drops_its_first_pick() { - for undo in [false, true] { +fn an_edit_undo_or_redo_made_outside_the_blend_tool_drops_its_first_pick() { + for case in ["edit", "undo", "redo"] { + let undo = case == "undo"; let mut s = session(); let (a, b, c) = (rect(&mut s, 0.0, 0.0, 40.0), rect(&mut s, 200.0, 0.0, 40.0), rect(&mut s, 400.0, 0.0, 40.0)); + if case == "redo" { + s.execute("paint.setFill", &json!({"ids": [c.0], "color": "#ff0000"})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + } s.select_tool("blend", ViewInfo::default()).unwrap(); let click = |s: &mut Session, x: f64, y: f64| s.pointer(&PointerEvent::new(PointerKind::Down, x, y), ViewInfo::default()).unwrap(); - // Undo takes away c, the object picked first; an edit recolors c, which is not picked. + // Undo takes away c, the object picked first; an edit or a redo recolors c, which is not picked. click(&mut s, if undo { 420.0 } else { 20.0 }, 20.0); assert!(!s.overlays(ViewInfo::default()).is_empty()); - if undo { - s.execute("edit.undo", &json!({})).unwrap(); - } else { - s.execute("paint.setFill", &json!({"ids": [c.0], "color": "#ff0000"})).unwrap(); - } - assert!(s.overlays(ViewInfo::default()).is_empty(), "undo {undo}: the pick is not marked"); + match case { + "undo" => s.execute("edit.undo", &json!({})).unwrap(), + "redo" => s.execute("edit.redo", &json!({})).unwrap(), + _ => s.execute("paint.setFill", &json!({"ids": [c.0], "color": "#ff0000"})).unwrap(), + }; + assert!(s.overlays(ViewInfo::default()).is_empty(), "{case}: the pick is not marked"); let (layers, depth) = (s.doc().unwrap().doc.layers.clone(), s.doc().unwrap().history.undo.len()); click(&mut s, 220.0, 20.0); - assert_eq!(s.doc().unwrap().selection.objects, vec![b], "undo {undo}: b is picked first"); - assert_eq!((&s.doc().unwrap().doc.layers, s.doc().unwrap().history.undo.len()), (&layers, depth), "undo {undo}: the click changes no art"); + assert_eq!(s.doc().unwrap().selection.objects, vec![b], "{case}: b is picked first"); + assert_eq!((&s.doc().unwrap().doc.layers, s.doc().unwrap().history.undo.len()), (&layers, depth), "{case}: the click changes no art"); click(&mut s, if undo { 20.0 } else { 420.0 }, 20.0); let g = s.doc().unwrap().selection.objects[0]; - assert_eq!(spec(&s, g).0, if undo { vec![a, b] } else { vec![b, c] }, "undo {undo}"); + assert_eq!(spec(&s, g).0, if undo { vec![a, b] } else { vec![b, c] }, "{case}"); } } +#[test] +fn two_picks_with_no_edit_between_them_blend() { + let mut s = session(); + let (a, b) = (rect(&mut s, 0.0, 0.0, 40.0), rect(&mut s, 200.0, 0.0, 40.0)); + s.select_tool("blend", ViewInfo::default()).unwrap(); + let click = |s: &mut Session, x: f64, y: f64| s.pointer(&PointerEvent::new(PointerKind::Down, x, y), ViewInfo::default()).unwrap(); + click(&mut s, 20.0, 20.0); + // Drawing the overlays between the picks does not drop the first one. + assert!(!s.overlays(ViewInfo::default()).is_empty()); + click(&mut s, 220.0, 20.0); + let g = s.doc().unwrap().selection.objects[0]; + assert_eq!(spec(&s, g).0, vec![a, b]); +} + #[test] fn removing_the_blend_the_blend_tool_adds_to_ends_adding() { let mut s = session(); diff --git a/crates/engine/src/tests/history_mem.rs b/crates/engine/src/tests/history_mem.rs index af5d495528..23665d9eca 100644 --- a/crates/engine/src/tests/history_mem.rs +++ b/crates/engine/src/tests/history_mem.rs @@ -179,3 +179,40 @@ fn redo_during_an_interaction_keeps_the_history_and_the_document_in_step() { s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(first_x(&s), start); } + +/// `History::step` changes with every new step, Undo and Redo, also when an undo and a new edit +/// leave as many steps as before, and stays the same for an edit merged into an undo group and for +/// a selection change. +#[test] +fn the_history_step_changes_with_each_step_undo_and_redo() { + let mut s = session_with_rects(2); + let step = |s: &Session| s.doc().unwrap().history.step(); + let start = step(&s); + assert!(start.0 != 0 && start.1 == 0, "the Add step, and nothing to redo: {start:?}"); + s.execute("object.move", &json!({"dx": 1, "dy": 0})).unwrap(); + let moved = step(&s); + assert!(moved.0 != start.0 && moved.1 == 0, "{moved:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + let undone = step(&s); + assert!(undone.0 == start.0 && undone.1 != 0, "{undone:?}"); + s.execute("edit.redo", &json!({})).unwrap(); + let redone = step(&s); + assert!(![start, moved, undone].contains(&redone) && redone.1 == 0, "{redone:?}"); + // An undo and a new edit: as many undo steps as after the move, at a different step. + s.execute("edit.undo", &json!({})).unwrap(); + let depth = s.doc().unwrap().history.undo.len(); + s.execute("object.move", &json!({"dx": 0, "dy": 1})).unwrap(); + let other = step(&s); + assert_eq!(s.doc().unwrap().history.undo.len(), depth + 1); + assert!(![start, moved, undone, redone].contains(&other), "{other:?}"); + s.execute("select.none", &json!({})).unwrap(); + assert_eq!(step(&s), other, "a selection change is no step"); + s.execute("select.all", &json!({})).unwrap(); + s.begin_undo_group(); + s.execute("object.move", &json!({"dx": 1, "dy": 0})).unwrap(); + let grouped = step(&s); + s.execute("object.move", &json!({"dx": 1, "dy": 0})).unwrap(); + assert_eq!(step(&s), grouped, "the second move is merged into the first"); + s.end_undo_group(false); + assert_ne!(grouped, other); +} From baeef1ec05717908707e646224ada0458b02a664 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 07:12:43 -0800 Subject: [PATCH 03/11] Blend: an edit merged into an open undo group drops the first pick An edit merged into the newest undo step (an undo group) left History::step unchanged, so a first pick made while the group was open survived the edit. The newest step now takes a new number whenever it is extended. --- crates/engine/src/history.rs | 7 ++++--- crates/engine/src/tests/blendopts.rs | 7 ++++++- crates/engine/src/tests/history_mem.rs | 16 ++++++++++------ 3 files changed, 20 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index ee6adccc49..4ce4e4599a 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -129,8 +129,8 @@ impl History { } /// Which step the document is at: the newest undo step and the next redo step, by numbers no - /// other step takes (0 for none). Every new step, Undo and Redo changes it; an edit merged into - /// the newest step (an undo group) and a selection change do not. + /// other step takes (0 for none). Every new step, Undo, Redo and edit merged into the newest + /// step (an undo group) changes it; a selection change does not. pub fn step(&self) -> (u64, u64) { (self.undo.last().map_or(0, |e| e.serial), self.redo.last().map_or(0, |e| e.serial)) } @@ -161,11 +161,12 @@ impl History { } /// Estimate the newest undo step again, its next state now being `now` (the steps after it were - /// merged into it, or an undo group extended it). + /// merged into it, or an undo group extended it). It takes a new number ([`History::step`]). pub(crate) fn recost_last(&mut self, now: &Document) { if let Some(e) = self.undo.last_mut() { (e.bytes, e.next_bytes) = e.doc.retained_bytes_each(now); e.next = std::ptr::from_ref(now) as usize; + e.serial = next_serial(); } } } diff --git a/crates/engine/src/tests/blendopts.rs b/crates/engine/src/tests/blendopts.rs index 366a19241f..059357ddb3 100644 --- a/crates/engine/src/tests/blendopts.rs +++ b/crates/engine/src/tests/blendopts.rs @@ -235,7 +235,7 @@ fn escape_drops_the_blend_tools_first_pick() { #[test] fn an_edit_undo_or_redo_made_outside_the_blend_tool_drops_its_first_pick() { - for case in ["edit", "undo", "redo"] { + for case in ["edit", "undo", "redo", "group"] { let undo = case == "undo"; let mut s = session(); let (a, b, c) = (rect(&mut s, 0.0, 0.0, 40.0), rect(&mut s, 200.0, 0.0, 40.0), rect(&mut s, 400.0, 0.0, 40.0)); @@ -243,6 +243,11 @@ fn an_edit_undo_or_redo_made_outside_the_blend_tool_drops_its_first_pick() { s.execute("paint.setFill", &json!({"ids": [c.0], "color": "#ff0000"})).unwrap(); s.execute("edit.undo", &json!({})).unwrap(); } + // In an open undo group, the edit after the pick is merged into the group's step. + if case == "group" { + s.begin_undo_group(); + s.execute("paint.setFill", &json!({"ids": [c.0], "color": "#00ff00"})).unwrap(); + } s.select_tool("blend", ViewInfo::default()).unwrap(); let click = |s: &mut Session, x: f64, y: f64| s.pointer(&PointerEvent::new(PointerKind::Down, x, y), ViewInfo::default()).unwrap(); // Undo takes away c, the object picked first; an edit or a redo recolors c, which is not picked. diff --git a/crates/engine/src/tests/history_mem.rs b/crates/engine/src/tests/history_mem.rs index 23665d9eca..c14ea4aca4 100644 --- a/crates/engine/src/tests/history_mem.rs +++ b/crates/engine/src/tests/history_mem.rs @@ -181,8 +181,8 @@ fn redo_during_an_interaction_keeps_the_history_and_the_document_in_step() { } /// `History::step` changes with every new step, Undo and Redo, also when an undo and a new edit -/// leave as many steps as before, and stays the same for an edit merged into an undo group and for -/// a selection change. +/// leave as many steps as before, and with an edit merged into an undo group's step. It stays the +/// same for a selection change. #[test] fn the_history_step_changes_with_each_step_undo_and_redo() { let mut s = session_with_rects(2); @@ -210,9 +210,13 @@ fn the_history_step_changes_with_each_step_undo_and_redo() { s.execute("select.all", &json!({})).unwrap(); s.begin_undo_group(); s.execute("object.move", &json!({"dx": 1, "dy": 0})).unwrap(); - let grouped = step(&s); - s.execute("object.move", &json!({"dx": 1, "dy": 0})).unwrap(); - assert_eq!(step(&s), grouped, "the second move is merged into the first"); - s.end_undo_group(false); + let (grouped, depth) = (step(&s), s.doc().unwrap().history.undo.len()); assert_ne!(grouped, other); + s.execute("object.move", &json!({"dx": 1, "dy": 0})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), depth, "the second move is merged into the first"); + let merged = step(&s); + assert!(merged != grouped && merged.1 == 0, "a merged edit moves the step: {merged:?}"); + s.execute("select.none", &json!({})).unwrap(); + assert_eq!(step(&s), merged); + s.end_undo_group(false); } From 5a4c3e12a5b076db5951eb1c465a976ce3193443 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 7 Nov 2026 15:02:39 -0800 Subject: [PATCH 04/11] 3D (Classic): Extrude & Bevel (Classic) extrudes art with Wireframe, No Shading, Diffuse and Plastic surfaces Effect > 3D and Materials > 3D (Classic) > Extrude & Bevel (Classic)... applies `threeD.classicExtrude`, a live effect built on the Extrude & Bevel solid. It takes Extrude Depth, Cap, a bevel with Height and Bevel Extent In or Out, the Position presets, rotation and Perspective, and draws the faces with the Wireframe, No Shading, Diffuse or Plastic surface: one to ten lights, Ambient Light, Highlight Intensity and Size, Blend Steps, a Black, Custom or no Shading Color, and Draw Hidden Faces. Invalid parameters are refused with an error. --- crates/effects/src/catalog.rs | 10 +- crates/effects/src/lib.rs | 4 +- crates/effects/src/solids.rs | 20 +- crates/effects/src/solids/classic.rs | 220 ++++++++++++++++++ crates/effects/src/solids/tests.rs | 164 ++++++++++++- crates/three-d/src/lib.rs | 2 +- crates/three-d/src/shading.rs | 94 +++++++- crates/three-d/src/solid.rs | 8 +- crates/three-d/src/solid/build.rs | 10 +- crates/three-d/src/solid/inflate.rs | 2 +- crates/three-d/src/solid/tests.rs | 23 ++ crates/three-d/src/tests.rs | 1 + crates/three-d/src/tests/classic.rs | 96 ++++++++ crates/ui-egui/src/dialogs.rs | 1 + crates/ui-egui/src/dialogs/effect.rs | 14 +- crates/ui-egui/src/dialogs/revolve.rs | 46 ++-- crates/ui-egui/src/dialogs/revolve/tests.rs | 62 +++++ crates/ui-egui/src/dialogs/revolve_gizmo.rs | 14 +- crates/ui-egui/src/dialogs/three_d_classic.rs | 85 +++++++ crates/ui-egui/src/i18n/bg.tsv | 11 + crates/ui-egui/src/i18n/bs.tsv | 11 + crates/ui-egui/src/i18n/ca.tsv | 11 + crates/ui-egui/src/i18n/cs.tsv | 11 + crates/ui-egui/src/i18n/da.tsv | 11 + crates/ui-egui/src/i18n/de.tsv | 11 + crates/ui-egui/src/i18n/el.tsv | 11 + crates/ui-egui/src/i18n/es.tsv | 11 + crates/ui-egui/src/i18n/fi.tsv | 11 + crates/ui-egui/src/i18n/fr.tsv | 11 + crates/ui-egui/src/i18n/hi.tsv | 11 + crates/ui-egui/src/i18n/hu.tsv | 11 + crates/ui-egui/src/i18n/id.tsv | 11 + crates/ui-egui/src/i18n/it.tsv | 11 + crates/ui-egui/src/i18n/ja.tsv | 11 + crates/ui-egui/src/i18n/ka.tsv | 11 + crates/ui-egui/src/i18n/ko.tsv | 11 + crates/ui-egui/src/i18n/nl.tsv | 11 + crates/ui-egui/src/i18n/pl.tsv | 11 + crates/ui-egui/src/i18n/pt-br.tsv | 11 + crates/ui-egui/src/i18n/ru.tsv | 11 + crates/ui-egui/src/i18n/sv.tsv | 11 + crates/ui-egui/src/i18n/tr.tsv | 11 + crates/ui-egui/src/i18n/uk.tsv | 11 + crates/ui-egui/src/i18n/vi.tsv | 11 + crates/ui-egui/src/i18n/zh-hans.tsv | 11 + crates/ui-egui/src/i18n/zh-hant.tsv | 11 + crates/ui-egui/src/menus/submenus.rs | 11 +- crates/ui-egui/src/menus/tests.rs | 16 ++ docs/effects-parity.md | 2 +- docs/mcp.md | 27 +++ 50 files changed, 1186 insertions(+), 43 deletions(-) create mode 100644 crates/effects/src/solids/classic.rs create mode 100644 crates/three-d/src/tests/classic.rs create mode 100644 crates/ui-egui/src/dialogs/three_d_classic.rs diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 8440639328..50bccaa830 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -1,4 +1,4 @@ -use super::{CROP_MARKS, EXTRUDE, INFLATE, PATHFINDER_EFFECTS, RASTERIZE, REVOLVE, ROTATE, TRAP, Value, json, trap}; +use super::{CLASSIC_EXTRUDE, CROP_MARKS, EXTRUDE, INFLATE, PATHFINDER_EFFECTS, RASTERIZE, REVOLVE, ROTATE, TRAP, Value, json, trap}; /// Catalogue entry for one effect. #[derive(Clone, Debug, PartialEq)] @@ -80,6 +80,7 @@ fn lengths_of(id: &str) -> Lengths { "path.offsetPath" => always(&["offset"]), "threeD.revolve" => always(&["offset"]), "threeD.extrude" => always(&["depth", "bevelWidth", "bevelHeight"]), + "threeD.classicExtrude" => always(&["depth", "bevelHeight"]), "threeD.inflate" => always(&["depth"]), "path.outlineStroke" => always(&["width"]), "stylize.roundCorners" | "stylize.feather" | "blur.gaussian" | "blur.smart" | "sharpen.unsharpMask" => always(&["radius"]), @@ -198,6 +199,13 @@ pub fn effect_catalog() -> Vec { "{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.", json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0}), ), + g( + CLASSIC_EXTRUDE, + "Extrude & Bevel (Classic)…", + &["Effect", "3D and Materials", "3D (Classic)"], + "{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none (black; the color the faces darken toward; none keeps the paint and adds only the highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults are VectorCraft's own.", + json!({"depth":50.0,"cap":true,"bevel":"none","bevelHeight":4.0,"bevelInside":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","drawHiddenFaces":false}), + ), g( "convertToShape.rectangle", "Rectangle…", diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 8835d769f7..c457df0330 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -84,8 +84,8 @@ pub use reshape::{ }; pub use revolve::{REVOLVE, has_revolve, revolve_art, revolve_options, validate_revolve}; pub use solids::{ - EXTRUDE, INFLATE, ROTATE, ROTATION_PRESETS, SOLIDS, extrude_options, has_solid, inflate_options, is_three_d, solid_art, validate_solid, - validate_three_d, view_options, + CLASSIC_EXTRUDE, EXTRUDE, INFLATE, ROTATE, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, classic_extrude_options, classic_shading, extrude_options, + has_solid, inflate_options, is_three_d, solid_art, validate_solid, validate_three_d, view_options, }; pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings}; pub use trap::TRAP; diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 7025f8f6f3..99b246a417 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -1,5 +1,5 @@ -//! Extrude & Bevel, Inflate and Rotate as live, shaded vector art, shared by the canvas and every -//! exporter. Like Revolve, the source path stays editable and the effect draws its 3D faces. +//! Extrude & Bevel, Inflate, Rotate and Extrude & Bevel (Classic) as live, shaded vector art, +//! shared by the canvas and every exporter. Like Revolve, the source path stays editable and the effect draws its 3D faces. use std::sync::Arc; use serde_json::Value; @@ -14,11 +14,14 @@ use vectorcraft_doc::color::Color; use crate::util::{flag, num, text}; use crate::{GeomContext, apply_geometry_with, is_geometry}; +mod classic; +pub use classic::{CLASSIC_EXTRUDE, SHADING_COLORS, classic_extrude_options, classic_shading}; + pub const EXTRUDE: &str = "threeD.extrude"; pub const INFLATE: &str = "threeD.inflate"; pub const ROTATE: &str = "threeD.rotate"; /// The 3D effects this module draws (Revolve has its own). -pub const SOLIDS: [&str; 3] = [EXTRUDE, INFLATE, ROTATE]; +pub const SOLIDS: [&str; 4] = [EXTRUDE, INFLATE, ROTATE, CLASSIC_EXTRUDE]; /// Is `id` one of the 3D and Materials effects (Revolve included)? pub fn is_three_d(id: &str) -> bool { @@ -93,6 +96,7 @@ pub fn extrude_options(p: &Value) -> Extrude { inside: flag(p, "bevelInside", false), both_sides: flag(p, "bevelBothSides", false), }), + hidden: false, } } @@ -146,6 +150,7 @@ fn facets(id: &str, path: &PathData, rule: FillRule, bounds: Rect, p: &Value) -> let view = view_options(p); match id { EXTRUDE => vectorcraft_three_d::extrude(path, rule, bounds, extrude_options(p), view), + CLASSIC_EXTRUDE => vectorcraft_three_d::extrude(path, rule, bounds, classic_extrude_options(p), view), INFLATE => vectorcraft_three_d::inflate(path, rule, bounds, inflate_options(p), view), _ => vectorcraft_three_d::plane(path, rule, bounds, view), } @@ -153,6 +158,9 @@ fn facets(id: &str, path: &PathData, rule: FillRule, bounds: Rect, p: &Value) -> /// Validate before a command changes the document; the evaluator bounds loaded files too. pub fn validate_solid(n: &Node, id: &str, p: &Value) -> Result<(), String> { + if id == CLASSIC_EXTRUDE { + classic::validate(p)?; + } crate::lighting::validate(p)?; let label = crate::effect_info(id).map_or("This effect", |e| e.label.trim_end_matches('…')); if let Some(v) = p.get("bevel") @@ -322,7 +330,8 @@ fn region(path: &PathData, rule: FillRule, item: &AppearanceItem) -> (PathData, fn art_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option>> { let b = union_bounds(shapes)?; let p = crate::merged_params(&fx.id, &fx.params); - let colored = view_options(&p).has_colored_lights(); + let classic = fx.id == CLASSIC_EXTRUDE; + let colored = !classic && view_options(&p).has_colored_lights(); if fx.id == ROTATE { // Every part turns about the centre of the object's own bounds (a group's members about // the centre of theirs), so they stay together. @@ -383,7 +392,8 @@ fn art_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option>> .map(|(item, member, f)| { let depths: Vec = f.iter().map(|f| f.depth).collect(); let (paint, opacity, blend) = paint_of(item, member); - (depths, surface(n, f, &paint, opacity, blend, colored)) + let art = if classic { classic::surface(n, f, &paint, opacity, blend, &p) } else { surface(n, f, &paint, opacity, blend, colored) }; + (depths, art) }) .collect(); // One order takes a plain group of faces from each solid, one face for each facet. With diff --git a/crates/effects/src/solids/classic.rs b/crates/effects/src/solids/classic.rs new file mode 100644 index 0000000000..730fb8e53b --- /dev/null +++ b/crates/effects/src/solids/classic.rs @@ -0,0 +1,220 @@ +//! Extrude & Bevel (Classic): the solid Extrude & Bevel builds from a path, drawn with the classic +//! surfaces (Wireframe, No Shading, Diffuse and Plastic), their highlight, blend steps and shading +//! color. +use std::sync::Arc; + +use serde_json::Value; +use vectorcraft_doc::color::{BlendMode, Color, Paint}; +use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, Node, StrokeLayer}; +use vectorcraft_geom::Rect; +use vectorcraft_three_d::{Bevel, BevelShape, ClassicShading, ClassicSurface, Extrude, Facet, Light}; + +use crate::util::{flag, num, text}; + +pub const CLASSIC_EXTRUDE: &str = "threeD.classicExtrude"; + +/// The width of a Wireframe edge, in points. +const WIRE: f64 = 0.5; + +/// The Shading Color choices: black, a custom color, or none. +pub const SHADING_COLORS: [&str; 3] = ["black", "custom", "none"]; + +/// The surface settings of Extrude & Bevel (Classic)'s parameters. +pub fn classic_shading(p: &Value) -> ClassicShading { + let d = ClassicShading::default(); + ClassicShading { + surface: ClassicSurface::parse(text(p, "surface", "plastic")).unwrap_or_default(), + ambient: num(p, "ambient", d.ambient * 100.0) / 100.0, + highlight_intensity: num(p, "highlightIntensity", d.highlight_intensity * 100.0) / 100.0, + highlight_size: num(p, "highlightSize", d.highlight_size * 100.0) / 100.0, + blend_steps: num(p, "blendSteps", f64::from(d.blend_steps)).round().clamp(1.0, 256.0) as u32, + } +} + +/// The solid of Extrude & Bevel (Classic)'s parameters: its depth, cap and bevel (as tall as it is +/// wide, added around the shape or carved into it), with the faces turned away from the viewer kept +/// for Draw Hidden Faces and for the Wireframe surface. +pub fn classic_extrude_options(p: &Value) -> Extrude { + let height = num(p, "bevelHeight", 4.0); + Extrude { + depth: num(p, "depth", 50.0), + cap: flag(p, "cap", true), + bevel: BevelShape::parse(text(p, "bevel", "none")).map(|shape| Bevel { + shape, + width: height, + height, + inside: flag(p, "bevelInside", false), + ..Bevel::default() + }), + hidden: flag(p, "drawHiddenFaces", false) || classic_shading(p).surface == ClassicSurface::Wireframe, + ..Extrude::default() + } +} + +/// The color faces darken toward: black, the custom color, or none (faces keep their paint and only +/// the highlight lightens them). +fn shading_color(p: &Value) -> Option { + match text(p, "shadingColor", "black") { + "none" => None, + "custom" => Some(p.get("shadingCustom").and_then(Value::as_str).and_then(parse_hex).unwrap_or(Color::BLACK)), + _ => Some(Color::BLACK), + } +} + +fn parse_hex(s: &str) -> Option { + (s.len() == 7 && s.starts_with('#') && s.bytes().skip(1).all(|b| b.is_ascii_hexdigit())).then(|| Color::from_hex(s)).flatten() +} + +/// The lights: the `lights` list when it is given, else the one light of `lightRotation`, +/// `lightHeight`, `lightBehind` and `lightIntensity`. Each is its direction toward the light in view +/// space and its intensity (0..1). +fn lights(p: &Value) -> Vec<([f64; 3], f64)> { + if let Some(list) = crate::lighting::lights(p) { + return list.iter().map(|l| (l.direction(), l.intensity)).collect(); + } + let light = Light { + rotation: num(p, "lightRotation", vectorcraft_three_d::DEFAULT_LIGHT.0), + height: num(p, "lightHeight", vectorcraft_three_d::DEFAULT_LIGHT.1), + behind: flag(p, "lightBehind", false), + ..Light::default() + }; + vec![(light.direction(), num(p, "lightIntensity", 100.0) / 100.0)] +} + +/// The numeric parameters: (key, lowest, highest, whole numbers only). +const RANGES: [(&str, f64, f64, bool); 13] = [ + ("depth", 0.0, 2000.0, false), + ("bevelHeight", 1.0, 100.0, false), + ("rotationX", -180.0, 180.0, false), + ("rotationY", -180.0, 180.0, false), + ("rotationZ", -180.0, 180.0, false), + ("perspectiveAngle", 0.0, 160.0, false), + ("lightRotation", -180.0, 180.0, false), + ("lightHeight", 0.0, 90.0, false), + ("lightIntensity", 0.0, 100.0, false), + ("ambient", 0.0, 100.0, false), + ("highlightIntensity", 0.0, 100.0, false), + ("highlightSize", 0.0, 100.0, false), + ("blendSteps", 1.0, 256.0, true), +]; + +const FLAGS: [&str; 4] = ["cap", "bevelInside", "lightBehind", "drawHiddenFaces"]; + +/// Check Extrude & Bevel (Classic)'s parameters `p` (its defaults filled in): every key is one of +/// its parameters, numbers are in range, flags are true or false, and `surface`, `shadingColor` and +/// `shadingCustom` name a surface, a shading color and a #rrggbb color. +pub fn validate(p: &Value) -> Result<(), String> { + let Some(map) = p.as_object() else { return Ok(()) }; + let defaults = crate::default_params(CLASSIC_EXTRUDE).unwrap_or(Value::Null); + let known: Vec<&str> = defaults.as_object().map(|m| m.keys().map(String::as_str).collect()).unwrap_or_default(); + for key in map.keys() { + if !known.contains(&key.as_str()) { + let keys = known.join(", "); + return Err(format!("unknown parameter `{key}`; the command takes: {keys}")); + } + } + for (key, min, max, whole) in RANGES { + let Some(v) = map.get(key) else { continue }; + let Some(x) = v.as_f64() else { return Err(format!("`{key}` must be a number")) }; + if whole && (x.fract() != 0.0 || !(min..=max).contains(&x)) { + return Err(format!("`{key}` must be a whole number between {min} and {max} (got {x})")); + } + if !(min..=max).contains(&x) { + return Err(format!("`{key}` must be between {min} and {max} (got {x})")); + } + } + for key in FLAGS { + if map.get(key).is_some_and(|v| !v.is_boolean()) { + return Err(format!("`{key}` must be true or false")); + } + } + let one_of = |key: &str, ids: &[&str]| -> Result<(), String> { + match map.get(key) { + Some(v) if !v.as_str().is_some_and(|s| ids.contains(&s)) => Err(format!("`{key}` must be one of {}", ids.join(", "))), + _ => Ok(()), + } + }; + let surfaces: Vec<&str> = ClassicSurface::ALL.iter().map(|s| s.id()).collect(); + one_of("surface", &surfaces)?; + one_of("shadingColor", &SHADING_COLORS)?; + let key = "shadingCustom"; + if map.get(key).is_some_and(|v| !v.as_str().is_some_and(|s| parse_hex(s).is_some())) { + return Err(format!("`{key}` must be a #rrggbb color")); + } + Ok(()) +} + +/// `c` with tone `tone` (0 the shading color, 1 the color itself) and highlight `spec` (toward +/// white) on top. +fn shaded(c: Color, tone: f64, spec: f64, shade: Option) -> Color { + let base = c.to_rgb(); + let dark = shade.map_or(base, |s| s.to_rgb()); + let (tone, spec) = (tone as f32, spec as f32); + let [r, g, b] = [0, 1, 2].map(|i| { + let mixed = dark[i] + (base[i] - dark[i]) * tone; + (mixed + (1.0 - mixed) * spec).clamp(0.0, 1.0) + }); + Color::rgb(r, g, b) +} + +/// One solid's faces in paint `paint`, as a group with the paint's opacity and blend mode, one child +/// for each facet: the edges of the faces on Wireframe, else each face filled in its paint shaded by +/// its tone and highlight. A gradient with transparent stops is shaded opaque and then masked by +/// its own transparency, so the shading follows the gradient's coverage. +pub(super) fn surface(n: &Node, facets: Vec, source: &Paint, opacity: f32, blend: BlendMode, p: &Value) -> Node { + let shading = classic_shading(p); + let lights = lights(p); + let shade = shading_color(p); + let wire = shading.surface == ClassicSurface::Wireframe; + let (paint, mask) = if wire { (source.clone(), None) } else { crate::lighting::opaque_paint(source) }; + let paint = &paint; + let children = facets + .into_iter() + .map(|face| { + if wire { + let mut edge = StrokeLayer::new(paint.clone(), WIRE); + edge.join = vectorcraft_doc::LineJoin::Round; + return Arc::new(Node::path(n.id, face.path(), Appearance { items: vec![AppearanceItem::Stroke(edge)], ..Default::default() })); + } + let (tone, spec) = shading.tone(face.normal, &lights); + // A narrow stroke of the face's own paint closes the hairline seams between faces. + let seam = (face.thickness() / 2.0).clamp(0.05, 0.75); + let items = match paint.color() { + // Unshaded (No Shading, no shading color, or a face in full light) with no + // highlight: the paint itself, its color space and swatch kept. + Some(_) if (tone >= 1.0 || shade.is_none()) && spec <= 0.0 => { + vec![AppearanceItem::Fill(FillLayer::new(paint.clone())), AppearanceItem::Stroke(StrokeLayer::new(paint.clone(), seam))] + } + Some(c) => { + let fill = Paint::solid(shaded(c, tone, spec, shade)); + vec![AppearanceItem::Fill(FillLayer::new(fill.clone())), AppearanceItem::Stroke(StrokeLayer::new(fill, seam))] + } + // Gradients and patterns keep their paint, darkened by a layer of the shading color + // and lightened by one of white. As with the other 3D effects' pattern shadow, the + // layers cover the whole face, transparent pattern cells included. + None => { + let mut items = + vec![AppearanceItem::Fill(FillLayer::new(paint.clone())), AppearanceItem::Stroke(StrokeLayer::new(paint.clone(), seam))]; + for (color, share) in [(shade, 1.0 - tone), (Some(Color::WHITE), spec)] { + if let Some(color) = color.filter(|_| share > 0.0) { + let mut layer = FillLayer::new(Paint::solid(color)); + layer.opacity = share as f32; + items.push(AppearanceItem::Fill(layer)); + } + } + items + } + }; + Arc::new(Node::path(n.id, face.path(), Appearance { items, ..Default::default() })) + }) + .collect(); + let mut group = Node::group(n.id, children); + group.opacity = opacity; + group.blend = blend; + if let Some(mask) = mask { + let bounds = group.visual_bounds().unwrap_or(Rect::ZERO).inflate(1.0, 1.0); + let coverage = Node::path(n.id, vectorcraft_geom::shapes::rectangle(bounds), Appearance::basic(mask, Paint::None, 0.0)); + group.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(coverage, true))); + } + group +} diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index a9997bb5d5..44204f83d0 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -45,10 +45,13 @@ fn every_solid_draws_shaded_faces_and_leaves_the_source_editable() { assert_eq!(n.path_data(), Some(&source), "{id}"); assert!(!faces(&art).is_empty(), "{id}"); // The faces are the fill's red or the stroke's black, shaded: never brighter, never another - // hue. + // hue (the classic Plastic surface adds a white highlight, tested on its own). for f in faces(&art) { let [r, g, b] = fill_rgb(f); - assert!(r <= 0.8 + 1e-6 && (g * 4.0 - r).abs() < 1e-4 && (b * 8.0 - r).abs() < 1e-4 || id == ROTATE, "{id}: {r} {g} {b}"); + assert!( + r <= 0.8 + 1e-6 && (g * 4.0 - r).abs() < 1e-4 && (b * 8.0 - r).abs() < 1e-4 || id == ROTATE || id == CLASSIC_EXTRUDE, + "{id}: {r} {g} {b}" + ); } // The art follows the source when it moves. let before = art.visual_bounds().unwrap(); @@ -595,3 +598,160 @@ fn a_3d_effect_on_a_group_turns_every_member_about_one_shared_axis() { assert!(err.contains("clipping groups"), "{err}"); assert!(solid_art(&g).is_none(), "drawn as the group it is"); } + +/// The red square without its stroke, with Extrude & Bevel (Classic) and `params`. +fn classic(params: Value) -> Node { + let mut n = square_node(); + n.appearance.items.retain(|i| matches!(i, AppearanceItem::Fill(_))); + n.appearance.effects.push(fx(CLASSIC_EXTRUDE, params)); + n +} + +fn classic_faces(params: Value) -> Vec { + let art = solid_art(&classic(params)).unwrap(); + faces(&art).into_iter().cloned().collect() +} + +fn close3(a: [f32; 3], b: [f32; 3]) -> bool { + a.iter().zip(b).all(|(a, b)| (a - b).abs() < 1e-4) +} + +#[test] +fn classic_surfaces_draw_edges_flat_paint_soft_light_and_a_highlight() { + // Wireframe: the edges of every face, the hidden ones too, in the paint; no fills. + let wire = classic_faces(json!({"surface": "wireframe"})); + let plastic = classic_faces(json!({})); + assert_eq!(plastic.len(), 3, "a box shows three faces"); + assert_eq!(wire.len(), 6, "and has six"); + for f in &wire { + let [AppearanceItem::Stroke(s)] = &f.appearance.items[..] else { panic!("a stroke alone: {:?}", f.appearance.items) }; + assert_eq!(s.paint, Paint::solid(RED)); + } + // No Shading: every face in the art's own paint, a CMYK color kept as it is. + assert!(classic_faces(json!({"surface": "none"})).iter().all(|f| close3(fill_rgb(f), RED.to_rgb()))); + let cmyk = Paint::solid(Color::Cmyk { c: 0.1, m: 0.9, y: 0.8, k: 0.0 }); + let mut n = classic(json!({"surface": "none"})); + if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() { + f.paint = cmyk.clone(); + } + for f in faces(&solid_art(&n).unwrap()) { + let AppearanceItem::Fill(fill) = &f.appearance.items[0] else { panic!("a fill first") }; + assert_eq!(fill.paint, cmyk); + } + // Diffuse: the red darkened toward black by how far each face turns from the light, so the + // faces differ but keep their hue. + let diffuse: Vec<[f32; 3]> = classic_faces(json!({"surface": "diffuse"})).iter().map(fill_rgb).collect(); + assert!(diffuse.iter().all(|[r, g, b]| *r <= 0.8 + 1e-6 && (g * 4.0 - r).abs() < 1e-4 && (b * 8.0 - r).abs() < 1e-4), "{diffuse:?}"); + assert!(diffuse.windows(2).any(|w| !close3(w[0], w[1])), "{diffuse:?}"); + // Plastic: the same faces, one of them lightened toward white by the highlight. + let shiny: Vec<[f32; 3]> = + classic_faces(json!({"highlightIntensity": 100, "highlightSize": 100, "lightHeight": 60})).iter().map(fill_rgb).collect(); + let soft: Vec<[f32; 3]> = classic_faces(json!({"surface": "diffuse", "lightHeight": 60})).iter().map(fill_rgb).collect(); + assert!(shiny.iter().zip(&soft).any(|(s, d)| s[1] > d[1] + 0.01), "{shiny:?} {soft:?}"); + assert!(shiny.iter().zip(&soft).all(|(s, d)| s[1] >= d[1] - 1e-4)); + // Without highlight, Plastic shades as Diffuse. + let dull: Vec<[f32; 3]> = classic_faces(json!({"highlightIntensity": 0, "lightHeight": 60})).iter().map(fill_rgb).collect(); + assert!(dull.iter().zip(&soft).all(|(a, b)| close3(*a, *b))); +} + +#[test] +fn classic_shading_color_blend_steps_and_lights() { + let base = json!({"surface": "diffuse", "ambient": 20}); + let with = |extra: Value| { + let mut p = base.clone(); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + classic_faces(p).iter().map(fill_rgb).collect::>() + }; + // A custom shading color darkens toward that color; None keeps the paint. + assert!(with(json!({"shadingColor": "custom", "shadingCustom": "#0000ff"})).iter().any(|c| c[2] > c[0] / 8.0 + 0.01)); + assert!(with(json!({"shadingColor": "none"})).iter().all(|c| close3(*c, RED.to_rgb()))); + // One blend step: every face fully lit or fully in shadow. + let stepped = with(json!({"blendSteps": 1, "ambient": 0})); + assert!(stepped.iter().all(|c| close3(*c, RED.to_rgb()) || close3(*c, [0.0; 3])), "{stepped:?}"); + // No light: the ambient share of the red. Two lights add up. + let dark = with(json!({"lightIntensity": 0, "blendSteps": 256})); + assert!(dark.iter().all(|c| (c[0] - 0.8 * 0.2).abs() < 0.01), "{dark:?}"); + let one = with(json!({"lights": [{"intensity": 30}], "blendSteps": 256})); + let two = with(json!({"lights": [{"intensity": 30}, {"intensity": 30}], "blendSteps": 256})); + assert!(one.iter().zip(&two).all(|(a, b)| b[0] >= a[0] - 1e-4) && one.iter().zip(&two).any(|(a, b)| b[0] > a[0] + 0.01)); + // Draw Hidden Faces keeps the faces turned away, drawn first. + assert_eq!(with(json!({"drawHiddenFaces": true})).len(), 6); +} + +#[test] +fn classic_bevel_height_extent_and_cap_shape_the_solid() { + let bounds = |p: Value| solid_art(&classic(p)).unwrap().visual_bounds().unwrap(); + let front = json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "bevel": "classic", "bevelHeight": 10}); + let out = bounds(front.clone()); + let mut inside = front.clone(); + inside["bevelInside"] = json!(true); + // Straight on, a bevel added around the shape widens it; one carved into it keeps its size. + assert!(out.width() > 100.0 + 15.0, "{out:?}"); + let carved = bounds(inside); + assert!((carved.width() - 100.0).abs() < 2.0, "{carved:?}"); + // Hollow: no caps, so the walls seen from inside show too. + assert!(classic_faces(json!({"cap": false})).len() > classic_faces(json!({})).len()); + // The depth sets how far back the solid goes. + let side = json!({"rotationX": 0, "rotationY": 90, "rotationZ": 0}); + let mut deep = side.clone(); + deep["depth"] = json!(120); + assert!((bounds(deep).width() - 120.0).abs() < 1.0); +} + +/// A gradient fill with a transparent stop is shaded opaque and masked by its own transparency, so +/// the shading does not cover the transparent part; an opaque gradient needs no mask. +#[test] +fn classic_shading_keeps_a_gradients_transparency() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + for (end, masked) in [(0.25, true), (1.0, false)] { + let mut stop = GradientStop::new(1.0, RED); + stop.opacity = end; + let gradient = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, RED), stop])); + let mut n = classic(json!({})); + if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() { + f.paint = Paint::Gradient(Box::new(gradient)); + } + let art = solid_art(&n).unwrap(); + let surface = &art.children().unwrap()[0]; + assert_eq!(surface.extras().mask.is_some(), masked, "{end}"); + let mut opaque = true; + surface.walk(&mut |c| { + for item in &c.appearance.items { + if let AppearanceItem::Fill(f) = item + && let Paint::Gradient(g) = &f.paint + { + opaque &= g.gradient.stops.iter().all(|s| s.opacity == 1.0); + } + } + }); + assert!(opaque, "{end}: the faces are drawn opaque"); + } +} + +#[test] +fn classic_parameters_are_checked() { + let n = classic(json!({})); + let check = |p: Value| validate_solid(&n, CLASSIC_EXTRUDE, &crate::merged_params(CLASSIC_EXTRUDE, &p)); + assert!(check(json!({})).is_ok()); + assert!(check(json!({"surface": "wireframe", "shadingColor": "custom", "shadingCustom": "#12aBcd", "blendSteps": 256, "bevel": "ogee"})).is_ok()); + for (p, says) in [ + (json!({"surface": "glossy"}), "`surface` must be one of wireframe, none, diffuse, plastic"), + (json!({"shadingColor": "red"}), "`shadingColor` must be one of black, custom, none"), + (json!({"shadingCustom": "blue"}), "`shadingCustom` must be a #rrggbb color"), + (json!({"shadingCustom": "#fff"}), "`shadingCustom` must be a #rrggbb color"), + (json!({"depth": 2001}), "`depth` must be between 0 and 2000 (got 2001)"), + (json!({"bevelHeight": 0}), "`bevelHeight` must be between 1 and 100 (got 0)"), + (json!({"ambient": -1}), "`ambient` must be between 0 and 100 (got -1)"), + (json!({"blendSteps": 2.5}), "`blendSteps` must be a whole number between 1 and 256 (got 2.5)"), + (json!({"blendSteps": 0}), "`blendSteps` must be a whole number between 1 and 256 (got 0)"), + (json!({"highlightSize": "big"}), "`highlightSize` must be a number"), + (json!({"cap": "yes"}), "`cap` must be true or false"), + (json!({"drawHiddenFaces": 1}), "`drawHiddenFaces` must be true or false"), + (json!({"bevel": "fancy"}), "bevel must be none or one of"), + (json!({"twist": 10}), "unknown parameter `twist`"), + (json!({"lights": []}), "lights must contain one to ten lights"), + ] { + let err = check(p.clone()).unwrap_err(); + assert!(err.starts_with(says), "{p}: {err}"); + } +} diff --git a/crates/three-d/src/lib.rs b/crates/three-d/src/lib.rs index 43ec2d72a1..188a87a472 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -11,7 +11,7 @@ mod visibility; pub use solid::{Bevel, BevelShape, Extrude, Facet, Inflate, View, extrude, inflate, inflate_together, plane}; pub use visibility::{VisibleFace, visible_faces}; mod shading; -pub use shading::{LightGradient, RgbGradient, ShadeGradient}; +pub use shading::{ClassicShading, ClassicSurface, LightGradient, RgbGradient, ShadeGradient}; mod lights; pub use lights::{Light, Lights, MAX_LIGHTS}; mod caps; diff --git a/crates/three-d/src/shading.rs b/crates/three-d/src/shading.rs index b0772e7cf1..d351e97494 100644 --- a/crates/three-d/src/shading.rs +++ b/crates/three-d/src/shading.rs @@ -1,7 +1,99 @@ -//! Gouraud lighting represented by an ordinary vector linear gradient on each triangle. +//! Gouraud lighting represented by an ordinary vector linear gradient on each triangle, and the +//! flat surface shading of the classic 3D effects. use vectorcraft_geom::{Point, Vec2}; +/// The surface of a classic 3D effect: how its faces are drawn and lit. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum ClassicSurface { + /// Only the outline of every face, hidden ones included; the faces are transparent. + Wireframe, + /// Every face in the art's own paint, unlit. + NoShading, + /// Soft light: each face as bright as it faces the light. + Diffuse, + /// Diffuse light plus a glossy highlight where a face mirrors the light toward the viewer. + #[default] + Plastic, +} + +impl ClassicSurface { + pub const ALL: [ClassicSurface; 4] = [Self::Wireframe, Self::NoShading, Self::Diffuse, Self::Plastic]; + + pub fn id(self) -> &'static str { + match self { + Self::Wireframe => "wireframe", + Self::NoShading => "none", + Self::Diffuse => "diffuse", + Self::Plastic => "plastic", + } + } + + pub fn parse(s: &str) -> Option { + Self::ALL.into_iter().find(|v| v.id() == s) + } +} + +/// The surface settings of a classic 3D effect. Shares are 0..1. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ClassicShading { + pub surface: ClassicSurface, + /// Light every face gets, whichever way it faces. + pub ambient: f64, + /// How bright the highlight is at its center (Plastic only). + pub highlight_intensity: f64, + /// How wide the highlight spreads: 1 broad, 0 a pinpoint (Plastic only). + pub highlight_size: f64, + /// How many levels the shading and the highlight are rounded to, 1..256. + pub blend_steps: u32, +} + +impl Default for ClassicShading { + fn default() -> Self { + Self { surface: ClassicSurface::Plastic, ambient: 0.5, highlight_intensity: 0.6, highlight_size: 0.9, blend_steps: 25 } + } +} + +impl ClassicShading { + /// The shine exponent of the highlight: 2 at the largest size, 256 at the smallest. + fn shininess(self) -> f64 { + 2f64.powf(1.0 + 7.0 * (1.0 - self.highlight_size.clamp(0.0, 1.0))) + } + + /// `x` (0..1) rounded to the nearest of the blend steps' levels. + fn stepped(self, x: f64) -> f64 { + let steps = f64::from(self.blend_steps.clamp(1, 256)); + ((x.clamp(0.0, 1.0) * steps).round() / steps).clamp(0.0, 1.0) + } + + /// The tone (0 in full shadow, 1 fully lit) and the highlight (0 none, 1 white) of a face with + /// view-space unit normal `normal`, seen from the front and lit by `lights`: each a unit + /// direction toward the light and its intensity (0..1). The lights add up. Wireframe and No + /// Shading are unlit: tone 1, no highlight. + pub fn tone(self, normal: [f64; 3], lights: &[([f64; 3], f64)]) -> (f64, f64) { + if matches!(self.surface, ClassicSurface::Wireframe | ClassicSurface::NoShading) { + return (1.0, 0.0); + } + let dot = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; + let (mut tone, mut spec) = (self.ambient.clamp(0.0, 1.0), 0.0); + for &(light, intensity) in lights { + let intensity = if intensity.is_finite() { intensity.clamp(0.0, 1.0) } else { 0.0 }; + let lit = dot(normal, light).max(0.0); + tone += intensity * lit; + // The halfway direction between the light and the eye in front of the page. + let half = [light[0], light[1], light[2] + 1.0]; + let length = dot(half, half).sqrt(); + if self.surface == ClassicSurface::Plastic && length > 1e-12 && lit > 0.0 { + spec += intensity * (dot(normal, half) / length).max(0.0).powf(self.shininess()) * self.highlight_intensity.clamp(0.0, 1.0); + } + } + if !tone.is_finite() || !spec.is_finite() { + return (1.0, 0.0); + } + (self.stepped(tone), self.stepped(spec)) + } +} + /// Document-space gradient placement and the brightness at its two ends. Clipping a /// face must keep this placement unchanged, so newly cut edges retain their lighting. #[derive(Clone, Copy, Debug, PartialEq)] diff --git a/crates/three-d/src/solid.rs b/crates/three-d/src/solid.rs index 043e347661..337ea7b230 100644 --- a/crates/three-d/src/solid.rs +++ b/crates/three-d/src/solid.rs @@ -201,11 +201,14 @@ pub struct Extrude { /// Closed ends (a solid) or open ones (a hollow tube). pub cap: bool, pub bevel: Option, + /// Keep the faces of a closed solid that are turned away from the viewer (Draw Hidden Faces, + /// and the classic Wireframe surface), drawn behind the faces turned toward it. + pub hidden: bool, } impl Default for Extrude { fn default() -> Self { - Self { depth: 50.0, twist: 0.0, taper: 1.0, cap: true, bevel: None } + Self { depth: 50.0, twist: 0.0, taper: 1.0, cap: true, bevel: None, hidden: false } } } @@ -239,6 +242,9 @@ pub struct Facet { pub depth: f64, pub brightness: f64, pub illumination: [f64; 3], + /// The face's unit normal in view space (x right, y down, z toward the viewer), turned to the + /// side the viewer sees. + pub normal: [f64; 3], /// Smooth lighting on an inflated triangle, before clipping individual RGB channels. pub rgb_gradient: Option, /// The contours in view space, before projection, for tests that measure depths. diff --git a/crates/three-d/src/solid/build.rs b/crates/three-d/src/solid/build.rs index c78f2a38b4..f32de3e4de 100644 --- a/crates/three-d/src/solid/build.rs +++ b/crates/three-d/src/solid/build.rs @@ -47,6 +47,9 @@ pub(super) struct Builder<'a> { /// A closed solid hides the faces turned away from the viewer; an open one shows their /// insides. pub(super) closed: bool, + /// A closed solid keeps the faces turned away from the viewer too, with their outward normals, + /// drawn behind the others. + pub(super) hidden: bool, pub(super) facets: Vec, } @@ -83,7 +86,7 @@ impl Builder<'_> { // leave gaps. let (n, behind) = if facing > 0.0 { (n, false) - } else if self.closed && facing > -0.02 { + } else if self.closed && (facing > -0.02 || self.hidden) { (n, true) } else if self.closed { return Ok(()); @@ -111,6 +114,7 @@ impl Builder<'_> { depth, brightness: self.camera.brightness(n), illumination: crate::illumination(&self.camera.view, n, self.camera.light), + normal: [n.0, n.1, n.2], rgb_gradient: None, #[cfg(test)] view, @@ -378,7 +382,7 @@ pub fn extrude(path: &PathData, rule: FillRule, bounds: Rect, options: Extrude, } let rings = rings(path, rule, bounds.width().max(bounds.height()), MAX_SOLID_POINTS)?; let camera = Camera::new(view, bounds, o.depth); - let mut b = Builder { camera: &camera, closed: o.cap, facets: vec![] }; + let mut b = Builder { camera: &camera, closed: o.cap, hidden: o.hidden, facets: vec![] }; let steps = steps(&o); let z = |t: f64| o.depth / 2.0 - o.depth * t; let ring_at = @@ -431,7 +435,7 @@ pub fn plane(path: &PathData, rule: FillRule, bounds: Rect, view: View) -> Resul check_bounds(bounds)?; let rings = rings(path, rule, bounds.width().max(bounds.height()), MAX_PLANE_POINTS)?; let camera = Camera::new(view, bounds, 0.0); - let mut b = Builder { camera: &camera, closed: false, facets: vec![] }; + let mut b = Builder { camera: &camera, closed: false, hidden: false, facets: vec![] }; let contours: Vec> = rings.iter().map(|r| r.iter().map(|p| camera.place(*p, 0.0)).collect()).collect(); // A plane is one flat face, seen from either side. Its normal is turned toward the viewer, so // it is drawn last, as a cap is, and planes drawn in one order keep the order they are given in. diff --git a/crates/three-d/src/solid/inflate.rs b/crates/three-d/src/solid/inflate.rs index d80fef1859..4b421c207d 100644 --- a/crates/three-d/src/solid/inflate.rs +++ b/crates/three-d/src/solid/inflate.rs @@ -106,7 +106,7 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64) -> Result let smooth = view.shade && view.has_colored_lights(); let camera = Camera::new(view, bounds, o.depth + 2.0 * height.max(reach)); // Without its back cap the object is a shell open behind, its inside showing. - let mut b = Builder { camera: &camera, closed: o.cap, facets: vec![] }; + let mut b = Builder { camera: &camera, closed: o.cap, hidden: false, facets: vec![] }; let half = o.depth / 2.0; // The back: turned and scaled by the twist and taper, its puff too. let back_turn = Turn::new(bounds, o.twist, o.taper, 1.0); diff --git a/crates/three-d/src/solid/tests.rs b/crates/three-d/src/solid/tests.rs index 0f78aa7123..5f04a0793c 100644 --- a/crates/three-d/src/solid/tests.rs +++ b/crates/three-d/src/solid/tests.rs @@ -76,6 +76,28 @@ fn no_depth_is_the_flat_shape_and_no_cap_shows_the_inside() { assert!(hollow.iter().all(|f| f.contours.len() == 1 && f.contours[0].len() == 4)); } +#[test] +fn hidden_faces_draw_every_face_of_the_solid_behind_the_visible_ones() { + let (p, b) = shape(&square(0.0, 0.0, 100.0)); + let v = View { rotation_x: 20.0, rotation_y: 30.0, ..front() }; + let shown = extrude(&p, FillRule::EvenOdd, b, Extrude::default(), v).unwrap(); + let all = extrude(&p, FillRule::EvenOdd, b, Extrude { hidden: true, ..Extrude::default() }, v).unwrap(); + // A box: the three faces turned to the viewer, then the three turned away, drawn first. + assert_eq!(shown.len(), 3); + assert_eq!(all.len(), 6); + assert!(all.windows(2).all(|w| w[0].depth <= w[1].depth)); + // The faces turned away keep their outward normals, so a light behind the solid lights them. + assert!(all[..3].iter().all(|f| f.normal[2] < 0.0), "{:?}", all.iter().map(|f| f.normal).collect::>()); + for f in shown.iter().chain(&all) { + let [x, y, z] = f.normal; + assert!(close(x.hypot(y).hypot(z), 1.0, 1e-9), "{:?}", f.normal); + } + // The visible faces keep their normals and their place at the front. + for (front, kept) in shown.iter().rev().zip(all.iter().rev()) { + assert_eq!(front.normal, kept.normal); + } +} + #[test] fn taper_shrinks_the_back_and_twist_turns_it() { let (p, b) = shape(&square(0.0, 0.0, 100.0)); @@ -232,6 +254,7 @@ fn malformed_and_degenerate_input_is_bounded() { taper: -3.0, cap: true, bevel: Some(Bevel { width: f64::NAN, height: 1e12, repeat: usize::MAX, space: 7.0, ..Bevel::default() }), + hidden: false, }; let f = extrude(&p, FillRule::EvenOdd, b, wild, View { rotation_x: f64::NAN, perspective: 900.0, ..front() }).unwrap(); assert!(f.iter().flat_map(|f| f.contours.iter().flatten()).all(|q| q.x.is_finite() && q.y.is_finite())); diff --git a/crates/three-d/src/tests.rs b/crates/three-d/src/tests.rs index a164c08fe6..e2b6985fbc 100644 --- a/crates/three-d/src/tests.rs +++ b/crates/three-d/src/tests.rs @@ -1,6 +1,7 @@ use super::*; mod caps; +mod classic; mod lighting; mod multiple_lights; mod smooth; diff --git a/crates/three-d/src/tests/classic.rs b/crates/three-d/src/tests/classic.rs new file mode 100644 index 0000000000..1d807b4a3e --- /dev/null +++ b/crates/three-d/src/tests/classic.rs @@ -0,0 +1,96 @@ +use crate::*; + +const TOWARD: [f64; 3] = [0.0, 0.0, 1.0]; + +fn close(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-9 +} + +fn one(light: [f64; 3], intensity: f64) -> [([f64; 3], f64); 1] { + [(light, intensity)] +} + +#[test] +fn wireframe_and_no_shading_leave_every_face_unlit() { + for surface in [ClassicSurface::Wireframe, ClassicSurface::NoShading] { + let s = ClassicShading { surface, ..ClassicShading::default() }; + for normal in [TOWARD, [1.0, 0.0, 0.0], [0.0, 0.0, -1.0]] { + assert_eq!(s.tone(normal, &one(TOWARD, 1.0)), (1.0, 0.0), "{surface:?}"); + } + } +} + +#[test] +fn diffuse_adds_the_light_to_the_ambient_and_has_no_highlight() { + let s = ClassicShading { surface: ClassicSurface::Diffuse, ambient: 0.3, blend_steps: 256, ..ClassicShading::default() }; + let (lit, spec) = s.tone(TOWARD, &one(TOWARD, 0.4)); + assert!((lit - 0.7).abs() < 1.0 / 256.0, "{lit}"); + assert_eq!(spec, 0.0); + // A face turned away from the light gets the ambient light only. + let (away, _) = s.tone(TOWARD, &one([1.0, 0.0, 0.0], 0.4)); + assert!((away - 0.3).abs() < 1.0 / 256.0, "{away}"); + // A face at 60° to the light gets half of it. + let (half, _) = s.tone(TOWARD, &one([3f64.sqrt() / 2.0, 0.0, 0.5], 0.4)); + assert!((half - 0.5).abs() < 1.0 / 256.0, "{half}"); + // The tone stays within full shadow and full light. + assert_eq!(ClassicShading { ambient: 1.0, ..s }.tone(TOWARD, &one(TOWARD, 1.0)).0, 1.0); + // Without lights a face gets the ambient light only. + assert!((s.tone(TOWARD, &[]).0 - 0.3).abs() < 1.0 / 256.0); +} + +#[test] +fn lights_add_up() { + let s = ClassicShading { surface: ClassicSurface::Diffuse, ambient: 0.0, blend_steps: 256, ..ClassicShading::default() }; + let left = [-0.6, 0.0, 0.8]; + let right = [0.6, 0.0, 0.8]; + let both = s.tone(TOWARD, &[(left, 0.3), (right, 0.3)]).0; + let single = s.tone(TOWARD, &one(left, 0.3)).0; + assert!((both - 2.0 * single).abs() < 2.0 / 256.0, "{both} {single}"); + // A light behind the object lights the faces turned away from the viewer only. + assert_eq!(s.tone(TOWARD, &one([0.0, 0.0, -1.0], 1.0)).0, 0.0); + assert!(s.tone([0.0, 0.0, -1.0], &one([0.0, 0.0, -1.0], 1.0)).0 > 0.99); +} + +#[test] +fn plastic_highlight_peaks_where_a_face_mirrors_the_light_to_the_eye() { + let s = ClassicShading { highlight_intensity: 0.8, blend_steps: 256, ..ClassicShading::default() }; + let light = one([0.6, 0.0, 0.8], 1.0); + // The face halfway between the light and the eye mirrors the light straight to the viewer. + let length = 0.6f64.hypot(1.8); + let half = [0.6 / length, 0.0, 1.8 / length]; + let (_, peak) = s.tone(half, &light); + assert!((peak - 0.8).abs() < 1.0 / 256.0, "{peak}"); + let (_, aside) = s.tone([-0.6, 0.0, 0.8], &light); + assert!(aside < peak / 4.0, "{aside}"); + // A smaller highlight falls off faster. + let tilted = [0.3, 0.0, 0.954]; + let broad = s.tone(tilted, &light).1; + let narrow = ClassicShading { highlight_size: 0.1, ..s }.tone(tilted, &light).1; + assert!(narrow < broad, "{narrow} {broad}"); + // No highlight on a face the light does not reach, without Highlight Intensity, or on Diffuse. + assert_eq!(s.tone(TOWARD, &one([0.0, 0.0, -1.0], 1.0)).1, 0.0); + assert_eq!(ClassicShading { highlight_intensity: 0.0, ..s }.tone(half, &light).1, 0.0); + assert_eq!(ClassicShading { surface: ClassicSurface::Diffuse, ..s }.tone(half, &light).1, 0.0); +} + +#[test] +fn blend_steps_round_the_shading_to_that_many_levels() { + let s = ClassicShading { surface: ClassicSurface::Diffuse, ambient: 0.0, blend_steps: 2, ..ClassicShading::default() }; + let tones: Vec = (0..=20).map(|k| f64::from(k) / 20.0).map(|c| s.tone(TOWARD, &one([(1.0 - c * c).sqrt(), 0.0, c], 0.5)).0).collect(); + assert!(tones.iter().all(|t| close(*t, 0.0) || close(*t, 0.5)), "{tones:?}"); + assert!(tones.iter().any(|t| close(*t, 0.0)) && tones.iter().any(|t| close(*t, 0.5)), "{tones:?}"); + // Out-of-range step counts and intensities are kept within their ranges. + for steps in [0, 100_000] { + let t = ClassicShading { blend_steps: steps, ..s }.tone(TOWARD, &one(TOWARD, f64::NAN)).0; + assert!((0.0..=1.0).contains(&t)); + } +} + +#[test] +fn surfaces_round_trip_through_their_ids() { + for surface in ClassicSurface::ALL { + assert_eq!(ClassicSurface::parse(surface.id()), Some(surface)); + } + assert_eq!(ClassicSurface::parse("glossy"), None); + assert_eq!(ClassicSurface::default(), ClassicSurface::Plastic); +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 43e274505e..8f1656931a 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -120,6 +120,7 @@ pub mod symbolism_options; pub mod tate_chu_yoko; mod text_export; pub mod text_import; +mod three_d_classic; mod tiff_bmp_tga; pub mod tile_edge_color; mod tools; diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index a77d0eed68..38d1f659a4 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -346,15 +346,20 @@ fn choices(effect: &str, key: &str) -> Option { /// The parameters whose dialogs list their values in their own bodies, as (label, value), each /// label as that dialog passes it to its dropdown or radio buttons, which translate it into the UI -/// language: Revolve's edge, Extrude & Bevel's bevel (Rounded translated in the "3d" context -/// first), every Warp style's orientation, Rasterize's Color Model (its `document` value labeled +/// language: Revolve's edge, the bevel of both Extrude & Bevels (Rounded translated in the "3d" +/// context first), Extrude & Bevel (Classic)'s surface and shading color, every Warp style's +/// orientation, Rasterize's Color Model (its `document` value labeled /// CMYK when `cmyk`, for a document in CMYK, and RGB otherwise), Background and Anti-aliasing, and /// the channel of Levels and Curves. pub(super) fn own_choices(effect: &str, key: &str, cmyk: bool) -> Option> { let c3 = |s: &'static str| crate::i18n::tr_ctx(crate::i18n::current(), "3d", s); Some(match (effect, key) { (vectorcraft_effects::REVOLVE, "edge") => vec![(tl!("Left"), "left"), (tl!("Right"), "right")], - (vectorcraft_effects::EXTRUDE, "bevel") => vec![ + (vectorcraft_effects::CLASSIC_EXTRUDE, "surface") => { + vec![(tl!("Wireframe"), "wireframe"), (tl!("No Shading"), "none"), (tl!("Diffuse"), "diffuse"), (tl!("Plastic"), "plastic")] + } + (vectorcraft_effects::CLASSIC_EXTRUDE, "shadingColor") => vec![(tl!("Black"), "black"), (tl!("Custom"), "custom"), (tl!("None"), "none")], + (vectorcraft_effects::EXTRUDE | vectorcraft_effects::CLASSIC_EXTRUDE, "bevel") => vec![ (tl!("None"), "none"), (tl!("Classic"), "classic"), (c3("Rounded"), "rounded"), @@ -915,6 +920,9 @@ mod tests { for (effect, key) in [ (vectorcraft_effects::REVOLVE, "edge"), (vectorcraft_effects::EXTRUDE, "bevel"), + (vectorcraft_effects::CLASSIC_EXTRUDE, "bevel"), + (vectorcraft_effects::CLASSIC_EXTRUDE, "surface"), + (vectorcraft_effects::CLASSIC_EXTRUDE, "shadingColor"), ("warp.arc", "orientation"), ("warp.twist", "orientation"), (vectorcraft_effects::RASTERIZE, "background"), diff --git a/crates/ui-egui/src/dialogs/revolve.rs b/crates/ui-egui/src/dialogs/revolve.rs index 7146117b07..13af7bfef6 100644 --- a/crates/ui-egui/src/dialogs/revolve.rs +++ b/crates/ui-egui/src/dialogs/revolve.rs @@ -1,11 +1,12 @@ -//! Compact controls for the 3D and Materials effects: Extrude & Bevel, Revolve, Inflate and Rotate. -//! The object and the rotation and light gizmos live on the artboard. All document changes run -//! through the effect dialog's existing preview/commit commands. +//! Compact controls for the 3D and Materials effects: Extrude & Bevel, Revolve, Inflate and Rotate, +//! and Extrude & Bevel (Classic), whose own controls are in `three_d_classic`. The object and the +//! rotation and light gizmos live on the artboard. All document changes run through the effect +//! dialog's existing preview/commit commands. use egui::{Align2, FontId, Id, Pos2, Sense, Stroke, vec2}; use serde_json::{Value, json}; use vectorcraft_doc::Unit; -use vectorcraft_effects::{EXTRUDE, INFLATE, REVOLVE, ROTATION_PRESETS}; +use vectorcraft_effects::{CLASSIC_EXTRUDE, EXTRUDE, INFLATE, REVOLVE, ROTATION_PRESETS}; use crate::state::Dialog; use crate::theme::Tokens; @@ -136,14 +137,15 @@ fn controls(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { } /// `s` as the 3D effects mean it (a solid's cap, not a stroke's; a bevelled edge, not a join). -fn c3(s: &'static str) -> &'static str { +pub(super) fn c3(s: &'static str) -> &'static str { crate::i18n::tr_ctx(crate::i18n::current(), "3d", s) } -/// Extrude & Bevel and Inflate: Object, Rotation and Lighting tabs (Rotate has no Object tab). -/// The rotation gizmo shows on the first two, the light gizmo on Lighting. +/// Extrude & Bevel, Inflate and Extrude & Bevel (Classic): Object, Rotation and Lighting tabs +/// (Rotate has no Object tab). The rotation gizmo shows on the first two, the light gizmo on +/// Lighting. fn solid_controls(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, id: &str) { - let object = id == EXTRUDE || id == INFLATE; + let object = id == EXTRUDE || id == INFLATE || id == CLASSIC_EXTRUDE; let mut tabs = vec![]; if object { tabs.push(tl!("Object")); @@ -163,10 +165,16 @@ fn solid_controls(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, id: & } ui.add_space(8.0); if super::revolve_gizmo::lighting(d) { - lighting_controls(ui, d); + if id == CLASSIC_EXTRUDE { + super::three_d_classic::surface_controls(ui, d); + } else { + lighting_controls(ui, d); + } } else if object && d.str("__tab") != "rotation" { let unit = app.session.general_unit(); - if id == EXTRUDE { + if id == CLASSIC_EXTRUDE { + super::three_d_classic::object_controls(ui, d, unit); + } else if id == EXTRUDE { extrude_controls(ui, d, unit); } else { heading(ui, tl!("Object")); @@ -245,7 +253,7 @@ fn view_controls(ui: &mut egui::Ui, d: &mut Dialog) { } /// A dropdown of `options` (value, label) for `key`, with its reset dot. -fn choice(ui: &mut egui::Ui, d: &mut Dialog, key: &str, name: &str, options: &[(Value, &str)]) { +pub(super) fn choice(ui: &mut egui::Ui, d: &mut Dialog, key: &str, name: &str, options: &[(Value, &str)]) { let id = d.str("__effect"); let default = vectorcraft_effects::default_params(&id).and_then(|p| p.get(key).cloned()).unwrap_or(Value::Null); let value = d.fields.get(key).cloned().unwrap_or_else(|| default.clone()); @@ -268,7 +276,7 @@ fn choice(ui: &mut egui::Ui, d: &mut Dialog, key: &str, name: &str, options: &[( } /// A checkbox for `key`, with its reset dot. -fn toggle(ui: &mut egui::Ui, d: &mut Dialog, key: &str, name: &str, default: bool) { +pub(super) fn toggle(ui: &mut egui::Ui, d: &mut Dialog, key: &str, name: &str, default: bool) { ui.horizontal(|ui| { let on = d.bool(key); if widgets::check(ui, name, on, ui.is_enabled()) { @@ -370,11 +378,11 @@ pub(super) fn light_options(d: &Dialog) -> vectorcraft_three_d::Revolve { vectorcraft_effects::revolve_options(&super::form::params(&selected_light(d))) } -fn light_record(d: &Dialog) -> Value { +pub(super) fn light_record(d: &Dialog) -> Value { Value::Object(LIGHT_KEYS.iter().filter_map(|(key, field)| d.fields.get(*field).map(|v| ((*key).into(), v.clone()))).collect()) } -fn store_selected(d: &mut Dialog, selected: &Dialog) { +pub(super) fn store_selected(d: &mut Dialog, selected: &Dialog) { if let Some(list) = explicit_lights(d) { let index = light_index(d, list.len()); let mut list = list.clone(); @@ -397,7 +405,7 @@ pub(super) fn set_light_value(d: &mut Dialog, key: &str, value: Value) { store_selected(d, &selected); } -fn light_list(ui: &mut egui::Ui, d: &mut Dialog) { +pub(super) fn light_list(ui: &mut egui::Ui, d: &mut Dialog) { let mut list = explicit_lights(d).cloned().unwrap_or_else(|| vec![light_record(d)]); let mut index = light_index(d, list.len()); let names: Vec<_> = (1..=list.len()).map(|i| format!("{} {i}", c3("Light"))).collect(); @@ -464,12 +472,12 @@ fn light_color(ui: &mut egui::Ui, d: &mut Dialog) { }); } -fn heading(ui: &mut egui::Ui, text: &str) { +pub(super) fn heading(ui: &mut egui::Ui, text: &str) { let t = Tokens::get(ui.ctx()); ui.label(egui::RichText::new(text).font(crate::theme::semibold(13.0)).color(t.text)); } -fn label(ui: &mut egui::Ui, name: &str) { +pub(super) fn label(ui: &mut egui::Ui, name: &str) { let t = Tokens::get(ui.ctx()); let (r, _) = ui.allocate_exact_size(vec2(LABEL_W, 24.0), Sense::hover()); ui.put(r, egui::Label::new(egui::RichText::new(name).size(12.5).color(t.text)).halign(egui::Align::Min).truncate()).on_hover_text(name); @@ -482,7 +490,7 @@ fn rail_width(ui: &egui::Ui) -> f32 { /// A value can be typed, dragged, scrubbed by its label, or moved on its slider. #[allow(clippy::too_many_arguments)] -fn number(ui: &mut egui::Ui, d: &mut Dialog, key: &str, name: &str, range: (f64, f64), suffix: &str, decimals: usize, unit: Option) { +pub(super) fn number(ui: &mut egui::Ui, d: &mut Dialog, key: &str, name: &str, range: (f64, f64), suffix: &str, decimals: usize, unit: Option) { let default = vectorcraft_effects::default_params(&d.str("__effect")).and_then(|p| p.get(key).and_then(Value::as_f64)).unwrap_or(0.0); let from = |n| unit.map_or(n, |u| u.from_pt(n)); let to = |n| unit.map_or(n, |u| u.to_pt(n)); @@ -570,7 +578,7 @@ fn dot(ui: &egui::Ui, p: Pos2, changed: bool) { } } -fn reset_dot(ui: &mut egui::Ui, key: &str, changed: bool, default: &str) -> bool { +pub(super) fn reset_dot(ui: &mut egui::Ui, key: &str, changed: bool, default: &str) -> bool { let (r, _) = ui.allocate_exact_size(vec2(24.0, 24.0), Sense::hover()); let response = ui.interact(r, Id::unique(("revolve-reset", key)), Sense::click()); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), tl!("Reset to default"))); diff --git a/crates/ui-egui/src/dialogs/revolve/tests.rs b/crates/ui-egui/src/dialogs/revolve/tests.rs index bbaea52552..103fbe6ad0 100644 --- a/crates/ui-egui/src/dialogs/revolve/tests.rs +++ b/crates/ui-egui/src/dialogs/revolve/tests.rs @@ -297,6 +297,68 @@ fn the_other_3d_effects_show_their_options_and_position_presets() { } } +/// Extrude & Bevel (Classic): its extrude and bevel options on the Object tab, Position on the +/// Rotation tab, and the surface with its lights, highlight, blend steps and shading color on the +/// Lighting tab; OK keeps the edit as one undo step. +#[test] +fn classic_extrude_bevel_shows_its_options_and_applies_as_one_step() { + use vectorcraft_effects::CLASSIC_EXTRUDE; + let mut h = Harness::with("M100 100 L200 100 L200 200 L100 200 Z", CLASSIC_EXTRUDE, vec2(1400.0, 1000.0)); + let before = h.app.session.doc().unwrap().doc.clone(); + h.settle(); + for text in ["Depth", "Cap", "Bevel Shape", "Height", "Bevel Inside"] { + h.rect(text); + } + assert!(!h.texts.iter().any(|(t, _)| t == "Twist" || t == "Taper" || t == "Width"), "the newer effect's options stay out"); + assert!(!h.ctx.read_response(Id::unique(("revolve-reset", "bevelHeight"))).unwrap().enabled(), "no bevel: its height is off"); + h.app.ui.dialog.as_mut().unwrap().fields.insert("__tab".into(), json!("rotation")); + h.settle(); + for text in ["Presets", "Rotation X", "Perspective", "Off-Axis Front"] { + h.rect(text); + } + h.click(h.rect("Lighting").center()); + h.settle(); + for text in [ + "Surface", + "Plastic", + "Light Intensity", + "Ambient Light", + "Highlight Intensity", + "Highlight Size", + "Blend Steps", + "Shading Color", + "Draw Hidden Faces", + ] { + h.rect(text); + } + assert!(h.ctx.read_response(Id::unique(("revolve-reset", "highlightSize"))).unwrap().enabled()); + // The light gizmo is on for a lit surface. + assert_eq!(dialogs::revolve_gizmo::hint(h.app.ui.dialog.as_ref().unwrap()), "Drag the light, or its rings. Shift snaps to 15°."); + // Diffuse has no highlight; Wireframe and No Shading take no light. + h.app.ui.dialog.as_mut().unwrap().fields.insert("surface".into(), json!("diffuse")); + h.settle(); + assert!(!h.ctx.read_response(Id::unique(("revolve-reset", "highlightSize"))).unwrap().enabled()); + assert!(h.ctx.read_response(Id::unique(("revolve-reset", "ambient"))).unwrap().enabled()); + h.app.ui.dialog.as_mut().unwrap().fields.insert("surface".into(), json!("wireframe")); + h.settle(); + assert!(!h.ctx.read_response(Id::unique(("revolve-reset", "ambient"))).unwrap().enabled()); + assert!(h.ctx.read_response(Id::unique(("revolve-reset", "drawHiddenFaces"))).unwrap().enabled()); + assert_eq!(dialogs::revolve_gizmo::hint(h.app.ui.dialog.as_ref().unwrap()), "Drag values or labels. Double-click a value to type."); + // A custom shading color shows its color row. + let d = h.app.ui.dialog.as_mut().unwrap(); + d.fields.insert("surface".into(), json!("diffuse")); + d.fields.insert("shadingColor".into(), json!("custom")); + h.settle(); + h.rect("#000000"); + dialogs::confirm(&mut h.app).unwrap(); + let state = h.app.session.doc().unwrap(); + let fx = &state.doc.node(state.selection.objects[0]).unwrap().appearance.effects[0]; + assert_eq!(fx.id, CLASSIC_EXTRUDE); + assert_eq!((fx.params["surface"].clone(), fx.params["shadingColor"].clone()), (json!("diffuse"), json!("custom"))); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc().unwrap().doc, before); +} + #[test] fn extrude_bevel_options_enable_with_a_bevel_shape() { let mut h = Harness::with("M100 100 L200 100 L200 200 L100 200 Z", vectorcraft_effects::EXTRUDE, vec2(1400.0, 1000.0)); diff --git a/crates/ui-egui/src/dialogs/revolve_gizmo.rs b/crates/ui-egui/src/dialogs/revolve_gizmo.rs index c9194d5d02..6ef51d38ed 100644 --- a/crates/ui-egui/src/dialogs/revolve_gizmo.rs +++ b/crates/ui-egui/src/dialogs/revolve_gizmo.rs @@ -20,8 +20,18 @@ pub(crate) fn lighting(d: &Dialog) -> bool { d.str("__gizmo") == "light" } +/// Does the effect take light: Shading on, or for Extrude & Bevel (Classic) a Diffuse or Plastic +/// surface? +fn lit(d: &Dialog) -> bool { + if d.str("__effect") == vectorcraft_effects::CLASSIC_EXTRUDE { + matches!(d.str("surface").as_str(), "diffuse" | "plastic") + } else { + d.bool("shade") + } +} + pub(crate) fn hint(d: &Dialog) -> &'static str { - if !d.bool("preview") || (lighting(d) && !d.bool("shade")) { + if !d.bool("preview") || (lighting(d) && !lit(d)) { tl!("Drag values or labels. Double-click a value to type.") } else if lighting(d) { tl!("Drag the light, or its rings. Shift snaps to 15°.") @@ -190,7 +200,7 @@ fn snap_height(height: f64, snap: bool) -> f64 { pub(super) fn show(app: &VectorcraftApp, ctx: &egui::Context, d: &mut Dialog) { let light_mode = lighting(d); - if !d.bool("preview") || (light_mode && !d.bool("shade")) { + if !d.bool("preview") || (light_mode && !lit(d)) { clear(ctx); return; } diff --git a/crates/ui-egui/src/dialogs/three_d_classic.rs b/crates/ui-egui/src/dialogs/three_d_classic.rs new file mode 100644 index 0000000000..06d034fce4 --- /dev/null +++ b/crates/ui-egui/src/dialogs/three_d_classic.rs @@ -0,0 +1,85 @@ +//! Extrude & Bevel (Classic)'s own controls in the compact 3D dialog: the extrude and bevel options +//! on the Object tab, and the surface with its lights, highlight, blend steps and shading color on +//! the Lighting tab. Position (presets, rotation, perspective) is the Rotation tab every 3D effect +//! shares. + +use serde_json::{Value, json}; +use vectorcraft_doc::Unit; +use vectorcraft_effects::CLASSIC_EXTRUDE; + +use super::revolve::{c3, choice, heading, label, light_list, light_record, number, reset_dot, selected_light, store_selected, toggle}; +use crate::state::Dialog; + +/// Depth and cap, then the bevel: its shape, its height and whether it is added around the shape +/// or carved into it. +pub(super) fn object_controls(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) { + heading(ui, tl!("Object")); + number(ui, d, "depth", tl!("Depth"), (0.0, 2000.0), "", 1, Some(unit)); + choice(ui, d, "cap", c3("Cap"), &[(json!(true), c3("Solid")), (json!(false), c3("Hollow"))]); + ui.add_space(10.0); + heading(ui, c3("Bevel")); + choice(ui, d, "bevel", tl!("Bevel Shape"), &options("bevel")); + ui.add_enabled_ui(d.str("bevel") != "none", |ui| { + number(ui, d, "bevelHeight", tl!("Height"), (1.0, 100.0), "", 1, Some(unit)); + toggle(ui, d, "bevelInside", tl!("Bevel Inside"), false); + }); +} + +/// The surface, then for Diffuse and Plastic the lights, Ambient Light, the highlight (Plastic +/// only), Blend Steps and Shading Color; Draw Hidden Faces last. +pub(super) fn surface_controls(ui: &mut egui::Ui, d: &mut Dialog) { + choice(ui, d, "surface", tl!("Surface"), &options("surface")); + let surface = d.str("surface"); + ui.add_enabled_ui(surface == "diffuse" || surface == "plastic", |ui| { + light_list(ui, d); + let mut selected = selected_light(d); + let before = light_record(&selected); + number(ui, &mut selected, "lightIntensity", tl!("Light Intensity"), (0.0, 100.0), "%", 1, None); + number(ui, &mut selected, "lightRotation", tl!("Rotation"), (-180.0, 180.0), "°", 1, None); + number(ui, &mut selected, "lightHeight", tl!("Height"), (0.0, 90.0), "°", 1, None); + toggle(ui, &mut selected, "lightBehind", tl!("Light behind the object"), false); + if light_record(&selected) != before { + store_selected(d, &selected); + } + number(ui, d, "ambient", tl!("Ambient Light"), (0.0, 100.0), "%", 1, None); + ui.add_enabled_ui(surface == "plastic", |ui| { + number(ui, d, "highlightIntensity", tl!("Highlight Intensity"), (0.0, 100.0), "%", 1, None); + number(ui, d, "highlightSize", tl!("Highlight Size"), (0.0, 100.0), "%", 1, None); + }); + number(ui, d, "blendSteps", tl!("Blend Steps"), (1.0, 256.0), "", 0, None); + choice(ui, d, "shadingColor", tl!("Shading Color"), &options("shadingColor")); + if d.str("shadingColor") == "custom" { + shading_custom(ui, d); + } + }); + toggle(ui, d, "drawHiddenFaces", tl!("Draw Hidden Faces"), false); +} + +/// The values of Extrude & Bevel (Classic)'s `key` as the dropdowns list them, (value, label). +fn options(key: &str) -> Vec<(Value, &'static str)> { + super::effect::own_choices(CLASSIC_EXTRUDE, key, false).unwrap_or_default().into_iter().map(|(label, value)| (json!(value), label)).collect() +} + +/// The custom shading color: a color button, its hex value and its reset dot. +fn shading_custom(ui: &mut egui::Ui, d: &mut Dialog) { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 6.0; + label(ui, tl!("Color")); + let color = d + .fields + .get("shadingCustom") + .and_then(Value::as_str) + .filter(|s| s.len() == 7 && s.starts_with('#')) + .and_then(vectorcraft_color::Color::from_hex) + .unwrap_or(vectorcraft_color::Color::BLACK); + let mut rgb = color.to_rgb_uncalibrated().map(|c| (c * 255.0).round() as u8); + if ui.color_edit_button_srgb(&mut rgb).on_hover_text(tl!("Shading Color")).changed() { + d.fields.insert("shadingCustom".into(), json!(format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2]))); + } + ui.label(format!("#{:02X}{:02X}{:02X}", rgb[0], rgb[1], rgb[2])); + ui.add_space((ui.available_width() - 24.0).max(0.0)); + if reset_dot(ui, "shadingCustom", rgb != [0; 3], "#000000") { + d.fields.insert("shadingCustom".into(), json!("#000000")); + } + }); +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index f6a8debdc7..b95bfc13ed 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1079,6 +1079,17 @@ font-technology Variable Променливи Exporting {} Експортиране на {} Export… Експортиране… Extrude & Bevel… Избутване и фасетка… + 3D (Classic) 3D (класически) + Extrude & Bevel (Classic)… Избутване и фасетка (класически)… + Surface Повърхност + Wireframe Телена рамка + No Shading Без засенчване + Plastic Пластмаса + Highlight Intensity Интензивност на отблясъка + Highlight Size Размер на отблясъка + Blend Steps Стъпки на преливане + Shading Color Цвят на засенчването + Draw Hidden Faces Изчертаване на скритите страни Eyedropper Пипета Eyedropper Applies: Пипетата прилага: Eyedropper Options Опции за пипетата diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index a8db1ebeaf..b11a403b85 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -449,6 +449,17 @@ Vector Effects Vektorski efekti 3D and Materials 3D i materijali Extrude & Bevel… Istiskivanje i zakošenje… + 3D (Classic) 3D (klasično) + Extrude & Bevel (Classic)… Istiskivanje i zakošenje (klasično)… + Surface Površina + Wireframe Žičani model + No Shading Bez sjenčenja + Plastic Plastika + Highlight Intensity Intenzitet odsjaja + Highlight Size Veličina odsjaja + Blend Steps Koraci prelaza + Shading Color Boja sjenčenja + Draw Hidden Faces Crtaj skrivene strane Revolve… Rotaciono tijelo… Inflate… Napuhni… Materials… Materijali… diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 3898a677f4..811c937b6e 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1492,6 +1492,17 @@ Exporting {} S’està exportant {} Export… Exporta… Extrude & Bevel… Extrudeix i bisella… + 3D (Classic) 3D (clàssic) + Extrude & Bevel (Classic)… Extrudeix i bisella (clàssic)… + Surface Superfície + Wireframe Filferro + No Shading Sense ombra + Plastic Plàstic + Highlight Intensity Intensitat de la brillantor + Highlight Size Mida de la brillantor + Blend Steps Passos de fusió + Shading Color Color de l’ombra + Draw Hidden Faces Dibuixa les cares ocultes Eyedropper Comptagotes Eyedropper Applies: El comptagotes aplica: Eyedropper Options Opcions del comptagotes diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index eff1d2d343..4cc191dd93 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -457,6 +457,17 @@ Vector Effects Vektorové efekty 3D and Materials 3D a materiály Extrude & Bevel… Vysunutí a zkosení… + 3D (Classic) 3D (klasické) + Extrude & Bevel (Classic)… Vysunutí a zkosení (klasické)… + Surface Povrch + Wireframe Drátový model + No Shading Bez stínování + Plastic Plast + Highlight Intensity Intenzita odlesku + Highlight Size Velikost odlesku + Blend Steps Kroky prolnutí + Shading Color Barva stínování + Draw Hidden Faces Kreslit skryté stěny Revolve… Rotační těleso… Inflate… Nafouknutí… Materials… Materiály… diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index abfe581e70..67b9fd42dd 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -415,6 +415,17 @@ Vector Effects Vektoreffekter 3D and Materials 3D og materialer Extrude & Bevel… Ekstrudér og facet… + 3D (Classic) 3D (klassisk) + Extrude & Bevel (Classic)… Ekstrudér og facet (klassisk)… + Surface Overflade + Wireframe Trådmodel + No Shading Ingen skyggelægning + Plastic Plastik + Highlight Intensity Højlysintensitet + Highlight Size Højlysstørrelse + Blend Steps Overgangstrin + Shading Color Skyggefarve + Draw Hidden Faces Tegn skjulte flader Revolve… Omdrej… Inflate… Pust op… Materials… Materialer… diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 4a4142d883..1bedbc649d 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1079,6 +1079,17 @@ font-technology Variable Variabel Exporting {} {} wird exportiert Export… Exportieren… Extrude & Bevel… Extrudieren und abgeflachte Kante… + 3D (Classic) 3D (klassisch) + Extrude & Bevel (Classic)… Extrudieren und abgeflachte Kante (klassisch)… + Surface Oberfläche + Wireframe Drahtmodell + No Shading Keine Schattierung + Plastic Kunststoff + Highlight Intensity Glanzpunktintensität + Highlight Size Glanzpunktgröße + Blend Steps Angleichungsstufen + Shading Color Schattierungsfarbe + Draw Hidden Faces Verdeckte Flächen zeichnen Eyedropper Pipette Sample Color from Screen Farbe vom Bildschirm aufnehmen This system has no screen color sampler Dieses System hat keine Farbaufnahme vom Bildschirm diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 6b2a022d58..c633b775d5 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1052,6 +1052,17 @@ font-technology Variable Μεταβλητές Exporting {} Εξαγωγή {} Export… Εξαγωγή… Extrude & Bevel… Εξώθηση και λοξότμηση… + 3D (Classic) 3D (κλασικό) + Extrude & Bevel (Classic)… Εξώθηση και λοξότμηση (κλασικό)… + Surface Επιφάνεια + Wireframe Συρματόπλεγμα + No Shading Χωρίς σκίαση + Plastic Πλαστικό + Highlight Intensity Ένταση ανταύγειας + Highlight Size Μέγεθος ανταύγειας + Blend Steps Βήματα ανάμειξης + Shading Color Χρώμα σκίασης + Draw Hidden Faces Σχεδίαση κρυφών εδρών Eyedropper Σταγονόμετρο (Eyedropper Tool) Eyedropper Applies: Το σταγονόμετρο εφαρμόζει: Eyedropper Options Επιλογές σταγονόμετρου diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 6ccd50b466..1ff0790d54 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1108,6 +1108,17 @@ font-technology Variable Variables Exporting {} Exportando {} Export… Exportar… Extrude & Bevel… Extrusión y biselado… + 3D (Classic) 3D (clásico) + Extrude & Bevel (Classic)… Extrusión y biselado (clásico)… + Surface Superficie + Wireframe Malla + No Shading Sin sombreado + Plastic Plástico + Highlight Intensity Intensidad del brillo + Highlight Size Tamaño del brillo + Blend Steps Pasos de fusión + Shading Color Color de sombreado + Draw Hidden Faces Dibujar caras ocultas Eyedropper Cuentagotas Sample Color from Screen Tomar color de la pantalla This system has no screen color sampler Este sistema no tiene muestreador de color de la pantalla diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 3cf8607c0b..31dc319278 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -454,6 +454,17 @@ Vector Effects Vektoritehosteet 3D and Materials 3D ja materiaalit Extrude & Bevel… Pursota ja viistä… + 3D (Classic) 3D (perinteinen) + Extrude & Bevel (Classic)… Pursota ja viistä (perinteinen)… + Surface Pinta + Wireframe Rautalanka + No Shading Ei varjostusta + Plastic Muovi + Highlight Intensity Kiillon voimakkuus + Highlight Size Kiillon koko + Blend Steps Sulautusvaiheet + Shading Color Varjostusväri + Draw Hidden Faces Piirrä piilotetut pinnat Revolve… Pyöräytä… Inflate… Täytä ilmalla… Materials… Materiaalit… diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 67a7cb29c8..8d7fa4b70a 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1103,6 +1103,17 @@ font-technology Variable Variables Exporting {} Exportation de {} Export… Exporter… Extrude & Bevel… Extrusion et biseautage… + 3D (Classic) 3D (classique) + Extrude & Bevel (Classic)… Extrusion et biseautage (classique)… + Surface Surface + Wireframe Fil de fer + No Shading Sans ombrage + Plastic Plastique + Highlight Intensity Intensité de la brillance + Highlight Size Taille de la brillance + Blend Steps Étapes de transition + Shading Color Couleur d’ombrage + Draw Hidden Faces Dessiner les faces cachées Eyedropper Pipette Sample Color from Screen Prélever une couleur à l’écran This system has no screen color sampler Ce système n’a pas d’outil de prélèvement de couleur à l’écran diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e1af82a3a9..bda7cd219f 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -1665,6 +1665,17 @@ Extension Lines एक्सटेंशन लाइन Extension: विस्तार: Extrude & Bevel… एक्सट्रूडेड और बेवेल… + 3D (Classic) 3D (क्लासिक) + Extrude & Bevel (Classic)… एक्सट्रूडेड और बेवेल (क्लासिक)… + Surface सतह + Wireframe वायरफ़्रेम + No Shading कोई शेडिंग नहीं + Plastic प्लास्टिक + Highlight Intensity हाइलाइट तीव्रता + Highlight Size हाइलाइट आकार + Blend Steps ब्लेंड चरण + Shading Color शेडिंग रंग + Draw Hidden Faces छिपे हुए फलक बनाएँ Eyedropper आईड्रॉपर Eyedropper Applies: आईड्रॉपपर लागू होता है: Eyedropper Options आईड्रॉपर ऑप्शन्स diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 82f75da721..bbb808b73a 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1388,6 +1388,17 @@ font-technology Variable Változó Exporting {} Exportálás: {} Export… Exportálás… Extrude & Bevel… Kihúzás és élletörés… + 3D (Classic) 3D (klasszikus) + Extrude & Bevel (Classic)… Kihúzás és élletörés (klasszikus)… + Surface Felület + Wireframe Drótváz + No Shading Nincs árnyékolás + Plastic Műanyag + Highlight Intensity Csillanás erőssége + Highlight Size Csillanás mérete + Blend Steps Átmenetlépések + Shading Color Árnyékolás színe + Draw Hidden Faces Rejtett lapok rajzolása Eyedropper Pipetta Sample Color from Screen Szín mintavétele a képernyőről This system has no screen color sampler Ezen a rendszeren nincs képernyős színmintavevő diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 7230b6bfa5..70b8fca6d6 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -415,6 +415,17 @@ Vector Effects Efek vektor 3D and Materials 3D dan material Extrude & Bevel… Ekstrusi & bevel… + 3D (Classic) 3D (klasik) + Extrude & Bevel (Classic)… Ekstrusi & bevel (klasik)… + Surface Permukaan + Wireframe Kerangka kawat + No Shading Tanpa pengarsiran + Plastic Plastik + Highlight Intensity Intensitas kilau + Highlight Size Ukuran kilau + Blend Steps Langkah campuran + Shading Color Warna pengarsiran + Draw Hidden Faces Gambar sisi tersembunyi Revolve… Revolusi… Inflate… Gelembungkan… Materials… Material… diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 723fa4ab08..6d2b7fd148 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1109,6 +1109,17 @@ font-technology Variable Variabili Exporting {} Esportazione di {} in corso Export… Esporta… Extrude & Bevel… Estrusione e smusso… + 3D (Classic) 3D (classico) + Extrude & Bevel (Classic)… Estrusione e smusso (classico)… + Surface Superficie + Wireframe Reticolo + No Shading Nessuna ombreggiatura + Plastic Plastica + Highlight Intensity Intensità lucentezza + Highlight Size Dimensione lucentezza + Blend Steps Passaggi di fusione + Shading Color Colore ombreggiatura + Draw Hidden Faces Disegna facce nascoste Eyedropper Contagocce Sample Color from Screen Campiona colore dallo schermo This system has no screen color sampler Questo sistema non ha un campionatore di colore dello schermo diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 8bb1012693..77e5ac59a4 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -488,6 +488,17 @@ digits Malayalam マラヤーラム数字 Vector Effects ベクター効果 3D and Materials 3D とマテリアル Extrude & Bevel… 押し出しとベベル… + 3D (Classic) 3D(クラシック) + Extrude & Bevel (Classic)… 押し出しとベベル(クラシック)… + Surface 表面 + Wireframe ワイヤーフレーム + No Shading 陰影なし + Plastic プラスチック + Highlight Intensity ハイライトの強さ + Highlight Size ハイライトのサイズ + Blend Steps ブレンドの階調 + Shading Color 陰影のカラー + Draw Hidden Faces 隠れた面を描画 Revolve… 回転体… Inflate… 膨張… Materials… マテリアル… diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 343b415a48..46385a71bd 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -381,6 +381,17 @@ Vector Effects ვექტორული ეფექტები 3D and Materials 3D და მასალები Extrude & Bevel… ამოწევა და წაკვეთა… + 3D (Classic) 3D (კლასიკური) + Extrude & Bevel (Classic)… ამოწევა და წაკვეთა (კლასიკური)… + Surface ზედაპირი + Wireframe მავთულის ჩარჩო + No Shading დაჩრდილვის გარეშე + Plastic პლასტიკური + Highlight Intensity ელვარების ინტენსივობა + Highlight Size ელვარების ზომა + Blend Steps შერევის საფეხურები + Shading Color დაჩრდილვის ფერი + Draw Hidden Faces დამალული წახნაგების დახატვა Revolve… ბრუნვა… Inflate… გაბერვა… Materials… მასალები… diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index f4cc45b827..c892240011 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -481,6 +481,17 @@ digits Malayalam 말라얄람어 Vector Effects 벡터 효과 3D and Materials 3D 및 재질 Extrude & Bevel… 돌출 및 경사… + 3D (Classic) 3D(클래식) + Extrude & Bevel (Classic)… 돌출 및 경사(클래식)… + Surface 표면 + Wireframe 와이어프레임 + No Shading 셰이딩 없음 + Plastic 플라스틱 + Highlight Intensity 하이라이트 강도 + Highlight Size 하이라이트 크기 + Blend Steps 혼합 단계 + Shading Color 셰이딩 색상 + Draw Hidden Faces 숨겨진 면 그리기 Revolve… 회전체… Inflate… 부풀리기… Materials… 재질… diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 2e8d6f34c3..cb54cffb49 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -429,6 +429,17 @@ Vector Effects Vectoreffecten 3D and Materials 3D en materialen Extrude & Bevel… Extruderen en afschuinen… + 3D (Classic) 3D (klassiek) + Extrude & Bevel (Classic)… Extruderen en afschuinen (klassiek)… + Surface Oppervlak + Wireframe Draadmodel + No Shading Geen arcering + Plastic Plastic + Highlight Intensity Glansintensiteit + Highlight Size Glansgrootte + Blend Steps Overvloeistappen + Shading Color Arceringskleur + Draw Hidden Faces Verborgen vlakken tekenen Revolve… Draaien… Inflate… Opblazen… Materials… Materialen… diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index c9e1256c3e..0972f8ebf2 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -417,6 +417,17 @@ Vector Effects Efekty wektorowe 3D and Materials 3D i materiały Extrude & Bevel… Wyciągnięcie i fazowanie… + 3D (Classic) 3D (klasyczne) + Extrude & Bevel (Classic)… Wyciągnięcie i fazowanie (klasyczne)… + Surface Powierzchnia + Wireframe Szkielet + No Shading Bez cieniowania + Plastic Plastik + Highlight Intensity Intensywność połysku + Highlight Size Rozmiar połysku + Blend Steps Kroki przejścia + Shading Color Kolor cieniowania + Draw Hidden Faces Rysuj ukryte ściany Revolve… Obrót… Inflate… Nadmuchanie… Materials… Materiały… diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 062b7d88b4..de3b6bad26 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1001,6 +1001,17 @@ Export: Exportar: Export… Exportar… Extrude & Bevel… Extrusão e Bisel… + 3D (Classic) 3D (Clássico) + Extrude & Bevel (Classic)… Extrusão e Bisel (Clássico)… + Surface Superfície + Wireframe Aramado + No Shading Sem Sombreamento + Plastic Plástico + Highlight Intensity Intensidade do Realce + Highlight Size Tamanho do Realce + Blend Steps Etapas de Mesclagem + Shading Color Cor do Sombreamento + Draw Hidden Faces Desenhar Faces Ocultas Eyedropper Conta-gotas Eyedropper Applies: O Conta-gotas Aplica: Eyedropper Options Opções do Conta-gotas diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index a83d9edf36..6c8d9e3c77 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1106,6 +1106,17 @@ font-technology Variable Вариативные Exporting {} Экспорт {} Export… Экспорт… Extrude & Bevel… Выдавливание и фаска… + 3D (Classic) 3D (классические) + Extrude & Bevel (Classic)… Выдавливание и фаска (классическое)… + Surface Поверхность + Wireframe Каркас + No Shading Без затенения + Plastic Пластик + Highlight Intensity Интенсивность блика + Highlight Size Размер блика + Blend Steps Шаги перехода + Shading Color Цвет затенения + Draw Hidden Faces Рисовать скрытые грани Eyedropper Пипетка Sample Color from Screen Взять цвет с экрана This system has no screen color sampler В этой системе нет средства выбора цвета с экрана diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 780d23beae..bb06265405 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1087,6 +1087,17 @@ font-technology Variable Variabla Exporting {} Exporterar {} Export… Exportera… Extrude & Bevel… Extrudera och fasa… + 3D (Classic) 3D (klassisk) + Extrude & Bevel (Classic)… Extrudera och fasa (klassisk)… + Surface Yta + Wireframe Trådram + No Shading Ingen skuggning + Plastic Plast + Highlight Intensity Högdagerintensitet + Highlight Size Högdagerstorlek + Blend Steps Övergångssteg + Shading Color Skuggningsfärg + Draw Hidden Faces Rita dolda ytor Eyedropper Pipett Eyedropper Applies: Pipetten tillämpar: Eyedropper Options Pipettalternativ diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 55a9cdc737..908872b500 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1079,6 +1079,17 @@ font-technology Variable Değişken Exporting {} {} dışa aktarılıyor Export… İhracat… Extrude & Bevel… Ekstrüzyon ve Eğim… + 3D (Classic) 3D (Klasik) + Extrude & Bevel (Classic)… Ekstrüzyon ve Eğim (Klasik)… + Surface Yüzey + Wireframe Tel Kafes + No Shading Gölgeleme Yok + Plastic Plastik + Highlight Intensity Parlama Yoğunluğu + Highlight Size Parlama Boyutu + Blend Steps Karışım Adımları + Shading Color Gölgeleme Rengi + Draw Hidden Faces Gizli Yüzleri Çiz Eyedropper Damlalık Sample Color from Screen Ekrandan Örnek Renk This system has no screen color sampler Bu sistemin ekran rengi örnekleyicisi yok diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index bbfc332f91..0690a9362f 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1103,6 +1103,17 @@ font-technology Variable Варіативні Exporting {} Експорт {} Export… Експорт… Extrude & Bevel… Видавлювання та фаска… + 3D (Classic) 3D (класичні) + Extrude & Bevel (Classic)… Видавлювання та фаска (класичне)… + Surface Поверхня + Wireframe Каркас + No Shading Без затінення + Plastic Пластик + Highlight Intensity Інтенсивність відблиску + Highlight Size Розмір відблиску + Blend Steps Кроки переходу + Shading Color Колір затінення + Draw Hidden Faces Малювати приховані грані Eyedropper Піпетка Sample Color from Screen Взяти колір з екрана This system has no screen color sampler У цій системі немає засобу вибору кольору з екрана diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 47915fb171..3df8d6f2c8 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1265,6 +1265,17 @@ font-technology Variable Biến thiên Exporting {} Đang xuất {} Export… Xuất… Extrude & Bevel… Kéo dài & vát… + 3D (Classic) 3D (cổ điển) + Extrude & Bevel (Classic)… Kéo dài & vát (cổ điển)… + Surface Bề mặt + Wireframe Khung dây + No Shading Không tô bóng + Plastic Nhựa + Highlight Intensity Cường độ điểm sáng + Highlight Size Kích thước điểm sáng + Blend Steps Số bước hòa trộn + Shading Color Màu tô bóng + Draw Hidden Faces Vẽ các mặt ẩn Eyedropper Ống hút màu Sample Color from Screen Lấy mẫu màu từ màn hình This system has no screen color sampler Hệ thống này không có công cụ lấy mẫu màu trên màn hình diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index e646c956bb..46ea58b15f 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1049,6 +1049,17 @@ Exporting {} 正在导出 {} Export… 导出… Extrude & Bevel… 突出与斜角… + 3D (Classic) 3D (经典) + Extrude & Bevel (Classic)… 突出与斜角 (经典)… + Surface 表面 + Wireframe 线框 + No Shading 无底纹 + Plastic 塑料 + Highlight Intensity 高光强度 + Highlight Size 高光大小 + Blend Steps 混合步骤 + Shading Color 底纹颜色 + Draw Hidden Faces 绘制隐藏表面 Eyedropper 吸管 Sample Color from Screen 从屏幕取样颜色 This system has no screen color sampler 此系统没有屏幕取色工具 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 468ad851aa..36f3c4511b 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1073,6 +1073,17 @@ font-technology Variable 可變 Exporting {} 正在匯出 {} Export… 匯出… Extrude & Bevel… 突出與斜角… + 3D (Classic) 3D (經典) + Extrude & Bevel (Classic)… 突出與斜角 (經典)… + Surface 表面 + Wireframe 線框 + No Shading 無網底 + Plastic 塑膠 + Highlight Intensity 亮部強度 + Highlight Size 亮部大小 + Blend Steps 漸變階數 + Shading Color 網底顏色 + Draw Hidden Faces 繪製隱藏表面 Eyedropper 滴管 Sample Color from Screen 從螢幕取樣顏色 This system has no screen color sampler 此系統沒有螢幕取色工具 diff --git a/crates/ui-egui/src/menus/submenus.rs b/crates/ui-egui/src/menus/submenus.rs index a878f7f0cc..76fb47e90c 100644 --- a/crates/ui-egui/src/menus/submenus.rs +++ b/crates/ui-egui/src/menus/submenus.rs @@ -108,6 +108,9 @@ pub(super) fn font_items(english_names: bool) -> Vec { items.3.clone() } +/// The catalogue's menu path of the effects in 3D and Materials › 3D (Classic). +const CLASSIC_3D: &[&str] = &["Effect", "3D and Materials", "3D (Classic)"]; + /// The raster effects' submenus of the Effect menu (the Photoshop-style effects, below the /// vector effects): (submenu, the catalogue's menu path of its effects). /// The raster Stylize submenu shares its path with the vector one and lists only the effects at @@ -190,6 +193,10 @@ pub(super) fn effect_menu() -> Vec { _ => 9, }); items.push(todo("Materials…")); + let classic: Vec = cat.iter().filter(|e| e.menu == CLASSIC_3D).map(item).collect(); + if !classic.is_empty() { + items.push(sub("3D (Classic)", classic)); + } } out.push(sub(sub_name, items)); } @@ -210,7 +217,9 @@ pub(super) fn effect_menu() -> Vec { out.extend(raster); } // Anything not placed above (future effects) still shows up. - let placed = |e: &vectorcraft_effects::EffectInfo| top_level(e) || in_vector_menu(e) || RASTER_MENUS.iter().any(|(_, path)| e.menu == *path); + let placed = |e: &vectorcraft_effects::EffectInfo| { + top_level(e) || in_vector_menu(e) || e.menu == CLASSIC_3D || RASTER_MENUS.iter().any(|(_, path)| e.menu == *path) + }; for e in cat.iter().filter(|e| !placed(e)) { out.push(Item::Cmd(e.label, "effect.dialog", json!({ "effect": e.id }))); } diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 3918b9fb1c..82c8e809f5 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -354,6 +354,22 @@ fn saved_views_store_and_restore_the_view() { assert!(!menu_entries(&app).iter().any(|e| e.command.as_deref() == Some("view.goto2"))); } +/// Effect › 3D and Materials › 3D (Classic) › Extrude & Bevel (Classic)… opens its effect dialog, +/// after Materials…, and nowhere else. +#[test] +fn classic_extrude_bevel_is_in_the_3d_classic_submenu() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let entries = menu_entries(&app); + let classic: Vec<_> = entries.iter().filter(|e| e.params.get("effect").and_then(Value::as_str) == Some("threeD.classicExtrude")).collect(); + assert_eq!(classic.len(), 1, "listed once"); + let e = classic[0]; + assert_eq!(e.path, ["Effect", "3D and Materials", "3D (Classic)"]); + assert_eq!((e.label.as_str(), e.command.as_deref()), ("Extrude & Bevel (Classic)…", Some("effect.dialog"))); + let at = |label: &str| entries.iter().position(|x| x.label == label && x.path.get(1).is_some_and(|p| p == "3D and Materials")); + assert!(at("Materials…").unwrap() < at("Extrude & Bevel (Classic)…").unwrap()); +} + /// A document's 25 views are all listed at the bottom of the View menu, by name, and the last /// one brings back its zoom, centre and rotation after the view changed. #[test] diff --git a/docs/effects-parity.md b/docs/effects-parity.md index 2307add80e..66e1b713e6 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -181,7 +181,7 @@ VectorCraft choices; an original approximation, never compared with another appl | Revolve | initial: live, editable profile, rotation and light gizmos, default-on Cap with continuous curved rims, smooth vector shading and round seam joins, SVG/PDF output, Expand Appearance ([revolve.md](revolve.md), #846) | | Extrude & Bevel, Inflate, Rotate | initial: live, depth, twist, taper, solid or hollow caps, five original bevel shapes, Inflate volume, both sides, twist, taper and cap, Rotate of every fill and stroke, groups and layers turned about one shared axis (#4506), Position presets, rotation and light gizmos, SVG/PDF output, Expand Appearance ([three-d.md](three-d.md)) | | Materials panel, lighting, ray-traced render | one to ten directional lights with per-light Color (opaque RGB, white by default), Intensity, Rotation, Height, Softness and neutral Ambient Light, Revolve and colored Inflate use smooth vector shading; Extrude & Bevel and Rotate retain planar shading; original Standard, Diffuse, Top Left and Right lighting rigs; no materials, shadows or ray tracing | -| 3D (Classic): Extrude & Bevel, Revolve, Rotate | none | +| 3D (Classic): Extrude & Bevel, Revolve, Rotate | Extrude & Bevel (Classic) initial: live, Extrude Depth, Cap, five original bevel shapes with Height and Bevel Extent In or Out, Position presets and rotation gizmo, Perspective, Wireframe, No Shading, Diffuse and Plastic surfaces with one to ten lights, Light Intensity, Ambient Light, Highlight Intensity and Size, Blend Steps, Black, Custom or no Shading Color, Draw Hidden Faces ([create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html)); Revolve (Classic), Rotate (Classic) and Map Art: none | | Turntable (30.0 beta) | none | | Export 3D objects (OBJ, USDA, glTF) | none | diff --git a/docs/mcp.md b/docs/mcp.md index 1adcf32b1b..168c377b86 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2165,6 +2165,33 @@ All three take `rotationX/Y/Z` (degrees, -180..180, default the Off-Axis Front p `perspectiveAngle` and the lighting parameters as Revolve. See [three-d.md](three-d.md) for the Position presets, the scope and what differs from the public documentation. +## Extrude & Bevel (Classic) + +`effect.apply {effect: "threeD.classicExtrude", params: {...}, ids?, item?}` is Effect › 3D and Materials › +3D (Classic) › Extrude & Bevel (Classic)…. It builds the same solid as `threeD.extrude` and draws its faces with the +classic surfaces. Parameters: `depth` (points, 0..2000, default 50), `cap` (true solid, false hollow), `bevel` (`none`, +`classic`, `rounded`, `cove`, `step`, `ogee`), `bevelHeight` (points, 1..100, default 4; the bevel is as wide as it +is tall), `bevelInside` (false adds the bevel around the shape, true carves it into the shape), `rotationX/Y/Z` and +`perspectiveAngle` as above, and the surface: + +- `surface`: `wireframe` (the edges of every face, hidden faces included, with no fill), `none` (the art's own paint, + unlit), `diffuse` (soft light) or `plastic` (soft light plus a highlight; the default). +- `lightRotation`, `lightHeight`, `lightBehind` and `lightIntensity` (0..100%, default 100) place one light, or + `lights` holds one to ten (`intensity`, `rotation`, `height`, `behind`; their light adds up, and `color` and + `softness` are not used). `ambient` (0..100%, default 50) lights every face. +- `highlightIntensity` (0..100%, default 60) and `highlightSize` (0..100%, default 90; 100 is broad) shape the Plastic + highlight. `blendSteps` (whole number, 1..256, default 25) is how many levels the shading is rounded to. +- `shadingColor`: `black` (the default), `custom` (darkens toward `shadingCustom`, a `#rrggbb` color) or `none` (the + paint is kept and only the highlight lightens it). `drawHiddenFaces` also draws the faces turned away from the + viewer, behind the others. + +The defaults are VectorCraft's own. An unknown parameter, a number out of range, a flag that is not true or false, or +an unknown surface or shading color is refused with an error and the document is not changed. + +```json +{"name":"run_command","arguments":{"command":"effect.apply","params":{"effect":"threeD.classicExtrude","item":null,"params":{"depth":40,"bevel":"rounded","bevelHeight":6,"surface":"diffuse","blendSteps":64}}}} +``` + ## Edit Colors and Recolor Artwork From 20accc594320e88e74c31c8a3d52b15576507328 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 7 Nov 2026 16:00:09 -0800 Subject: [PATCH 05/11] Docs: 3D remaining-work lists name what 3D (Classic) still lacks Extrude & Bevel (Classic) ships, so the remaining-work lists in effects-parity.md, gaps.md (G3), target-app-parity.md and three-d.md name Revolve (Classic), Rotate (Classic) and Map Art instead of all of 3D Classic. --- docs/effects-parity.md | 2 +- docs/gaps.md | 4 ++-- docs/target-app-parity.md | 8 ++++---- docs/three-d.md | 4 ++-- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/docs/effects-parity.md b/docs/effects-parity.md index 66e1b713e6..c8cadd7244 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -187,7 +187,7 @@ VectorCraft choices; an original approximation, never compared with another appl The `three-d` crate (depends on `geom` and `pathops`, with no UI or GPU dependencies) builds, rotates, projects, shades and depth-sorts the surfaces; the effects crate turns them into art. What's left (materials and shadows, ray-traced rendering, -angular cut caps, exact visibility, 3D Classic, Turntable, 3D export) is 25–45 h. +angular cut caps, exact visibility, Revolve (Classic), Rotate (Classic), Map Art, Turntable, 3D export) is 25–45 h. ## Revision history diff --git a/docs/gaps.md b/docs/gaps.md index 4dac9431ee..9150803dc4 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -632,8 +632,8 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall - **Done:** an initial live Revolve in the `three-d` crate (#846, from the contributor who offered in #605), with automatic smooth vector shading, default-on circular caps and spike-free continuous rims; Extrude & Bevel, Inflate and Rotate with Position presets ([three-d.md](three-d.md), #1407). Colored Inflate has automatic smooth vector lighting from shared membrane normals. White-light Inflate keeps its existing appearance. All four take one to ten colored directional lights, with neutral ambient applied once, a light list and independent previewing controls. Standard, Diffuse, Top Left and Right select original rigs, shared with commands; manual settings show Custom. - **Missing:** materials (base, Substance, graphics), shadows, - ray-traced rendering, angular cut caps, exact visibility for intersecting and concave surfaces, 3D Classic, - Turntable, 3D export (OBJ, USDA, glTF). + ray-traced rendering, angular cut caps, exact visibility for intersecting and concave surfaces, Revolve (Classic), + Rotate (Classic), Map Art, Turntable, 3D export (OBJ, USDA, glTF). - **Impact:** specialist; Materials is the one menu stub left. - **Estimate:** 25–45 h; plan in `plan/` before coding. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0af2f06708..3e109e4557 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -185,7 +185,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors | 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged | | Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (four generated libraries, User Defined, Other Library…, Save Brushes); remaining: Art brush Overlap, Pattern brush auto corners, pen pressure on macOS, tilt/bearing/rotation | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | | Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated; Transform typing, sliders, preview, and undo are covered in `crates/ui-egui/src/panels/tests_appearance.rs` | -| 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, 3D Classic, Turntable views, 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12) | +| 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, Revolve (Classic), Rotate (Classic), Map Art, Turntable views, 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12) | | Type core | 9 | 80% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; remaining: Optical Margin Alignment, Middle Eastern features beyond bidi layout, optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; eleven-language pattern hyphenation in both composers, with grapheme and shaping-cluster protection (#4947, `hyphen::tests` and `layout::wrapping_tests`); Sanskrit patterns pending an allowlisted source; recent-font groups in font pickers (#3515); full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); Fractional Widths per type object regression-tested; color emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; threading ports: every selected area type and type on a path shows its in and out ports (empty, arrow, red "+"), and the Selection tool threads from either, the in port into a frame before it, and a double-click on a threaded port breaks the thread there (`threads::tests::break_splits_the_thread_and_the_story_flows_into_the_first_part`, `select::tests::a_double_click_on_a_threaded_port_breaks_the_thread`, `canvas::tests::a_double_click_on_a_threaded_out_port_breaks_the_thread`) (#2572; `select::tests::a_click_on_the_in_port_threads_into_a_frame_before_it`, `text::tests::selected_type_shows_its_ports_in_each_state`, `threads::tests::add_before_threads_the_story_from_the_new_frame_into_the_clicked_one`, live screenshot); the Glyphs panel highlights and scrolls to the character selected with the Type tool (#4908, `panels::glyphs` tests); the OpenType panel lists only `ss01`–`ss20` sets present in the selected font and uses its custom names when supplied; Type-range desktop Copy publishes styled art and keeps font family, size and color on canvas Paste after editing (#5636) | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), variable font axes, tab leaders, spell check, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Symbols, blends, envelopes, Repeat, perspective | 5 | 87% | 30.7's Blend panel with ease in/out, on-canvas Direct Selection of parts inside dynamic symbol instances and their `.ai` round trip, more built-in symbol libraries, envelope Anti-Alias/Preserve Shape; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic symbols keep per-instance appearance linked, #4938) are done | 4–8 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested; scores and hours unchanged | @@ -193,7 +193,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Symbols, blends, envelopes, Repeat, perspective | 5 | 87% | 30.7's Blend panel with ease in/out, on-canvas Direct Selection of parts inside dynamic symbol instances and their `.ai` round trip, symbol libraries, Start Global Edit, envelope Anti-Alias/Preserve Shape; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic symbols keep per-instance appearance linked, #4938) are done | 4–8 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested; scores and hours unchanged | | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; simpler contour walk, identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments, so Paths is monotone on the code-drawn sweep) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them; Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views (scores/hours unchanged) | | Live vector effects | 5 | 85% | Outline Object, SVG Filters | 4–8 | measured count 49/50 (Pathfinder 13/13 with Trap), depth estimated; Warp Options controls verified by focused checks and original-image review | -| 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, original lighting presets, painter visibility); materials, shadows, ray tracing, 3D Classic, Turntable views, 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12) | +| 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, original lighting presets, painter visibility); materials, shadows, ray tracing, Revolve (Classic), Rotate (Classic), Map Art, Turntable views, 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12) | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), variable font axes, tab leaders, spell check, Touch Type, Retype | 20–28 | estimated; No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), tab leaders, spell check, Touch Type, Retype | 20–28 | estimated; No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Raster effects (Effect Gallery) | 4 | 52% | the Effect Gallery's filter thumbnails and in-dialog preview area ([Filter Gallery overview](https://helpx.adobe.com/photoshop/desktop/effects-filters/get-started-with-filters/filter-gallery.html)) | 1–2 | estimated (raised from 49%: the Effect Gallery shipped, #2883, six categories, per-filter settings, ordered stack, live canvas preview, one undo step, `dialogs::effect_gallery::tests::stack_ok_is_one_undo_step`, `stack_preview_is_one_interaction`); measured count 57/57 (Artistic complete with Colored Pencil, Fresco, Paint Daubs, Palette Knife, Rough Pastels and Underpainting; Sketch complete with Torn Edges and Conté Crayon, `pixel::tests_sketch::conte_crayon_*`); texture redraw distances optimized (#1257), pixels verified; depth estimated | @@ -455,10 +455,10 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Strokes, brushes, width profiles | 5 | 90% | the Art brush's Overlap, auto-generated Pattern brush corners and new tile art in Pattern Brush Options (Brush Options for every brush type done), more built-in brush libraries (four generated in code are done), pen pressure on macOS (the windowing layer reports none there), brushes driven by pen tilt, bearing and barrel rotation (6D art pens) | 8–15 | | Appearance, transparency, graphic styles, masks | 5 | 98% | raster effect reach in preview bounds (flattener presets apply in PDF, EPS and print) | 1–2 | | Live vector effects | 5 | 85% | Outline Object, Pathfinder Hard/Soft Mix and Trap (since done: #3061, #3063, #3785), SVG Filters, Transform Patterns and Scale Strokes & Effects on a fill's or stroke's own Transform effect | 6–10 | -| 3D and Materials | 4 | ~25% | Initial Revolve, Extrude & Bevel, Inflate and Rotate, with simple lighting; materials, light presets, shadows, ray tracing, 3D Classic and more complete visibility remain | 25–45 | +| 3D and Materials | 4 | ~25% | Initial Revolve, Extrude & Bevel, Inflate and Rotate, with simple lighting; materials, light presets, shadows, ray tracing, Revolve (Classic), Rotate (Classic), Map Art and more complete visibility remain | 25–45 | | Type advanced | 4 | 50% | CJK composition for vertical type (ruby, mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), custom kinsoku sets (beyond Hard, Soft and None) and the Mojikumi Settings dialog —, manual tate-chu-yoko), tab leaders, spell check (open dictionary), Touch Type, Retype; vertical point/area/path type and Type Orientation have initial support (beyond parity, not scored: inline symbols in text) | 20–28 | | Raster effects (Effect Gallery, Document Raster Effects Settings) | 4 | 35% | ~36 Photoshop-style filters (Artistic, Brush Strokes, Sketch, Stylize) and Texturizer's Load Texture (since done, see the area table above, as is the Effect Gallery, #2883); Document Raster Effects Settings, raster effects in PDF, the pixel-filter pipeline, Radial Blur, Smart Blur (Normal, Edge Only and Overlay Edge), Unsharp Mask, Glowing Edges, Distort (Diffuse Glow, Glass, Ocean Ripple), Pixelate (Color Halftone, Crystallize, Mezzotint, Pointillize), Texture (Craquelure, Grain, Mosaic Tiles, Patchwork, Stained Glass, Texturizer) and Video (De-Interlace, NTSC Colors) are done | 8–14 | -| 3D and Materials | 4 | ~25% | Initial Revolve, Extrude & Bevel, Inflate and Rotate, with simple lighting and four original lighting presets; materials, shadows, ray tracing, 3D Classic and more complete visibility remain | 25–45 | +| 3D and Materials | 4 | ~25% | Initial Revolve, Extrude & Bevel, Inflate and Rotate, with simple lighting and four original lighting presets; materials, shadows, ray tracing, Revolve (Classic), Rotate (Classic), Map Art and more complete visibility remain | 25–45 | | Type advanced | 4 | 50% | CJK composition for vertical type (mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), custom kinsoku sets (beyond Hard, Soft and None) and the Mojikumi Settings dialog —, manual tate-chu-yoko is done, its up/down settings remain; No Break is done), tab leaders, spell check (open dictionary), Touch Type, Retype; vertical point/area/path type and Type Orientation have initial support (beyond parity, not scored: inline symbols in text) | 20–28 | | Type core | 9 | 80% | Middle Eastern features beyond bidi layout and Paragraph Direction (the Middle Eastern composers, editable bidirectional SVG text, a split caret where directions meet); Every-line Composer fidelity for justified and ragged text (available per object; mixed type sizes in a paragraph still break single-line in non-rectangular area type and with text wrap), Optical Margin Alignment, paragraph spacing limit for vertically justified area type, hidden characters, paragraph attributes in the Type tool's copy and paste (the characters keep their styles, the paragraphs take the destination's), mixed-value display in the Paragraph panel for a selection across differing paragraphs, partial selection of type-area anchors by marquee, optional font-size preservation during group scaling (scaled character controls fixed in #1034). Hyphenation and Justification options, Fractional Widths, System Layout, styled Type-range canvas Paste (#5636), and pattern hyphenation for eleven Indian languages with grapheme/cluster protection (#4947) are done; Sanskrit automatic patterns remain pending an allowlisted source | 14–19 | | Symbols, blends, envelopes, Repeat, perspective | 5 | 90% | more built-in symbol libraries (original), dynamic symbols, envelope Anti-Alias/Preserve Shape output and warp point editing, brush interpolation in blends (M8 fidelity pass done); Symbol Options › Registration and Export Type are done; symbol editing shows draggable 9-slice guides (#5280), while guides outside the artwork remain unsupported | 4–7 | diff --git a/docs/three-d.md b/docs/three-d.md index 7cc339dffa..f454e1a5ff 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -200,8 +200,8 @@ out, perspective). No Adobe software, assets, presets or bevel shapes were used. - Curves are followed within 1/2000 of the shape's size (at least 0.05 pt), so a small curve takes a few points and a large one up to 32. Extrude & Bevel and Inflate take up to 2,048 outline points (a stroke's outline is counted on its own), Rotate (which only turns the outline) 65,536. -- **3D (Classic)** (the track cube, surface types, blend steps, map art), Turntable and 3D export are separate, - unbuilt items. +- **3D (Classic)**: Extrude & Bevel (Classic) is built, with its surface types and blend steps. Revolve (Classic), + Rotate (Classic), the track cube, map art, Turntable and 3D export are separate, unbuilt items. Release measurements and a repeatable CLI scene are in [3D lighting performance](3d-lighting-performance.md). From decb3321d1b02e3b5fb73df19a0d5d2cfafb174f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 7 Nov 2026 16:27:43 -0800 Subject: [PATCH 06/11] Docs: the 3D effects summary counts Extrude & Bevel (Classic) --- docs/effects-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/effects-parity.md b/docs/effects-parity.md index c8cadd7244..37771d1019 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -13,7 +13,7 @@ Part of [target-app-parity.md](target-app-parity.md); open work is in [gaps.md]( |---|---:|---:|---:|---:| | Illustrator effects (vector and stylize) | 50 | 49 | 98% | 4–8 | | Photoshop effects (raster, Effect Gallery) | 57 | 57 | 100% | 1–2 (Effect Gallery thumbnails and in-dialog preview) | -| 3D and Materials | 4 (+3 Classic) | 4 (initial: Extrude & Bevel, Revolve, Inflate, Rotate) | ~25% | 25–45 | +| 3D and Materials | 4 (+3 Classic) | 4 (+1 Classic; initial: Extrude & Bevel, Revolve, Inflate, Rotate, Extrude & Bevel (Classic)) | ~25% | 25–45 | | Beyond Illustrator: Effect › Color Adjustments (6), effect plug-ins (WebAssembly) | — | 6 + plug-ins | — | — | ## Illustrator effects From d503688e16f4960cd99f41a33dfb04c42951b9cd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 7 Nov 2026 20:10:52 -0800 Subject: [PATCH 07/11] 3D (Classic): effect.lightingPreset refuses Extrude & Bevel (Classic) Extrude & Bevel (Classic) has no lighting presets; its lights are set in its own options. effect.lightingPreset now refuses a target whose effect at the index is Extrude & Bevel (Classic) with an error that names it, before any object changes. Before, every preset failed on it with an unknown-parameter error for lightColor. The params text and docs/mcp.md state the rule. --- crates/engine/src/cmd/effectcmd.rs | 9 ++++++- .../cmd/effectcmd/lighting_presets_tests.rs | 24 +++++++++++++++++++ docs/mcp.md | 5 ++-- 3 files changed, 35 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index a823ee161a..3b9b66194b 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -62,7 +62,7 @@ pub fn specs() -> Vec { "3D Lighting Preset", [], None, - "{index: int, preset: standard|diffuse|topLeft|right, item?: appearance item index|null (omitted: the active item, else the object's), ids?|id?: [..], target?: object|contents, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} replace an applied 3D effect's light rig and ambient with an original lighting preset; preserve shading, geometry and view; all targets must have a 3D effect at index; one undo step → {ids}", + "{index: int, preset: standard|diffuse|topLeft|right, item?: appearance item index|null (omitted: the active item, else the object's), ids?|id?: [..], target?: object|contents, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} replace an applied 3D effect's light rig and ambient with an original lighting preset; preserve shading, geometry and view; all targets must have a 3D effect at index other than Extrude & Bevel (Classic), which has no lighting presets; one undo step → {ids}", has_doc, lighting_preset ), @@ -441,6 +441,13 @@ fn lighting_preset(s: &mut Session, p: &Value) -> Result { if !effect.is_some_and(|e| effects::is_three_d(&e.id)) { return Err(bad(C, format!("object {} needs a 3D effect at index {index}", id.0))); } + // Extrude & Bevel (Classic) has no lighting presets; its lights are set in its own options. + if effect.is_some_and(|e| e.id == effects::CLASSIC_EXTRUDE) { + return Err(bad( + C, + format!("object {}: Extrude & Bevel (Classic) at index {index} has no lighting presets; set its lights with effect.setParams", id.0), + )); + } } let mut options = p.clone(); let map = options.as_object_mut().ok_or_else(|| bad(C, "parameters must be an object"))?; diff --git a/crates/engine/src/cmd/effectcmd/lighting_presets_tests.rs b/crates/engine/src/cmd/effectcmd/lighting_presets_tests.rs index 82426c5ea0..812ce09664 100644 --- a/crates/engine/src/cmd/effectcmd/lighting_presets_tests.rs +++ b/crates/engine/src/cmd/effectcmd/lighting_presets_tests.rs @@ -91,3 +91,27 @@ fn lighting_presets_reject_a_mixed_selection_before_changing_any_effect() { assert_eq!(s.doc().unwrap().history.undo.len(), history); assert!(!s.doc().unwrap().is_dirty()); } + +#[test] +fn lighting_presets_refuse_extrude_and_bevel_classic_and_leave_a_mixed_selection_unchanged() { + let (mut s, first) = setup("threeD.rotate", Value::Null); + let classic = s.execute("shape.rectangle", &json!({"x":250,"y":100,"width":80,"height":80})).unwrap()["id"].as_u64().unwrap(); + s.execute("effect.apply", &json!({"effect":"threeD.classicExtrude","item":null,"params":{"surface":"diffuse","lightRotation":40}})).unwrap(); + for ids in [vec![classic], vec![first.0, classic]] { + for preset in LIGHTING_PRESETS { + s.doc_mut().unwrap().mark_saved(); + let before = s.doc().unwrap().doc.clone(); + let history = s.doc().unwrap().history.undo.len(); + let p = json!({"ids":ids,"index":0,"item":null,"preset":preset.id}); + let err = s.execute("effect.lightingPreset", &p).unwrap_err().to_string(); + assert!(err.contains(&format!("object {classic}: Extrude & Bevel (Classic) at index 0 has no lighting presets")), "{err}"); + assert_eq!(s.doc().unwrap().doc, before); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + assert!(!s.doc().unwrap().is_dirty()); + } + } + // Its lights are set with its own parameters instead. + s.execute("effect.setParams", &json!({"ids":[classic],"index":0,"item":null,"params":{"lightRotation":135,"lightHeight":45}})).unwrap(); + let params = &s.doc().unwrap().doc.node(NodeId(classic)).unwrap().appearance.effects[0].params; + assert_eq!((params["lightRotation"].as_f64(), params["lightHeight"].as_f64()), (Some(135.0), Some(45.0))); +} diff --git a/docs/mcp.md b/docs/mcp.md index 168c377b86..f2d9f5f133 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2137,8 +2137,9 @@ See [Revolve](revolve.md) for the scope and limitations. `effect.lightingPreset {index: int, preset: "standard" | "diffuse" | "topLeft" | "right", item?, ids?, target?}` replaces the lighting rig and ambient of an existing Revolve, Extrude & Bevel, Inflate or Rotate effect. `item: null` addresses object-level effects; an item index addresses a fill/stroke's -effects. All targets must have a 3D effect at `index`, otherwise nothing changes. The operation -is one undo step and preserves Shading, geometry, source paint and the view. +effects. All targets must have a 3D effect at `index`, otherwise nothing changes. Extrude & Bevel +(Classic) has no lighting presets: a target with it at `index` is an error, nothing changes, and +`effect.setParams` sets its lights. The operation is one undo step and preserves Shading, geometry, source paint and the view. The four original rigs use one white front light at 80% intensity. Standard keeps the existing default; Diffuse uses 100% Softness and 35% Ambient Light, Top Left uses Rotation 135 and Height From f384d27beeec2fbe4c04b10ceab76819d5cbf7ea Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 8 Nov 2026 06:35:38 -0800 Subject: [PATCH 08/11] 3D (Classic): the solids test checks the classic faces' hue every_solid_draws_shaded_faces_and_leaves_the_source_editable no longer skips the color check for Extrude & Bevel (Classic). Its faces must be the fill's red or the stroke's black, shaded, or lightened toward white by the Plastic highlight, which keeps r - g to r - b at 6 to 7. --- crates/effects/src/solids/tests.rs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index 44204f83d0..461f5610d8 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -45,13 +45,15 @@ fn every_solid_draws_shaded_faces_and_leaves_the_source_editable() { assert_eq!(n.path_data(), Some(&source), "{id}"); assert!(!faces(&art).is_empty(), "{id}"); // The faces are the fill's red or the stroke's black, shaded: never brighter, never another - // hue (the classic Plastic surface adds a white highlight, tested on its own). + // hue. The classic Plastic surface, its default, also lightens a face toward white, which + // scales every channel's distance from white by the same factor and so keeps r - g to + // r - b at 6 to 7. for f in faces(&art) { let [r, g, b] = fill_rgb(f); - assert!( - r <= 0.8 + 1e-6 && (g * 4.0 - r).abs() < 1e-4 && (b * 8.0 - r).abs() < 1e-4 || id == ROTATE || id == CLASSIC_EXTRUDE, - "{id}: {r} {g} {b}" - ); + let shaded = r <= 0.8 + 1e-6 && (g * 4.0 - r).abs() < 1e-4 && (b * 8.0 - r).abs() < 1e-4; + let highlighted = + id == CLASSIC_EXTRUDE && [r, g, b].iter().all(|c| (0.0..=1.0).contains(c)) && ((r - g) * 7.0 - (r - b) * 6.0).abs() < 1e-4; + assert!(shaded || highlighted || id == ROTATE, "{id}: {r} {g} {b}"); } // The art follows the source when it moves. let before = art.visual_bounds().unwrap(); From 517e0b7ae85d36e26f045ec066cddcc53f234eaa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 8 Nov 2026 06:35:39 -0800 Subject: [PATCH 09/11] Effects: hiding a 3D effect still checks the values given with it effect.setParams with visible: false skipped every 3D parameter check, so a hidden edit could store a Classic depth of 2001, an unknown surface or bevel, an empty light list or a Revolve edge other than left or right. The values given are now checked by validate_three_d_params (the checks of validate_three_d that do not build the art); after a change of 3D type the values the effect keeps are checked too. The object still does not need to fit while the effect is hidden. --- crates/effects/src/lib.rs | 3 +- crates/effects/src/revolve.rs | 10 ++++- crates/effects/src/solids.rs | 20 ++++++++-- crates/engine/src/cmd/effectcmd.rs | 12 ++++-- crates/engine/src/cmd/effectcmd/tests.rs | 50 ++++++++++++++++++++++++ 5 files changed, 86 insertions(+), 9 deletions(-) diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 417292b526..bf9fba23d4 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -85,7 +85,8 @@ pub use reshape::{ pub use revolve::{REVOLVE, has_revolve, revolve_art, revolve_options, validate_revolve}; pub use solids::{ CLASSIC_EXTRUDE, EXTRUDE, INFLATE, ROTATE, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, THREE_D_TYPES, classic_extrude_options, classic_shading, - extrude_options, has_solid, inflate_options, is_three_d, solid_art, three_d_params_as, validate_solid, validate_three_d, view_options, + extrude_options, has_solid, inflate_options, is_three_d, solid_art, three_d_params_as, validate_solid, validate_three_d, validate_three_d_params, + view_options, }; pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings}; pub use trap::TRAP; diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index b2528818bc..9e71799417 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -66,19 +66,25 @@ pub fn revolve_options(p: &Value) -> Revolve { /// Validate before a command mutates the document. Loading external files is still bounded /// by the evaluator; unsupported source kinds remain unchanged when rendered. pub fn validate_revolve(n: &Node, p: &Value) -> Result<(), String> { - crate::lighting::validate(p)?; + validate_revolve_params(p)?; let path = profile(n).ok_or("Revolve currently requires a path or compound path. Select a profile drawn with the Pen tool.")?; let b = path.bounds().ok_or("Revolve requires a profile with at least two anchors")?; if !path.subpaths.iter().any(|sp| sp.anchors.len() >= 2) { return Err("Revolve requires at least two anchors".into()); } + vectorcraft_three_d::revolve(&path, b, revolve_options(p)).map(|_| ()) +} + +/// Check Revolve's parameter values `p` alone: its lights, `edge` and `cap`. +pub(crate) fn validate_revolve_params(p: &Value) -> Result<(), String> { + crate::lighting::validate(p)?; if p.get("edge").is_some_and(|v| v.as_str() != Some("left") && v.as_str() != Some("right")) { return Err("Revolve edge must be left or right".into()); } if p.get("cap").is_some_and(|v| v.as_bool().is_none()) { return Err("Revolve cap must be a boolean".into()); } - vectorcraft_three_d::revolve(&path, b, revolve_options(p)).map(|_| ()) + Ok(()) } fn profile(n: &Node) -> Option { diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 818fd6c1b7..c31dbe856d 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -182,19 +182,26 @@ fn facets(id: &str, path: &PathData, rule: FillRule, bounds: Rect, p: &Value) -> } } -/// Validate before a command changes the document; the evaluator bounds loaded files too. -pub fn validate_solid(n: &Node, id: &str, p: &Value) -> Result<(), String> { +/// Check solid `id`'s parameter values `p` alone: the part of [`validate_solid`] that does not +/// need the object. +fn validate_solid_params(id: &str, p: &Value) -> Result<(), String> { if id == CLASSIC_EXTRUDE { classic::validate(p)?; } crate::lighting::validate(p)?; - let label = crate::effect_info(id).map_or("This effect", |e| e.label.trim_end_matches('…')); if let Some(v) = p.get("bevel") && !v.as_str().is_some_and(|s| s == "none" || BevelShape::parse(s).is_some()) { let names: Vec<_> = BevelShape::ALL.iter().map(|b| b.id()).collect(); return Err(format!("bevel must be none or one of {}", names.join(", "))); } + Ok(()) +} + +/// Validate before a command changes the document; the evaluator bounds loaded files too. +pub fn validate_solid(n: &Node, id: &str, p: &Value) -> Result<(), String> { + validate_solid_params(id, p)?; + let label = crate::effect_info(id).map_or("This effect", |e| e.label.trim_end_matches('…')); if is_container(n) { let shapes = members(n, label)?; let b = union_bounds(&shapes).ok_or_else(|| format!("{label} requires a group holding a shape with at least two anchors"))?; @@ -277,6 +284,13 @@ pub fn validate_three_d(n: &Node, id: &str, p: &Value) -> Result<(), String> { if id == crate::REVOLVE { crate::validate_revolve(n, p) } else { validate_solid(n, id, p) } } +/// Are 3D effect `id`'s parameter values `p` valid? The checks of [`validate_three_d`] that do not +/// build the art, for an edit that hides the effect: hidden, it draws nothing, so its object does +/// not need to fit. +pub fn validate_three_d_params(id: &str, p: &Value) -> Result<(), String> { + if id == crate::REVOLVE { crate::revolve::validate_revolve_params(p) } else { validate_solid_params(id, p) } +} + /// One surface: each facet a path shaded from `paint`, as a group with the paint's opacity and /// blend mode (so overlapping facets don't add up their transparency). fn surface(n: &Node, facets: Vec, paint: &Paint, opacity: f32, blend: BlendMode, colored: bool) -> Node { diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 450dbe0e50..2b90dc6b4c 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -487,7 +487,7 @@ fn lighting_preset(s: &mut Session, p: &Value) -> Result { /// `effect.setParams`: merges `params` into the effect at `index` of the targets' active item, and /// sets its Warp style (`warpStyle`), its 3D type (`threeDType`) or visibility (`visible`), as one /// undo step. They are checked as `effect.apply` checks them, and a visible 3D effect must still -/// fit. → `{ids}`. +/// fit; a hidden one has its given values checked. → `{ids}`. fn set_params(s: &mut Session, p: &Value) -> Result { const C: &str = "effect.setParams"; let index = index_param(p, "index", C)?; @@ -539,7 +539,6 @@ fn set_params(s: &mut Session, p: &Value) -> Result { } if let Some(e) = effect && effects::is_three_d(&e.id) - && visible != Some(false) { let to = kind.unwrap_or(&e.id); let mut prospective = @@ -547,7 +546,14 @@ fn set_params(s: &mut Session, p: &Value) -> Result { if let (Some(cur), Value::Object(new)) = (prospective.as_object_mut(), effects::upgrade_params(to, ¶ms)) { cur.extend(new); } - effects::validate_three_d(n, to, &prospective).map_err(|e| bad(C, e))?; + if visible != Some(false) { + effects::validate_three_d(n, to, &prospective).map_err(|e| bad(C, e))?; + } else { + // Hidden, the effect draws nothing, so its object need not fit. The values given are + // checked, and after a change of 3D type so is every value it keeps. + let checked = if to == e.id { effects::upgrade_params(to, ¶ms) } else { prospective }; + effects::validate_three_d_params(to, &checked).map_err(|e| bad(C, e))?; + } } } let ids = edit_effects(s, p, item, C, "Effect Options", &format!("{C}: no effect at index {index}"), index, |fx, index| { diff --git a/crates/engine/src/cmd/effectcmd/tests.rs b/crates/engine/src/cmd/effectcmd/tests.rs index be1dd443c3..e3fca957b8 100644 --- a/crates/engine/src/cmd/effectcmd/tests.rs +++ b/crates/engine/src/cmd/effectcmd/tests.rs @@ -46,6 +46,56 @@ fn revolve_commands_keep_profile_live_edit_options_expand_and_undo() { assert_eq!(effects_for_test(&s, id), before); } +/// `effect.setParams` checks the values it is given for a 3D effect when the same edit hides it: +/// a bad value is refused and the document is left as it was, and good values are stored. +#[test] +fn hiding_a_3d_effect_still_checks_its_new_values() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let rect = |s: &mut Session, x: u32| { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 100, "width": 60, "height": 60})).unwrap()["id"].as_u64().unwrap()) + }; + let classic = rect(&mut s, 20); + s.execute("effect.apply", &json!({"effect": effects::CLASSIC_EXTRUDE, "ids": [classic.0], "item": null})).unwrap(); + let extrude = rect(&mut s, 120); + s.execute("effect.apply", &json!({"effect": effects::EXTRUDE, "ids": [extrude.0], "item": null})).unwrap(); + let profile = NodeId(s.execute("path.create", &json!({"d": "M 300 40 L 330 60 L 330 140 L 300 160"})).unwrap()["id"].as_u64().unwrap()); + s.execute("effect.apply", &json!({"effect": effects::REVOLVE, "ids": [profile.0], "item": null})).unwrap(); + for (id, params, why) in [ + (classic, json!({"depth": 2001}), "`depth` must be between 0 and 2000"), + (classic, json!({"surface": "glossy"}), "`surface` must be one of"), + (classic, json!({"bevel": "wavy"}), "bevel must be none or one of"), + (extrude, json!({"lights": []}), "lights must contain one to ten lights"), + (extrude, json!({"lightColor": "red"}), "lightColor must be an opaque RGB color"), + (profile, json!({"edge": "top"}), "Revolve edge must be left or right"), + ] { + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + let p = json!({"ids": [id.0], "index": 0, "item": null, "params": params, "visible": false}); + let e = s.execute("effect.setParams", &p).unwrap_err().to_string(); + assert!(e.contains(why), "{params}: {e}"); + assert_eq!(s.doc().unwrap().doc, before, "{params}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{params}"); + } + // A hidden switch of 3D type checks the values given with it for the new type. + let before = s.doc().unwrap().doc.clone(); + let p = json!({"ids": [extrude.0], "index": 0, "item": null, "threeDType": "inflate", "params": {"lights": []}, "visible": false}); + let e = s.execute("effect.setParams", &p).unwrap_err().to_string(); + assert!(e.contains("lights must contain one to ten lights"), "{e}"); + assert_eq!(s.doc().unwrap().doc, before); + // Hiding alone checks nothing. + s.execute("effect.setParams", &json!({"ids": [extrude.0], "index": 0, "item": null, "visible": false})).unwrap(); + assert!(!node(&s, extrude).appearance.effects[0].visible); + s.execute("effect.setParams", &json!({"ids": [classic.0], "index": 0, "item": null, "params": {"depth": 2000}, "visible": false})).unwrap(); + let e = &node(&s, classic).appearance.effects[0]; + assert_eq!((e.params["depth"].as_f64(), e.visible), (Some(2000.0), false)); + // A value the effect already holds is not checked again: a key it does not take, as a file + // can carry, does not stop a hidden edit of another value. + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(classic).unwrap().appearance.effects[0].params["extra"] = json!(1); + s.execute("effect.setParams", &json!({"ids": [classic.0], "index": 0, "item": null, "params": {"depth": 10}, "visible": false})).unwrap(); + assert_eq!(node(&s, classic).appearance.effects[0].params["depth"].as_f64(), Some(10.0)); +} + /// Extrude & Bevel, Inflate and Rotate: applied by command, saved and reopened, edited, /// exported, expanded and undone; one 3D effect per object. #[test] From a5ea32b3869e3b67a43355c113113232b97fa9dc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 8 Nov 2026 07:31:27 -0800 Subject: [PATCH 10/11] Effects: fitted gradients turn with the Transform effect MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A gradient fitted to the object refit to the outline after the object's Transform effect rotated, reflected or scaled it unevenly, so the gradient kept running left to right while the shape turned under it. Object › Transform already turns such a gradient. A Transform effect that a refit would not reproduce now fixes the gradient to its fit on the geometry the effect takes, and then maps it with that effect and the effects after it, as a placed gradient. Under moves and even scales it draws as a refit does, and an effect that scales the object to nothing across leaves it fitted. This applies to an object's own effects, a fill's or stroke's own effects, and a group's: in a group, the gradients fitted to its paths, to its own fill, to the groups inside it and to its images' and symbol instances' own fills each fix to the fit on their own object. Object › Expand of the fill draws the same. This changes how existing documents draw: art with a fitted gradient and a Transform effect that rotates, reflects or scales it unevenly now shows the gradient turned with the art. How gradients follow the effect is VectorCraft's own rule. --- crates/doc/src/node.rs | 1 + crates/doc/src/node/ops.rs | 2 +- crates/effects/src/bake/tests.rs | 119 +++++++++++++++++++++++++++ crates/effects/src/catalog.rs | 2 +- crates/effects/src/geometry.rs | 56 +++++++++---- crates/effects/src/group/tests.rs | 64 ++++++++++++++ crates/effects/src/reshape.rs | 16 +++- crates/engine/src/tests/objexpand.rs | 27 ++++++ crates/render/src/tests/objectfx.rs | 35 ++++++++ docs/target-app-parity.md | 1 + 10 files changed, 303 insertions(+), 20 deletions(-) diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index 3dd07351e3..550ac37704 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -31,6 +31,7 @@ pub use ids::{LAYER_COLORS, LayerColor, NodeId}; pub use kind::{ImageObject, MAX_BUFFERED_VALUES, NodeKind, with_buffered_value_budget}; pub use live_shape::{LiveShape, Scaling}; pub use opacity::{Knockout, OpacityMask, whiten}; +pub use ops::keeps_gradient_fit; use wire::NodeWire; pub use wire::{MAX_READ_NODES, with_node_budget}; diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index 2b2bef296d..c15b1d05e1 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -768,7 +768,7 @@ impl Node { } /// Is `a` a move plus a positive uniform scale (after which a refit gradient still matches)? -fn keeps_gradient_fit(a: Affine) -> bool { +pub fn keeps_gradient_fit(a: Affine) -> bool { let [m0, m1, m2, m3, _, _] = a.as_coeffs(); let eps = 1e-12 * m0.abs().max(1.0); m0 > 0.0 && m1.abs() <= eps && m2.abs() <= eps && (m0 - m3).abs() <= eps diff --git a/crates/effects/src/bake/tests.rs b/crates/effects/src/bake/tests.rs index 0ff1cdac06..d42199a682 100644 --- a/crates/effects/src/bake/tests.rs +++ b/crates/effects/src/bake/tests.rs @@ -210,6 +210,125 @@ fn baked_free_distort_moves_placed_gradients_from_the_bounds_to_the_distorted_bo assert_eq!(baked(&fitted, distort()).1.geom, None); } +/// A gradient fitted to the object turns, reflects and stretches with a Transform effect that a +/// refit would not reproduce: it is fixed to its fit on the geometry the effect takes, then mapped. +/// Moves and even scales leave it fitted. +#[test] +fn a_fitted_gradient_turns_reflects_and_stretches_with_a_transform_effect() { + use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop}; + let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))]; + let fitted = |kind| Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(kind, stops.clone())))); + let geom = |start: (f64, f64), end: (f64, f64)| GradientGeom { start: start.into(), end: end.into(), aspect: 1.0, focal: None }; + // The geometry of the baked fill (`own`: the Transform effect is the fill's own effect). + let baked = |kind, effects: &[Effect], own: bool| { + let mut ap = Appearance::basic(fitted(kind), Paint::None, 0.0); + if own { + *ap.items[0].effects_mut() = effects.to_vec(); + } + let mut n = Node::path(NodeId(50), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), ap); + if !own { + n.appearance.effects = effects.to_vec(); + } + let d = bake_document(&doc_with(n)).unwrap(); + let mut found = vec![]; + d.node(NodeId(50)).unwrap().walk(&mut |c: &Node| { + if let Paint::Gradient(g) = c.appearance.fill_paint() { + found.push(g.geom); + } + }); + assert_eq!(found.len(), 1, "{effects:?}, own {own}"); + found[0] + }; + let t = |params| fx("distort.transform", params); + let offset = fx("path.offsetPath", json!({"offset": 10.0, "joins": "miter"})); + let corners = json!({"corners": [[1.0, 0.0], [2.0, 0.0], [2.0, 1.0], [1.0, 1.0]]}); + let linear = GradientKind::Linear; + let cases = [ + // A quarter turn about the center: the left to right ramp runs from the bottom up. + (linear, vec![t(json!({"rotate": 90.0}))], geom((50.0, 100.0), (50.0, 0.0))), + // Reflected left to right: the ramp runs from right to left. + (linear, vec![t(json!({"reflectX": true}))], geom((100.0, 50.0), (0.0, 50.0))), + // With Scale Strokes & Effects on, the same. + (linear, vec![t(json!({"rotate": 90.0, "strokes": true}))], geom((50.0, 100.0), (50.0, 0.0))), + // Offset Path grows the square to -10..110 first: the turn takes the fit across 120 pt. + (linear, vec![offset.clone(), t(json!({"rotate": 90.0}))], geom((50.0, 110.0), (50.0, -10.0))), + // Stretched to twice the width: the circle of radius 50 about the center becomes an + // ellipse 100 pt across and 50 pt tall. + (GradientKind::Radial, vec![t(json!({"scaleH": 200.0}))], GradientGeom { aspect: 0.5, ..geom((50.0, 50.0), (150.0, 50.0)) }), + // Turned, then moved one width right by Free Distort: the fixed gradient moves with it. + (linear, vec![t(json!({"rotate": 90.0})), fx("distort.freeDistort", corners)], geom((150.0, 100.0), (150.0, 0.0))), + ]; + for (kind, effects, want) in cases { + for own in [false, true] { + let what = format!("{kind:?} {effects:?}, own {own}"); + let got = baked(kind, &effects, own).unwrap_or_else(|| panic!("{what}: fixed to its fit")); + assert_geom_near(got, want, &what); + } + } + // A move and an even scale are what a refit gives: the gradient stays fitted. + for effects in [vec![t(json!({"moveH": 30.0}))], vec![t(json!({"scaleH": 150.0, "scaleV": 150.0})), offset]] { + for own in [false, true] { + assert_eq!(baked(linear, &effects, own), None, "{effects:?}, own {own}"); + } + } + // A stroke's gradient is fixed to its fit on the box grown by half its weight (4 pt), -2..102, + // with Scale Strokes & Effects off or on. + let stroked = |effects: &[Effect], own: bool| { + let mut ap = Appearance::basic(Paint::None, fitted(linear), 4.0); + let Some(stroke) = ap.items.iter_mut().find(|i| matches!(i, AppearanceItem::Stroke(_))) else { panic!("a stroke") }; + if own { + *stroke.effects_mut() = effects.to_vec(); + } + let mut n = Node::path(NodeId(50), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), ap); + if !own { + n.appearance.effects = effects.to_vec(); + } + let d = bake_document(&doc_with(n)).unwrap(); + let mut found = vec![]; + d.node(NodeId(50)).unwrap().walk(&mut |c: &Node| { + for item in &c.appearance.items { + if let AppearanceItem::Stroke(s) = item + && let Paint::Gradient(g) = &s.paint + { + found.push(g.geom); + } + } + }); + assert_eq!(found.len(), 1, "{effects:?}, own {own}"); + found[0] + }; + for strokes in [false, true] { + for own in [false, true] { + let what = format!("stroke, strokes {strokes}, own {own}"); + let got = stroked(&[t(json!({"rotate": 90.0, "strokes": strokes}))], own).unwrap_or_else(|| panic!("{what}: fixed to its fit")); + assert_geom_near(got, geom((50.0, 102.0), (50.0, -2.0)), &what); + } + } +} + +/// A Transform effect that scales the geometry to nothing across leaves a fitted gradient fitted: +/// mapping it with the effect would flatten it to one color. +#[test] +fn a_transform_effect_that_scales_to_nothing_leaves_a_fitted_gradient_fitted() { + use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))]; + let fitted = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + let mut n = Node::path(NodeId(50), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::basic(Paint::None, fitted, 4.0)); + n.appearance.effects = vec![fx("distort.transform", json!({"scaleH": 0.0, "rotate": 30.0}))]; + let d = bake_document(&doc_with(n)).unwrap(); + let mut found = vec![]; + d.node(NodeId(50)).unwrap().walk(&mut |c: &Node| { + for item in &c.appearance.items { + if let AppearanceItem::Stroke(s) = item + && let Paint::Gradient(g) = &s.paint + { + found.push(g.geom); + } + } + }); + assert_eq!(found, [None]); +} + #[test] fn item_effects_split_into_one_path_per_item() { let mut n = Node::path(NodeId(50), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art()); diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index a014807a77..8a34fc0d73 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -238,7 +238,7 @@ pub fn effect_catalog() -> Vec { "distort.transform", "Transform…", DT, - "{scaleH: % (100), scaleV: % (100), moveH: pt (0; right = +), moveV: pt (0; down = +), rotate: deg (0; counter-clockwise), copies: 0..1000 (0; each copy transforms the last again; placed gradients transform with the object and with each copy), reflectX: bool (false; flips left to right), reflectY: bool (false; flips top to bottom), reference: 0..8 (4; the point of the bounds' 9-point grid it scales, rotates and reflects about: 0 top left, 4 centre, 8 bottom right), random: bool (false; each scale goes a random share of the way from 100 % to its value, each move and the angle a random share of theirs, differently for each object and the same on every redraw), objects: bool (true; Transform Objects: off, the geometry stays where it is and makes no copies, and only the two options below apply, once), patterns: bool (false; Transform Patterns: pattern fills and strokes transform along; with copies the original keeps its pattern and copy k takes the transformation k times), strokes: bool (false; Scale Strokes & Effects: stroke weights and dashes, and the distances of the effects on the fills and strokes, scale by the mean scale √|scaleH·scaleV|, copy k by its k-th power)}", + "{scaleH: % (100), scaleV: % (100), moveH: pt (0; right = +), moveV: pt (0; down = +), rotate: deg (0; counter-clockwise; when the effect turns, reflects or scales the object unevenly, a gradient fitted to the object is fixed to its fit and turns with the object and with each copy), copies: 0..1000 (0; each copy transforms the last again; placed gradients transform with the object and with each copy), reflectX: bool (false; flips left to right), reflectY: bool (false; flips top to bottom), reference: 0..8 (4; the point of the bounds' 9-point grid it scales, rotates and reflects about: 0 top left, 4 centre, 8 bottom right), random: bool (false; each scale goes a random share of the way from 100 % to its value, each move and the angle a random share of theirs, differently for each object and the same on every redraw), objects: bool (true; Transform Objects: off, the geometry stays where it is and makes no copies, and only the two options below apply, once), patterns: bool (false; Transform Patterns: pattern fills and strokes transform along; with copies the original keeps its pattern and copy k takes the transformation k times), strokes: bool (false; Scale Strokes & Effects: stroke weights and dashes, and the distances of the effects on the fills and strokes, scale by the mean scale √|scaleH·scaleV|, copy k by its k-th power)}", json!({"scaleH": 100.0, "scaleV": 100.0, "moveH": 0.0, "moveV": 0.0, "rotate": 0.0, "copies": 0, "reflectX": false, "reflectY": false, "reference": 4, "random": false, "objects": true, "patterns": false, "strokes": false}), ), g( diff --git a/crates/effects/src/geometry.rs b/crates/effects/src/geometry.rs index 715143e1ae..b9799ef938 100644 --- a/crates/effects/src/geometry.rs +++ b/crates/effects/src/geometry.rs @@ -174,21 +174,34 @@ pub fn apply_geometry_bez_carrying(effects: &[Effect], path: &BezPath, bounds: R (out.to_bezpath(), carry) } -/// How placed gradients follow geometry effects. The Transform effect without copies maps them as -/// it maps the object (with copies, `crate::reshape` gives each copy its own). Free Distort moves -/// and scales them from the object's bounds before the effect to its bounds after it. For the -/// other geometry effects it is empty. It does not change gradients fitted to the object. +/// How gradients follow geometry effects. The Transform effect without copies maps placed +/// gradients as it maps the object (with copies, `crate::reshape` gives each copy its own). Free +/// Distort moves and scales them from the object's bounds before the effect to its bounds after +/// it. For the other geometry effects it is empty. A gradient fitted to the object fits the +/// geometry each effect makes, until a Transform effect turns, reflects or scales it unevenly +/// (a map after which a refit would not match the mapped gradient): it is fixed to its fit on the +/// geometry that effect takes, and then follows that effect and the ones after it as a placed +/// gradient does. #[derive(Clone, Debug, Default, PartialEq)] pub struct Carry(Vec); +/// Does `m` fix a gradient fitted to the object to its fit before mapping it? It does when a refit +/// would not reproduce the map (a turn, a reflection or an uneven scale) and `m` keeps area: a map +/// that flattens the geometry to a line (a scale of 0) leaves the gradient fitted, since mapping it +/// would flatten it to one color. +pub(crate) fn fixes_fit(m: vectorcraft_geom::Affine) -> bool { + let [a, b, c, d, _, _] = m.as_coeffs(); + let norm = a * a + b * b + c * c + d * d; + m.is_finite() && m.determinant().abs() > 1e-12 * norm && !vectorcraft_doc::node::keeps_gradient_fit(m) +} + #[derive(Clone, Copy, Debug, PartialEq)] enum CarryStep { - Affine(vectorcraft_geom::Affine), + /// Map `m`; `from` is the geometric bounds of the geometry it takes, which a fitted gradient + /// fits before `m` moves it (none: fitted gradients stay fitted). + Affine { m: vectorcraft_geom::Affine, from: Option }, /// From box `from` to box `to` (strokes: their stroke-inflated boxes). - Boxes { - from: Rect, - to: Rect, - }, + Boxes { from: Rect, to: Rect }, } impl Carry { @@ -220,7 +233,7 @@ impl Carry { return Carry::default(); } let step = match id { - "distort.transform" => Some(CarryStep::Affine(distort::transform_map(b, p, seed).0)), + "distort.transform" => Some(CarryStep::Affine { m: distort::transform_map(b, p, seed).0, from }), _ => match (from, to) { (Some(from), Some(to)) if from != to && [to.x0, to.y0, to.x1, to.y1].iter().all(|v| v.is_finite()) => { Some(CarryStep::Boxes { from, to }) @@ -239,17 +252,32 @@ impl Carry { /// Does it move any of the gradients of `ap`? Callers check first, so an appearance shared /// with other objects is not copied for nothing. pub fn moves(&self, ap: &Appearance) -> bool { - !self.0.is_empty() && ap.has_placed_gradient() + !self.0.is_empty() && (ap.has_placed_gradient() || (self.pin().is_some() && ap.has_unplaced_gradient())) } - /// Move the placed gradients of `ap` along, through each step in turn. + /// The first step that fixes gradients fitted to the object: a map a refit would not + /// reproduce, on geometry whose bounds are known. + fn pin(&self) -> Option { + self.0.iter().position(|s| matches!(s, CarryStep::Affine { m, from: Some(_) } if fixes_fit(*m))) + } + + /// Move the gradients of `ap` along. Placed gradients take every step in turn; fitted ones + /// are fixed to their fit at the first step [`Self::pin`] finds and take it and the steps + /// after it. pub fn apply(&self, ap: &mut Appearance) { if !self.moves(ap) { return; } - for s in &self.0 { + // The steps move placed gradients only; fitted ones become placed at the pin. + let pin = self.pin(); + for (k, s) in self.0.iter().enumerate() { + if Some(k) == pin + && let CarryStep::Affine { from: Some(b), .. } = *s + { + ap.pin_gradients(b); + } match *s { - CarryStep::Affine(m) => ap.transform_gradients(m), + CarryStep::Affine { m, .. } => ap.transform_gradients(m), CarryStep::Boxes { from, to } => crate::reshape::follow_boxes(ap, from, to), } } diff --git a/crates/effects/src/group/tests.rs b/crates/effects/src/group/tests.rs index a0cddc94d3..fa02ff004d 100644 --- a/crates/effects/src/group/tests.rs +++ b/crates/effects/src/group/tests.rs @@ -450,6 +450,70 @@ fn a_groups_transform_moves_the_gradients_placed_on_an_images_own_fills() { } } +/// A group's Transform effect that turns its art turns the gradients fitted to its paths, to the +/// group's own fill, to a nested group's own fill and to an image's and a symbol instance's own +/// fills: each is fixed to its fit on its own object first. A move leaves the members' gradients +/// fitted. +#[test] +fn a_groups_transform_turns_the_gradients_fitted_to_its_members_and_its_own_fill() { + use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop}; + use vectorcraft_doc::ImageObject; + let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))]; + let fitted = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + let square = |id: u64, x: f64| { + Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0)), Appearance::basic(fitted.clone(), Paint::None, 0.0))) + }; + let mut image = Node::new( + NodeId(4), + NodeKind::Image(Box::new(ImageObject { + key: "k".into(), + width: 10, + height: 10, + xf: vectorcraft_geom::Affine::translate((30.0, 0.0)), + link: None, + placement: Default::default(), + pixels: None, + })), + ); + image.appearance = Appearance::basic(fitted.clone(), Paint::None, 0.0).into(); + // A symbol instance whose symbol is not in a document is measured as the 20 pt square about + // its origin: here 22.5..27.5 across and 2.5..7.5 down. + let at = vectorcraft_geom::Affine::translate((25.0, 5.0)) * vectorcraft_geom::Affine::scale(0.25); + let mut instance = Node::new(NodeId(6), NodeKind::SymbolInstance { symbol: "s".into(), xf: at }); + instance.appearance = Appearance::basic(fitted.clone(), Paint::None, 0.0).into(); + // Ends of each gradient by object id; none for a gradient still fitted. + let ends = |params: serde_json::Value| { + let mut inner = Node::group(NodeId(5), vec![square(2, 10.0)]); + inner.appearance.items.push(AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(fitted.clone()))); + let mut g = Node::group(NodeId(10), vec![square(1, 0.0), Arc::new(inner), Arc::new(image.clone()), Arc::new(instance.clone())]); + g.appearance.items.push(AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(fitted.clone()))); + g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true }); + let art = evaluate_container(None, &g).unwrap(); + let mut out = std::collections::BTreeMap::new(); + art.walk(&mut |c: &Node| { + if let Paint::Gradient(p) = c.appearance.fill_paint() { + out.insert(c.id.0, p.geom.map(|g| (g.start, g.end))); + } + }); + out + }; + let near = |a: Point, b: Point| a.distance(b) < 1e-6; + // A quarter turn about the group's center (20, 5): (x, 5) goes to (20, 5 + 20 - x), so a ramp + // from (x0, 5) to (x1, 5) runs from (20, 25 - x0) up to (20, 25 - x1). + let turned = ends(serde_json::json!({"rotate": 90})); + let want = [(1, 0.0, 10.0), (2, 10.0, 20.0), (5, 10.0, 20.0), (4, 30.0, 40.0), (6, 22.5, 27.5), (10, 0.0, 40.0)]; + for (id, x0, x1) in want { + let got = turned.get(&id).copied().flatten(); + let ok = got.is_some_and(|(s, e)| near(s, Point::new(20.0, 25.0 - x0)) && near(e, Point::new(20.0, 25.0 - x1))); + assert!(ok, "object {id}: {got:?} in {turned:?}"); + } + // The group's own fill is fixed to its fit on the art it paints, which the move took to 30..70. + let moved = ends(serde_json::json!({"moveH": 30})); + let group = moved.get(&10).copied().flatten(); + assert!(group.is_some_and(|(s, e)| near(s, Point::new(30.0, 5.0)) && near(e, Point::new(70.0, 5.0))), "{moved:?}"); + assert!(moved.len() == 6 && [1, 2, 4, 5, 6].iter().all(|id| moved[id].is_none()), "{moved:?}"); +} + #[test] fn a_transform_on_a_group_paints_each_copy_with_its_own_gradient() { use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop}; diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index 4ea3e4610e..9382fc5b5e 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -714,8 +714,12 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: b return; }; used = used.minus(before).plus(Budget::of(&out)); - if follows && !boxes && leaf.appearance.has_placed_gradient() { - crate::Carry::of(&e.id, ¶ms, bounds, None, None, seed).apply(&mut leaf.appearance); + if follows && !boxes { + // A gradient fitted to the path fits the path's own bounds. + let carry = crate::Carry::of(&e.id, ¶ms, bounds, path.bounds(), None, seed); + if carry.moves(&leaf.appearance) { + carry.apply(&mut leaf.appearance); + } } set_geometry(leaf, out, rule); }); @@ -1048,7 +1052,7 @@ fn is_member_group(n: &Node) -> bool { } /// A group below the art that [`is_member_group`] takes and whose own fills or strokes hold a -/// placed gradient: the child indices that lead to it from the art, its geometric bounds, and +/// gradient: the child indices that lead to it from the art, its geometric bounds, and /// whether a path below it kept its shape. type GroupMark = (Vec, Option, bool); @@ -1065,7 +1069,7 @@ fn group_marks(n: &Node, at: &mut Vec, kept: &HashSet, out: &mut for (i, c) in children.iter().enumerate() { at.push(i); let (b, h) = group_marks(c, at, kept, out); - if is_member_group(c) && c.appearance.has_placed_gradient() { + if is_member_group(c) && (c.appearance.has_placed_gradient() || c.appearance.has_unplaced_gradient()) { out.push((at.clone(), b, h)); } at.pop(); @@ -1218,6 +1222,10 @@ fn copy_placed(n: &mut Node, m: Affine, copies: usize, room: &mut usize) { let src = (**c).clone(); let placed = |xf: Affine| { let mut one = src.clone(); + // Gradients fitted to it are fixed to their fit first when a refit would not match. + if crate::geometry::fixes_fit(xf) { + one.pin_gradients(); + } match &mut one.kind { NodeKind::Image(im) => im.xf = xf * im.xf, NodeKind::SymbolInstance { xf: at, .. } => *at = xf * *at, diff --git a/crates/engine/src/tests/objexpand.rs b/crates/engine/src/tests/objexpand.rs index 4210a1d963..64e495b5e9 100644 --- a/crates/engine/src/tests/objexpand.rs +++ b/crates/engine/src/tests/objexpand.rs @@ -164,6 +164,33 @@ fn a_placed_gradient_moved_by_a_transform_or_free_distort_expands_as_the_canvas_ } } +/// A gradient fitted to the object turns with a Transform effect on the canvas, and Object › Expand +/// of the fill makes strips that draw the same. +#[test] +fn a_fitted_gradient_turned_by_a_transform_expands_as_the_canvas_draws_it() { + // The gray level at (x, y). + let gray = |r: &vectorcraft_render::Rendered, x: usize, y: usize| r.pixels[(y * 200 + x) * 4] as i32; + // The object's own effect, and the fill's (the first appearance item). + for (params, item) in + [(json!({"rotate": 90}), json!(null)), (json!({"rotate": 90}), json!(0)), (json!({"rotate": 30, "scaleH": 60}), json!(null))] + { + let mut s = session(); + let id = gradient_rect(&mut s, Rect::new(60.0, 60.0, 140.0, 140.0), white_black(), false); + run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": params, "ids": [id.0], "item": item})); + let before = render(&s); + if params["rotate"] == 90 { + // The white to black ramp runs up or down the turned square, not across it. + let (top, bottom) = (gray(&before, 100, 70), gray(&before, 100, 130)); + let (left, right) = (gray(&before, 70, 100), gray(&before, 130, 100)); + assert!((top - bottom).abs() > 100 && (left - right).abs() < 20, "{params} on item {item}: {top} {bottom} {left} {right}"); + } + run(&mut s, "object.expand", json!({"object": false, "stroke": false, "steps": 64})); + let after = render(&s); + let diff = mean_diff(&before, &after); + assert!(diff < 1.0, "{params} on item {item}: mean difference {diff}"); + } +} + #[test] fn eight_strips_match_the_gradient_samples() { let mut s = session(); diff --git a/crates/render/src/tests/objectfx.rs b/crates/render/src/tests/objectfx.rs index 173d91bb07..316f2b19bb 100644 --- a/crates/render/src/tests/objectfx.rs +++ b/crates/render/src/tests/objectfx.rs @@ -857,6 +857,41 @@ fn a_paths_gradient_moves_with_its_transform_and_free_distort() { assert!(red(rb(&img, 51, 50)) && blue(rb(&img, 78, 50)), "{:?} {:?}", rb(&img, 51, 50), rb(&img, 78, 50)); } +/// The canvas turns and reflects a gradient fitted to the square with its Transform effect, on the +/// object and as the fill's own effect. +#[test] +fn a_fitted_gradient_turns_and_reflects_with_its_transform_on_the_canvas() { + let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))]; + let fitted = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + let draw = |e: Effect, own: bool| { + let square = shapes::rectangle(vectorcraft_geom::Rect::new(10.0, 35.0, 40.0, 65.0)); + let mut n = Node::path(NodeId(0), square, Appearance::basic(fitted.clone(), Paint::None, 0.0)); + if own { + n.appearance.items[0].effects_mut().push(e); + } else { + n.appearance.effects.push(e); + } + render(&doc_with(Document::new(100.0, 100.0), n)) + }; + let rb = |img: &Rendered, x: u32, y: u32| { + let p = img.pixel(x, y); + (p[0], p[2]) + }; + let red = |(r, b): (u8, u8)| r > 200 && b < 60; + let blue = |(r, b): (u8, u8)| b > 200 && r < 60; + for own in [false, true] { + // A quarter turn: the left (red) to right (blue) ramp runs from the bottom up. + let img = draw(fx("distort.transform", json!({"rotate": 90})), own); + let (top, bottom) = (rb(&img, 25, 36), rb(&img, 25, 63)); + assert!(blue(top) && red(bottom), "own {own}: {top:?} {bottom:?}"); + assert_eq!(rb(&img, 12, 50), rb(&img, 38, 50), "own {own}: the same color across"); + // Reflected left to right: blue on the left, red on the right. + let img = draw(fx("distort.transform", json!({"reflectX": true})), own); + let (left, right) = (rb(&img, 11, 50), rb(&img, 38, 50)); + assert!(blue(left) && red(right), "own {own}: {left:?} {right:?}"); + } +} + #[test] fn darkness_subtracts_from_rgb_before_shadow_opacity() { for opacity in [50.0, 100.0] { diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index cdb4efaa10..78f040f84c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -539,6 +539,7 @@ since 2026-10-01. - **Warp Options (#1760):** Effect > Warp and existing Appearance effect links share the fifteen existing styles, original schematic previews, orientation choices and percent Bend/Distortion controls. Focused tests passed for real numeric entry and slider input, Preview/Cancel, immediate Enter/OK, mixed-style edits, target/slot/visibility preservation and Undo/Redo. Each applied style stays unchanged until an explicit Style choice. Original style-menu and live-preview captures were reviewed; their numeric values were supplied programmatically. Public references: [Reshaping with effects](https://helpx.adobe.com/illustrator/using/reshaping-objects-effects.html) and [Using effects](https://helpx.adobe.com/illustrator/using/effects.html). Warp geometry, optional Properties integration and remembered defaults are unchanged; no broader parity claim. - **Distort Appearance with Transform effect options:** with Envelope Options › Distort Appearance on, a path whose Transform effect has Scale Strokes & Effects or Transform Patterns on, or copies it with a gradient, is bent as the same per-copy art it draws and expands as outside the envelope: each copy's own stroke weight, dashes, pattern placement and gradient (effects `bake::tests`). Scores and hours unchanged. - **Placed gradients follow Transform and Free Distort effects:** a gradient placed with the Gradient tool moves, turns and scales with the object when the object's Transform effect moves its outline, and each copy of the Transform effect takes it as many times as it takes the transform. Under Free Distort it moves and scales from the path's bounds before the effect to its bounds after it. This holds on the canvas, in export, in Expand Appearance, in Pathfinder and compound shapes, and in Object › Expand of the fill, for an object's own effects, a group's (the own fills of the group, of the groups inside it, of a symbol's art, and of the images and symbol instances it moves, included) and a fill's or stroke's own. A gradient on a path inside a group with a Transform effect now moves with the path (#2214 moved only the gradients of type), and so does a gradient on an image's or symbol instance's own fill. When a path keeps its shape because the effect would pass the geometry budget, the group's own gradients stay in place. How gradients follow each effect is VectorCraft's own rule; what each effect does to the object is described in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (effects `bake::tests::a_baked_transform_moves_a_placed_gradient_with_the_path`, `bake::tests::a_strokes_own_transform_and_free_distort_move_its_placed_gradient`, `bake::tests::a_fills_gradient_follows_the_effects_around_its_transform_with_options`, `bake::tests::baked_free_distort_moves_placed_gradients_from_the_bounds_to_the_distorted_bounds`, `group::tests::a_groups_transform_and_free_distort_move_the_gradients_placed_on_its_paths`, `group::tests::a_groups_transform_moves_the_gradient_of_its_own_fill`, `group::tests::a_nested_groups_own_gradient_follows_the_outer_groups_transform_and_free_distort`, `group::tests::a_groups_transform_moves_the_gradients_placed_on_an_images_own_fills`, `group::tests::shape_art_moves_gradients_with_a_transform_effect`, `group::tests::shape_art_moves_the_gradient_of_a_symbol_instances_art_with_its_transform`, `tests::art_past_the_budget_keeps_its_own_gradients_in_place`; render `objectfx::a_paths_gradient_moves_with_its_transform_and_free_distort`; engine `objexpand::a_placed_gradient_moved_by_a_transform_or_free_distort_expands_as_the_canvas_draws_it`). Scores and hours unchanged. +- **Fitted gradients turn with the Transform effect:** a gradient fitted to the object (not placed with the Gradient tool) turns, reflects and stretches with the object when its Transform effect rotates, reflects or scales it unevenly, as Object › Transform already does: the gradient is fixed to its fit on the geometry the effect takes, then follows the effect and the effects after it as a placed gradient does. Under moves and even scales it draws as a refit does, and a Transform effect that scales the object to nothing across leaves it fitted. This holds on the canvas and in Object › Expand of the fill, for an object's own effects, a fill's or stroke's own, and a group's, where the gradients fitted to its paths, to its own fill, to the groups inside it and to its images' and symbol instances' own fills each fix to their own object's fit. Existing documents with such a Transform effect on fitted-gradient art draw differently: before, the gradient refit to the turned outline. How gradients follow the effect is VectorCraft's own rule; what the effect does to the object is described in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (effects `bake::tests::a_fitted_gradient_turns_reflects_and_stretches_with_a_transform_effect`, `bake::tests::a_transform_effect_that_scales_to_nothing_leaves_a_fitted_gradient_fitted`, `group::tests::a_groups_transform_turns_the_gradients_fitted_to_its_members_and_its_own_fill`; render `objectfx::a_fitted_gradient_turns_and_reflects_with_its_transform_on_the_canvas`; engine `objexpand::a_fitted_gradient_turned_by_a_transform_expands_as_the_canvas_draws_it`). Scores and hours unchanged. - **Constrain Angle (#394):** General › Constrain Angle turns the arrow keys' axes (guides stay on the page's), holds Shift drags of the Selection, Direct Selection, Free Transform, Slice Selection, Reshape and Measure tools and the Pen's handles to the turned axes, and new rectangles, rounded rectangles, ellipses, grids, point and area type, Shift-drawn polygons and stars and the shape size dialogs are drawn along it with their bounding box turned; 0° and whole turns are exactly as before, quarter turns exact (). Tests: `tests_constrain_tools`, `tests_constrain_new` (engine), `geom` `constrain_axes` / `rotate_deg`, the shape, grid and type tool tests. - **Clipping paths on their outline (G1):** the selection tools (Selection, Direct Selection, Group Selection), Object Highlighting and a right-click take a clipping path on its outline before the art it clips; Select Behind lists the same; the eyedropper, the tools that act on what is drawn and the selection tools' double-clicks, loaded text and guide release take the art. Doc and tool regression tests; score unchanged. From 83f1333d1c779223254f70407c848ae5507f23b9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 8 Nov 2026 14:14:48 -0800 Subject: [PATCH 11/11] Effects: a Transform effect that flattens the object leaves a fitted gradient fitted with its options on With Scale Strokes & Effects or Transform Patterns on, the path and each copy are moved by Node::transform, which fixed a fitted gradient to its fit before a scale of 0 flattened it to one color. Scaling::keep_fit_when_flat keeps the gradient fitted under a map that flattens the object (node::flattens, the gate fixes_fit already used), and the Transform effect's path transforms set it. docs/target-app-parity.md also says that the Gradient tool still shows a fitted gradient's vector at its unturned fit. --- crates/doc/src/node.rs | 2 +- crates/doc/src/node/live_shape.rs | 4 +++ crates/doc/src/node/ops.rs | 15 ++++++++-- crates/doc/src/node/tests.rs | 3 +- crates/effects/src/bake/tests.rs | 40 ++++++++++++++++++--------- crates/effects/src/geometry.rs | 6 ++-- crates/effects/src/reshape.rs | 5 +++- crates/eps/src/import/native/build.rs | 3 +- docs/target-app-parity.md | 2 +- 9 files changed, 56 insertions(+), 24 deletions(-) diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index 550ac37704..774e824390 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -31,7 +31,7 @@ pub use ids::{LAYER_COLORS, LayerColor, NodeId}; pub use kind::{ImageObject, MAX_BUFFERED_VALUES, NodeKind, with_buffered_value_budget}; pub use live_shape::{LiveShape, Scaling}; pub use opacity::{Knockout, OpacityMask, whiten}; -pub use ops::keeps_gradient_fit; +pub use ops::{flattens, keeps_gradient_fit}; use wire::NodeWire; pub use wire::{MAX_READ_NODES, with_node_budget}; diff --git a/crates/doc/src/node/live_shape.rs b/crates/doc/src/node/live_shape.rs index 93f2022e0b..9ddc4e1bb6 100644 --- a/crates/doc/src/node/live_shape.rs +++ b/crates/doc/src/node/live_shape.rs @@ -329,6 +329,10 @@ pub struct Scaling { /// Pattern fills and strokes move with the art (Transform Patterns; General › Transform /// Pattern Tiles is its default): their tiles transform too, instead of staying put. pub patterns: bool, + /// Gradients fitted to the object stay fitted under a transform that flattens it to a line or + /// a point (no area left), as a Transform effect leaves them, instead of being fixed to their + /// fit and flattened to one color with the object. + pub keep_fit_when_flat: bool, } impl Scaling { diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index bc1f72e743..f908e50a1e 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -431,7 +431,7 @@ impl Node { // Type and symbols in perspective keep looking the same, moved by `a`. self.transform_projection(a); // Refitting an unplaced gradient only reproduces moves and uniform scales. - if !keeps_gradient_fit(a) { + if !keeps_gradient_fit(a) && !(sc.keep_fit_when_flat && flattens(a)) { self.pin_gradients(); } let k = Scaling::factor(a); @@ -770,13 +770,24 @@ impl Node { } } -/// Is `a` a move plus a positive uniform scale (after which a refit gradient still matches)? +/// Is `a` a move plus a positive uniform scale (after which a refit gradient still matches)? The +/// terms are compared within 1e-12 of the scale (at least of 1). A scale of 0 or less, a turn, a +/// reflection and an uneven scale give false, and so does a map that flattens the object +/// ([`flattens`]), which callers that keep a fitted gradient there check apart. pub fn keeps_gradient_fit(a: Affine) -> bool { let [m0, m1, m2, m3, _, _] = a.as_coeffs(); let eps = 1e-12 * m0.abs().max(1.0); m0 > 0.0 && m1.abs() <= eps && m2.abs() <= eps && (m0 - m3).abs() <= eps } +/// Does `a` flatten what it maps to a line or a point (its determinant 0, within 1e-12 of the +/// squares of its terms), or is it not finite? +pub fn flattens(a: Affine) -> bool { + let [m0, m1, m2, m3, _, _] = a.as_coeffs(); + let norm = m0 * m0 + m1 * m1 + m2 * m2 + m3 * m3; + !a.is_finite() || a.determinant().abs() <= 1e-12 * norm +} + impl Node { /// Whether a document point lies in this object's filled regions ([`Node::clip_shapes`]; true /// everywhere for objects without them, such as type, whose boxes stand in). diff --git a/crates/doc/src/node/tests.rs b/crates/doc/src/node/tests.rs index 43a8ac97b5..335eb6312e 100644 --- a/crates/doc/src/node/tests.rs +++ b/crates/doc/src/node/tests.rs @@ -221,7 +221,8 @@ fn assert_round_corners(n: &Node, back: Affine, r: f64) { } } -const KEEP_CORNERS: Scaling = Scaling { strokes: false, effects: None, keep_type_strokes: false, keep_corners: true, patterns: false }; +const KEEP_CORNERS: Scaling = + Scaling { strokes: false, effects: None, keep_type_strokes: false, keep_corners: true, patterns: false, keep_fit_when_flat: false }; #[test] fn uneven_scales_keep_live_corners_circular() { diff --git a/crates/effects/src/bake/tests.rs b/crates/effects/src/bake/tests.rs index d42199a682..6643d91cb1 100644 --- a/crates/effects/src/bake/tests.rs +++ b/crates/effects/src/bake/tests.rs @@ -313,20 +313,34 @@ fn a_transform_effect_that_scales_to_nothing_leaves_a_fitted_gradient_fitted() { use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop}; let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))]; let fitted = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); - let mut n = Node::path(NodeId(50), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::basic(Paint::None, fitted, 4.0)); - n.appearance.effects = vec![fx("distort.transform", json!({"scaleH": 0.0, "rotate": 30.0}))]; - let d = bake_document(&doc_with(n)).unwrap(); - let mut found = vec![]; - d.node(NodeId(50)).unwrap().walk(&mut |c: &Node| { - for item in &c.appearance.items { - if let AppearanceItem::Stroke(s) = item - && let Paint::Gradient(g) = &s.paint - { - found.push(g.geom); - } + // With Scale Strokes & Effects or Transform Patterns on, and for each copy, as without them. + for (options, strokes) in [ + (json!({}), 1), + (json!({"strokes": true}), 1), + (json!({"patterns": true}), 1), + (json!({"copies": 2}), 3), + (json!({"strokes": true, "copies": 2}), 3), + (json!({"patterns": true, "copies": 2}), 3), + ] { + let mut n = Node::path(NodeId(50), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::basic(Paint::None, fitted.clone(), 4.0)); + let mut p = json!({"scaleH": 0.0, "rotate": 30.0}); + if let (Some(p), Some(o)) = (p.as_object_mut(), options.as_object()) { + p.extend(o.clone()); } - }); - assert_eq!(found, [None]); + n.appearance.effects = vec![fx("distort.transform", p)]; + let d = bake_document(&doc_with(n)).unwrap(); + let mut found = vec![]; + d.node(NodeId(50)).unwrap().walk(&mut |c: &Node| { + for item in &c.appearance.items { + if let AppearanceItem::Stroke(s) = item + && let Paint::Gradient(g) = &s.paint + { + found.push(g.geom); + } + } + }); + assert_eq!(found, vec![None; strokes], "{options}"); + } } #[test] diff --git a/crates/effects/src/geometry.rs b/crates/effects/src/geometry.rs index 0d51e1d2b3..ed5de8daf3 100644 --- a/crates/effects/src/geometry.rs +++ b/crates/effects/src/geometry.rs @@ -188,11 +188,9 @@ pub struct Carry(Vec); /// Does `m` fix a gradient fitted to the object to its fit before mapping it? It does when a refit /// would not reproduce the map (a turn, a reflection or an uneven scale) and `m` keeps area: a map /// that flattens the geometry to a line (a scale of 0) leaves the gradient fitted, since mapping it -/// would flatten it to one color. +/// would flatten it to one color ([`vectorcraft_doc::node::flattens`]). pub(crate) fn fixes_fit(m: vectorcraft_geom::Affine) -> bool { - let [a, b, c, d, _, _] = m.as_coeffs(); - let norm = a * a + b * b + c * c + d * d; - m.is_finite() && m.determinant().abs() > 1e-12 * norm && !vectorcraft_doc::node::keeps_gradient_fit(m) + !vectorcraft_doc::node::flattens(m) && !vectorcraft_doc::node::keeps_gradient_fit(m) } #[derive(Clone, Copy, Debug, PartialEq)] diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index 5ab50dff9c..441981f771 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -701,7 +701,8 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: b return; } if separate { - let made = copy_leaf(leaf, &path, m, copies, vectorcraft_doc::Scaling::default(), room); + let scaling = vectorcraft_doc::Scaling { keep_fit_when_flat: true, ..Default::default() }; + let made = copy_leaf(leaf, &path, m, copies, scaling, room); used = used.minus(before).plus(made); return; } @@ -771,6 +772,8 @@ fn transform_leaf( strokes: options.strokes, effects: options.strokes.then_some(crate::scale_effect as fn(&mut Effect, f64)), patterns: options.patterns, + // A map that flattens the path leaves its fitted gradients fitted, as `fixes_fit` does. + keep_fit_when_flat: true, ..Default::default() }; if !options.objects { diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index 57d9611816..39c751bfcf 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -22,7 +22,8 @@ pub(super) enum Page { /// How art moved from a page to its place in the layers' document transforms: its pattern tiles /// move with it. -pub(super) const PAGE_MOVE: Scaling = Scaling { strokes: false, effects: None, keep_type_strokes: false, keep_corners: false, patterns: true }; +pub(super) const PAGE_MOVE: Scaling = + Scaling { strokes: false, effects: None, keep_type_strokes: false, keep_corners: false, patterns: true, keep_fit_when_flat: false }; /// The page (`visible`, the file read as its page) and the place of its area in the layers' /// document. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 5082cb6f4c..7679101f0d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -549,7 +549,7 @@ since 2026-10-01. - **Transform effect options (#885):** Effect › Distort & Transform › Transform… has visible Transform Objects, Transform Patterns and Scale Strokes & Effects checkboxes (`distort.transform` params `objects`, `patterns`, `strokes`; files without them draw as before). With Transform Objects off the geometry stays and makes no copies; Scale Strokes & Effects scales stroke weights, dashes and the fills' and strokes' effect distances by the mean scale, and Transform Patterns moves pattern tiles, each copy `k` by the transformation `k` times. Such objects draw, export and expand through the same per-copy art, so the canvas and Expand Appearance agree (engine `tests_transformfx`, effects `tests_transformfx`, the dialog test). A Transform effect in a fill's or stroke's own effects applies the same options to that fill or stroke: its weight and dashes, the distances of its later effects and its pattern follow the transformation, and with copies each copy is an object of its own; the canvas, export, Expand Appearance and Use Preview Bounds use the same art (effects `tests_transformfx`). Not yet: object effects after a Transform effect keep their distances. Public reference: [Scale objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html), [How to apply effects](https://helpx.adobe.com/illustrator/using/effects.html), [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html). Scores and hours unchanged. - **Warp Options (#1760):** Effect > Warp and existing Appearance effect links share the fifteen existing styles, original schematic previews, orientation choices and percent Bend/Distortion controls. Focused tests passed for real numeric entry and slider input, Preview/Cancel, immediate Enter/OK, mixed-style edits, target/slot/visibility preservation and Undo/Redo. Each applied style stays unchanged until an explicit Style choice. Original style-menu and live-preview captures were reviewed; their numeric values were supplied programmatically. Public references: [Reshaping with effects](https://helpx.adobe.com/illustrator/using/reshaping-objects-effects.html) and [Using effects](https://helpx.adobe.com/illustrator/using/effects.html). Warp geometry, optional Properties integration and remembered defaults are unchanged; no broader parity claim. - **Distort Appearance with Transform effect options:** with Envelope Options › Distort Appearance on, a path whose Transform effect has Scale Strokes & Effects or Transform Patterns on, or copies it with a gradient, is bent as the same per-copy art it draws and expands as outside the envelope: each copy's own stroke weight, dashes, pattern placement and gradient (effects `bake::tests`). Scores and hours unchanged. -- **Fitted gradients turn with the Transform effect:** a gradient fitted to the object (not placed with the Gradient tool) turns, reflects and stretches with the object when its Transform effect rotates, reflects or scales it unevenly, as Object › Transform already does: the gradient is fixed to its fit on the geometry the effect takes, then follows the effect and the effects after it as a placed gradient does. Under moves and even scales it draws as a refit does, and a Transform effect that scales the object to nothing across leaves it fitted. This holds on the canvas and in Object › Expand of the fill, for an object's own effects, a fill's or stroke's own, and a group's, where the gradients fitted to its paths, to its own fill, to the groups inside it and to its images' and symbol instances' own fills each fix to their own object's fit. Existing documents with such a Transform effect on fitted-gradient art draw differently: before, the gradient refit to the turned outline. How gradients follow the effect is VectorCraft's own rule; what the effect does to the object is described in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (effects `bake::tests::a_fitted_gradient_turns_reflects_and_stretches_with_a_transform_effect`, `bake::tests::a_transform_effect_that_scales_to_nothing_leaves_a_fitted_gradient_fitted`, `group::tests::a_groups_transform_turns_the_gradients_fitted_to_its_members_and_its_own_fill`; render `objectfx::a_fitted_gradient_turns_and_reflects_with_its_transform_on_the_canvas`; engine `objexpand::a_fitted_gradient_turned_by_a_transform_expands_as_the_canvas_draws_it`). Scores and hours unchanged. +- **Fitted gradients turn with the Transform effect:** a gradient fitted to the object (not placed with the Gradient tool) turns, reflects and stretches with the object when its Transform effect rotates, reflects or scales it unevenly, as Object › Transform already does: the gradient is fixed to its fit on the geometry the effect takes, then follows the effect and the effects after it as a placed gradient does. Under moves and even scales it draws as a refit does, and a Transform effect that scales the object to nothing across leaves it fitted, with Scale Strokes & Effects or Transform Patterns on too, and on each copy. This holds on the canvas and in Object › Expand of the fill, for an object's own effects, a fill's or stroke's own, and a group's, where the gradients fitted to its paths, to its own fill, to the groups inside it and to its images' and symbol instances' own fills each fix to their own object's fit. Existing documents with such a Transform effect on fitted-gradient art draw differently: before, the gradient refit to the turned outline. The Gradient tool still shows a fitted gradient's vector at its unturned fit. How gradients follow the effect is VectorCraft's own rule; what the effect does to the object is described in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (effects `bake::tests::a_fitted_gradient_turns_reflects_and_stretches_with_a_transform_effect`, `bake::tests::a_transform_effect_that_scales_to_nothing_leaves_a_fitted_gradient_fitted`, `group::tests::a_groups_transform_turns_the_gradients_fitted_to_its_members_and_its_own_fill`; render `objectfx::a_fitted_gradient_turns_and_reflects_with_its_transform_on_the_canvas`; engine `objexpand::a_fitted_gradient_turned_by_a_transform_expands_as_the_canvas_draws_it`). Scores and hours unchanged. - **Placed gradients follow Transform and Free Distort effects:** a gradient placed with the Gradient tool moves, turns and scales with the object when the object's Transform effect moves its outline, and each copy of the Transform effect takes it as many times as it takes the transform. Under Free Distort it moves and scales from the path's bounds before the effect to its bounds after it. This holds on the canvas, in export, in Expand Appearance, in Pathfinder and compound shapes, and in Object › Expand of the fill, for an object's own effects, a group's (the own fills of the group, of the groups inside it, of a symbol's art, and of the images and symbol instances it moves, included) and a fill's or stroke's own. A gradient on a path inside a group with a Transform effect now moves with the path (#2214 moved only the gradients of type), and so does a gradient on an image's or symbol instance's own fill. When a path keeps its shape because the effect would pass the geometry budget, the group's own gradients stay in place; a hidden path in a layer, which the layer's bounds leave out, does not hold them. A freeform gradient whose points were edited moves its points in the same way. How gradients follow each effect is VectorCraft's own rule; what each effect does to the object is described in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (effects `bake::tests::a_baked_transform_moves_a_placed_gradient_with_the_path`, `bake::tests::a_strokes_own_transform_and_free_distort_move_its_placed_gradient`, `bake::tests::a_fills_gradient_follows_the_effects_around_its_transform_with_options`, `bake::tests::baked_free_distort_moves_placed_gradients_from_the_bounds_to_the_distorted_bounds`, `group::tests::a_groups_transform_and_free_distort_move_the_gradients_placed_on_its_paths`, `group::tests::a_groups_transform_moves_the_gradient_of_its_own_fill`, `group::tests::a_nested_groups_own_gradient_follows_the_outer_groups_transform_and_free_distort`, `group::tests::a_groups_transform_moves_the_gradients_placed_on_an_images_own_fills`, `group::tests::shape_art_moves_gradients_with_a_transform_effect`, `group::tests::shape_art_moves_the_gradient_of_a_symbol_instances_art_with_its_transform`, `tests::art_past_the_budget_keeps_its_own_gradients_in_place`, `tests::a_hidden_path_past_the_budget_leaves_a_layers_gradients_free_to_move`, `tests::edited_freeform_points_follow_a_transform_effect_and_free_distort`; render `objectfx::a_paths_gradient_moves_with_its_transform_and_free_distort`; engine `objexpand::a_placed_gradient_moved_by_a_transform_or_free_distort_expands_as_the_canvas_draws_it`). Scores and hours unchanged. - **Constrain Angle (#394):** General › Constrain Angle turns the arrow keys' axes (guides stay on the page's), holds Shift drags of the Selection, Direct Selection, Free Transform, Slice Selection, Reshape and Measure tools and the Pen's handles to the turned axes, and new rectangles, rounded rectangles, ellipses, grids, point and area type, Shift-drawn polygons and stars and the shape size dialogs are drawn along it with their bounding box turned; 0° and whole turns are exactly as before, quarter turns exact (). Tests: `tests_constrain_tools`, `tests_constrain_new` (engine), `geom` `constrain_axes` / `rotate_deg`, the shape, grid and type tool tests.