Skip to content

armgit / klad

Public Imported from GitHub
0

A drawing app built for agent/human collaboration

Rust

Transform a whole layer or group (cmd T, klad transform --layer)

Indicode BV4ecef16e77a0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ff5d8b8..0478e55 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,6 +18,7 @@ The first builds, and klad's licences.
- Help > Report a problem shows the report before it is copied (version, system, the last messages and lines of klad's log, with your home folder hidden) and can zip the drawing to attach; `klad report` prints the same. Errors and crashes are kept in a small log for it.
- Messages say what happened and what to do next; when klad itself goes wrong it says so, and that your work is saved.
- Bones: a layer or group gets a skeleton (`klad bone`, the bone tool J), weights from the bones or painted (`klad weights`), and poses that bend the drawing (`klad pose`, pose mode); in-betweens of two poses turn the bones. The bone tool lists the skeleton, picks a bone in every mode, and moves ends, joints and whole bones with their children (`klad bone --move` with `--by`).
+- Transform a whole layer or group: cmd T puts handles round it, and a drag moves, turns or scales every drawing on it, its shapes, and its bones and poses (`klad transform --layer`).
- Bones are drawn as chains: letting go of a bone starts the next one from its end, each click adds one, shift fans them from one joint, Esc ends the chain (`klad bone --chain`).
- IK: a bone and its parent become a limb (or a bone alone an aim) that reaches for a target, bending the way it is drawn, with softness so knees do not snap straight (`klad ik`, the bone tool's options). In pose mode, drag a limb's end and the limb follows; move the whole by a root bone's head and planted feet stay where they are (`klad pose --target`, `--mix`); in-betweens keep them planted. Exports to Godot carry the solved turns.
- A first start: the start window welcomes, offers first steps (draw a shape, fill it, hand the drawing to an agent, ticked off as you go; Help > First steps opens them again) and six sample drawings that open as copies (`klad samples` lists and copies them).
diff --git a/crates/app/src/commands.rs b/crates/app/src/commands.rs
index aa3096d..94316fd 100644
--- a/crates/app/src/commands.rs
+++ b/crates/app/src/commands.rs
@@ -38,6 +38,7 @@ pub enum Cmd {
Copy,
Paste,
SelectAll,
+ TransformLayer,
CutLasso,
Recolour,
Thinner,
@@ -490,7 +491,7 @@ use Repeat as R;
use Trigger as T;
impl Cmd {
- pub const ALL: [Cmd; 163] = [
+ pub const ALL: [Cmd; 164] = [
Cmd::Brush,
Cmd::Eraser,
Cmd::Fill,
@@ -525,6 +526,7 @@ impl Cmd {
Cmd::Copy,
Cmd::Paste,
Cmd::SelectAll,
+ Cmd::TransformLayer,
Cmd::CutLasso,
Cmd::Recolour,
Cmd::Thinner,
@@ -955,6 +957,15 @@ impl Cmd {
R::No,
"copy the kept strokes into the active layer's drawing at this frame, in place",
),
+ Cmd::TransformLayer => spec(
+ "edit.transform-layer",
+ "transform the whole layer",
+ icon::SHAPES,
+ G::Edit,
+ T::Press(const { &[cmd(Key::T)] }),
+ R::No,
+ "move, turn or scale the whole active layer or group, in every drawing, with its bones and poses",
+ ),
Cmd::SelectAll => spec(
"edit.select-all",
"select every stroke on this layer",
@@ -2160,6 +2171,7 @@ impl Cmd {
Cmd::Copy => "Copy",
Cmd::Paste => "Paste",
Cmd::SelectAll => "Select all",
+ Cmd::TransformLayer => "Transform layer",
Cmd::CutLasso => "Lasso cuts strokes",
Cmd::Recolour => "Recolour",
Cmd::Thinner => "Thinner",
@@ -2357,6 +2369,8 @@ pub const MENUS: [Menu; 9] = [
Sub(
"Transform",
&[
+ Run(Cmd::TransformLayer),
+ Line,
Run(Cmd::FlipH),
Run(Cmd::FlipV),
Run(Cmd::TurnLeft90),
@@ -2681,6 +2695,10 @@ mod tests {
("copy strokes, cmd C (M3 batch 4)", "edit.copy"),
("paste strokes, cmd V (M3 batch 4)", "edit.paste"),
("select all on this layer (M2 batch 3)", "edit.select-all"),
+ (
+ "transform a whole layer or group, cmd T (2026-11-08)",
+ "edit.transform-layer",
+ ),
("a lasso cuts strokes at its edge (M2 batch 4)", "edit.cut-lasso"),
("recolour (M2 batch 3)", "edit.recolour"),
("thinner (M2 batch 3)", "edit.thinner"),
diff --git a/crates/app/src/editor.rs b/crates/app/src/editor.rs
index d3d837e..edbdfee 100644
--- a/crates/app/src/editor.rs
+++ b/crates/app/src/editor.rs
@@ -22,6 +22,7 @@ mod panels;
mod pins;
mod prefs;
mod selection;
+mod shift;
mod text;
mod timeline;
mod tweens;
@@ -647,6 +648,7 @@ pub(crate) struct Editor {
paintover: paintover::Form,
compare: Option<compare::Compared>,
bones: bones::BoneTool,
+ shifting: Option<shift::Shifting>,
first: first::FirstSteps,
settings_section: prefs::Section,
report_drawing: bool,
@@ -823,6 +825,7 @@ impl Editor {
paintover: paintover::Form::default(),
compare: None,
bones: bones::BoneTool::default(),
+ shifting: None,
first: first::FirstSteps::default(),
settings_section: prefs::Section::default(),
report_drawing: false,
@@ -1353,6 +1356,9 @@ impl Editor {
}
fn handles(&self) -> Option<(String, [Vec2; 4])> {
+ if let Some(found) = self.shift_handles() {
+ return Some(found);
+ }
match self.tool {
Tool::Direct => None,
_ if self.on_marks() => self.picked_corners(),
@@ -1388,6 +1394,9 @@ impl Editor {
fn drag_ops(&self) -> Option<Vec<Op>> {
let drag = self.drag.as_ref().filter(|d| d.moved() && !d.copy)?;
+ if self.shifting.is_some() {
+ return self.shift_ops(drag, false).ok().flatten();
+ }
match drag.strokes {
true => self
.picked_ops(LassoAction::Transform(drag.mark_transform()))
@@ -1397,6 +1406,9 @@ impl Editor {
}
fn preview_cels(&self) -> Vec<String> {
+ if self.shifting.is_some() {
+ return self.shift_cels();
+ }
match self.drag.as_ref().is_some_and(|d| d.strokes) {
true => self
.picked
@@ -1609,8 +1621,8 @@ impl Editor {
fn start_drag(&mut self, id: String, grab: Grab, corners: [Vec2; 4], at: Vec2, fresh: bool) {
self.drop_preview();
- let strokes = self.on_marks();
- if !strokes && !matches!(self.scene.bundle.doc.item(&id), Some(Item::Node(..))) {
+ let strokes = self.on_marks() && self.shifting.is_none();
+ if !strokes && self.shifting.is_none() && !matches!(self.scene.bundle.doc.item(&id), Some(Item::Node(..))) {
return;
}
let center = corners.iter().fold(Vec2::ZERO, |a, c| a + *c) / 4.0;
@@ -1676,6 +1688,9 @@ impl Editor {
let Some(drag) = self.drag.take() else {
return Ok(());
};
+ if self.shifting.is_some() {
+ return self.finish_shift_drag(&drag);
+ }
if drag.strokes {
return self.finish_stroke_drag(&drag);
}
@@ -2601,7 +2616,10 @@ impl Editor {
(Tool::Brush, Phase::Up) => self.finish()?,
(Tool::Select, Phase::Down) => match self.grab_at(view, rect, e.pos) {
Some((id, grab, corners)) => self.start_drag(id, grab, corners, c, false),
- None => self.grab_under(c, e.pos)?,
+ None => {
+ self.end_shift();
+ self.grab_under(c, e.pos)?
+ }
},
(Tool::Select, Phase::Move) => {
if let Some(drag) = self.drag.as_mut() {
@@ -2938,6 +2956,7 @@ impl Editor {
self.typing_keys(ui)?;
self.pen_keys(ui)?;
self.bone_keys(ui);
+ self.shift_keys(ui)?;
self.command_keys(ui)?;
let ctx = ui.ctx().clone();
let was_focused = self.focused;
diff --git a/crates/app/src/editor/commands.rs b/crates/app/src/editor/commands.rs
index 566e800..588417f 100644
--- a/crates/app/src/editor/commands.rs
+++ b/crates/app/src/editor/commands.rs
@@ -94,6 +94,12 @@ impl Editor {
(_, true) => Some("finish the drag first".into()),
_ => None,
},
+ Cmd::TransformLayer => self
+ .scene
+ .active_layer()
+ .filter(|l| l.kind() != klad_core::doc::Kind::Adjust)
+ .is_none()
+ .then(|| "pick a layer or group with something on it".to_string()),
Cmd::SelectAll => (!self.active_paint() || self.scene.active_marks().is_empty())
.then(|| "the active layer has no strokes on this frame".to_string()),
Cmd::Recolour | Cmd::Thinner | Cmd::Thicker => need_strokes().or(editing),
@@ -552,6 +558,7 @@ impl Editor {
}
Cmd::Paste => self.paste()?,
Cmd::SelectAll => self.select_all_strokes(),
+ Cmd::TransformLayer => self.start_shift()?,
Cmd::CutLasso => self.cut_lasso = !self.cut_lasso,
Cmd::Recolour => self.recolour_picked()?,
Cmd::FillShape => self.recolour_shape(false)?,
diff --git a/crates/app/src/editor/options.rs b/crates/app/src/editor/options.rs
index 922638f..3f744d6 100644
--- a/crates/app/src/editor/options.rs
+++ b/crates/app/src/editor/options.rs
@@ -336,6 +336,7 @@ impl Editor {
self.command_button(ui, Cmd::SelectAll, Some("select all"));
ui.label(RichText::new("click or lasso strokes; the bar under them edits them").color(theme::WEAK));
}
+ Tool::Select if self.shifting.is_some() => self.shift_options(ui),
Tool::Select => {
self.pick_scope(ui);
ui.label(
diff --git a/crates/app/src/editor/shift.rs b/crates/app/src/editor/shift.rs
new file mode 100644
index 0000000..197891a
--- /dev/null
+++ b/crates/app/src/editor/shift.rs
@@ -0,0 +1,160 @@
+use super::{Drag, Editor, Tool};
+use crate::messages::Tone;
+use anyhow::{Context, Result};
+use egui::{Key, Modifiers, RichText, Vec2, vec2};
+use klad_core::doc::Kind;
+use klad_core::ops::{Op, ShiftSpec};
+use klad_render::shift::{Targets, shifted, targets};
+
+pub(super) struct Shifting {
+ pub layer: String,
+ pub every: bool,
+ pub frame: u32,
+ pub rev: u64,
+ pub found: Targets,
+ pub corners: [Vec2; 4],
+}
+
+fn corners(found: &Targets) -> Option<[Vec2; 4]> {
+ let [x0, y0, x1, y1] = found.bounds?;
+ Some([vec2(x0, y0), vec2(x1, y0), vec2(x1, y1), vec2(x0, y1)])
+}
+
+impl Editor {
+ pub(super) fn start_shift(&mut self) -> Result<()> {
+ let layer = self
+ .scene
+ .active_id()
+ .context("pick a layer or group to transform first")?;
+ let frame = self.scene.frame;
+ let found = targets(&self.scene.bundle, &layer, Some(frame))?;
+ let Some(box_) = corners(&found) else {
+ self.say(
+ Tone::Refused,
+ format!("{} has nothing to transform at this frame", found.name),
+ );
+ return Ok(());
+ };
+ self.say(
+ Tone::Info,
+ format!(
+ "transforming {}: drag inside to move, a corner to scale, outside to turn; Esc when done",
+ found.name
+ ),
+ );
+ self.shifting = Some(Shifting {
+ layer,
+ every: true,
+ frame,
+ rev: self.scene.bundle.doc.rev,
+ found,
+ corners: box_,
+ });
+ self.selection = None;
+ self.picked = None;
+ self.tool = Tool::Select;
+ Ok(())
+ }
+
+ pub(super) fn end_shift(&mut self) {
+ if self.shifting.take().is_some() {
+ self.say(Tone::Info, "layer transform done");
+ }
+ }
+
+ pub(super) fn shift_keys(&mut self, ui: &mut egui::Ui) -> Result<()> {
+ let Some(shifting) = &self.shifting else {
+ return Ok(());
+ };
+ if self.tool != Tool::Select || self.scene.active_id().as_deref() != Some(shifting.layer.as_str()) {
+ self.shifting = None;
+ return Ok(());
+ }
+ if !self.keys_busy {
+ let done = ui.input_mut(|i| {
+ i.consume_key(Modifiers::NONE, Key::Escape) || i.consume_key(Modifiers::NONE, Key::Enter)
+ });
+ if done {
+ self.end_shift();
+ return Ok(());
+ }
+ }
+ let (rev, frame) = (self.scene.bundle.doc.rev, self.scene.frame);
+ if self.drag.is_none() && (shifting.rev != rev || shifting.frame != frame) {
+ let layer = shifting.layer.clone();
+ let found = targets(&self.scene.bundle, &layer, Some(frame))?;
+ match (corners(&found), self.shifting.as_mut()) {
+ (Some(box_), Some(s)) => {
+ s.found = found;
+ s.corners = box_;
+ s.rev = rev;
+ s.frame = frame;
+ }
+ _ => self.shifting = None,
+ }
+ }
+ Ok(())
+ }
+
+ pub(super) fn shift_handles(&self) -> Option<(String, [Vec2; 4])> {
+ let s = self.shifting.as_ref().filter(|_| self.tool == Tool::Select)?;
+ Some((format!("layer:{}", s.layer), s.corners))
+ }
+
+ pub(super) fn shift_ops(&self, drag: &Drag, every: bool) -> Result<Option<Vec<Op>>> {
+ let Some(s) = &self.shifting else {
+ return Ok(None);
+ };
+ let mut transform = drag.mark_transform();
+ let only = (!every).then_some(s.frame);
+ let found = match every {
+ true => targets(&self.scene.bundle, &s.layer, None)?,
+ false => s.found.clone(),
+ };
+ let resolved = shifted(&found, &mut transform)?;
+ Ok(Some(vec![Op::Shift(ShiftSpec {
+ layer: s.layer.clone(),
+ transform,
+ only,
+ resolved: Some(resolved),
+ })]))
+ }
+
+ pub(super) fn shift_cels(&self) -> Vec<String> {
+ self.shifting
+ .as_ref()
+ .map(|s| s.found.marks.iter().map(|(cel, _)| cel.clone()).collect())
+ .unwrap_or_default()
+ }
+
+ pub(super) fn finish_shift_drag(&mut self, drag: &Drag) -> Result<()> {
+ if !drag.moved() {
+ return Ok(());
+ }
+ let every = self.shifting.as_ref().is_some_and(|s| s.every);
+ let (Some(shown), Some(ops)) = (self.shift_ops(drag, false)?, self.shift_ops(drag, every)?) else {
+ self.drop_preview();
+ return Ok(());
+ };
+ let before = self.scene.bundle.doc.rev;
+ let dirty = self.commit(ops)?;
+ self.finish_preview(shown, dirty, before);
+ Ok(())
+ }
+
+ pub(super) fn shift_options(&mut self, ui: &mut egui::Ui) {
+ let Some(s) = self.shifting.as_mut() else {
+ return;
+ };
+ let kind = match self.scene.bundle.doc.layer(&s.layer).map(|l| l.kind()) {
+ Some(Kind::Group) => "group",
+ _ => "layer",
+ };
+ ui.label(RichText::new(format!("transforming the {kind} {}", s.found.name)).strong());
+ ui.checkbox(&mut s.every, "every drawing").on_hover_text(
+ "on: every drawing on it moves (with its bones and poses); off: only the drawing shown here",
+ );
+ ui.label(RichText::new("drag inside, a corner or outside; Esc: done").color(crate::theme::WEAK))
+ .on_hover_text("drag inside to move, a corner to scale, an edge to stretch, outside to turn; Esc, Return or a click outside ends it");
+ }
+}
diff --git a/crates/app/src/editor/ui_tests.rs b/crates/app/src/editor/ui_tests.rs
index 9c31778..bdf3aca 100644
--- a/crates/app/src/editor/ui_tests.rs
+++ b/crates/app/src/editor/ui_tests.rs
@@ -3339,6 +3339,90 @@ fn bones_are_drawn_weighted_and_posed_on_the_canvas() {
let _ = std::fs::remove_dir_all(&path);
}
+#[test]
+fn cmd_t_moves_a_whole_layer_in_every_drawing_or_only_this_one() {
+ let path = sample("shift");
+ Bundle::open(&path)
+ .unwrap()
+ .apply(
+ &parse_lines(
+ r#"{"op":"cel","new":"l6","frame":6}
+{"op":"stroke","layer":"l6","frame":6,"path":"M100 100 L200 150","size":6}"#,
+ )
+ .unwrap(),
+ )
+ .unwrap();
+ let mut h = harness(editor(&path), vec2(1440.0, 1000.0));
+ activate(&mut h, "lines");
+ let boxes = |h: &Harness<'static, Editor>| -> Vec<[f32; 4]> {
+ let bundle = &h.state().scene.bundle;
+ bundle
+ .doc
+ .layer("l6")
+ .unwrap()
+ .cels()
+ .iter()
+ .map(|c| {
+ bundle
+ .read_marks("l6", &c.id)
+ .unwrap()
+ .iter()
+ .filter_map(klad_core::stroke::Mark::bounds)
+ .reduce(|a, b| [a[0].min(b[0]), a[1].min(b[1]), a[2].max(b[2]), a[3].max(b[3])])
+ .unwrap()
+ })
+ .collect()
+ };
+ let near = |a: [f32; 4], b: [f32; 4], dx: f32, dy: f32| {
+ (b[0] - a[0] - dx).abs() < 1.5 && (b[1] - a[1] - dy).abs() < 1.5 && (b[2] - b[0] - (a[2] - a[0])).abs() < 0.5
+ };
+ let before = boxes(&h);
+ assert_eq!(before.len(), 2);
+ h.key_press_modifiers(Modifiers::COMMAND, Key::T);
+ h.run_steps(2);
+ let corners = h
+ .state()
+ .shifting
+ .as_ref()
+ .expect("cmd T starts a layer transform")
+ .corners;
+ assert_eq!(h.state().tool, Tool::Select);
+ let centre = (corners[0] + corners[2]) / 2.0;
+ let (from, to) = (
+ canvas_at(&h, centre.x, centre.y),
+ canvas_at(&h, centre.x + 40.0, centre.y + 20.0),
+ );
+ drag(&mut h, from, to);
+ h.run_steps(3);
+ let moved = boxes(&h);
+ assert!(
+ before.iter().zip(&moved).all(|(a, b)| near(*a, *b, 40.0, 20.0)),
+ "every drawing moves: {before:?} {moved:?}"
+ );
+ assert!(h.state().shifting.is_some(), "the transform stays on for the next drag");
+ h.state_mut().shifting.as_mut().unwrap().every = false;
+ let corners = h.state().shifting.as_ref().unwrap().corners;
+ let centre = (corners[0] + corners[2]) / 2.0;
+ let (from, to) = (
+ canvas_at(&h, centre.x, centre.y),
+ canvas_at(&h, centre.x + 30.0, centre.y),
+ );
+ drag(&mut h, from, to);
+ h.run_steps(3);
+ let once = boxes(&h);
+ assert!(
+ near(moved[0], once[0], 30.0, 0.0),
+ "the drawing shown moves: {:?} {:?}",
+ moved[0],
+ once[0]
+ );
+ assert_eq!(once[1], moved[1], "the other drawing stays");
+ h.key_press(Key::Escape);
+ h.run_steps(2);
+ assert!(h.state().shifting.is_none(), "Esc ends it");
+ let _ = std::fs::remove_dir_all(&path);
+}
+
#[test]
fn bones_are_drawn_as_a_chain_that_fans_ends_and_takes_back_its_last_bone() {
let path = sample("chain");
diff --git a/crates/app/src/lift.rs b/crates/app/src/lift.rs
index 404a6cc..4c57ed4 100644
--- a/crates/app/src/lift.rs
+++ b/crates/app/src/lift.rs
@@ -2,7 +2,7 @@ use anyhow::Result;
use klad_brush::Raster;
use klad_core::doc::{Node, Transform};
use klad_core::rng::{FNV_OFFSET, fnv};
-use klad_render::{rasterize_nodes, vector};
+use klad_render::rasterize_nodes;
use std::sync::mpsc::{Receiver, channel};
fn spawn<T: Send + 'static>(
@@ -29,22 +29,7 @@ pub fn affine_apply(a: [f32; 6], (x, y): (f32, f32)) -> (f32, f32) {
}
pub fn committed(node: &Node, affine: [f32; 6], scale: f32, degrees: f32) -> Result<Transform> {
- let mut t = node.transform;
- let pivot = match t.pivot {
- Some(p) => p,
- None => {
- let mut plain = node.clone();
- plain.transform = Transform::default();
- vector::local_bounds(&plain)?.map_or([0.0, 0.0], |r| [r.center_x(), r.center_y()])
- }
- };
- let (qx, qy) = affine_apply(affine, (t.x + pivot[0], t.y + pivot[1]));
- t.x = qx - pivot[0];
- t.y = qy - pivot[1];
- t.sx *= scale;
- t.sy *= scale;
- t.rotate += degrees;
- Ok(t)
+ klad_render::shift::moved_node(node, affine, scale, degrees)
}
pub fn square(node: &Node) -> bool {
diff --git a/crates/cli/src/agent.rs b/crates/cli/src/agent.rs
index 30ae6e0..94610f4 100644
--- a/crates/cli/src/agent.rs
+++ b/crates/cli/src/agent.rs
@@ -583,7 +583,8 @@ pub fn edit(path: &Path, ops: &[Op], out: &Output) -> Result<()> {
crate::paintover::resolve(&bundle, &mut ops)?
.iter()
.for_each(|n| eprintln!("{n}"));
- let ops = crate::shapes::expand(&bundle, ops)?;
+ let mut ops = crate::shapes::expand(&bundle, ops)?;
+ klad_render::shift::resolve(&bundle, &mut ops)?;
let mut ops = vector::pinned(&bundle.doc, &ops)?;
resolve_strokes(&bundle, &mut ops)?;
crate::fonts::settle(&bundle, &mut ops)?;
diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs
index c309aaf..d292a60 100644
--- a/crates/cli/src/main.rs
+++ b/crates/cli/src/main.rs
@@ -36,8 +36,8 @@ use klad_core::history::Stack;
use klad_core::markedit::{LassoAction, MarkTransform};
use klad_core::ops::{
BoneSpec, ClipEdit, CopySpec, CopyTarget, FillSpec, FoliageSpec, GrassSpec, HatchSpec, IkSpec, InbetweenSpec,
- InkSpec, LassoSpec, LightSpec, Op, PaintOverSpec, PaintSpec, PaletteEdit, Place, PoseSpec, ScatterSpec, StrokeSpec,
- WeightsSpec,
+ InkSpec, LassoSpec, LightSpec, Op, PaintOverSpec, PaintSpec, PaletteEdit, Place, PoseSpec, ScatterSpec, ShiftSpec,
+ StrokeSpec, WeightsSpec,
};
use klad_core::retime::{Retime, RetimeSpec};
use klad_core::stroke::{fills_of, strokes_of};
@@ -526,12 +526,19 @@ enum Command {
flags: EditFlags,
},
#[command(
- about = "Move, rotate or scale strokes and fills (<cel>:s<id>)",
- long_about = "Move, rotate or scale strokes and fills, addressed as <cel>:s<id> (klad strokes lists them). Rotation and scale turn about --pivot, by default the middle of the marks' bounds. Stroke sizes and tapers scale with them; fills move by whole pixels and are resampled when turned or scaled.\n\n klad transform art.klad c4:s12 c4:s13 --move 40,-10\n klad transform art.klad c4:s12 --rotate 15 --scale 1.2\n klad transform art.klad c4:s3 c4:s5 --sx -1 --pivot 512,400\n\nAlso a transform op in klad apply: {\"op\":\"transform\",\"ids\":[\"c4:s12\"],\"x\":40,\"y\":-10,\"rotate\":15,\"sx\":1.2,\"sy\":1.2}"
+ about = "Move, rotate or scale strokes and fills (<cel>:s<id>), or a whole layer or group (--layer)",
+ long_about = "Move, rotate or scale strokes and fills, addressed as <cel>:s<id> (klad strokes lists them). Rotation and scale turn about --pivot, by default the middle of the marks' bounds. Stroke sizes and tapers scale with them; fills move by whole pixels and are resampled when turned or scaled.\n\n--layer moves a whole layer or group instead: the marks of every drawing on it and on the layers in it (--only <frame>: just the drawings shown at that frame), its shapes, and with every drawing also its bones, its weights and its poses' roots and targets, so a rigged character moves as one. Shapes scale evenly only, and a layer with keyed shapes can only be moved. The pivot defaults to the middle of everything moved.\n\n klad transform art.klad c4:s12 c4:s13 --move 40,-10\n klad transform art.klad c4:s12 --rotate 15 --scale 1.2\n klad transform art.klad c4:s3 c4:s5 --sx -1 --pivot 512,400\n klad transform art.klad --layer figure --move -120,0\n klad transform art.klad --layer sky --scale 1.1 --only 12\n\nAlso a transform op in klad apply: {\"op\":\"transform\",\"ids\":[\"c4:s12\"],\"x\":40,\"y\":-10,\"rotate\":15,\"sx\":1.2,\"sy\":1.2}, or for a layer {\"op\":\"transform\",\"layer\":\"figure\",\"x\":-120,\"y\":0,\"only\":12}."
)]
Transform {
bundle: PathBuf,
ids: Vec<String>,
+ #[arg(
+ long,
+ help = "a whole layer or group, every drawing on it (with its bones and poses), instead of ids"
+ )]
+ layer: Option<String>,
+ #[arg(long, help = "with --layer: only the drawings shown at this frame")]
+ only: Option<u32>,
#[arg(long = "move", value_parser = parse_pair, allow_hyphen_values = true, help = "dx,dy in px")]
offset: Option<[f32; 2]>,
#[arg(long, allow_hyphen_values = true, help = "Degrees, clockwise")]
@@ -2349,6 +2356,8 @@ fn run() -> Result<()> {
Command::Transform {
bundle,
ids,
+ layer,
+ only,
offset,
rotate,
scale,
@@ -2359,16 +2368,24 @@ fn run() -> Result<()> {
frame,
flags,
} => {
- if ids.is_empty() {
- return Err(anyhow!("give the strokes and fills to transform (<cel>:s<id>)"));
- }
let transform = mark_transform(offset, rotate, (scale, sx, sy), pivot, flip.as_deref())?
.ok_or_else(|| anyhow!("say how: --move, --rotate, --scale, --sx, --sy or --flip"))?;
- agent::edit(
- &bundle,
- &[Op::Transform { ids, transform }],
- &output(&flags.edit(), frame),
- )?;
+ let op = match (layer, ids.is_empty()) {
+ (Some(_), false) => return Err(anyhow!("give ids or --layer, not both")),
+ (Some(layer), true) => Op::Shift(ShiftSpec {
+ layer: layer_id(&bundle, &layer)?,
+ transform,
+ only,
+ resolved: None,
+ }),
+ (None, true) => {
+ return Err(anyhow!(
+ "give the strokes and fills to transform (<cel>:s<id>), or --layer for a whole layer"
+ ));
+ }
+ (None, false) => Op::Transform { ids, transform },
+ };
+ agent::edit(&bundle, &[op], &output(&flags.edit(), frame))?;
}
Command::Lasso {
bundle,
diff --git a/crates/cli/src/rig.rs b/crates/cli/src/rig.rs
index 754e551..51ee102 100644
--- a/crates/cli/src/rig.rs
+++ b/crates/cli/src/rig.rs
@@ -593,6 +593,78 @@ mod tests {
std::fs::remove_dir_all(&dir).unwrap();
}
+ #[test]
+ fn a_whole_layer_moves_with_every_drawing_its_bones_poses_and_weights() {
+ let dir = arm("shift");
+ edit(
+ &dir,
+ r#"{"op":"bone","layer":"l1","chain":["upper","fore","hand"],"through":[[100,200],[300,200],[480,200],[520,200]]}
+{"op":"ik","layer":"l1","add":"fore"}
+{"op":"weights","layer":"l1","auto":true}
+{"op":"pose","layer":"l1","from":0,"to":4,"ik":{"fore":{"target":[400,300]}}}"#,
+ )
+ .unwrap();
+ let before = Bundle::open(&dir).unwrap();
+ let (rest, posed) = (end_of(&before, 0), end_of(&before, 4));
+ let strongest = |b: &Bundle, at: [f32; 2]| {
+ let layer = b.doc.layer("l1").unwrap();
+ let w = b.read_weights("l1").unwrap().at(&layer.bones, at);
+ (0..w.len()).max_by(|x, y| w[*x].total_cmp(&w[*y])).unwrap()
+ };
+ let held = strongest(&before, [200.0, 200.0]);
+ edit(&dir, r#"{"op":"transform","layer":"l1","x":12,"y":20}"#).unwrap();
+ let after = Bundle::open(&dir).unwrap();
+ let moved = |a: (f32, f32), b: (f32, f32)| (b.0 - a.0 - 12.0).abs() < 0.01 && (b.1 - a.1 - 20.0).abs() < 0.01;
+ assert!(moved(rest, end_of(&after, 0)), "the rest drawing moves");
+ assert!(moved(posed, end_of(&after, 4)), "and the posed one");
+ let layer = after.doc.layer("l1").unwrap();
+ assert_eq!(layer.bones[0].head, [112.0, 220.0], "the bones move along");
+ let pose = layer.content_at(4).unwrap().pose.clone().unwrap();
+ assert_eq!(pose.ik["fore"].target, [412.0, 320.0], "so does the pose's target");
+ assert_eq!(strongest(&after, [212.0, 220.0]), held, "and the weights");
+ let was = end_of(&after, 0);
+ edit(&dir, r#"{"op":"transform","layer":"l1","rotate":90,"pivot":[300,200]}"#).unwrap();
+ let turned = end_of(&Bundle::open(&dir).unwrap(), 0);
+ let want = (300.0 - (was.1 - 200.0), 200.0 + (was.0 - 300.0));
+ assert!(
+ (turned.0 - want.0).abs() < 0.05 && (turned.1 - want.1).abs() < 0.05,
+ "{turned:?} {want:?}"
+ );
+ let once = Bundle::open(&dir).unwrap();
+ let (zero, four) = (end_of(&once, 0), end_of(&once, 4));
+ edit(&dir, r#"{"op":"transform","layer":"l1","x":5,"only":4}"#).unwrap();
+ let only = Bundle::open(&dir).unwrap();
+ assert_eq!(end_of(&only, 0), zero, "only the drawing at frame 4 moves");
+ assert!((end_of(&only, 4).0 - four.0 - 5.0).abs() < 0.01);
+ assert_eq!(
+ only.doc.layer("l1").unwrap().bones,
+ once.doc.layer("l1").unwrap().bones,
+ "and the bones stay"
+ );
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn a_group_moves_its_shapes_and_shapes_only_scale_evenly() {
+ let dir = arm("group-shift");
+ edit(
+ &dir,
+ r##"{"op":"add","layer":{"id":"g","kind":"group","name":"g"}}
+{"op":"add","layer":{"id":"v","kind":"vector","name":"v"},"in":"g"}
+{"op":"add","node":{"id":"box","type":"rect","x":10,"y":10,"w":20,"h":20,"fill":"#ff0000"},"in":"v"}"##,
+ )
+ .unwrap();
+ edit(&dir, r#"{"op":"transform","layer":"g","x":7,"y":-3}"#).unwrap();
+ let bundle = Bundle::open(&dir).unwrap();
+ let Some(klad_core::doc::Item::Node(_, _, node)) = bundle.doc.item("box") else {
+ panic!("no box");
+ };
+ assert_eq!((node.transform.x, node.transform.y), (7.0, -3.0));
+ let stretched = edit(&dir, r#"{"op":"transform","layer":"g","sx":2,"sy":1}"#).unwrap_err();
+ assert!(format!("{stretched:#}").contains("scale evenly"), "{stretched:#}");
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+
#[test]
fn bones_weights_and_poses_through_the_cli_and_undo() {
let dir = arm("pose");
diff --git a/crates/core/src/bundle.rs b/crates/core/src/bundle.rs
index 92f601b..ead859e 100644
--- a/crates/core/src/bundle.rs
+++ b/crates/core/src/bundle.rs
@@ -488,6 +488,7 @@ pub fn summarize(ops: &[Op]) -> String {
Op::Fill(spec) => format!("fill on {}", spec.layer),
Op::Palette(_) => "palette".to_string(),
Op::Transform { ids, .. } => format!("transform {}", ids.join(" ")),
+ Op::Shift(spec) => format!("transform {}", spec.layer),
Op::Path { id, .. } => format!("path {id}"),
Op::Copy(spec) => format!(
"copy {} mark{} to {}",
diff --git a/crates/core/src/ops.rs b/crates/core/src/ops.rs
index 2582cba..1ddbf05 100644
--- a/crates/core/src/ops.rs
+++ b/crates/core/src/ops.rs
@@ -123,6 +123,7 @@ pub enum Op {
ids: Vec<String>,
transform: MarkTransform,
},
+ Shift(ShiftSpec),
Path {
id: String,
edit: PathEdit,
@@ -659,6 +660,21 @@ pub struct BoneSpec {
pub through: Option<Vec<[f32; 2]>>,
}
+#[derive(Clone, Debug, PartialEq)]
+pub struct ShiftSpec {
+ pub layer: String,
+ pub transform: MarkTransform,
+ pub only: Option<u32>,
+ pub resolved: Option<Shifted>,
+}
+
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct Shifted {
+ pub marks: Vec<(String, Vec<u32>)>,
+ pub nodes: Vec<(String, crate::doc::Transform)>,
+ pub weights: Vec<(String, crate::rig::Weights)>,
+}
+
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum BendSpec {
@@ -1440,6 +1456,19 @@ impl Op {
Op::Fill(spec)
}
"palette" => Op::Palette(parse_palette(&mut map)?),
+ "transform" if map.contains_key("layer") => {
+ let layer = take_str(&mut map, "layer")?.unwrap_or_default();
+ let only = match map.remove("only") {
+ Some(v) => Some(v.as_u64().ok_or_else(|| anyhow!("only must be a frame number"))? as u32),
+ None => None,
+ };
+ Op::Shift(ShiftSpec {
+ layer,
+ transform: MarkTransform::parse(&mut map)?,
+ only,
+ resolved: None,
+ })
+ }
"transform" => {
let mut ids: Vec<String> = match map.remove("ids") {
Some(v) => serde_json::from_value(v).map_err(|_| anyhow!("ids must be a list of strings"))?,
@@ -3226,6 +3255,7 @@ pub fn apply(doc: &mut Document, op: &Op, out: &mut Applied) -> Result<()> {
})?;
out.changed.extend(ids.iter().cloned());
}
+ Op::Shift(spec) => shift(doc, spec, out)?,
Op::Move { id, place } => {
move_item(doc, id, place).with_context(|| format!("mv {id}"))?;
out.changed.push(id.clone());
@@ -3444,6 +3474,77 @@ pub fn everything(doc: &Document) -> Fill {
.by(Author::Agent)
}
+fn shift(doc: &mut Document, spec: &ShiftSpec, out: &mut Applied) -> Result<()> {
+ let Some(made) = &spec.resolved else {
+ bail!("a layer transform is worked out by klad transform (or klad apply) first");
+ };
+ let pivot = spec
+ .transform
+ .pivot
+ .ok_or_else(|| anyhow!("a layer transform needs its pivot"))?;
+ let a = spec.transform.affine(pivot);
+ let at = |p: [f32; 2]| {
+ let (x, y) = crate::markedit::apply_affine(a, (p[0], p[1]));
+ [x, y]
+ };
+ let id = doc.find_layer(&spec.layer)?.id.clone();
+ let path = layer_path(doc, &id)?;
+ made.marks.iter().try_for_each(|(cel, ids)| {
+ let layer = mark_owner(doc, cel)?;
+ out.push(
+ &layer,
+ cel,
+ MarkChange::Transform {
+ ids: ids.clone(),
+ transform: spec.transform,
+ },
+ );
+ Ok::<_, anyhow::Error>(())
+ })?;
+ let moving = spec.transform.rotate == 0.0 && spec.transform.sx == 1.0 && spec.transform.sy == 1.0;
+ made.nodes.iter().try_for_each(|(node, t)| {
+ let Some(Loc::Node(layer, cel, nodes)) = doc.locate(node) else {
+ bail!("no shape {node}");
+ };
+ let (last, parent) = nodes.split_last().ok_or_else(|| anyhow!("no shape {node}"))?;
+ let target = &mut node_list(doc, &layer, cel, parent)?[*last];
+ target.transform = *t;
+ if moving {
+ [("x", spec.transform.x), ("y", spec.transform.y)]
+ .into_iter()
+ .for_each(|(name, by)| {
+ if let Some(keys) = target.keys.get_mut(name) {
+ keys.iter_mut().for_each(|k| k.value += by);
+ }
+ });
+ }
+ out.changed.push(node.clone());
+ Ok::<_, anyhow::Error>(())
+ })?;
+ if spec.only.is_none() {
+ let linear = |v: [f32; 2]| [a[0] * v[0] + a[1] * v[1], a[2] * v[0] + a[3] * v[1]];
+ crate::doc::family_paths(doc, &path).iter().for_each(|p| {
+ let layer = doc.layer_at_mut(p);
+ layer.bones.iter_mut().for_each(|b| {
+ b.head = at(b.head);
+ b.tail = at(b.tail);
+ });
+ if let Some(cels) = layer.cels_mut() {
+ cels.iter_mut().filter_map(|c| c.pose.as_mut()).for_each(|pose| {
+ pose.root = linear(pose.root);
+ pose.ik.values_mut().for_each(|r| r.target = at(r.target));
+ });
+ }
+ });
+ made.weights.iter().for_each(|(owner, w)| {
+ out.weights.retain(|(l, _)| l != owner);
+ out.weights.push((owner.clone(), w.clone()));
+ });
+ }
+ out.changed.push(id);
+ Ok(())
+}
+
fn mark_owner(doc: &Document, cel: &str) -> Result<String> {
match doc.locate(cel) {
Some(Loc::Cel(path, c)) => {
diff --git a/crates/core/src/rig.rs b/crates/core/src/rig.rs
index 9f04039..f396cab 100644
--- a/crates/core/src/rig.rs
+++ b/crates/core/src/rig.rs
@@ -924,6 +924,34 @@ impl<'a> Rig<'a> {
}
}
+pub fn moved_weights(w: &Weights, back: crate::markedit::Affine) -> Weights {
+ let cell = CELL as f32;
+ let (width, height) = (w.width as i64, w.height as i64);
+ Weights {
+ width: w.width,
+ height: w.height,
+ maps: w
+ .maps
+ .iter()
+ .map(|(bone, map)| {
+ let moved = (0..height)
+ .flat_map(|y| (0..width).map(move |x| (x, y)))
+ .map(|(x, y)| {
+ let (sx, sy) =
+ crate::markedit::apply_affine(back, ((x as f32 + 0.5) * cell, (y as f32 + 0.5) * cell));
+ let (cx, cy) = ((sx / cell).floor() as i64, (sy / cell).floor() as i64);
+ match (0..width).contains(&cx) && (0..height).contains(&cy) {
+ true => map[(cy * width + cx) as usize],
+ false => 0,
+ }
+ })
+ .collect();
+ (bone.clone(), moved)
+ })
+ .collect(),
+ }
+}
+
pub fn family(layer: &Layer) -> Vec<&Layer> {
std::iter::once(layer)
.chain(layer.children().iter().flat_map(family))
diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs
index 518655d..66a165b 100644
--- a/crates/render/src/lib.rs
+++ b/crates/render/src/lib.rs
@@ -8,6 +8,7 @@ pub mod overlay;
pub mod pngwrite;
pub mod shapes;
pub mod sheet;
+pub mod shift;
pub mod sprites;
pub mod text;
pub mod vector;
diff --git a/crates/render/src/shift.rs b/crates/render/src/shift.rs
new file mode 100644
index 0000000..964a74d
--- /dev/null
+++ b/crates/render/src/shift.rs
@@ -0,0 +1,156 @@
+use crate::vector;
+use anyhow::{Result, anyhow, bail};
+use klad_core::bundle::Bundle;
+use klad_core::doc::{Cel, Kind, Layer, Node, Transform};
+use klad_core::markedit::{MarkTransform, apply_affine, invert};
+use klad_core::ops::{Op, ShiftSpec, Shifted};
+use klad_core::rig;
+use klad_core::stroke::Mark;
+
+pub fn moved_node(node: &Node, affine: [f32; 6], scale: f32, degrees: f32) -> Result<Transform> {
+ let mut t = node.transform;
+ let pivot = match t.pivot {
+ Some(p) => p,
+ None => {
+ let mut plain = node.clone();
+ plain.transform = Transform::default();
+ vector::local_bounds(&plain)?.map_or([0.0, 0.0], |r| [r.center_x(), r.center_y()])
+ }
+ };
+ let (qx, qy) = apply_affine(affine, (t.x + pivot[0], t.y + pivot[1]));
+ t.x = qx - pivot[0];
+ t.y = qy - pivot[1];
+ t.sx *= scale;
+ t.sy *= scale;
+ t.rotate += degrees;
+ Ok(t)
+}
+
+pub fn resolve(bundle: &Bundle, ops: &mut [Op]) -> Result<()> {
+ ops.iter_mut().try_for_each(|op| match op {
+ Op::Shift(spec) if spec.resolved.is_none() => resolve_one(bundle, spec),
+ _ => Ok(()),
+ })
+}
+
+pub fn moved_cels(root: &Layer, only: Option<u32>) -> Vec<(&Layer, &Cel)> {
+ rig::family(root)
+ .into_iter()
+ .filter(|l| matches!(l.kind(), Kind::Paint | Kind::Vector))
+ .flat_map(|l| {
+ l.cels()
+ .iter()
+ .filter(move |c| c.link.is_none())
+ .filter(move |c| only.is_none_or(|f| l.content_at(f).is_some_and(|shown| shown.id == c.id)))
+ .map(move |c| (l, c))
+ })
+ .collect()
+}
+
+#[derive(Clone, Debug, Default)]
+pub struct Targets {
+ pub name: String,
+ pub marks: Vec<(String, Vec<u32>)>,
+ pub nodes: Vec<Node>,
+ pub weights: Vec<(String, rig::Weights)>,
+ pub bounds: Option<[f32; 4]>,
+}
+
+pub fn targets(bundle: &Bundle, layer: &str, only: Option<u32>) -> Result<Targets> {
+ let doc = &bundle.doc;
+ let root = doc.find_layer(layer)?;
+ let cels = moved_cels(root, only);
+ let mut boxes: Vec<[f32; 4]> = Vec::new();
+ let mut marks = Vec::new();
+ cels.iter()
+ .filter(|(l, _)| l.kind() == Kind::Paint)
+ .try_for_each(|(l, c)| {
+ let found = bundle.read_marks(&l.id, &c.id)?;
+ boxes.extend(found.iter().filter_map(Mark::bounds));
+ if !found.is_empty() {
+ marks.push((c.id.clone(), found.iter().map(Mark::id).collect::<Vec<_>>()));
+ }
+ Ok::<_, anyhow::Error>(())
+ })?;
+ let nodes: Vec<Node> = cels
+ .iter()
+ .filter(|(l, _)| l.kind() == Kind::Vector)
+ .flat_map(|(_, c)| c.nodes.iter().cloned())
+ .collect();
+ if let Some(r) = vector::nodes_bounds(&nodes)? {
+ boxes.push([r.left, r.top, r.right, r.bottom]);
+ }
+ let weights = match only {
+ Some(_) => Vec::new(),
+ None => rig::family(root)
+ .into_iter()
+ .filter(|l| !l.bones.is_empty())
+ .map(|l| bundle.read_weights(&l.id).map(|w| (l.id.clone(), w)))
+ .collect::<Result<Vec<_>>>()?
+ .into_iter()
+ .filter(|(_, w)| !w.maps.is_empty())
+ .collect(),
+ };
+ Ok(Targets {
+ name: root.name.clone(),
+ marks,
+ nodes,
+ weights,
+ bounds: boxes
+ .into_iter()
+ .reduce(|a, b| [a[0].min(b[0]), a[1].min(b[1]), a[2].max(b[2]), a[3].max(b[3])]),
+ })
+}
+
+pub fn shifted(targets: &Targets, t: &mut MarkTransform) -> Result<Shifted> {
+ let pivot = match (t.pivot, targets.bounds) {
+ (Some(p), _) => p,
+ (None, Some(w)) => [(w[0] + w[2]) / 2.0, (w[1] + w[3]) / 2.0],
+ (None, None) => bail!("{} has nothing to transform", targets.name),
+ };
+ t.pivot = Some(pivot);
+ let affine = t.affine(pivot);
+ let even = (t.sx - t.sy).abs() < 1e-6;
+ let moving = t.rotate == 0.0 && t.sx == 1.0 && t.sy == 1.0;
+ let keyed = |n: &Node| {
+ ["x", "y", "rotate", "sx", "sy", "scale"]
+ .iter()
+ .any(|k| n.keys.contains_key(*k))
+ };
+ let nodes: Vec<(String, Transform)> = targets
+ .nodes
+ .iter()
+ .map(|n| {
+ if !even {
+ bail!(
+ "{} has shapes, which scale evenly: give one scale, or move and turn it only",
+ targets.name
+ );
+ }
+ if keyed(n) && !moving {
+ bail!(
+ "shape {} moves by its keys, so {} can only be moved, not turned or scaled",
+ n.id,
+ targets.name
+ );
+ }
+ Ok((n.id.clone(), moved_node(n, affine, t.sx, t.rotate)?))
+ })
+ .collect::<Result<_>>()?;
+ let back = invert(affine).ok_or_else(|| anyhow!("that transform flattens the layer to a line"))?;
+ Ok(Shifted {
+ marks: targets.marks.clone(),
+ nodes,
+ weights: targets
+ .weights
+ .iter()
+ .map(|(id, w)| (id.clone(), rig::moved_weights(w, back)))
+ .collect(),
+ })
+}
+
+pub fn resolve_one(bundle: &Bundle, spec: &mut ShiftSpec) -> Result<()> {
+ let found = targets(bundle, &spec.layer, spec.only)?;
+ spec.resolved = Some(shifted(&found, &mut spec.transform)?);
+ Ok(())
+}
diff --git a/docs/DESIGN.md b/docs/DESIGN.md
index 7090e98..46d5901 100644
--- a/docs/DESIGN.md
+++ b/docs/DESIGN.md
@@ -248,6 +248,7 @@ Every layer has `blend`, `opacity`, `visible`, `locked`, optional `mask`, `clip`
- **No agent inside the editor (M8).** A first version ran a model in an Agent pane with the user's Claude API key; it was removed on 2026-11-06 in favour of an MCP server that any agent client can use (planned). Agents work on a drawing through the `klad` CLI, and the person reaches them through notes, the selection and the shared history.
- **Rigs (M6).** A paint layer or a group gets `bones` (format 9): each a name, an optional parent that comes before it, a head and a tail in canvas px. A group's skeleton poses every paint layer in it together, so a character's lines, colour and shading layers stay in step. Each bone has a weight map in `weights/<owner>.weights` (zstd: a JSON header with the grid size and bone names, then one byte per cell per bone, cells of 4 px), written by `Bundle::apply` with the edit and kept in its history step; weights are normalised across bones when read (bilinear between cells), and a place no bone weighs follows the nearest bone. Automatic weights are 1/(d + 0.15 L + 1)^3 by distance to each bone segment (L its length), so joints blend over a short stretch; `set` paints soft dabs (smoothstep falloff towards a value), `part` gives a named part's cells to one bone at 1 and the others 0, `smooth` blurs every map once. A pose (`pose` on a cel: its rest drawing's id, an angle per bone in degrees from rest, a root move) is linear blend skinning: each bone's rest matrix (head, angle) and posed matrix (its parent's posed matrix times the rest offset times its turn) give a skin matrix, and every stroke sample moves by the weighted sum; stroke sizes scale by the mean local stretch (the Jacobian's determinant, square-rooted); polygon fills move their points; flood fills are warped through a 4 px triangle mesh over their coverage (each posed triangle rasterised, sampling the rest coverage by barycentric position). The rest pose returns the marks untouched. `pose` (computed by the CLI, `cli/src/rig.rs`) makes or re-poses a drawing at `to` on every paint layer under the skeleton from the rest drawing shown at `from` (a posed drawing's own rest when `from` shows one). In-betweens of two poses of one rest drawing (or a pose and its rest) mix the angles and root by t instead of matching strokes (`rig::posed_pair`), and keep the mixed pose. A bone `move` with a `tail` takes along the heads of the children that start at the old tail (within half a pixel), and `by` moves a bone with all its children (`rig::moved`, which the editor also draws while dragging). The editor's bone tool (J) has three modes (draw, weights, pose) and in every mode a skeleton list in its options (each bone under its parent; picking one highlights it on the canvas); with no skeleton on the active layer the options name the layers and groups that have one, each a button that makes it active. Picking on the canvas is a click in draw and pose mode and cmd click (ctrl outside macOS) in weights mode. In draw mode a drag on empty canvas draws a root bone and starts a chain (S6.9, as Spine's create tool makes the new bone the next one's parent, but welded: Spine has no snapping and its users have asked for it): the next bone runs from the last tail to the pointer and each release (a click or a drag) adds it, its head exactly on that tail, so `rig::moved` and the joint grips treat it as a joint; shift as you let go keeps the joint and parent for the next bone (a fan); Esc, Enter, a right click, a click on the open end, or a change of mode, tool or skeleton owner ends it; a chain only commits on a release whose press reached the canvas, and each bone is its own undo step, so after cmd Z the chain (checked every frame against the bones) carries on from the last bone still there. With no chain, a press on a bone picks it and drags what is under the pointer (the picked bone shows handles at both ends): an end moves that end, the middle moves the bone and its children, and the head of a child that starts at its parent's tail is that joint, so dragging it moves the parent's tail; alt drag from a tail starts a chain from it (from a bone's middle, a child starting there); the options rename, reparent (a parent menu without the bone's own children), add or change the picked bone's IK, and remove. Draw and weights modes show the skeleton at rest. Weights are painted in the editor's own process (`klad_core::rig::weights_for`) over a tint of the picked bone's map, and pose mode turns bones, committing the pose (angles, root and targets) through `klad pose` as a job; it loads the pose of the frame shown again whenever the frame, the owner or that pose changes; the drawing is not deformed live while posing, only the skeleton.
- **IK (M6, S6.10).** Taken from Spine (constraints on one or two bones, a bend side, softness, a mix, solved parent first, posing a limb by its end) with two changes: a target is a point kept in each pose (`pose.ik`), not a bone, because klad bones carry weight maps and go to Godot as `Bone2D`s, and constraints are ordered by the skeleton itself (the limb's top bone, then its bone), so there is no order to keep by hand. Constraints (`layer.ik`: bone, chain 1 or 2, bend, softness) live on the skeleton; a pose without a target for one leaves that limb to its angles, so adding a constraint changes no pose, and removing one (or a bone it holds) first writes its solved turns into the angles of every pose that used it (`ops::bake`, in frame order, each turn within half a turn of the pose before, so in-betweens made later go the short way), so those poses keep their look; where another IK in the same pose shares a bone with it, that one's target becomes turns too, since no stored turn survives a second solve. A bone edit that breaks a limb (a reparent that leaves it without a parent, a move that puts its head on its parent's head) drops the IK as Spine does and writes its turns, but the limb changed, so those poses need posing again, and the note says so; `ik --set` also lists the poses that now solve differently from how their drawings were bent. `rig::applied` solves (f64, libm): FK frames from the angles and root, then per constraint an aim (atan2 to the target) or a limb by two circles meeting (the upper segment runs from the parent's head to the bone's head, so a child that starts off its parent's tail is exact), with Spine-like softness as a quadratic ease into full reach (r = d - (d - L + s)^2 / 4s between L - s and L + s, smooth at both ends, straight at L + s), and the mix along the short way round from the angle. `skinning`, `tips` and `Rig::new` take the constraints, so every place a pose bends a drawing or draws a skeleton (the CLI's poses, in-betweens, the bones overlay, the Godot export's rotation tracks, the editor) uses the solved turns. In-betweens mix the targets, not the solved angles: a 100 + 100 px leg whose hip moves 120 px over a planted foot keeps the foot exactly with mixed targets and pushes it 9.7 px through the floor with mixed angles (`rig::tests`). A constraint in one key only is handed over as turns: that key's limb takes its solved turns, each within half a turn of the other key's, and the in-betweens turn it (fading the IK out instead flipped elbows when the solve and the angles stored under it were over half a turn apart). Pose values that are not finite, and mixes outside 0 to 1, are refused by `Document::validate`, since JSON would store them as null. Joint limits, stretch and chains of three or more bones (Spine refuses them: the result would depend on earlier frames) are not built. The editor's pose mode: a press near an IK limb's end or its target drags the target (making one where the solve gives back the limb as shown, `rig::target_for_end`, which inverts the softness ease, so nothing jumps, when the pose had none; a limb posed against its IK's bend side turns over, and a message says so); near a root bone's head moves the root, the targets staying where they are; on a bone an IK holds moves its target with the pointer; anywhere else it turns the bone, and alt turns a bone by hand after writing its limb's solved turns into the angles (IK off). The options show an IK switch and a mix for the picked bone's limb. The pose being built stays across mode switches; it is loaded again when the frame, the owner or the frame's stored pose changes, never mid-drag, and after "make this pose a drawing" what was posed since is kept. Chains end with Return or Esc only when no field, palette, settings window or key capture has the keyboard (`keys_busy`, read at the top of the frame; the pen's Return and Esc follow it too). The options bar stays one row: the picked bone's hints live in tooltips.
+- **Layer transforms (2026-11-08).** Kevin: "a better way to select and transform a full layer instead of individual brush strokes only"; his choices: the marks themselves move (not a transform kept on the layer), every drawing by default, started with cmd T. The `transform` op with `layer` (`ops::ShiftSpec`) moves, turns, scales or stretches a layer or group as one: the marks of every drawing on it and on the layers in it (`only`: just the drawings shown at one frame), its shapes (composed onto each top-level node's transform, so shapes scale evenly only, and keyed shapes may only be moved, their x and y keys shifted with them), and with every drawing also its bones, the weight maps (resampled through the inverse transform, nearest cell) and its poses' roots (turned and scaled) and IK targets, so a rigged character moves as one. Mark ids, shape transforms and moved weights need the stroke files and shape bounds, so `klad_render::shift` works them out (`targets`, read once, then `shifted` per transform) for the CLI and the editor, and core applies them. In the editor cmd T (Edit > Transform > Transform layer) puts the selection handles round the active layer's content at the frame shown (the V tool's handles: drag inside moves, corners scale, edges stretch, outside turns); each drag previews the frame on screen through the drag preview and commits for every drawing (an "every drawing" switch in the options), and Esc, Return, a click outside or another tool ends it.
- **Keys (M6, S6.5).** Layers, groups and vector nodes keep `keys`: per property (`x`, `y`, `rotate`, `sx`, `sy`, `opacity`) a sorted list of frame, value and ease (linear, in, out, in-out, step, or a cubic curve x1,y1,x2,y2 solved by bisection). A segment follows its first key's ease; values hold before the first key and after the last. Layers and groups composite with their keyed opacity and, when moved, with their keyed transform about the canvas centre (drawn whole, not tile by tile, while moved); nodes take keyed transforms and opacity when rasterised (`nodes_at`). The editor's frame and plane caches hash the keyed values; its vector raster cache does not follow node keys yet, so keyed shapes move in `klad render` and the exports, not in the editor.
- **Godot scenes (M6, S6.6, S6.7).** `export --godot-scene` flattens each visible top-level layer (with its fog; the background with the first) into a texture on a `Parallax2D` with `scroll_scale` 1/(1 + depth), the factor the editor's depth preview (hold D) uses. `export --godot-rig` writes per skeleton: each part of the rest drawing (named parts of each paint layer's rest drawing, the loose marks as one) replayed alone, trimmed, on a `Polygon2D` with a 16 px triangle mesh over its pixels (one cell of margin), UVs, and per-vertex weights sampled from the maps; a `Skeleton2D` with a `Bone2D` per bone at rest (local position and angle against the parent, `rest`, `length`); and an `AnimationPlayer` with one animation per clip (or one for the timeline) whose value tracks hold each bone's rest angle plus its pose at the frame each posed drawing starts (stepped, so drawings hold as in klad); frames that are not poses of the rest drawing are listed for the frames export. Re-exports keep their uids. `samples/rig` builds a figure with all of it.
- **Paint over (M5, S5.29).** `paintover` (`cli/src/paintover.rs`, resolved before the shape ops, alone in its batch) flattens the source (the `from` layers, or every visible layer below the target's top-level layer with the background) into OKLab, then follows Hertzmann's painterly method: for each brush size, biggest first, the source is blurred to that size, a grid at half the size finds cells whose mean difference from the painting so far (an estimate made by stamping discs of each stroke's colour) exceeds `threshold`, and a stroke starts at each such cell's worst pixel in a seeded random order. A stroke walks in steps of half its size across the luminance gradient (Sobel), turning towards it by `curve` times how sure the gradient is (weak gradients keep the stroke's direction; with none, a smooth seeded field of mostly level angles), and stops past its minimum length when the source there is closer to the painting than to the stroke's colour, at a colour change over twice the threshold, at the edge of the region or at its maximum length. `focus` keeps the last size to a shape grown by three of those sizes. Each stroke becomes a stroke op with a press-in and lift-off pressure, its size a little varied, its colour broken by `vary` from a hash of its seed, in the part `part`. `like <cel>` carries a paint-over to another drawing: every source paint layer's two drawings are paired as in-betweens pair them; each stroke rides the topmost source mark under its centre (a stroke within half its size, a polygon fill, a flood fill's coverage) with `tween::carry` along that mark's line (still marks: it stays; marks gone: it fades to opacity 0); it keeps its seed and is recoloured from the new source at its start, faded when it would now cross an edge; new strokes, in `<part> added at <frame>` (one part per drawing, so in-betweens never pair one drawing's added strokes with another's: marks in parts with different names never pair by id, order or nearness, only a forced pair joins them), only go where the source changed (its colour or alpha, grown by the biggest size) or where carried strokes left a gap. `--frames a-b` repeats that drawing to drawing, making a drawing on the target wherever a source layer starts one (a link where they link). `samples/paintover` paints over the lemons and carries a paint-over through the creature's walk; frame to frame its background changes by 0.03 of 255 on average.
diff --git a/docs/cli.md b/docs/cli.md
index 76c9ca5..5407783 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -28,7 +28,7 @@ This reference is licensed under the MIT License (`LICENSE-MIT`), unlike klad it
- [`klad add`](#klad-add): Add a layer, cel or shape
- [`klad set`](#klad-set): Change properties: klad set art.klad n4 fill=#ff0000 transform.rotate=15 (null removes)
- [`klad rm`](#klad-rm): Remove layers, cels or nodes
-- [`klad transform`](#klad-transform): Move, rotate or scale strokes and fills (<cel>:s<id>)
+- [`klad transform`](#klad-transform): Move, rotate or scale strokes and fills (<cel>:s<id>), or a whole layer or group (--layer)
- [`klad lasso`](#klad-lasso): Lasso strokes and fills on a paint layer; --cut also takes the parts crossing the edge
- [`klad path`](#klad-path): List the points of a path, rect or ellipse, or edit them
- [`klad mv`](#klad-mv): Move a layer or node: --above, --below, --in, --index
@@ -963,11 +963,15 @@ Options:
```text
Move, rotate or scale strokes and fills, addressed as <cel>:s<id> (klad strokes lists them). Rotation and scale turn about --pivot, by default the middle of the marks' bounds. Stroke sizes and tapers scale with them; fills move by whole pixels and are resampled when turned or scaled.
+--layer moves a whole layer or group instead: the marks of every drawing on it and on the layers in it (--only <frame>: just the drawings shown at that frame), its shapes, and with every drawing also its bones, its weights and its poses' roots and targets, so a rigged character moves as one. Shapes scale evenly only, and a layer with keyed shapes can only be moved. The pivot defaults to the middle of everything moved.
+
klad transform art.klad c4:s12 c4:s13 --move 40,-10
klad transform art.klad c4:s12 --rotate 15 --scale 1.2
klad transform art.klad c4:s3 c4:s5 --sx -1 --pivot 512,400
+ klad transform art.klad --layer figure --move -120,0
+ klad transform art.klad --layer sky --scale 1.1 --only 12
-Also a transform op in klad apply: {"op":"transform","ids":["c4:s12"],"x":40,"y":-10,"rotate":15,"sx":1.2,"sy":1.2}
+Also a transform op in klad apply: {"op":"transform","ids":["c4:s12"],"x":40,"y":-10,"rotate":15,"sx":1.2,"sy":1.2}, or for a layer {"op":"transform","layer":"figure","x":-120,"y":0,"only":12}.
Usage: klad transform [OPTIONS] <BUNDLE> [IDS]...
@@ -979,6 +983,12 @@ Arguments:
Options:
+ --layer <LAYER>
+ a whole layer or group, every drawing on it (with its bones and poses), instead of ids
+
+ --only <ONLY>
+ with --layer: only the drawings shown at this frame
+
--move <OFFSET>
dx,dy in px
diff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.md
index 3d5c5dc..de0a022 100644
--- a/docs/skill/SKILL.md
+++ b/docs/skill/SKILL.md
@@ -66,6 +66,7 @@ klad set art.klad c4:s12 color=#c84a3a size=6 brush=pencil
klad set art.klad c4:s7 color=skin opacity=0.8
klad rm art.klad c4:s12 c4:s13
klad transform art.klad c4:s3 c4:s5 --move 40,-10 --rotate 15 --scale 1.2
+klad transform art.klad --layer figure --move -120,0 # a whole layer or group: every drawing, its shapes, bones and poses
klad show art.klad c4:s12
klad render art.klad --focus c4:s12
```