Skip to content

armgit / klad

Public Imported from GitHub
0

A drawing app built for agent/human collaboration

Rust

Selecting and editing pixels: boxes that take pixels, whole-pixel moves, exact flips, turns and recolours

Indicode BV2526e623615c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bd31d78..57d80f4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,7 @@
The first builds, and klad's licences.
- A new icon, painted in klad: a K in two brush strokes.
+- Selecting and editing pixels. On a pixel layer the stroke tool (**S**) drags a box, or a loop, around pixels and takes them, cutting marks between whole pixels; drag them to move by whole pixels, scale by whole numbers or turn by quarters, and the bar under them flips, turns, recolours (exactly the current colour), copies and deletes. **Select same colour** takes every mark in the selected colours. From the command line: `klad lasso` takes `--box x,y,w,h`, `klad strokes --entry skin` lists one colour's marks, and `klad recolour` gives pixel marks the exact palette colour.
- Shapes and fill on the grid. On a pixel layer the fill tool (**G**) fills every pixel joined to the one you click that has exactly its colour (**across corners**, **read all pixel layers**), and the shape tool (**U**) drags a rectangle, an ellipse or a line of whole pixels, outlined or **filled**. From the command line: `klad pixel` with `--line`, `--rect`, `--ellipse` (`--filled`) and `--fill x,y` (`--diagonal`, `--ref`).
- Sprites as text, for agents. `klad pixel sprite.klad l1 --grid sprite.txt` draws a sprite from a legend (`i = ink`) and rows of characters, one per pixel, each character becoming one mark bound to its palette colour; `klad pixels sprite.klad l1` reads a pixel layer back the same way, with its legend and numbered rows and columns (`--plain` in the form `--grid` reads, `--json`).
- The pixel pencil and eraser. On a pixel layer the brush tool (**B**) draws whole pixels in the current colour, which joins the palette, and the eraser (**E**, or the pen's eraser end) clears them; each drag is one mark. A one-pixel line is pixel perfect (no doubled corners), the size is a square of whole pixels (**[** and **]**), and shift click draws a straight line from the last pixel. From the command line, `klad pixel` takes `--path` (SVG path data as a line of pixels) and `--size`.
diff --git a/crates/app/src/commands.rs b/crates/app/src/commands.rs
index 8d0c0a8..56d6fb8 100644
--- a/crates/app/src/commands.rs
+++ b/crates/app/src/commands.rs
@@ -38,6 +38,7 @@ pub enum Cmd {
Copy,
Paste,
SelectAll,
+ SelectSameColour,
TransformLayer,
CutLasso,
Recolour,
@@ -512,7 +513,7 @@ use Repeat as R;
use Trigger as T;
impl Cmd {
- pub const ALL: [Cmd; 185] = [
+ pub const ALL: [Cmd; 186] = [
Cmd::Brush,
Cmd::Eraser,
Cmd::Fill,
@@ -547,6 +548,7 @@ impl Cmd {
Cmd::Copy,
Cmd::Paste,
Cmd::SelectAll,
+ Cmd::SelectSameColour,
Cmd::TransformLayer,
Cmd::CutLasso,
Cmd::Recolour,
@@ -1008,6 +1010,15 @@ impl Cmd {
R::No,
"move, turn or scale the whole active layer or group, in every drawing, with its bones and poses",
),
+ Cmd::SelectSameColour => spec(
+ "select.same-colour",
+ "select the same colour",
+ icon::PALETTE,
+ G::Edit,
+ T::None,
+ R::No,
+ "on a pixel layer: every mark of this drawing in the colours of the selected marks, or in the current colour when nothing is selected",
+ ),
Cmd::SelectAll => spec(
"edit.select-all",
"select every stroke on this layer",
@@ -2402,6 +2413,7 @@ impl Cmd {
Cmd::Copy => "Copy",
Cmd::Paste => "Paste",
Cmd::SelectAll => "Select all",
+ Cmd::SelectSameColour => "Select same colour",
Cmd::TransformLayer => "Transform layer",
Cmd::CutLasso => "Lasso cuts strokes",
Cmd::Recolour => "Recolour",
@@ -2614,6 +2626,7 @@ pub const MENUS: [Menu; 9] = [
Run(Cmd::Delete),
Line,
Run(Cmd::SelectAll),
+ Run(Cmd::SelectSameColour),
Run(Cmd::Deselect),
Run(Cmd::CutLasso),
Run(Cmd::PickAllLayers),
diff --git a/crates/app/src/editor.rs b/crates/app/src/editor.rs
index 0bb956e..06b385a 100644
--- a/crates/app/src/editor.rs
+++ b/crates/app/src/editor.rs
@@ -334,6 +334,7 @@ struct Drag {
grab: Grab,
node: String,
strokes: bool,
+ whole: bool,
fresh: bool,
copy: bool,
start: Vec2,
@@ -354,14 +355,30 @@ impl Drag {
if self.grab != Grab::Scale {
return 1.0;
}
- ((self.now - self.center).length() / (self.start - self.center).length().max(1.0)).clamp(0.02, 50.0)
+ let free = ((self.now - self.center).length() / (self.start - self.center).length().max(1.0)).clamp(0.02, 50.0);
+ match self.whole {
+ true => free.round().max(1.0),
+ false => free,
+ }
}
fn angle(&self) -> f32 {
if self.grab != Grab::Rotate {
return 0.0;
}
- (self.now - self.center).angle() - (self.start - self.center).angle()
+ let free = (self.now - self.center).angle() - (self.start - self.center).angle();
+ match self.whole {
+ true => (free / std::f32::consts::FRAC_PI_2).round() * std::f32::consts::FRAC_PI_2,
+ false => free,
+ }
+ }
+
+ fn slide(&self) -> Vec2 {
+ let d = self.now - self.start;
+ match self.whole {
+ true => vec2(d.x.round(), d.y.round()),
+ false => d,
+ }
}
fn stretch(&self) -> Option<(usize, Vec2, f32)> {
@@ -381,6 +398,11 @@ impl Drag {
} else {
k.clamp(-50.0, 50.0)
};
+ let k = match self.whole {
+ true if k.round() == 0.0 => 1.0f32.copysign(k),
+ true => k.round(),
+ false => k,
+ };
Some((axis, pivot, k))
}
@@ -394,7 +416,7 @@ impl Drag {
}
match self.grab {
Grab::Move => {
- let d = self.now - self.start;
+ let d = self.slide();
[1.0, 0.0, 0.0, 1.0, d.x, d.y]
}
Grab::Scale => {
@@ -433,7 +455,7 @@ impl Drag {
}
match self.grab {
Grab::Move => {
- let d = self.now - self.start;
+ let d = self.slide();
MarkTransform {
x: d.x,
y: d.y,
@@ -726,6 +748,7 @@ pub(crate) struct Editor {
pub(crate) pixel_filled: bool,
pub(crate) pixel_diagonal: bool,
pub(crate) pixel_fill_all: bool,
+ pub(crate) pixel_box: bool,
pixel_live: Option<PixelLive>,
pixel_last: Option<klad_core::pixel::Cell>,
hover_cell: Option<[i32; 2]>,
@@ -923,6 +946,7 @@ impl Editor {
pixel_filled: false,
pixel_diagonal: false,
pixel_fill_all: false,
+ pixel_box: true,
pixel_live: None,
pixel_last: None,
hover_cell: None,
@@ -1382,10 +1406,16 @@ impl Editor {
fn picked_corners(&self) -> Option<(String, [Vec2; 4])> {
let picked = self.picked.as_ref()?;
+ let area = picked.cut.as_ref().filter(|_| self.scene.on_grid()).map(|polygon| {
+ polygon.iter().fold([f32::MAX, f32::MAX, f32::MIN, f32::MIN], |b, p| {
+ [b[0].min(p[0]), b[1].min(p[1]), b[2].max(p[0]), b[3].max(p[1])]
+ })
+ });
let [x0, y0, x1, y1] = self
.picked_parts()
.iter()
.map(|(_, _, marks, ids)| markedit::bounds_of(marks, ids))
+ .chain(std::iter::once(area))
.fold(None, union_box)?;
Some((picked.key(), [vec2(x0, y0), vec2(x1, y0), vec2(x1, y1), vec2(x0, y1)]))
}
@@ -1787,11 +1817,17 @@ impl Editor {
if !strokes && self.shifting.is_none() && !matches!(self.scene.bundle.doc.item(&id), Some(Item::Node(..))) {
return;
}
+ let whole = strokes && self.scene.on_grid();
let center = corners.iter().fold(Vec2::ZERO, |a, c| a + *c) / 4.0;
+ let center = match whole {
+ true => vec2(center.x.round(), center.y.round()),
+ false => center,
+ };
self.drag = Some(Drag {
grab,
node: id,
strokes,
+ whole,
fresh,
copy: grab == Grab::Move && self.modifiers.alt,
start: at,
@@ -2071,6 +2107,18 @@ impl Editor {
.collect()
}
+ fn lasso_outline(&self, lasso: &Lasso) -> Vec<Vec2> {
+ let boxed = self.pixel_box && self.scene.on_grid() && matches!(self.tool, Tool::Strokes | Tool::Select);
+ match (boxed, lasso.points.first(), lasso.points.last()) {
+ (true, Some(a), Some(b)) => {
+ let (x0, y0) = (a.x.min(b.x).floor(), a.y.min(b.y).floor());
+ let (x1, y1) = (a.x.max(b.x).ceil(), a.y.max(b.y).ceil());
+ vec![vec2(x0, y0), vec2(x1, y0), vec2(x1, y1), vec2(x0, y1)]
+ }
+ _ => lasso.points.clone(),
+ }
+ }
+
fn finish_pick(&mut self) -> Result<()> {
let Some(lasso) = self.lasso.take() else {
return Ok(());
@@ -2098,8 +2146,8 @@ impl Editor {
};
let at = lasso.points[0];
let erased = self.erased();
- let polygon: Option<Vec<[f32; 2]>> =
- (lasso.far && lasso.points.len() >= 3).then(|| lasso.points.iter().map(|p| [p.x, p.y]).collect());
+ let polygon: Option<Vec<[f32; 2]>> = (lasso.far && lasso.points.len() >= 3)
+ .then(|| self.lasso_outline(&lasso).iter().map(|p| [p.x, p.y]).collect());
let pick = |marks: &[Mark]| -> (Vec<u32>, bool) {
match &polygon {
Some(polygon) => {
@@ -3892,7 +3940,11 @@ impl Editor {
self.draw_pins(&painter, |c| self.screen(view, rect, c));
self.draw_checks(&painter, |c| self.screen(view, rect, c));
if let Some(lasso) = self.lasso.as_ref().filter(|l| l.far) {
- let line: Vec<Pos2> = lasso.points.iter().map(|p| self.screen(view, rect, *p)).collect();
+ let line: Vec<Pos2> = self
+ .lasso_outline(lasso)
+ .iter()
+ .map(|p| self.screen(view, rect, *p))
+ .collect();
let tint = if matches!(self.tool, Tool::Strokes | Tool::Select) {
accent
} else {
@@ -4198,12 +4250,68 @@ impl Editor {
klad_core::color::recolour(&colours, target)
.into_iter()
.zip(&chosen)
- .map(|(c, (cel, m))| (cel.clone(), m.id(), "color", json!(klad_core::color::to_hex(c))))
+ .map(|(shade, (cel, m))| {
+ let colour = match m.as_fill().is_some_and(|f| f.on_grid()) {
+ true => target,
+ false => shade,
+ };
+ (cel.clone(), m.id(), "color", json!(klad_core::color::to_hex(colour)))
+ })
.collect()
});
self.set_picked(sets)
}
+ fn select_same_colour(&mut self) {
+ let Some(cel) = self.scene.active_cel() else {
+ return;
+ };
+ let marks = self.scene.active_marks();
+ let key = |m: &Mark| {
+ m.as_fill().filter(|f| f.on_grid() && !f.erases()).map(|f| {
+ f.entry()
+ .map_or_else(|| klad_core::color::to_hex(f.color()), String::from)
+ })
+ };
+ let held: Vec<u32> = self
+ .picked
+ .as_ref()
+ .filter(|p| p.cel == cel)
+ .map_or(Vec::new(), |p| p.ids.clone());
+ let wanted: BTreeSet<String> = match held.is_empty() {
+ false => marks
+ .iter()
+ .filter(|m| held.contains(&m.id()))
+ .filter_map(key)
+ .collect(),
+ true => {
+ let current = klad_core::color::to_hex(self.color);
+ marks
+ .iter()
+ .filter(|m| klad_core::color::to_hex(m.color()).eq_ignore_ascii_case(&current))
+ .filter_map(key)
+ .collect()
+ }
+ };
+ let ids: Vec<u32> = marks
+ .iter()
+ .filter(|m| key(m).is_some_and(|k| wanted.contains(&k)))
+ .map(Mark::id)
+ .collect();
+ match ids.is_empty() {
+ true => self.say(
+ Tone::Info,
+ "no pixels of this drawing have that colour: click a palette colour, or select a mark first",
+ ),
+ false => {
+ let count = ids.len();
+ self.tool = Tool::Strokes;
+ self.picked = Some(Picked::whole(cel, ids));
+ self.say(Tone::Done, format!("{count} marks of that colour selected"));
+ }
+ }
+ }
+
fn attached_parts(&self) -> Vec<(String, String, Vec<u32>)> {
self.picked_parts()
.into_iter()
@@ -5281,6 +5389,7 @@ mod tests {
grab,
node: "c1:1,2".into(),
strokes: true,
+ whole: false,
fresh: false,
copy: false,
start: vec2(140.0, 80.0),
diff --git a/crates/app/src/editor/commands.rs b/crates/app/src/editor/commands.rs
index abef28e..e79b512 100644
--- a/crates/app/src/editor/commands.rs
+++ b/crates/app/src/editor/commands.rs
@@ -105,6 +105,16 @@ impl Editor {
.filter(|l| l.kind() != klad_core::doc::Kind::Adjust)
.is_none()
.then(|| "pick a layer or group with something on it".to_string()),
+ Cmd::SelectSameColour => match self.scene.on_grid() {
+ false => {
+ Some("make a pixel layer active first: it selects pixel marks by their palette colour".to_string())
+ }
+ true => self
+ .scene
+ .active_marks()
+ .is_empty()
+ .then(|| "this drawing has no pixels yet".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),
@@ -659,6 +669,7 @@ impl Editor {
}
Cmd::Paste => self.paste()?,
Cmd::SelectAll => self.select_all_strokes(),
+ Cmd::SelectSameColour => self.select_same_colour(),
Cmd::TransformLayer => self.start_shift()?,
Cmd::CutLasso => self.cut_lasso = !self.cut_lasso,
Cmd::Recolour => self.recolour_picked()?,
diff --git a/crates/app/src/editor/options.rs b/crates/app/src/editor/options.rs
index 5a85d9f..b8588bb 100644
--- a/crates/app/src/editor/options.rs
+++ b/crates/app/src/editor/options.rs
@@ -381,6 +381,27 @@ impl Editor {
}
}
Tool::Fill => self.fill_panel(ui),
+ Tool::Strokes if self.scene.on_grid() => {
+ [(true, "box"), (false, "loop")].iter().for_each(|(boxed, label)| {
+ if ui
+ .selectable_label(self.pixel_box == *boxed, *label)
+ .hint(match boxed {
+ true => "drag a box around the pixels to select",
+ false => "draw a loop around the pixels to select",
+ })
+ .clicked()
+ {
+ self.pixel_box = *boxed;
+ }
+ });
+ self.command_check(ui, Cmd::CutLasso, "takes pixels, not whole marks");
+ self.command_button(ui, Cmd::SelectSameColour, Some("same colour"));
+ self.command_button(ui, Cmd::SelectAll, Some("select all"));
+ ui.label(
+ RichText::new("click a mark or drag around pixels; drag them to move by whole pixels; the bar under them edits them")
+ .color(theme::WEAK),
+ );
+ }
Tool::Strokes => {
self.pick_scope(ui);
self.command_check(ui, Cmd::CutLasso, "a lasso cuts strokes at its edge");
diff --git a/crates/app/src/editor/selection.rs b/crates/app/src/editor/selection.rs
index ce22cec..edcce02 100644
--- a/crates/app/src/editor/selection.rs
+++ b/crates/app/src/editor/selection.rs
@@ -344,6 +344,19 @@ impl Editor {
at.y.max(rect.top() + 8.0),
);
let commands: Vec<Cmd> = match selected {
+ Selected::Strokes if self.scene.on_grid() => vec![
+ Cmd::FlipH,
+ Cmd::FlipV,
+ Cmd::TurnLeft90,
+ Cmd::TurnRight90,
+ Cmd::Recolour,
+ Cmd::SelectSameColour,
+ Cmd::Copy,
+ Cmd::Paste,
+ Cmd::DuplicateInPlace,
+ Cmd::Delete,
+ Cmd::Deselect,
+ ],
Selected::Strokes => vec![
Cmd::FlipH,
Cmd::FlipV,
diff --git a/crates/app/src/editor/ui_tests.rs b/crates/app/src/editor/ui_tests.rs
index 3663656..121bb29 100644
--- a/crates/app/src/editor/ui_tests.rs
+++ b/crates/app/src/editor/ui_tests.rs
@@ -1908,6 +1908,126 @@ fn the_fill_and_shape_tools_draw_whole_pixels_on_a_pixel_layer() {
let _ = std::fs::remove_dir_all(&path);
}
+#[test]
+fn pixels_are_selected_by_box_or_colour_and_move_flip_turn_and_recolour_on_the_grid() {
+ let path = pixel_sample("pixel-edit");
+ let mut h = harness(editor(&path), vec2(1440.0, 900.0));
+ h.state_mut().tool = Tool::Strokes;
+ h.run_steps(2);
+ assert!(h.query_by_label("box").is_some() && h.query_by_label_contains("same colour").is_some());
+ let grid = |h: &Harness<'static, Editor>| -> Vec<String> {
+ let ed = h.state();
+ let doc = &ed.scene.bundle.doc;
+ let grid = klad_core::pixel::grid_of(ed.scene.active_marks(), doc.canvas.width, doc.canvas.height);
+ let legend = klad_core::pixel::legend(doc, &grid);
+ klad_core::pixel::rows(&grid, &legend)
+ };
+ assert_eq!(&grid(&h)[4][..9], "....aaa..");
+ assert_eq!(&grid(&h)[5][..9], "....aba..");
+ let (a, b) = (on_screen(&h, 3.6, 3.6), on_screen(&h, 5.4, 7.4));
+ h.hover_at(a);
+ h.run_steps(1);
+ h.drag_at(a);
+ h.run_steps(1);
+ (1..=6).for_each(|i| {
+ h.hover_at(a + (b - a) * (i as f32 / 6.0));
+ h.run_steps(1);
+ });
+ h.drop_at(b);
+ h.run_steps(3);
+ let picked = h.state().picked.clone().expect("the box holds pixels");
+ assert!(
+ picked.cut.is_some(),
+ "the box crosses the ring, so it takes pixels, not whole marks"
+ );
+ assert_eq!(
+ picked.cut.as_deref(),
+ Some(&[[3.0, 3.0], [6.0, 3.0], [6.0, 8.0], [3.0, 8.0]][..]),
+ "the box snaps out to whole pixels"
+ );
+ let (from, to) = (on_screen(&h, 4.5, 5.5), on_screen(&h, 14.2, 5.9));
+ drag(&mut h, from, to);
+ settle(&mut h, |ed| ed.drag.is_none() && ed.preview.is_none());
+ h.run_steps(3);
+ ready(&mut h);
+ let rows = grid(&h);
+ assert_eq!(
+ &rows[4][..18],
+ "......a.......aa..",
+ "the left two columns of the ring moved 10 pixels: {rows:?}"
+ );
+ assert_eq!(&rows[5][..18], "......a.......ab..");
+ assert_eq!(&rows[6][..18], "......a.......aa..");
+ assert!(
+ h.state()
+ .scene
+ .active_marks()
+ .iter()
+ .all(|m| m.cuts().is_empty() && m.as_fill().unwrap().coverage.alpha.iter().all(|a| *a == 0 || *a == 255)),
+ "every mark is still whole pixels with no soft edge"
+ );
+ h.state_mut().invoke(Cmd::FlipH).unwrap();
+ h.run_steps(3);
+ ready(&mut h);
+ let rows = grid(&h);
+ assert_eq!(&rows[5][..18], "......a.......ba..", "flipped in place: {rows:?}");
+ h.state_mut().invoke(Cmd::TurnRight90).unwrap();
+ h.run_steps(3);
+ ready(&mut h);
+ let turned = grid(&h);
+ let count = |rows: &[String], sign: char| rows.iter().flat_map(|r| r.chars()).filter(|c| *c == sign).count();
+ assert_eq!(
+ (count(&turned, 'a'), count(&turned, 'b')),
+ (8, 1),
+ "a quarter turn keeps every pixel: {turned:?}"
+ );
+ h.state_mut().invoke(Cmd::Deselect).unwrap();
+ h.state_mut()
+ .set_colour(klad_core::color::parse_hex("#2b2d42").unwrap());
+ h.state_mut().invoke(Cmd::SelectSameColour).unwrap();
+ h.run_steps(2);
+ let same = h.state().picked.clone().expect("the ink marks");
+ assert!(
+ same.ids.len() >= 2 && same.cut.is_none(),
+ "every mark in the ring's colour: {:?}",
+ same.ids
+ );
+ h.state_mut()
+ .set_colour(klad_core::color::parse_hex("#2a9d8f").unwrap());
+ h.state_mut().invoke(Cmd::Recolour).unwrap();
+ h.run_steps(3);
+ ready(&mut h);
+ let ed = h.state();
+ let teal = ed
+ .scene
+ .bundle
+ .doc
+ .swatch("#2a9d8f")
+ .expect("the new colour is a palette colour");
+ let id = ed.scene.bundle.doc.palette[teal].id.clone();
+ let recoloured = ed
+ .scene
+ .active_marks()
+ .iter()
+ .filter(|m| m.as_fill().unwrap().entry() == Some(id.as_str()))
+ .count();
+ assert_eq!(
+ recoloured,
+ same.ids.len(),
+ "each takes exactly the colour and its palette entry"
+ );
+ assert!(
+ ed.scene.bundle.doc.palette.len() <= 3,
+ "no shades were invented: {:?}",
+ ed.scene.bundle.doc.palette
+ );
+ let plain = sample("no-same-colour");
+ let other = harness(editor(&plain), vec2(1440.0, 900.0));
+ assert!(other.state().can_run(Cmd::SelectSameColour).is_some());
+ let _ = std::fs::remove_dir_all(&path);
+ let _ = std::fs::remove_dir_all(&plain);
+}
+
#[test]
fn a_tap_that_wobbles_selects_and_a_drag_past_three_points_moves() {
let path = sample("tap");
diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs
index 254d47b..31bdb94 100644
--- a/crates/cli/src/main.rs
+++ b/crates/cli/src/main.rs
@@ -620,11 +620,20 @@ enum Command {
Lasso {
bundle: PathBuf,
layer: String,
- #[arg(long, help = "x,y pairs separated by spaces")]
- polygon: String,
+ #[arg(long, required_unless_present = "area", help = "x,y pairs separated by spaces")]
+ polygon: Option<String>,
+ #[arg(
+ long = "box",
+ value_name = "X,Y,W,H",
+ value_parser = parse_box,
+ allow_hyphen_values = true,
+ conflicts_with = "polygon",
+ help = "A box in place of a polygon: its top left pixel and its size in pixels"
+ )]
+ area: Option<[i64; 4]>,
#[arg(
long,
- help = "Split strokes and fills crossing the edge and take the inside parts too"
+ help = "Split strokes and fills crossing the edge and take the inside parts too (pixel marks split between whole pixels)"
)]
cut: bool,
#[arg(long = "move", value_parser = parse_pair, allow_hyphen_values = true, help = "dx,dy in px")]
@@ -1951,6 +1960,12 @@ enum Command {
frame: u32,
#[arg(long, default_value_t = 0, help = "Only strokes with an id above this")]
after: u32,
+ #[arg(
+ long,
+ value_name = "COLOUR",
+ help = "On a pixel layer: only the marks of one palette colour (a name, a colour, an index or an id), to edit them together"
+ )]
+ entry: Option<String>,
#[arg(long, help = "Print strokes as JSON with their points (x, y, pressure)")]
json: bool,
},
@@ -2777,6 +2792,7 @@ fn run() -> Result<()> {
bundle,
layer,
polygon,
+ area,
cut,
offset,
rotate,
@@ -2789,7 +2805,14 @@ fn run() -> Result<()> {
frame,
flags,
} => {
- let polygon = polygon.split_whitespace().map(parse_pair).collect::<Result<Vec<_>>>()?;
+ let polygon = match (area, polygon) {
+ (Some([x, y, w, h]), _) => {
+ let (x0, y0, x1, y1) = (x as f32, y as f32, (x + w) as f32, (y + h) as f32);
+ vec![[x0, y0], [x1, y0], [x1, y1], [x0, y1]]
+ }
+ (None, Some(text)) => text.split_whitespace().map(parse_pair).collect::<Result<Vec<_>>>()?,
+ (None, None) => Vec::new(),
+ };
if polygon.len() < 3 {
return Err(anyhow!("--polygon needs at least 3 x,y points"));
}
@@ -2800,6 +2823,7 @@ fn run() -> Result<()> {
(false, Some(t)) => LassoAction::Transform(t),
(false, None) => return marks::lassoed(&bundle, &layer, frame, &polygon, flags.json),
};
+ let layer = Bundle::open(&bundle)?.doc.find_layer(&layer)?.id.clone();
let op = Op::Lasso(LassoSpec {
layer,
frame,
@@ -3951,8 +3975,9 @@ fn run() -> Result<()> {
layer,
frame,
after,
+ entry,
json,
- } => strokes(&bundle, &layer, frame, after, json)?,
+ } => strokes(&bundle, &layer, frame, after, entry.as_deref(), json)?,
Command::Hash {
bundle,
frame,
@@ -4202,7 +4227,7 @@ fn recolour_ops(path: &Path, ids: &[String], to: &str) -> Result<Vec<Op>> {
.map(|l| l.id.clone())
.ok_or_else(|| anyhow!("no drawing {cel}"))
};
- let colours = ids
+ let found = ids
.iter()
.map(|id| {
let (cel, mark) = klad_core::markedit::parse_address(id)
@@ -4211,16 +4236,24 @@ fn recolour_ops(path: &Path, ids: &[String], to: &str) -> Result<Vec<Op>> {
marks
.iter()
.find(|m| m.id() == mark)
- .map(klad_core::stroke::Mark::color)
+ .map(|m| (m.color(), m.as_fill().is_some_and(|f| f.on_grid())))
.ok_or_else(|| anyhow!("{id} does not exist"))
})
.collect::<Result<Vec<_>>>()?;
+ let colours: Vec<klad_core::color::Rgba> = found.iter().map(|(c, _)| *c).collect();
Ok(klad_core::color::recolour(&colours, target)
.into_iter()
.zip(ids)
- .map(|(c, id)| Op::Set {
+ .zip(&found)
+ .map(|((shade, id), (_, on_grid))| Op::Set {
id: id.clone(),
- props: serde_json::Map::from_iter([("color".to_string(), serde_json::json!(klad_core::color::to_hex(c)))]),
+ props: serde_json::Map::from_iter([(
+ "color".to_string(),
+ match on_grid {
+ true => serde_json::json!(to),
+ false => serde_json::json!(klad_core::color::to_hex(shade)),
+ },
+ )]),
})
.collect())
}
@@ -4284,14 +4317,34 @@ fn info(path: &Path) -> Result<()> {
})
}
-fn strokes(path: &Path, layer: &str, frame: u32, after: u32, as_json: bool) -> Result<()> {
+fn strokes(path: &Path, layer: &str, frame: u32, after: u32, entry: Option<&str>, as_json: bool) -> Result<()> {
let bundle = Bundle::open(path)?;
- let owner = bundle.doc.layer(layer).ok_or_else(|| anyhow!("no layer {layer}"))?;
+ let owner = bundle.doc.find_layer(layer)?;
+ let layer = owner.id.as_str();
let cel = owner
.content_at(frame)
.ok_or_else(|| anyhow!("layer {layer} has no cel at frame {frame}"))?;
let all = bundle.read_marks(layer, &cel.id)?;
- let marks: Vec<_> = all.iter().filter(|m| m.id() > after).cloned().collect();
+ let wanted = entry
+ .map(|key| {
+ bundle
+ .doc
+ .swatch(key)
+ .map(|at| bundle.doc.palette[at].id.clone())
+ .ok_or_else(|| anyhow!("the palette has no {key:?} (give a name, a colour, an index or an id)"))
+ })
+ .transpose()?;
+ let marks: Vec<_> = all
+ .iter()
+ .filter(|m| m.id() > after)
+ .filter(|m| match &wanted {
+ Some(id) => m
+ .as_fill()
+ .is_some_and(|f| !id.is_empty() && f.entry() == Some(id.as_str())),
+ None => true,
+ })
+ .cloned()
+ .collect();
let strokes: Vec<_> = strokes_of(&marks).collect();
let fills: Vec<_> = fills_of(&marks).collect();
if as_json {
diff --git a/crates/cli/tests/binary.rs b/crates/cli/tests/binary.rs
index cc3fe98..dbcc586 100644
--- a/crates/cli/tests/binary.rs
+++ b/crates/cli/tests/binary.rs
@@ -839,6 +839,98 @@ fn lines_rectangles_ellipses_and_fills_go_on_the_grid_from_the_command_line() {
std::fs::remove_dir_all(&dir).unwrap();
}
+#[test]
+fn pixel_marks_are_listed_by_colour_cut_by_a_box_and_recoloured_exactly() {
+ let dir = std::env::temp_dir().join(format!("draw-binary-pixel-edit-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ let bundle = dir.join("sprite.klad");
+ let path = bundle.to_str().unwrap();
+ let run = |args: &[&str]| Command::new(env!("CARGO_BIN_EXE_klad")).args(args).output().unwrap();
+ let draw = |args: &[&str]| {
+ let out = run(args);
+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
+ String::from_utf8_lossy(&out.stdout).to_string()
+ };
+ let rows = |layer: &str| -> Vec<String> {
+ draw(&["pixels", path, layer, "--plain"])
+ .lines()
+ .skip_while(|line| !line.is_empty())
+ .skip(1)
+ .map(String::from)
+ .collect()
+ };
+ draw(&["new", path, "--pixel", "12x6"]);
+ draw(&["palette", path, "--add", "#22223b", "--name", "ink"]);
+ draw(&["palette", path, "--add", "#f2c14e", "--name", "body"]);
+ draw(&["pixel", path, "l1", "--color", "ink", "--rect", "0,0,6,4"]);
+ draw(&["pixel", path, "l1", "--color", "body", "--rect", "1,1,4,2", "--filled"]);
+ draw(&["pixel", path, "l1", "--color", "ink", "--cells", "0,5"]);
+ let ink: serde_json::Value =
+ serde_json::from_str(&draw(&["strokes", path, "l1", "--entry", "ink", "--json"])).unwrap();
+ assert_eq!(
+ ink["fills"].as_array().unwrap().len(),
+ 2,
+ "the two ink marks, not the body"
+ );
+ assert!(draw(&["strokes", path, "l1", "--entry", "body"]).contains("1 pixel marks, 8 cells"));
+ let moved = draw(&["lasso", path, "pixel 1", "--box", "3,0,3,4", "--cut", "--move", "5,1"]);
+ assert!(moved.contains("moved"), "{moved}");
+ assert_eq!(
+ rows("l1"),
+ [
+ "iii.........",
+ "ibb.....iii.",
+ "ibb.....bbi.",
+ "iii.....bbi.",
+ "........iii.",
+ "i..........."
+ ],
+ "the right half of the box moved 5 across and 1 down, between whole pixels"
+ );
+ let marks: serde_json::Value = serde_json::from_str(&draw(&["strokes", path, "l1", "--json"])).unwrap();
+ let pieces = marks["fills"].as_array().unwrap();
+ assert_eq!(pieces.len(), 5, "the two marks the box crossed are four now");
+ assert!(
+ pieces.iter().all(|m| m.get("cuts").is_none()),
+ "with no cut left on them"
+ );
+ let body_moved = pieces
+ .iter()
+ .find(|m| m["color"] == "#f2c14eff" && m["bounds"][0].as_f64() == Some(8.0))
+ .map(|m| m["address"].as_str().unwrap().to_string())
+ .expect("the moved half of the body");
+ draw(&["recolour", path, &body_moved, "--to", "ink"]);
+ assert_eq!(
+ rows("l1")[2],
+ "ibb.....iii.",
+ "a recoloured pixel mark takes exactly the palette colour"
+ );
+ assert_eq!(
+ serde_json::from_str::<serde_json::Value>(&draw(&["palette", path, "--json"]))
+ .unwrap()
+ .as_array()
+ .unwrap()
+ .len(),
+ 2,
+ "and no shade is added to the palette"
+ );
+ draw(&["lasso", path, "l1", "--box", "8,1,3,4", "--flip", "h"]);
+ assert_eq!(rows("l1")[2], "ibb.....iii.");
+ draw(&["lasso", path, "l1", "--box", "0,0,3,4", "--rotate", "90"]);
+ let turned = rows("l1");
+ let count = |sign: char| turned.iter().flat_map(|r| r.chars()).filter(|c| *c == sign).count();
+ assert_eq!(
+ (count('i'), count('b')),
+ (8 + 12 + 1, 4),
+ "a quarter turn keeps every pixel: {turned:?}"
+ );
+ assert_eq!(&turned[1][..4], "iiii", "and the 3 by 4 piece now lies 4 by 3");
+ let missing = run(&["strokes", path, "l1", "--entry", "teal"]);
+ assert!(String::from_utf8_lossy(&missing.stderr).contains("the palette has no"));
+ std::fs::remove_dir_all(&dir).unwrap();
+}
+
#[test]
fn recolour_moves_strokes_together_and_keeps_their_shades() {
let dir = std::env::temp_dir().join(format!("draw-binary-recolour-{}", std::process::id()));
diff --git a/crates/core/src/markedit.rs b/crates/core/src/markedit.rs
index 19833a1..0290214 100644
--- a/crates/core/src/markedit.rs
+++ b/crates/core/src/markedit.rs
@@ -459,7 +459,19 @@ fn resampled(c: &Coverage, a: Affine, hard: bool) -> Coverage {
out
}
+fn on_the_grid(a: Affine) -> Affine {
+ let whole = |v: f32| (v - v.round()).abs() < 1e-4;
+ match a[..4].iter().all(|v| whole(*v)) {
+ true => a.map(f32::round),
+ false => a,
+ }
+}
+
pub fn transform_fill(fill: &mut Fill, a: Affine) {
+ let a = match fill.on_grid() {
+ true => on_the_grid(a),
+ false => a,
+ };
let map = |p: [f32; 2]| mapped(a, p);
match &mut fill.source {
FillSource::Seed { seed, .. } => [seed.x, seed.y] = map([seed.x, seed.y]),
@@ -632,6 +644,23 @@ pub fn split(marks: &mut Vec<Mark>, polygon: &[[f32; 2]], cut: bool, ids: MarkId
chosen.push(next);
pieces.push((mark.id(), next));
next += 1;
+ if let (Mark::Fill(outer), Mark::Fill(inner)) = (&mut mark, &mut part)
+ && outer.on_grid()
+ {
+ let shown: Vec<[u32; 2]> = outer
+ .coverage
+ .cells()
+ .filter(|c| cut::keeps(&outer.cuts, (c[0] as f32 + 0.5, c[1] as f32 + 0.5)))
+ .collect();
+ let (inside, outside): (Vec<[u32; 2]>, Vec<[u32; 2]>) = shown
+ .into_iter()
+ .partition(|c| inside_polygon(polygon, (c[0] as f32 + 0.5, c[1] as f32 + 0.5)));
+ outer.coverage = Coverage::from_cells(&outside);
+ inner.coverage = Coverage::from_cells(&inside);
+ outer.cuts.clear();
+ inner.cuts.clear();
+ return vec![mark, part];
+ }
mark.cuts_mut().push(Cut {
keep: Keep::Outside,
polygon: polygon.to_vec(),
@@ -1069,6 +1098,89 @@ mod tests {
assert_eq!(turned.pixels(), 4, "a quarter turn keeps every pixel");
}
+ #[test]
+ fn a_lasso_splits_pixel_marks_between_whole_pixels_and_turns_and_scales_land_on_the_grid() {
+ let grid = |id: u32, cells: &[[u32; 2]]| -> Mark {
+ Fill::cells(id, [1.0, 0.0, 0.0, 1.0], "p1", false, Coverage::from_cells(cells)).into()
+ };
+ let row: Vec<[u32; 2]> = (2..10).map(|x| [x, 5]).collect();
+ let mut marks = vec![grid(1, &row), grid(2, &[[20, 20]])];
+ let mut lasso = MarkChange::Lasso {
+ polygon: vec![[4.3, 3.0], [7.6, 3.0], [7.6, 8.0], [4.3, 8.0]],
+ cut: true,
+ action: LassoAction::Transform(MarkTransform {
+ y: 3.0,
+ ..Default::default()
+ }),
+ chosen: Vec::new(),
+ };
+ apply(&mut marks, &mut lasso, "c1", MarkIds::default()).unwrap();
+ assert_eq!(marks.len(), 3, "the row is two marks now");
+ let cells_of = |m: &Mark| m.as_fill().unwrap().coverage.cells().collect::<Vec<_>>();
+ assert_eq!(
+ cells_of(&marks[0]),
+ [[2, 5], [3, 5], [8, 5], [9, 5]],
+ "the pixels whose middle is outside the lasso stay"
+ );
+ assert_eq!(
+ cells_of(&marks[1]),
+ [[4, 8], [5, 8], [6, 8], [7, 8]],
+ "the others moved, as a mark of their own"
+ );
+ assert!(
+ marks.iter().all(
+ |m| m.cuts().is_empty() && m.as_fill().unwrap().coverage.alpha.iter().all(|a| *a == 0 || *a == 255)
+ ),
+ "no cut is left to soften an edge"
+ );
+ assert_eq!(marks[1].as_fill().unwrap().entry(), Some("p1"));
+ let pair = || vec![grid(1, &[[4, 4], [5, 4], [6, 4]]), grid(2, &[[4, 5]])];
+ let turned = |pivot: [f32; 2]| {
+ let mut marks = pair();
+ let mut change = MarkChange::Transform {
+ ids: vec![1, 2],
+ transform: MarkTransform {
+ rotate: 90.0,
+ pivot: Some(pivot),
+ ..Default::default()
+ },
+ };
+ apply(&mut marks, &mut change, "c1", MarkIds::default()).unwrap();
+ (cells_of(&marks[0]), cells_of(&marks[1]))
+ };
+ [[5.5, 5.0], [5.0, 5.0], [5.25, 4.75], [5.5, 5.5]]
+ .iter()
+ .for_each(|pivot| {
+ let (bar, foot) = turned(*pivot);
+ assert_eq!(bar.len(), 3, "about {pivot:?} the bar keeps its three pixels: {bar:?}");
+ assert!(
+ bar.windows(2).all(|w| w[0][0] == w[1][0] && w[1][1] == w[0][1] + 1),
+ "upright: {bar:?}"
+ );
+ assert_eq!(foot.len(), 1);
+ assert_eq!(
+ (foot[0][0] + 1, foot[0][1]),
+ (bar[0][0], bar[0][1]),
+ "the foot under the bar's left end is now left of its top: {bar:?} {foot:?}"
+ );
+ });
+ let mut doubled = pair();
+ let mut change = MarkChange::Transform {
+ ids: vec![1, 2],
+ transform: MarkTransform {
+ sx: 2.0,
+ sy: 2.0,
+ pivot: Some([5.5, 5.0]),
+ ..Default::default()
+ },
+ };
+ apply(&mut doubled, &mut change, "c1", MarkIds::default()).unwrap();
+ let (bar, foot) = (cells_of(&doubled[0]), cells_of(&doubled[1]));
+ assert_eq!((bar.len(), foot.len()), (12, 4), "every pixel is a 2 by 2 block");
+ let (bx, by) = (bar[0][0], bar[0][1]);
+ assert_eq!(foot[0], [bx, by + 2], "and the two marks still fit together");
+ }
+
#[test]
fn clicks_pick_the_topmost_mark_and_lassos_take_whole_marks() {
let mut marks = vec![square(1), line(2)];
diff --git a/docs/DESIGN.md b/docs/DESIGN.md
index 37cf232..821159b 100644
--- a/docs/DESIGN.md
+++ b/docs/DESIGN.md
@@ -1,4 +1,4 @@
-_Last updated: 2026-11-11 23:10_
+_Last updated: 2026-11-12 00:40_
# klad: design
@@ -232,7 +232,7 @@ Unknown keys are errors that list the valid ones, so a typo never passes silentl
Every layer has `blend`, `opacity`, `visible`, `locked`, optional `mask`, `clip` and (M5, format 8) `effects`. Effects are layer settings, not a layer kind: the planned `filter` kind became them.
-- **Pixel layers (M9).** A pixel layer is a paint layer flagged `pixel`, so it shares cels, masks, clipping, lock alpha, effects, the timeline and every export with paint layers. One pixel is one canvas pixel: a 64x64 sprite is a 64x64 drawing shown enlarged, and a drawing never mixes pixel sizes. Its marks stay data, as strokes do: a pixel mark is a fill record whose source is cells (`FillSource::Cells`), a set of whole pixels (coverage 0 or 255) with the id of the palette swatch it was drawn with, or a set of pixels to erase. So the same addresses, `set`, `rm`, `transform`, lasso, copy and history work on them; scaling, flipping and turning sample the nearest pixel (`markedit::resampled` with `hard`), which also makes an export above full size hard-edged. Colours are palette entries: `Document::bind_swatch` finds or adds the swatch and gives it an `id` the first time a mark uses it, and `set color=` on a pixel mark binds it to the new entry. The `pixel` op (`klad pixel`) is the first way to make marks; brush strokes and flood or lasso fills are refused on a pixel layer (`ops::off_the_grid`). A drawing with a pixel layer (`Document::pixel_art`) gets a sharp view on both sides. In the editor the zoom moves in whole screen pixels per pixel above real size (`View::whole`, `View::fit_whole`; free below it), a pixel grid shows from 8 screen pixels per pixel (a dark line with light dashes, so it reads on any colour; View > Pixel grid), the pixel under the pointer is outlined on a pixel layer and named in the status line, and the Real size pane (`Pane::Preview`, opened the first time a pixel drawing is opened) shows the composed frame at 1, 2 or 4 screen pixels per pixel for drawings up to 512 px. In the CLI, `klad render` and edit previews enlarge by a whole number to about 512 px (`agent::pixel_scale`), and `--overlay grid` draws the same lines with the pixel numbers along the top and left (`overlay::draw_cells`). The palette is what a pixel drawing is bound to. A mark stores its swatch's id and its colour, so every reader of a stroke file draws it without the palette; when a palette edit changes a swatch's colour, `ops::follow_palette` adds a `MarkChange::Entry` for every pixel drawing, which rewrites the colour of the marks bound to that swatch in the same transaction (one undo step), and a removed swatch unbinds its marks. A palette rewritten without ids keeps them by name, then by colour (`carry_ids`). Swatches carry an optional `ramp` name: a ramp is the swatches sharing it, in palette order, dark to light (`palettes::ramp` makes one from a base colour with `color::value_step`, darker and cooler to lighter and warmer). Palettes that come with klad are colour lists in `core/src/palettes.rs` (`klad palettes`), and `palettes::parse` reads a list of hex colours or a GIMP palette. The pencil is grid geometry in `core/src/pixel.rs`, shared by both hands: `line` (Bresenham), `extend` (a run that follows the pen with no holes), `perfect` (drops the corner pixel of an L, so a hand-drawn line stays one pixel thin), `stamp` (a size is a square of whole pixels) and `of_path` (SVG path data flattened and traced; corners the path asks for are kept, the corners that flattening a curve leaves are not). The `pixel` op takes `cells` or a `path`, and a `size`. In the editor the brush tool on a pixel layer is the pencil (the eraser command and the pen's eraser end erase): the run is drawn over the canvas as it grows and committed on release as one `pixel` op marked as made by hand, so the palette binding, history and sync are the op's. Shift click draws a straight line from the last pixel; `[` and `]` change the size. An agent reads and writes a pixel layer as text, which is exact where a picture is not. `pixel::grid_of` works out what a drawing's marks show, pixel by pixel (later marks over earlier ones, erasing marks, lock alpha, cuts), as the palette entry or the colour of each pixel; `pixel::legend` gives each one a character (the first letter of its name where free) and `pixel::ruled` or `pixel::plain` print the rows (`klad pixels`). The other way, `pixel::parse_text` reads a legend and rows and the grid form of the `pixel` op (`rows`, `legend`, `at`) turns each character into one mark bound to its colour (`klad pixel --grid`), so what `klad pixels --plain` prints draws the same picture again. Text grids are the agent's side only: a person draws with the pencil. Shapes and fills are the same op with other sources: `line`, `rect` and `ellipse` (the ellipse that fits a box of pixels, by an integer midpoint walk, so even and odd sizes stay symmetric; `filled` takes the rows between its outline) are pure geometry in `core/src/pixel.rs`; `fill` is a flood over what the drawing shows (`pixel::flood` on the grid of `grid_of`: pixels joined to the seed with exactly its entry or colour, four neighbours or eight), reading this layer, another pixel layer or all of them merged. A flood needs the marks, which an op cannot read, so `Bundle::settle_pixels` turns every `fill` into its cells before the ops are applied, walking the batch so a fill sees the marks the ops before it made; `Bundle::apply_as` calls it, so the CLI, `klad apply` and the editor share it. In the editor the fill tool floods on a click and the shape tool drags a rectangle, an ellipse or a line of pixels on a pixel layer, previewed as the pixels it will make. Shading, sharp exports and Aseprite files follow in the milestone's later stories.
+- **Pixel layers (M9).** A pixel layer is a paint layer flagged `pixel`, so it shares cels, masks, clipping, lock alpha, effects, the timeline and every export with paint layers. One pixel is one canvas pixel: a 64x64 sprite is a 64x64 drawing shown enlarged, and a drawing never mixes pixel sizes. Its marks stay data, as strokes do: a pixel mark is a fill record whose source is cells (`FillSource::Cells`), a set of whole pixels (coverage 0 or 255) with the id of the palette swatch it was drawn with, or a set of pixels to erase. So the same addresses, `set`, `rm`, `transform`, lasso, copy and history work on them; scaling, flipping and turning sample the nearest pixel (`markedit::resampled` with `hard`), which also makes an export above full size hard-edged. Colours are palette entries: `Document::bind_swatch` finds or adds the swatch and gives it an `id` the first time a mark uses it, and `set color=` on a pixel mark binds it to the new entry. The `pixel` op (`klad pixel`) is the first way to make marks; brush strokes and flood or lasso fills are refused on a pixel layer (`ops::off_the_grid`). A drawing with a pixel layer (`Document::pixel_art`) gets a sharp view on both sides. In the editor the zoom moves in whole screen pixels per pixel above real size (`View::whole`, `View::fit_whole`; free below it), a pixel grid shows from 8 screen pixels per pixel (a dark line with light dashes, so it reads on any colour; View > Pixel grid), the pixel under the pointer is outlined on a pixel layer and named in the status line, and the Real size pane (`Pane::Preview`, opened the first time a pixel drawing is opened) shows the composed frame at 1, 2 or 4 screen pixels per pixel for drawings up to 512 px. In the CLI, `klad render` and edit previews enlarge by a whole number to about 512 px (`agent::pixel_scale`), and `--overlay grid` draws the same lines with the pixel numbers along the top and left (`overlay::draw_cells`). The palette is what a pixel drawing is bound to. A mark stores its swatch's id and its colour, so every reader of a stroke file draws it without the palette; when a palette edit changes a swatch's colour, `ops::follow_palette` adds a `MarkChange::Entry` for every pixel drawing, which rewrites the colour of the marks bound to that swatch in the same transaction (one undo step), and a removed swatch unbinds its marks. A palette rewritten without ids keeps them by name, then by colour (`carry_ids`). Swatches carry an optional `ramp` name: a ramp is the swatches sharing it, in palette order, dark to light (`palettes::ramp` makes one from a base colour with `color::value_step`, darker and cooler to lighter and warmer). Palettes that come with klad are colour lists in `core/src/palettes.rs` (`klad palettes`), and `palettes::parse` reads a list of hex colours or a GIMP palette. The pencil is grid geometry in `core/src/pixel.rs`, shared by both hands: `line` (Bresenham), `extend` (a run that follows the pen with no holes), `perfect` (drops the corner pixel of an L, so a hand-drawn line stays one pixel thin), `stamp` (a size is a square of whole pixels) and `of_path` (SVG path data flattened and traced; corners the path asks for are kept, the corners that flattening a curve leaves are not). The `pixel` op takes `cells` or a `path`, and a `size`. In the editor the brush tool on a pixel layer is the pencil (the eraser command and the pen's eraser end erase): the run is drawn over the canvas as it grows and committed on release as one `pixel` op marked as made by hand, so the palette binding, history and sync are the op's. Shift click draws a straight line from the last pixel; `[` and `]` change the size. An agent reads and writes a pixel layer as text, which is exact where a picture is not. `pixel::grid_of` works out what a drawing's marks show, pixel by pixel (later marks over earlier ones, erasing marks, lock alpha, cuts), as the palette entry or the colour of each pixel; `pixel::legend` gives each one a character (the first letter of its name where free) and `pixel::ruled` or `pixel::plain` print the rows (`klad pixels`). The other way, `pixel::parse_text` reads a legend and rows and the grid form of the `pixel` op (`rows`, `legend`, `at`) turns each character into one mark bound to its colour (`klad pixel --grid`), so what `klad pixels --plain` prints draws the same picture again. Text grids are the agent's side only: a person draws with the pencil. Shapes and fills are the same op with other sources: `line`, `rect` and `ellipse` (the ellipse that fits a box of pixels, by an integer midpoint walk, so even and odd sizes stay symmetric; `filled` takes the rows between its outline) are pure geometry in `core/src/pixel.rs`; `fill` is a flood over what the drawing shows (`pixel::flood` on the grid of `grid_of`: pixels joined to the seed with exactly its entry or colour, four neighbours or eight), reading this layer, another pixel layer or all of them merged. A flood needs the marks, which an op cannot read, so `Bundle::settle_pixels` turns every `fill` into its cells before the ops are applied, walking the batch so a fill sees the marks the ops before it made; `Bundle::apply_as` calls it, so the CLI, `klad apply` and the editor share it. In the editor the fill tool floods on a click and the shape tool drags a rectangle, an ellipse or a line of pixels on a pixel layer, previewed as the pixels it will make. Editing pixel marks reuses the selection and transform of strokes and fills, with three differences that keep the grid. A lasso that cuts would leave a supersampled cut on a mark (a soft edge), so `markedit::split` divides a pixel mark's coverage between whole pixels instead, by pixel middles, and the two halves carry no cut. A transform whose matrix is whole numbers (flips, quarter turns, whole scales) is rounded onto the grid in `transform_fill` (`on_the_grid`: matrix and offset rounded), so every pixel lands on a pixel whatever the pivot and marks transformed together still fit; other transforms sample the nearest pixel. Recolouring pixel marks gives each exactly the target colour and its palette entry, where paint marks keep their shades. In the editor the stroke tool on a pixel layer drags a box (or a loop) that snaps out to whole pixels and takes pixels, its box is the selected area, drags move by whole pixels, scale by whole numbers and turn by quarters (`Drag.whole`), and Select same colour takes every mark of the selected marks' palette entries. Shading, sharp exports and Aseprite files follow in the milestone's later stories.
- **Blend modes.** `normal`, `multiply`, `screen`, `overlay`, `add`, and since M5 `color-dodge`, `soft-light`, `hard-light`, `lighten`, `darken`, `color`, `luminosity`, all as in the W3C compositing spec (Skia's modes; `look::blend_rgb` and `look::composite` hold the formulas the tests check them against).
- **Effects (M5).** `"effects": [{"glow": {...}}, {"outline": {...}}]`, applied in order to the layer's content (after its mask; for a clip base, to the base and its clipped layers together) before its opacity and blend: `blur` (radius, a Gaussian sigma), `glow` (radius, strength, threshold: 0 glows from every pixel, higher only from the bright ones; color: a tint; blend: how the glow mixes with what is under the layer, screen by default, normal lays it like paint under the layer), `outline` (width, color, inside), `shadow` (x, y, radius, color, laid under the layer), `noise` (amount, size, seed, mono: a grain fixed to the canvas), `displace` (amount, size, seed, by: smooth waves, or a layer whose red pushes across and green down), `relief` (strength, light, highlight, shade, softness: lights the paint height of the layer's drawings, below). Each effect knows its reach (`look::reach`), so a tile is composed from its content within the tile plus that margin and tiles meet without seams (noise and haze read only their own pixel and add no margin, so they cost no neighbouring tiles); a tile skips a clip stack or group that puts no pixel in it (none of its rasters, live tiles or onion ghosts has a tile in the tile grown by its effects' margin; layers moved by keys, adjustment layers and vector layers drawn from their nodes always count), which leaves the tile the same since every blend leaves the pixels under a transparent layer as they are; the pixels are computed in Rust (`klad-render/effects.rs`) on f32 with absolute coordinates, so a tile equals the same pixels of the whole image byte for byte (tested). Blurs use a direct kernel, below a sigma of 2 at full size and above it on a grid of 2, 4, ... px blocks anchored to the canvas, then sampled back.
- **Adjustment layers (M5).** An `adjust` layer changes what is under it in its list: the layers below it in its group, or, clipped, its base. A group holding an adjustment is composed apart, so the adjustment stays inside it. The colour math is on unpremultiplied sRGB values with alpha kept: `hsl` (hue in degrees, saturation and lightness -1..1), `levels` (black, white, gamma, low, high), `curves` (points, and red, green, blue applied before them; monotone cubic, no overshoot), `balance` (shadows, midtones, highlights: cyan to red, magenta to green, yellow to blue, keepLight), `gradient-map` (stops by brightness). The layer's opacity, blend and mask decide how much of the adjusted colour replaces the colour under it. `fill` (a solid or gradient paint) is drawn like a content layer instead, with the layer's blend.
diff --git a/docs/cli.md b/docs/cli.md
index bef6fdf..d97b00b 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -1183,7 +1183,7 @@ Select the strokes and fills of a paint layer inside a polygon and move, turn, s
Also a lasso op in klad apply: {"op":"lasso","layer":"l3","polygon":[[100,100],[400,120],[380,400]],"cut":true,"x":60,"y":-20} (or "rm":true).
-Usage: klad lasso [OPTIONS] --polygon <POLYGON> <BUNDLE> <LAYER>
+Usage: klad lasso [OPTIONS] <BUNDLE> <LAYER>
Arguments:
<BUNDLE>
@@ -1196,8 +1196,11 @@ Options:
--polygon <POLYGON>
x,y pairs separated by spaces
+ --box <X,Y,W,H>
+ A box in place of a polygon: its top left pixel and its size in pixels
+
--cut
- Split strokes and fills crossing the edge and take the inside parts too
+ Split strokes and fills crossing the edge and take the inside parts too (pixel marks split between whole pixels)
--move <OFFSET>
dx,dy in px
@@ -3639,6 +3642,9 @@ Options:
[default: 0]
+ --entry <COLOUR>
+ On a pixel layer: only the marks of one palette colour (a name, a colour, an index or an id), to edit them together
+
--json
Print strokes as JSON with their points (x, y, pressure)
diff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.md
index ef29348..b30de89 100644
--- a/docs/skill/SKILL.md
+++ b/docs/skill/SKILL.md
@@ -133,6 +133,8 @@ klad export sprite.klad --scale 8 -o [email protected] square pixels, to keep
- `--fill x,y` is a flood fill: every pixel joined to that one that has exactly its colour, or is empty like it, with no tolerance. It spreads to the four neighbours; `--diagonal` also crosses corners (a one-pixel diagonal line then no longer stops it). It reads this layer; `--ref all` reads every visible pixel layer and `--ref <layer>` another one, so flat colour can go on a layer under the outlines: `klad pixel sprite.klad colour --color body --fill 12,10 --ref lines`. Check the outline is closed first (`klad pixels`): through a gap the fill takes the whole background.
- `--color` is a palette name, a palette index or `#rrggbb`. Every pixel mark is bound to a palette entry: a colour the palette lacks is added to it, so name the colours first (`klad palette sprite.klad --add '#f0c8a0' --name skin`) and draw with the names. `klad palette` lists the entries with their ids.
- The palette is the drawing's colours, and changing one changes the picture: `klad palette sprite.klad --recolour skin --to '#e8b796'` (a name, a colour, an index or an id) recolours every pixel mark drawn with it, on every frame. So fix a colour in the palette, not mark by mark. `klad palette sprite.klad --load pico-8` adds a palette that comes with klad (`klad palettes` lists them: pico-8, resurrect-64, four-greens, 1-bit) or a file (`.hex`, one colour per line, or a GIMP `.gpl`); colours the palette holds are not added twice. A ramp is a row of colours for one material, dark to light: `klad palette sprite.klad --ramp wood --base '#8b5a2b' --steps 5` makes `wood-1` (dark, cooler) to `wood-5` (light, warmer) around the base, and `--ramp skin --of skin-dark,skin,skin-light` groups colours it has. Shade a form with the steps of its ramp, not with new colours.
+- Editing an area: `klad lasso sprite.klad l1 --box x,y,w,h --cut --move 2,0` takes the pixels in that box (its top left pixel and size; `--polygon` for another outline) and moves them by whole pixels; `--flip h`, `--rotate 90`, `--scale 2` and `--rm` work the same way. With `--cut` the box takes pixels: marks it crosses are split between whole pixels and the inside halves become marks of their own. Without it only marks that lie whole inside are taken. Quarter turns, flips and whole-number scales keep every pixel; other angles and scales stay hard but look jagged.
+- Editing by colour: `klad strokes sprite.klad l1 --entry skin` lists only the marks of one palette colour (with `--json`, their addresses), to move, remove or recolour them together. `klad recolour sprite.klad c2:s4 c2:s9 --to shadow` gives pixel marks exactly that palette colour (no shades are kept, unlike on paint layers).
- Each mark, `<cel>:s<id>`, stays editable: `klad set sprite.klad c2:s1 color=shadow` recolours it (and binds it to that entry), `klad transform ... --move 2,0` moves it by whole pixels, `--flip h` and `--rotate 90` keep it hard, `klad rm` removes it. `klad strokes sprite.klad l1` lists the marks with their entry and cell count; `--json` gives each one's `cells`.
- Later marks cover earlier ones; `--erase` (or `erase` in a grid's legend) makes a mark that clears what was drawn before it at those pixels (remove that mark and the pixels come back).
- Looking: `klad render` and the `--render` preview of an edit enlarge a pixel drawing by a whole number to about 512 px, so every pixel is a square you can see (`--scale 1` gives the real size, which is how the player sees it: check there too). `--overlay grid` draws a line between pixels and numbers them along the top and the left, so a pixel's `x,y` can be read off the picture: the number is on the line where that column or row starts. `klad export --scale 8` (whole numbers) writes the enlarged PNG to keep.