diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index ef18af36..2f78bc1a 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -56,6 +56,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::layer_ops::specs()); v.extend(crate::instance_cmds::specs()); v.extend(crate::mask_cmds::specs()); + v.extend(crate::effect_clipboard::specs()); v.extend(crate::tool_cmds::specs()); v.extend(crate::brush_preset_cmds::specs()); v.extend(crate::path_tool::specs()); diff --git a/crates/engine/src/effect_clipboard.rs b/crates/engine/src/effect_clipboard.rs new file mode 100644 index 00000000..8132c9ca --- /dev/null +++ b/crates/engine/src/effect_clipboard.rs @@ -0,0 +1,124 @@ +//! Copy and paste effects between layers, masks and texture sets. The clipboard is the layer +//! clipboard: it holds a layer or an effect. + +use serde_json::{Value, json}; +use texturecraft_core::{EffectKind, LayerId, Mask, MaskBackground, Source}; + +use crate::commands::{CommandSpec, bad, has_layer, layer_param, strp}; +use crate::layer_ops::{empty_texel, fit}; +use crate::mask_cmds::{anchor_source, content_target, effect_id}; +use crate::session::StackTarget; +use crate::{EngineError, Result, Session, cmd}; + +pub fn specs() -> Vec { + vec![ + cmd!("effect.copy", "Copy effect", [], None, "{effect?: the selected effect}", has_layer, copy), + cmd!("effect.cut", "Cut effect", [], None, "{effect?: the selected effect}", has_layer, cut), + cmd!( + "effect.paste", + "Paste effect", + [], + None, + "{layer?, target?: mask|content (default: the selection's stack)} → {effect} — above the selected effect, or on top of the stack", + can_paste, + paste + ), + ] +} + +/// The copied effect, if the clipboard holds one. +fn clipboard_effect(s: &Session) -> Option { + s.clipboard.as_ref().and_then(|(doc, id)| doc.project.effect(*id).map(|_| *id)) +} + +fn can_paste(s: &Session) -> std::result::Result<(), String> { + match clipboard_effect(s) { + Some(_) if s.selected_layer().is_some() => Ok(()), + Some(_) => Err("select a layer to paste the effect on".into()), + None => Err("the clipboard holds no effect".into()), + } +} + +fn copy(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "effect.copy"; + let eid = effect_id(s, p, CMD)?; + if s.doc.project.effect(eid).is_none() { + return Err(bad(CMD, format!("no effect {}", eid.0))); + } + s.clipboard = Some((s.doc.clone(), eid)); + Ok(json!({ "copied": eid.0 })) +} + +fn cut(s: &mut Session, p: &Value) -> Result { + let eid = copy(s, p)?["copied"].clone(); + crate::execute(s, "effect.remove", &json!({ "effect": eid }))?; + Ok(json!({ "cut": eid })) +} + +fn paste(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "effect.paste"; + let (src, eid) = s.clipboard.clone().ok_or_else(|| bad(CMD, "the clipboard holds no effect"))?; + let effect = src.project.effect(eid).map(|(_, e)| e.clone()).ok_or_else(|| bad(CMD, "the clipboard holds no effect"))?; + let layer = layer_param(s, CMD, p)?; + // The selected effect's stack, or the content or mask the selection targets. + let selected = match s.target { + StackTarget::Effect(x) if s.selected_layer() == Some(layer) => Some(x), + _ => None, + }; + let in_content = |s: &Session, x: LayerId| { + s.doc.project.effect(x).and_then(|(o, _)| s.doc.project.layers.get(&o)).is_some_and(|l| l.content_effects.iter().any(|e| e.id == x)) + }; + let asked = strp(p, "target").is_some(); + let content = match selected { + _ if asked => content_target(p, CMD)?, + Some(x) => in_content(s, x), + None => s.target == StackTarget::Content && s.selected_layer() == Some(layer), + }; + // Effects that fit one stack only go there, unless another was asked for. + let content = match effect.kind.content_only() { + Some(only) if only != content && asked => { + return Err(bad(CMD, format!("{} effects go on the {}", effect.kind.name(), if only { "layer content" } else { "mask" }))); + } + Some(only) => only, + None => content, + }; + // An instance's content and (unless it has its own) mask belong to its source. + let owner = if content { s.doc.project.content_layer(layer).map_or(layer, |l| l.id) } else { s.doc.project.mask_owner(layer) }; + let owner_layer = s.doc.project.layer(owner)?; + if content && owner_layer.is_group() { + return Err(EngineError::Other(format!("\"{}\" is a folder: content effects go on paint and fill layers", owner_layer.name))); + } + // A fill reading an anchor point needs one below its new layer. + if let EffectKind::Fill { source: Source::Anchor { anchor, channel }, .. } = &effect.kind { + anchor_source(s, CMD, owner, *anchor, *channel)?; + } + let (ts, _, _) = s.doc.project.locate(owner).ok_or_else(|| bad(CMD, "the layer is not in a stack"))?; + let (size, channels) = s.doc.project.texture_set(ts).map(|t| (t.size(), t.channel_list()))?; + let new = s.edit("Paste effect", |s| { + let new = s.doc.project.alloc_id(); + let l = s.doc.project.layer_mut(owner)?; + let list = if content { + &mut l.content_effects + } else { + let bg = if matches!(effect.kind, EffectKind::Generator(_) | EffectKind::Fill { .. }) { MaskBackground::Black } else { MaskBackground::White }; + &mut l.mask.get_or_insert_with(|| Mask::new(bg)).effects + }; + let at = selected.and_then(|x| list.iter().position(|e| e.id == x)).map_or(list.len(), |i| i + 1); + list.insert(at, texturecraft_core::Effect { id: new, ..effect.clone() }); + // Painted pixels come along, resampled to the set's size (a mask's paint stays a mask's). + if let Some(img) = src.pixels.masks.get(&eid).filter(|_| !content) { + s.doc.pixels.masks.insert(new, fit(img, size, &[0, 0])); + } + for c in channels.iter().copied().filter(|_| content) { + if let Some(img) = src.pixels.layer(eid, c) { + s.doc.pixels.layers.insert((new, c), fit(img, size, &empty_texel(c))); + } + } + if let Some((lts, _, _)) = s.doc.project.locate(layer) { + s.selected.insert(lts, layer); + } + s.target = StackTarget::Effect(new); + Ok(new) + })?; + Ok(json!({ "effect": new.0 })) +} diff --git a/crates/engine/src/instance_cmds.rs b/crates/engine/src/instance_cmds.rs index 255a69c3..a9307883 100644 --- a/crates/engine/src/instance_cmds.rs +++ b/crates/engine/src/instance_cmds.rs @@ -69,6 +69,7 @@ fn instance(s: &mut Session, p: &Value) -> Result { fn can_paste_instance(s: &Session) -> std::result::Result<(), String> { match &s.clipboard { Some((_, id)) if s.doc.project.locate(*id).is_some() => Ok(()), + Some((doc, id)) if doc.project.effect(*id).is_some() => Err("the clipboard holds an effect (effect.paste)".into()), Some(_) => Err("the copied layer is no longer in the project (paste it instead)".into()), None => Err("the layer clipboard is empty".into()), } diff --git a/crates/engine/src/layer_ops.rs b/crates/engine/src/layer_ops.rs index 0d260063..9493009b 100644 --- a/crates/engine/src/layer_ops.rs +++ b/crates/engine/src/layer_ops.rs @@ -36,7 +36,11 @@ pub fn specs() -> Vec { } fn can_paste(s: &Session) -> std::result::Result<(), String> { - if s.clipboard.is_some() { Ok(()) } else { Err("the layer clipboard is empty".into()) } + match &s.clipboard { + Some((doc, id)) if doc.project.layers.contains_key(id) => Ok(()), + Some(_) => Err("the clipboard holds an effect (effect.paste)".into()), + None => Err("the layer clipboard is empty".into()), + } } /// Encoded "nothing painted" texel for a channel image (value 0, coverage 0). @@ -47,7 +51,7 @@ pub(crate) fn empty_texel(c: Channel) -> Vec { v } -fn fit(img: &TileImage, (w, h): (u32, u32), empty: &[u16]) -> TileImage { +pub(crate) fn fit(img: &TileImage, (w, h): (u32, u32), empty: &[u16]) -> TileImage { if (img.width(), img.height()) == (w, h) { img.clone() } else { img.resampled(w, h, empty) } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 8016a5d0..678f66e0 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -13,6 +13,7 @@ pub mod brush_preset_cmds; pub mod camera_cmds; pub mod commands; pub mod decal_cmds; +pub mod effect_clipboard; pub mod file_cmds; pub mod filter_lib; pub mod inspect; diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 90d54c0b..784755c2 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -98,8 +98,16 @@ pub fn specs() -> Vec { has_layer, set ), - cmd!("effect.remove", "Remove effect", [], None, "{effect}", has_layer, remove_effect), - cmd!("effect.duplicate", "Duplicate effect", [], None, "{effect} → {effect} (the copy, just above it, pixels included)", has_layer, duplicate_effect), + cmd!("effect.remove", "Remove effect", [], None, "{effect?: the selected effect}", has_layer, remove_effect), + cmd!( + "effect.duplicate", + "Duplicate effect", + [], + None, + "{effect?: the selected effect} → {effect} (the copy, just above it, pixels included)", + has_layer, + duplicate_effect + ), cmd!("effect.move", "Move effect", [], None, "{effect, index: position in its stack, 0 = bottom (applied first)}", has_layer, move_effect), cmd!( "effect.histogram", @@ -211,7 +219,7 @@ fn remove(s: &mut Session, p: &Value) -> Result { /// Whether `effect.add.*` targets the layer content (`target: "content"`) or its mask (the /// default). -fn content_target(p: &Value, cmd: &str) -> Result { +pub(crate) fn content_target(p: &Value, cmd: &str) -> Result { match strp(p, "target") { None | Some("mask") => Ok(false), Some("content") => Ok(true), @@ -380,14 +388,19 @@ fn add_compare(s: &mut Session, p: &Value) -> Result { push_effect(s, p, kind, BlendMode::Normal) } -fn effect_id(p: &Value, cmd: &str) -> Result { - u64p(p, "effect").map(LayerId).ok_or_else(|| bad(cmd, "`effect` id is required")) +/// The `effect` param, or the selected effect. +pub(crate) fn effect_id(s: &Session, p: &Value, cmd: &str) -> Result { + match (u64p(p, "effect"), s.target) { + (Some(e), _) => Ok(LayerId(e)), + (None, StackTarget::Effect(e)) => Ok(e), + (None, _) => Err(bad(cmd, "`effect` is required (no effect is selected)")), + } } /// The distribution of the values entering an effect (what a levels effect remaps). fn histogram(s: &mut Session, p: &Value) -> Result { const CMD: &str = "effect.histogram"; - let eid = effect_id(p, CMD)?; + let eid = effect_id(s, p, CMD)?; let (owner, _) = s.doc.project.effect(eid).ok_or_else(|| bad(CMD, format!("no effect {}", eid.0)))?; let l = s.doc.project.layer(owner)?; let content = l.content_effects.iter().any(|e| e.id == eid); @@ -401,7 +414,7 @@ fn histogram(s: &mut Session, p: &Value) -> Result { } fn set(s: &mut Session, p: &Value) -> Result { - let eid = effect_id(p, "effect.set")?; + let eid = effect_id(s, p, "effect.set")?; let blend = blend_param("effect.set", p, "blend")?; // A fill reading an anchor: `anchor` picks the anchor point, `anchorChannel` alone // re-targets the current one. @@ -470,7 +483,7 @@ fn stack_of(project: &mut Project, eid: LayerId) -> Option<(&mut Vec, us fn duplicate_effect(s: &mut Session, p: &Value) -> Result { const CMD: &str = "effect.duplicate"; - let eid = effect_id(p, CMD)?; + let eid = effect_id(s, p, CMD)?; let new = s.edit("Duplicate effect", |s| { let new = s.doc.project.alloc_id(); let (list, i) = stack_of(&mut s.doc.project, eid).ok_or_else(|| bad(CMD, format!("no effect {}", eid.0)))?; @@ -498,7 +511,7 @@ fn duplicate_effect(s: &mut Session, p: &Value) -> Result { fn move_effect(s: &mut Session, p: &Value) -> Result { const CMD: &str = "effect.move"; - let eid = effect_id(p, CMD)?; + let eid = effect_id(s, p, CMD)?; let index = u64p(p, "index").ok_or_else(|| bad(CMD, "`index` is required"))?; s.edit("Move effect", |s| { let (list, i) = stack_of(&mut s.doc.project, eid).ok_or_else(|| bad(CMD, format!("no effect {}", eid.0)))?; @@ -511,7 +524,7 @@ fn move_effect(s: &mut Session, p: &Value) -> Result { } fn remove_effect(s: &mut Session, p: &Value) -> Result { - let eid = effect_id(p, "effect.remove")?; + let eid = effect_id(s, p, "effect.remove")?; s.edit("Remove effect", |s| { let content = match s.doc.project.effect(eid) { Some((owner, _)) => s.doc.project.layer(owner)?.content_effects.iter().any(|e| e.id == eid), diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index b19fbb02..9b5acfa5 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -333,7 +333,7 @@ pub struct Session { /// Viewport size (pixels) used by scripted strokes. pub viewport: Vec2, pub(crate) stroke: Option, - /// Layer clipboard: a document snapshot and the copied layer. + /// Layer clipboard: a document snapshot and the copied layer (or effect). pub clipboard: Option<(Document, LayerId)>, /// Decoded image resources (rebuilt from `doc.resources` by `Session::sync_images`). pub images: texturecraft_compose::ImageStore, diff --git a/crates/engine/tests/content_effects.rs b/crates/engine/tests/content_effects.rs index dca2378b..e6c75e1e 100644 --- a/crates/engine/tests/content_effects.rs +++ b/crates/engine/tests/content_effects.rs @@ -1,7 +1,7 @@ //! Content effects, HSL and anchor points through engine commands. use serde_json::{Value, json}; -use texturecraft_engine::core::{Channel, LayerId}; +use texturecraft_engine::core::{Channel, EffectKind, LayerId}; use texturecraft_engine::geom::primitives; use texturecraft_engine::{Session, StackTarget, execute}; @@ -155,6 +155,51 @@ fn effects_move_within_their_stack_and_duplicate_with_their_pixels() { assert_eq!(mask, [b, a]); } +#[test] +fn effects_copy_and_paste_between_layers_and_stacks() { + let mut s = session(); + let low = id(execute(&mut s, "layer.add.fill", &json!({"roughness": 0.3})).unwrap(), "layer"); + let paint = id(execute(&mut s, "effect.add.paint", &json!({"target": "content"})).unwrap(), "effect"); + execute(&mut s, "tool.material", &json!({"channel": "roughness", "value": 0.9})).unwrap(); + execute(&mut s, "tool.brush", &json!({"size": 20, "hardness": 90})).unwrap(); + execute(&mut s, "tool.stroke", &json!({"points": [[180, 200], [220, 200]]})).unwrap(); + assert_eq!(execute(&mut s, "effect.copy", &Value::Null).unwrap(), json!({"copied": paint}), "the selected effect"); + assert!(execute(&mut s, "layer.paste", &Value::Null).is_err(), "the clipboard holds an effect, not a layer"); + // Onto the content of a fill above that covers the first: its strokes come along. + let high = id(execute(&mut s, "layer.add.fill", &json!({"roughness": 0.3})).unwrap(), "layer"); + let pasted = id(execute(&mut s, "effect.paste", &Value::Null).unwrap(), "effect"); + assert_eq!(s.target, StackTarget::Effect(LayerId(pasted))); + assert!(s.doc.pixels.layer(LayerId(pasted), Channel::Roughness).is_some()); + execute(&mut s, "effect.remove", &json!({"effect": paint})).unwrap(); + assert!(center(&mut s, Channel::Roughness)[0] > 0.85, "{:?}", center(&mut s, Channel::Roughness)); + // Above the selected effect. + let inv = id(execute(&mut s, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(), "effect"); + execute(&mut s, "effect.copy", &json!({"effect": inv})).unwrap(); + execute(&mut s, "layer.select", &json!({"layer": high, "target": pasted})).unwrap(); + let again = id(execute(&mut s, "effect.paste", &Value::Null).unwrap(), "effect"); + let order: Vec = s.doc.project.layer(LayerId(high)).unwrap().content_effects.iter().map(|e| e.id.0).collect(); + assert_eq!(order, [pasted, again, inv]); + // A generator goes on a mask (made for it) even with the content selected; asking for the + // content is an error. Cut removes the original. + execute(&mut s, "layer.select", &json!({"layer": high})).unwrap(); + let generator = id(execute(&mut s, "effect.add.generator", &Value::Null).unwrap(), "effect"); + execute(&mut s, "effect.cut", &json!({"effect": generator})).unwrap(); + assert!(s.doc.project.effect(LayerId(generator)).is_none()); + execute(&mut s, "layer.select", &json!({"layer": low})).unwrap(); + assert!(execute(&mut s, "effect.paste", &json!({"target": "content"})).is_err()); + execute(&mut s, "effect.paste", &Value::Null).unwrap(); + let mask = &s.doc.project.layer(LayerId(low)).unwrap().mask; + assert!(mask.as_ref().is_some_and(|m| m.effects.iter().any(|e| matches!(e.kind, EffectKind::Generator(_))))); + // A fill reading an anchor point needs one below its new layer. + execute(&mut s, "layer.select", &json!({"layer": low})).unwrap(); + let anchor = id(execute(&mut s, "effect.add.anchor", &Value::Null).unwrap(), "effect"); + execute(&mut s, "layer.select", &json!({"layer": high})).unwrap(); + let reader = id(execute(&mut s, "effect.add.fill", &json!({"target": "mask", "anchor": anchor})).unwrap(), "effect"); + execute(&mut s, "effect.copy", &json!({"effect": reader})).unwrap(); + execute(&mut s, "layer.select", &json!({"layer": low})).unwrap(); + assert!(execute(&mut s, "effect.paste", &Value::Null).is_err(), "the anchor is on the layer itself"); +} + #[test] fn histogram_counts_what_an_effect_reads() { let mut s = session(); diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 889478fb..5d0f6186 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -581,14 +581,26 @@ fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, stack: &[Ef app.run("effect.move", json!({"effect": src.0, "index": index})); } resp.context_menu(|ui| { - if ui.button(tr("Duplicate effect")).clicked() { - app.run("layer.select", json!({"layer": layer.id.0, "target": eid.0})); - app.run("effect.duplicate", json!({"effect": eid.0})); - ui.close(); - } - if ui.button(tr("Remove effect")).clicked() { - app.run("effect.remove", json!({"effect": eid.0})); - ui.close(); + let keymap = app.ui.keymap.clone(); + let paste = crate::menus::enabled(app, "effect.paste"); + // The clipboard items show the layer clipboard's shortcuts, which act on a selected effect. + for (label, id, keys, enabled) in [ + (tr("Copy effect"), "effect.copy", Some("layer.copy"), true), + (tr("Cut effect"), "effect.cut", Some("layer.cut"), true), + (tr("Paste effect"), "effect.paste", Some("layer.paste"), paste), + (tr("Duplicate effect"), "effect.duplicate", None, true), + (tr("Remove effect"), "effect.remove", None, true), + ] { + let mut b = egui::Button::new(label); + if let Some(sc) = keys.and_then(|k| crate::keymap::shortcut_of(&keymap, k)) { + b = b.shortcut_text(sc); + } + if ui.add_enabled(enabled, b).clicked() { + // Selected first: a paste lands above it, a duplicate takes the selection. + app.run("layer.select", json!({"layer": layer.id.0, "target": eid.0})); + app.run(id, json!({"effect": eid.0})); + ui.close(); + } } }); } @@ -681,7 +693,9 @@ fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { ui.separator(); run(app, ui, tr("Cut layer(s)"), "layer.cut", json!({"layer": lid}), true); run(app, ui, tr("Copy layer(s)"), "layer.copy", json!({"layer": lid}), true); - run(app, ui, tr("Paste layer(s)"), "layer.paste", json!({}), app.session.clipboard.is_some()); + let (paste_layer, paste_effect) = (crate::menus::enabled(app, "layer.paste"), crate::menus::enabled(app, "effect.paste")); + run(app, ui, tr("Paste layer(s)"), "layer.paste", json!({}), paste_layer); + run(app, ui, tr("Paste effect"), "effect.paste", json!({}), paste_effect); let paste_instance = crate::menus::enabled(app, "layer.pasteInstance"); run(app, ui, tr("Paste as instance"), "layer.pasteInstance", json!({}), paste_instance); run(app, ui, tr("Duplicate layer(s)"), "layer.duplicate", json!({"layer": lid}), true); diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 102df4d8..2b4d1eb9 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -187,6 +187,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Contrast/Luminosity", "التباين / الإضاءة"), ("Converted maps", "الخرائط المحوّلة"), ("Copy RGB values", "نسخ قيم RGB"), + ("Copy effect", "نسخ التأثير"), ("Copy from", "نسخ من"), ("Copy layer(s)", "نسخ الطبقة (الطبقات)"), ("Copy the selected layer alone (its empty parts copy nothing)", "نسخ الطبقة المحددة وحدها (الأجزاء الفارغة لا تنسخ شيئاً)"), @@ -213,6 +214,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Cube", "مكعب"), ("Current layer", "الطبقة الحالية"), ("Curvature", "الانحناء"), + ("Cut effect", "قص التأثير"), ("Cut layer(s)", "قص الطبقة (الطبقات)"), ("Cyan / red", "سماوي / أحمر"), ("Cylinder", "أسطوانة"), @@ -587,6 +589,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Particles", "جسيمات"), ("Passthrough", "تمرير مباشر (Passthrough)"), ("Paste as instance", "لصق كنسخة مرتبطة (Instance)"), + ("Paste effect", "لصق التأثير"), ("Paste layer(s)", "لصق الطبقة (الطبقات)"), ("Path", "مسار"), ("Path trace on the processor instead of the graphics card (slower)", "تتبع المسار على المعالج بدلاً من بطاقة الرسوميات (أبطأ)"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 0f0069ab..22d868a9 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -199,6 +199,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Contrast/Luminosity", "Kontrast/Luminanz"), ("Converted maps", "Konvertierte Maps"), ("Copy RGB values", "RGB-Werte kopieren"), + ("Copy effect", "Effekt kopieren"), ("Copy from", "Kopieren aus"), ("Copy layer(s)", "Ebene(n) kopieren"), ("Copy the selected layer alone (its empty parts copy nothing)", "Nur die ausgewählte Ebene kopieren (ihre leeren Bereiche kopieren nichts)"), @@ -225,6 +226,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Cube", "Würfel"), ("Current layer", "Aktuelle Ebene"), ("Curvature", "Krümmung"), + ("Cut effect", "Effekt ausschneiden"), ("Cut layer(s)", "Ebene(n) ausschneiden"), ("Cyan / red", "Cyan / Rot"), ("Cylinder", "Zylinder"), @@ -623,6 +625,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Particles", "Partikel"), ("Passthrough", "Hindurchwirken"), ("Paste as instance", "Als Instanz einfügen"), + ("Paste effect", "Effekt einfügen"), ("Paste layer(s)", "Ebene(n) einfügen"), ("Path", "Pfad"), ("Path trace on the processor instead of the graphics card (slower)", "Path Tracing auf dem Prozessor statt auf der Grafikkarte (langsamer)"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 85ddf17e..076fe369 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -196,6 +196,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Contrast/Luminosity", "Contraste/Luminosidad"), ("Converted maps", "Mapas convertidos"), ("Copy RGB values", "Copiar los valores RGB"), + ("Copy effect", "Copiar efecto"), ("Copy from", "Copiar de"), ("Copy layer(s)", "Copiar capa(s)"), ("Copy the selected layer alone (its empty parts copy nothing)", "Copiar solo la capa seleccionada (sus partes vacías no copian nada)"), @@ -222,6 +223,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Cube", "Cubo"), ("Current layer", "Capa actual"), ("Curvature", "Curvatura"), + ("Cut effect", "Cortar efecto"), ("Cut layer(s)", "Cortar capa(s)"), ("Cyan / red", "Cian / rojo"), ("Cylinder", "Cilindro"), @@ -614,6 +616,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Particles", "Partículas"), ("Passthrough", "Paso directo"), ("Paste as instance", "Pegar como instancia"), + ("Paste effect", "Pegar efecto"), ("Paste layer(s)", "Pegar capa(s)"), ("Path", "Trazado"), ("Path trace on the processor instead of the graphics card (slower)", "Trazar trayectorias en el procesador en lugar de la tarjeta gráfica (más lento)"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index cd6dde9f..3d970991 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -199,6 +199,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Contrast/Luminosity", "Contraste/Luminosité"), ("Converted maps", "Cartes converties"), ("Copy RGB values", "Copier les valeurs RVB"), + ("Copy effect", "Copier l'effet"), ("Copy from", "Copier depuis"), ("Copy layer(s)", "Copier le(s) calque(s)"), ("Copy the selected layer alone (its empty parts copy nothing)", "Copier uniquement le calque sélectionné (ses parties vides ne copient rien)"), @@ -225,6 +226,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Cube", "Cube"), ("Current layer", "Calque actuel"), ("Curvature", "Courbure"), + ("Cut effect", "Couper l'effet"), ("Cut layer(s)", "Couper le(s) calque(s)"), ("Cyan / red", "Cyan / rouge"), ("Cylinder", "Cylindre"), @@ -626,6 +628,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Particles", "Particules"), ("Passthrough", "Transfert"), ("Paste as instance", "Coller comme instance"), + ("Paste effect", "Coller l'effet"), ("Paste layer(s)", "Coller le(s) calque(s)"), ("Path", "Tracé"), ("Path trace on the processor instead of the graphics card (slower)", "Tracé de chemins sur le processeur au lieu de la carte graphique (plus lent)"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 0bfc3d40..3fb774b3 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -202,6 +202,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Contrast/Luminosity", "Contrasto/Luminosità"), ("Converted maps", "Mappe convertite"), ("Copy RGB values", "Copia i valori RGB"), + ("Copy effect", "Copia effetto"), ("Copy from", "Copia da"), ("Copy layer(s)", "Copia livello/i"), ("Copy the selected layer alone (its empty parts copy nothing)", "Copia solo il livello selezionato (le sue parti vuote non copiano nulla)"), @@ -228,6 +229,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Cube", "Cubo"), ("Current layer", "Livello corrente"), ("Curvature", "Curvatura"), + ("Cut effect", "Taglia effetto"), ("Cut layer(s)", "Taglia livello/i"), ("Cyan / red", "Ciano / rosso"), ("Cylinder", "Cilindro"), @@ -620,6 +622,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Particles", "Particelle"), ("Passthrough", "Pass-through"), ("Paste as instance", "Incolla come istanza"), + ("Paste effect", "Incolla effetto"), ("Paste layer(s)", "Incolla livello/i"), ("Path", "Tracciato"), ("Path trace on the processor instead of the graphics card (slower)", "Esegui il path tracing sul processore anziché sulla scheda grafica (più lento)"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 2a2dc2e9..ef2d2d12 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -199,6 +199,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Contrast/Luminosity", "コントラスト/輝度"), ("Converted maps", "変換マップ"), ("Copy RGB values", "RGB 値をコピー"), + ("Copy effect", "エフェクトをコピー"), ("Copy from", "コピー元"), ("Copy layer(s)", "レイヤーをコピー"), ("Copy the selected layer alone (its empty parts copy nothing)", "選択中のレイヤーのみをコピー (空の部分は何もコピーしない)"), @@ -225,6 +226,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Cube", "立方体"), ("Current layer", "現在のレイヤー"), ("Curvature", "曲率"), + ("Cut effect", "エフェクトを切り取り"), ("Cut layer(s)", "レイヤーを切り取り"), ("Cyan / red", "シアン / レッド"), ("Cylinder", "円柱"), @@ -602,6 +604,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Particles", "パーティクル"), ("Passthrough", "通過"), ("Paste as instance", "インスタンスとして貼り付け"), + ("Paste effect", "エフェクトを貼り付け"), ("Paste layer(s)", "レイヤーを貼り付け"), ("Path", "パス"), ("Path trace on the processor instead of the graphics card (slower)", "グラフィックカードではなくプロセッサーでパストレース (低速)"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index d4078a4d..a021ae91 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -190,6 +190,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Contrast/Luminosity", "대비/광도"), ("Converted maps", "변환된 맵"), ("Copy RGB values", "RGB 값 복사"), + ("Copy effect", "이펙트 복사"), ("Copy from", "복사 원본"), ("Copy layer(s)", "레이어 복사"), ("Copy the selected layer alone (its empty parts copy nothing)", "선택한 레이어만 복사합니다 (빈 부분은 복사되지 않음)"), @@ -216,6 +217,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Cube", "큐브"), ("Current layer", "현재 레이어"), ("Curvature", "곡률"), + ("Cut effect", "이펙트 잘라내기"), ("Cut layer(s)", "레이어 잘라내기"), ("Cyan / red", "녹청 / 빨강"), ("Cylinder", "실린더"), @@ -593,6 +595,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Particles", "파티클"), ("Passthrough", "통과"), ("Paste as instance", "인스턴스로 붙여넣기"), + ("Paste effect", "이펙트 붙여넣기"), ("Paste layer(s)", "레이어 붙여넣기"), ("Path", "패스"), ("Path trace on the processor instead of the graphics card (slower)", "그래픽 카드 대신 프로세서에서 패스 트레이싱합니다 (더 느림)"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index dc751c1e..de48dd90 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -196,6 +196,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Contrast/Luminosity", "Contraste/Luminosidade"), ("Converted maps", "Mapas convertidos"), ("Copy RGB values", "Copiar os valores RGB"), + ("Copy effect", "Copiar efeito"), ("Copy from", "Copiar de"), ("Copy layer(s)", "Copiar camada(s)"), ("Copy the selected layer alone (its empty parts copy nothing)", "Copiar apenas a camada selecionada (suas partes vazias não copiam nada)"), @@ -222,6 +223,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Cube", "Cubo"), ("Current layer", "Camada atual"), ("Curvature", "Curvatura"), + ("Cut effect", "Recortar efeito"), ("Cut layer(s)", "Recortar camada(s)"), ("Cyan / red", "Ciano / vermelho"), ("Cylinder", "Cilindro"), @@ -611,6 +613,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Particles", "Partículas"), ("Passthrough", "Passagem"), ("Paste as instance", "Colar como instância"), + ("Paste effect", "Colar efeito"), ("Paste layer(s)", "Colar camada(s)"), ("Path", "Caminho"), ("Path trace on the processor instead of the graphics card (slower)", "Fazer path tracing no processador em vez da placa de vídeo (mais lento)"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index b36b308b..13ad0ce8 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -169,6 +169,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Contrast/Luminosity", "对比度/亮度"), ("Converted maps", "转换贴图"), ("Copy RGB values", "复制 RGB 值"), + ("Copy effect", "复制效果"), ("Copy from", "复制自"), ("Copy layer(s)", "复制图层"), ("Copy the selected layer alone (its empty parts copy nothing)", "仅复制所选图层(其空白部分不复制任何内容)"), @@ -195,6 +196,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Cube", "立方体"), ("Current layer", "当前图层"), ("Curvature", "曲率"), + ("Cut effect", "剪切效果"), ("Cut layer(s)", "剪切图层"), ("Cyan / red", "青色 / 红色"), ("Cylinder", "圆柱体"), @@ -545,6 +547,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Particles", "粒子"), ("Passthrough", "穿透"), ("Paste as instance", "粘贴为实例"), + ("Paste effect", "粘贴效果"), ("Paste layer(s)", "粘贴图层"), ("Path", "路径"), ("Path trace on the processor instead of the graphics card (slower)", "在处理器而非显卡上进行路径追踪(较慢)"), diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 3f83a1ad..015566e8 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -269,7 +269,21 @@ pub fn forwarded_shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context, event let event = clipboard_key(&event, held).unwrap_or(event); let egui::Event::Key { key, pressed: true, repeat: false, modifiers, .. } = event else { continue }; let Some((id, _)) = active.iter().find(|(_, sc)| sc.logical_key == key && modifiers.matches_logically(sc.modifiers)) else { continue }; - invoke(app, ctx, id); + invoke(app, ctx, effect_command(app, id)); + } +} + +/// Layer shortcuts act on the selected effect instead of its layer (copy, cut, duplicate, +/// remove), and paste a copied effect onto the selection. +fn effect_command<'a>(app: &TextureCraftApp, id: &'a str) -> &'a str { + let effect = matches!(app.session.target, texturecraft_engine::StackTarget::Effect(_)); + match id { + "layer.copy" if effect => "effect.copy", + "layer.cut" if effect => "effect.cut", + "layer.duplicate" if effect => "effect.duplicate", + "layer.remove" if effect => "effect.remove", + "layer.paste" if enabled(app, "effect.paste") => "effect.paste", + _ => id, } } @@ -311,7 +325,7 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { // Ctrl+V reaches the app only while the system clipboard holds text or an image. ctx.copy_text(layer.name.clone()); } - invoke(app, ctx, id); + invoke(app, ctx, effect_command(app, id)); } } diff --git a/crates/ui-egui/tests/layer_clipboard.rs b/crates/ui-egui/tests/layer_clipboard.rs index 3db97ca2..36c20ff9 100644 --- a/crates/ui-egui/tests/layer_clipboard.rs +++ b/crates/ui-egui/tests/layer_clipboard.rs @@ -43,3 +43,27 @@ fn ctrl_c_then_ctrl_v_pastes_a_copy() { h.run_steps(3); assert!(count(&h) > before, "Ctrl+V pastes the layer"); } + +#[test] +fn layer_shortcuts_act_on_a_selected_effect() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let id = |v: serde_json::Value, key: &str| LayerId(v[key].as_u64().unwrap()); + let layer = id(texturecraft_engine::execute(&mut session, "layer.add.fill", &serde_json::Value::Null).unwrap(), "layer"); + let p = serde_json::json!({"target": "content", "filter": "invert"}); + let effect = id(texturecraft_engine::execute(&mut session, "effect.add.filter", &p).unwrap(), "effect"); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(4); + let effects = |h: &Harness<'_, TextureCraftApp>| h.state().session.doc.project.layers.get(&layer).map(|l| l.content_effects.len()); + h.event(egui::Event::Copy); + h.run_steps(3); + assert_eq!(h.state().session.clipboard.as_ref().map(|(_, id)| *id), Some(effect), "Ctrl+C copies the selected effect"); + h.event(egui::Event::Paste("Fill".into())); + h.run_steps(3); + assert_eq!(effects(&h), Some(2), "Ctrl+V pastes it above"); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::D); + h.run_steps(3); + assert_eq!(effects(&h), Some(3), "Ctrl+D duplicates the effect"); + h.key_press(egui::Key::Delete); + h.run_steps(3); + assert_eq!(effects(&h), Some(2), "Delete removes the effect, not its layer"); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 917d45ad..a8b4c5b9 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -16,7 +16,8 @@ painted tile count, so an agent can verify its work without a screenshot. `effect.histogram {effect, channel?, bins?}` counts the values an effect reads (a levels effect's input), so an agent can pick its input range from the data. `effect.move {effect, index}` reorders an effect within its stack (0 = bottom) and `effect.duplicate {effect}` copies -one just above itself. +one just above itself. `effect.copy {effect?}` and `effect.cut {effect?}` put an effect on the +layer clipboard, and `effect.paste {layer?, target?}` adds it to another layer's content or mask. `edit.undo {steps?}` and `edit.redo {steps?}` go back or forward several steps at once (as far as the history reaches); `edit.history` lists the steps done and the undone ones, next first. diff --git a/docs/features.md b/docs/features.md index e3007dcc..b16a29c1 100644 --- a/docs/features.md +++ b/docs/features.md @@ -45,7 +45,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA **mesh-map generators** (edge wear, dirt, thin areas, curvature, AO, position and direction gradients, all with world-space noise), filters, ID color selection and compare. Alt+click a mask to view it alone. Drag an effect to reorder its stack, or right-click it to duplicate it - (painted strokes included). + (painted strokes included) or copy it onto another layer or mask (Ctrl+C, Ctrl+V); with an + effect selected, Ctrl+D and Delete duplicate or remove it. - **Fill layers** take uniform values, **23 procedurals** (clouds, cells, grunge, scratches, wood grain, bricks, fabric weave, twill, leather grain, marble veins, Voronoi, paint chips…) or your own **images**, through UV, tri-planar, planar, spherical, cylindrical or decal projection.