Skip to content

armgit / klad

Public Imported from GitHub
0

A drawing app built for agent/human collaboration

Rust

The pixel pencil and eraser, by pen and from the command line

Indicode BV0fc45b527135
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fe2ab13..88109b6 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.
+- 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`.
- The palette of a pixel drawing. Changing a palette colour changes every pixel painted with it: click the colour in the palette, change it, and press **update** (or `klad palette art.klad --recolour skin --to '#e8b796'`). **palettes** adds the colours of a palette that comes with klad (PICO-8, Sweetie 16, DawnBringer 16 and 32, Endesga 32, Resurrect 64, AAP-64, Game Boy, 1-bit; `klad palettes` lists them) or of a palette file, a list of hex colours or a GIMP palette (`klad palette art.klad --load pico-8`). **ramp** adds five steps of the current colour, from dark and cool to light and warm (`klad palette art.klad --ramp wood --base '#8b5a2b'`), and `--ramp skin --of skin-dark,skin,skin-light` groups colours the palette has.
- A sharp view for pixel drawings. In the editor the zoom steps in whole pixels, so every pixel is the same size; a grid shows between the pixels once you are zoomed in (**View > Pixel grid**), the pixel under the pointer is outlined and its position shows in the status line, and the **Real size** panel shows the drawing as the player sees it, at 1x, 2x or 4x. `klad render` enlarges a pixel drawing to about 512 px, and `--overlay grid` numbers its pixels along the top and the left.
- Pixel layers, the start of pixel art in klad. A pixel drawing (**Pixel art** in the start window, or `klad new sprite.klad --pixel 64x64`) is a small drawing of whole pixels with no soft edges; **Layer > New pixel layer** or `klad add art.klad layer pixel` adds a pixel layer to any drawing. `klad pixel sprite.klad l1 --color skin --cells '4-11,5-9'` puts pixels on it as one mark bound to a palette colour (a colour the palette lacks is added), and `--erase` clears them. Each mark stays editable: recolour it with `klad set`, move it with `klad transform`, remove it with `klad rm`; `klad strokes` lists them. Exports above full size keep the pixels square. Brush strokes and fills stay off pixel layers. The format is now `klad/7` (stroke files version 3); older drawings open unchanged.
diff --git a/crates/app/src/editor.rs b/crates/app/src/editor.rs
index d5dbf55..2894627 100644
--- a/crates/app/src/editor.rs
+++ b/crates/app/src/editor.rs
@@ -486,6 +486,11 @@ impl PreviewState {
}
}
+struct PixelLive {
+ run: Vec<klad_core::pixel::Cell>,
+ erase: bool,
+}
+
struct Live {
stroke: Stroke,
painter: StrokePainter,
@@ -708,6 +713,10 @@ pub(crate) struct Editor {
outbox: Arc<Mutex<Outbox>>,
zoom_px: f32,
zoom_wanted: Option<f32>,
+ pub(crate) pixel_size: u32,
+ pub(crate) pixel_perfect: bool,
+ pixel_live: Option<PixelLive>,
+ pixel_last: Option<klad_core::pixel::Cell>,
hover_cell: Option<[i32; 2]>,
painted: u64,
real: Option<(RealKey, egui::TextureHandle)>,
@@ -903,6 +912,10 @@ impl Editor {
outbox: Arc::default(),
zoom_px: 1.0,
zoom_wanted: None,
+ pixel_size: 1,
+ pixel_perfect: true,
+ pixel_live: None,
+ pixel_last: None,
hover_cell: None,
painted: 0,
real: None,
@@ -2957,10 +2970,27 @@ impl Editor {
match (self.tool, e.phase) {
(_, Phase::Down) if !was_focused || !on_canvas || self.navigating => {}
(_, Phase::Down) if picking => self.pick_colour(c, self.modifiers.shift)?,
- (Tool::Fill | Tool::Brush, Phase::Down) if self.scene.on_grid() => self.say(
+ (Tool::Fill, Phase::Down) if self.scene.on_grid() => self.say(
Tone::Refused,
- "this is a pixel layer: it takes whole pixels, not brush strokes or fills",
+ "this is a pixel layer: it takes whole pixels (the pencil, B), not flood or lasso fills",
),
+ (Tool::Brush, Phase::Down) if self.scene.on_grid() => {
+ if self.pixel_live.is_none() && self.scene.can_paint() {
+ let at = klad_core::pixel::cell_at(c.x, c.y);
+ let run = match self.pixel_last.filter(|_| self.modifiers.shift) {
+ Some(last) => klad_core::pixel::line(last, at),
+ None => vec![at],
+ };
+ let erase = e.eraser || self.brush == "eraser";
+ self.pixel_live = Some(PixelLive { run, erase });
+ }
+ }
+ (Tool::Brush, Phase::Move) if self.pixel_live.is_some() => {
+ if let Some(live) = self.pixel_live.as_mut() {
+ klad_core::pixel::extend(&mut live.run, klad_core::pixel::cell_at(c.x, c.y));
+ }
+ }
+ (Tool::Brush, Phase::Up) if self.pixel_live.is_some() => self.finish_pixels()?,
(Tool::Fill, Phase::Down) => {
if self.scene.can_paint() {
self.lasso = Some(Lasso {
@@ -3306,6 +3336,49 @@ impl Editor {
}
}
+ fn pixel_cells(&self, live: &PixelLive) -> Vec<klad_core::pixel::Cell> {
+ let run = match self.pixel_perfect && self.pixel_size == 1 {
+ true => klad_core::pixel::perfect(&live.run),
+ false => live.run.clone(),
+ };
+ klad_core::pixel::stamp(&run, self.pixel_size)
+ }
+
+ fn finish_pixels(&mut self) -> Result<()> {
+ let Some(live) = self.pixel_live.take() else {
+ return Ok(());
+ };
+ let Some(layer) = self.scene.active_id() else {
+ return Ok(());
+ };
+ self.pixel_last = live.run.last().copied();
+ let (w, h) = self.scene.size();
+ let cells: Vec<klad_core::pixel::Cell> = self
+ .pixel_cells(&live)
+ .into_iter()
+ .filter(|c| c[0] >= 0 && c[1] >= 0 && c[0] < w as i64 && c[1] < h as i64)
+ .collect();
+ if cells.is_empty() {
+ return Ok(());
+ }
+ let spec = klad_core::ops::PixelSpec {
+ layer,
+ frame: self.scene.frame,
+ color: (!live.erase).then(|| color::hex(self.color)),
+ erase: live.erase,
+ cells,
+ path: None,
+ size: 1,
+ part: None,
+ by_hand: true,
+ };
+ self.apply(vec![Op::Pixel(spec)])?;
+ if !live.erase {
+ self.used_colour();
+ }
+ Ok(())
+ }
+
fn finish_fill(&mut self) -> Result<()> {
let Some(lasso) = self.lasso.take() else {
return Ok(());
@@ -3594,9 +3667,25 @@ impl Editor {
.map(|y| y as f32)
.for_each(|y| rule(to_screen(x0, y), to_screen(x1, y)));
}
+ if let Some(live) = self.pixel_live.as_ref() {
+ let fill = match live.erase {
+ true => Color32::from_rgba_unmultiplied(255, 255, 255, 120),
+ false => color::color32(self.color),
+ };
+ self.pixel_cells(live).iter().for_each(|c| {
+ let (x, y) = (c[0] as f32, c[1] as f32);
+ let corners = [(x, y), (x + 1.0, y), (x + 1.0, y + 1.0), (x, y + 1.0)]
+ .map(|(x, y)| self.screen(view, rect, vec2(x, y)))
+ .to_vec();
+ painter.add(egui::Shape::convex_polygon(corners, fill, egui::Stroke::NONE));
+ });
+ }
+ let pencil = self.tool == Tool::Brush && self.scene.on_grid();
if let Some([x, y]) = self.hover_cell.filter(|_| self.scene.on_grid() && self.zoom_px >= 3.0) {
- let (x, y) = (x as f32, y as f32);
- let cell = [(x, y), (x + 1.0, y), (x + 1.0, y + 1.0), (x, y + 1.0)]
+ let side = if pencil { self.pixel_size.max(1) as f32 } else { 1.0 };
+ let low = ((side - 1.0) / 2.0).floor();
+ let (x, y) = (x as f32 - low, y as f32 - low);
+ let cell = [(x, y), (x + side, y), (x + side, y + side), (x, y + side)]
.map(|(x, y)| self.screen(view, rect, vec2(x, y)))
.to_vec();
painter.add(egui::Shape::closed_line(
diff --git a/crates/app/src/editor/commands.rs b/crates/app/src/editor/commands.rs
index 809af94..017f9ab 100644
--- a/crates/app/src/editor/commands.rs
+++ b/crates/app/src/editor/commands.rs
@@ -593,6 +593,10 @@ impl Editor {
}
Cmd::Parallax => {}
Cmd::Note => self.tool = Tool::Note,
+ Cmd::Smaller if self.scene.on_grid() => self.pixel_size = self.pixel_size.saturating_sub(1).max(1),
+ Cmd::Bigger if self.scene.on_grid() => {
+ self.pixel_size = (self.pixel_size + 1).min(klad_core::pixel::MAX_SIZE)
+ }
Cmd::Smaller => self.size = (self.size / 1.25).max(0.5),
Cmd::Bigger => self.size = (self.size * 1.25).min(800.0),
Cmd::Fit => {
diff --git a/crates/app/src/editor/options.rs b/crates/app/src/editor/options.rs
index 637b1e4..e99a257 100644
--- a/crates/app/src/editor/options.rs
+++ b/crates/app/src/editor/options.rs
@@ -308,9 +308,33 @@ impl Editor {
Tool::Note => (Cmd::Note, "note"),
Tool::Bone => (Cmd::BoneTool, "bones"),
};
+ let name = match (self.tool, self.scene.on_grid()) {
+ (Tool::Brush, true) if cmd == Cmd::Brush => "pixel pencil",
+ (Tool::Brush, true) => "pixel eraser",
+ _ => name,
+ };
ui.label(RichText::new(format!("{} {name}", cmd.spec().icon)).strong());
ui.separator();
match self.tool {
+ Tool::Brush if self.scene.on_grid() => {
+ let label = ui.label("size");
+ ui.add(
+ egui::DragValue::new(&mut self.pixel_size)
+ .range(1..=klad_core::pixel::MAX_SIZE)
+ .suffix(" px"),
+ )
+ .labelled_by(label.id)
+ .hint("the pencil is a square of this many pixels a side; [ and ] change it");
+ ui.checkbox(&mut self.pixel_perfect, "pixel perfect")
+ .hint("a one-pixel line drops the corner pixels a hand leaves, so curves stay one pixel thin");
+ ui.label(
+ RichText::new("draws whole pixels in the palette colour; shift click: a straight line from the last pixel")
+ .color(theme::WEAK),
+ );
+ if !self.scene.can_paint() {
+ ui.colored_label(theme::REFUSED, "this layer is locked: unlock it to draw on it");
+ }
+ }
Tool::Brush => {
self.brush_main(ui);
ui.menu_button(format!("{} more", icon::MORE), |ui| {
@@ -339,11 +363,6 @@ impl Editor {
theme::REFUSED,
"this is a vector layer: P draws paths on it; brushes paint on paint layers",
);
- } else if self.scene.on_grid() {
- ui.colored_label(
- theme::REFUSED,
- "this is a pixel layer: it takes whole pixels, not brush strokes",
- );
} else if !self.scene.can_paint() {
ui.colored_label(theme::REFUSED, "pick a paint layer to draw on");
}
diff --git a/crates/app/src/editor/ui_tests.rs b/crates/app/src/editor/ui_tests.rs
index 7cb3f19..8afb903 100644
--- a/crates/app/src/editor/ui_tests.rs
+++ b/crates/app/src/editor/ui_tests.rs
@@ -1469,17 +1469,34 @@ fn a_pixel_layer_is_added_shows_its_marks_hard_and_keeps_brush_strokes_out() {
h.query_by_label("pixel layer").is_some(),
"layer settings say what kind of layer it is"
);
- h.state_mut().tool = Tool::Brush;
+ h.state_mut().tool = Tool::Fill;
let rect = h.state().canvas_rect;
let (a, b) = (rect.center() + vec2(-60.0, -20.0), rect.center() + vec2(40.0, 30.0));
drag(&mut h, a, b);
h.run_steps(2);
assert!(
h.state().scene.active_marks().is_empty(),
- "no brush stroke lands on a pixel layer"
+ "no fill lands on a pixel layer"
);
let refused = h.state().messages.latest().map(|m| m.text.clone()).unwrap_or_default();
assert!(refused.contains("pixel layer"), "{refused}");
+ h.state_mut().tool = Tool::Brush;
+ drag(&mut h, a, b);
+ h.run_steps(3);
+ ready(&mut h);
+ assert!(
+ !h.state().scene.active_marks().is_empty()
+ && h.state()
+ .scene
+ .active_marks()
+ .iter()
+ .all(|m| m.as_fill().is_some_and(|f| f.on_grid())),
+ "the brush tool draws whole pixels there, never a brush stroke"
+ );
+ h.state_mut().invoke(Cmd::Undo).unwrap();
+ h.run_steps(3);
+ ready(&mut h);
+ assert!(h.state().scene.active_marks().is_empty());
h.state_mut()
.apply(
parse_lines(&format!(
@@ -1508,7 +1525,10 @@ fn a_pixel_layer_is_added_shows_its_marks_hard_and_keeps_brush_strokes_out() {
});
assert_eq!(at(11, 11), [0.0; 4], "no soft edge beside the pixels");
assert_eq!(at(9, 10), [0.0; 4]);
- assert_eq!(ed.scene.bundle.doc.palette.len(), 1, "its colour joined the palette");
+ assert!(
+ ed.scene.bundle.doc.swatch("#3a86ff").is_some(),
+ "its colour joined the palette"
+ );
assert!(ed.scene.active_marks()[0].as_fill().is_some_and(|f| f.on_grid()));
let _ = std::fs::remove_dir_all(&path);
}
@@ -1721,6 +1741,100 @@ fn a_clicked_palette_colour_is_updated_with_its_pixels_and_ramps_and_palettes_jo
let _ = std::fs::remove_dir_all(&path);
}
+#[test]
+fn the_brush_tool_is_a_pixel_pencil_and_eraser_on_a_pixel_layer() {
+ let path = pixel_sample("pencil");
+ let mut h = harness(editor(&path), vec2(1440.0, 900.0));
+ h.state_mut().tool = Tool::Brush;
+ h.state_mut()
+ .set_colour(klad_core::color::parse_hex("#2a9d8f").unwrap());
+ h.run_steps(2);
+ assert!(
+ h.query_by_label_contains("pixel pencil").is_some(),
+ "the options bar names the pencil"
+ );
+ let cells_of = |h: &Harness<'static, Editor>, at: usize| -> Vec<[u32; 2]> {
+ h.state().scene.active_marks()[at]
+ .as_fill()
+ .unwrap()
+ .coverage
+ .cells()
+ .collect()
+ };
+ let before = h.state().scene.active_marks().len();
+ let (a, b) = (on_screen(&h, 10.5, 10.5), on_screen(&h, 16.5, 13.5));
+ h.hover_at(a);
+ h.run_steps(1);
+ h.drag_at(a);
+ h.run_steps(1);
+ (1..=12).for_each(|i| {
+ h.hover_at(a + (b - a) * (i as f32 / 12.0));
+ h.run_steps(1);
+ });
+ assert!(h.state().pixel_live.is_some(), "the line shows while it is drawn");
+ h.drop_at(b);
+ h.run_steps(3);
+ ready(&mut h);
+ let marks = h.state().scene.active_marks().to_vec();
+ assert_eq!(marks.len(), before + 1, "one drag is one mark");
+ let line = marks[before].as_fill().unwrap();
+ assert!(line.on_grid() && line.author == klad_core::stroke::Author::Human);
+ assert_eq!(klad_core::color::to_hex(line.color()), "#2a9d8f");
+ let teal = h
+ .state()
+ .scene
+ .bundle
+ .doc
+ .swatch("#2a9d8f")
+ .expect("the colour joined the palette");
+ assert_eq!(line.entry(), Some(h.state().scene.bundle.doc.palette[teal].id.as_str()));
+ let cells = cells_of(&h, before);
+ assert_eq!(cells.len(), 7, "one pixel per column from 10 to 16: {cells:?}");
+ assert!(cells.contains(&[10, 10]) && cells.contains(&[16, 13]));
+ let raster = h.state().scene.active_raster().unwrap();
+ assert!(raster.alpha_at(12.5, 11.5) + raster.alpha_at(12.5, 10.5) + raster.alpha_at(12.5, 12.5) >= 1.0);
+ let far = on_screen(&h, 16.5, 20.5);
+ click_with(&mut h, far, Modifiers::SHIFT);
+ h.run_steps(3);
+ assert_eq!(
+ cells_of(&h, before + 1),
+ (13..=20).map(|y| [16, y]).collect::<Vec<_>>(),
+ "shift click draws a straight line from the last pixel"
+ );
+ h.key_press(Key::CloseBracket);
+ h.key_press(Key::CloseBracket);
+ h.run_steps(2);
+ assert_eq!(h.state().pixel_size, 3, "] makes the pencil a pixel larger");
+ let dot = on_screen(&h, 25.5, 5.5);
+ click_with(&mut h, dot, Modifiers::NONE);
+ h.run_steps(3);
+ let block = cells_of(&h, before + 2);
+ assert_eq!(block.len(), 9);
+ assert!(block.contains(&[24, 4]) && block.contains(&[26, 6]));
+ h.state_mut().invoke(Cmd::Eraser).unwrap();
+ h.run_steps(2);
+ assert!(h.query_by_label_contains("pixel eraser").is_some());
+ h.state_mut().pixel_size = 1;
+ click_with(&mut h, dot, Modifiers::NONE);
+ h.run_steps(3);
+ ready(&mut h);
+ let marks = h.state().scene.active_marks().to_vec();
+ assert!(marks[before + 3].as_fill().unwrap().erases());
+ let raster = h.state().scene.active_raster().unwrap();
+ assert_eq!(raster.alpha_at(25.5, 5.5), 0.0, "the erased pixel is clear");
+ assert_eq!(raster.alpha_at(24.5, 5.5), 1.0, "its neighbour is still there");
+ let palette = h.state().scene.bundle.doc.palette.len();
+ h.state_mut().invoke(Cmd::Undo).unwrap();
+ h.run_steps(3);
+ assert_eq!(
+ h.state().scene.active_marks().len(),
+ before + 3,
+ "undo takes the eraser mark back"
+ );
+ assert_eq!(h.state().scene.bundle.doc.palette.len(), palette);
+ let _ = std::fs::remove_dir_all(&path);
+}
+
#[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 6b84658..f8c8736 100644
--- a/crates/cli/src/main.rs
+++ b/crates/cli/src/main.rs
@@ -869,16 +869,29 @@ enum Command {
},
#[command(
about = "Put whole pixels of one palette colour on a pixel layer, or erase them",
- long_about = "Put whole pixels of one palette colour on a pixel layer, or erase them. A pixel layer is a grid with no anti-aliasing where one pixel is one canvas pixel; make a pixel drawing with klad new --pixel 64x64, or add a layer with klad add <bundle> layer pixel.\n\n--cells lists them: x,y for one pixel, x0-x1,y for a run along a row, x,y0-y1 for a run down a column and x0-x1,y0-y1 for a block. --color is a palette name, a palette index or #rrggbb; a colour the palette does not have yet is added to it. The pixels become one mark bound to that palette entry, so it can be recoloured (klad set <cel>:s<id> color=...), moved (klad transform) or removed (klad rm) later, and klad strokes lists it. --erase clears the pixels under it instead.\n\n klad pixel sprite.klad l1 --color '#2b2d42' --cells '3-12,4 3,5-9 12,5-9 3-12,10'\n klad pixel sprite.klad l1 --color skin --cells '4-11,5-9'\n klad pixel sprite.klad l1 --erase --cells '7,7 8,7'\n\nAlso a pixel op in klad apply: {\"op\":\"pixel\",\"layer\":\"l1\",\"color\":\"skin\",\"cells\":[[4,5],[5,5]]} or with \"erase\":true."
+ long_about = "Put whole pixels of one palette colour on a pixel layer, or erase them. A pixel layer is a grid with no anti-aliasing where one pixel is one canvas pixel; make a pixel drawing with klad new --pixel 64x64, or add a layer with klad add <bundle> layer pixel.\n\n--cells lists them: x,y for one pixel, x0-x1,y for a run along a row, x,y0-y1 for a run down a column and x0-x1,y0-y1 for a block. --color is a palette name, a palette index or #rrggbb; a colour the palette does not have yet is added to it. The pixels become one mark bound to that palette entry, so it can be recoloured (klad set <cel>:s<id> color=...), moved (klad transform) or removed (klad rm) later, and klad strokes lists it. --erase clears the pixels under it instead.\n\n--path draws SVG path data as a line of pixels: a pixel is the square from x,y to x+1,y+1, so aim at pixel middles (3.5, not 3). Straight segments keep the corners they are given; curves are cleaned so no corner is doubled. --size makes the pencil a square of that many pixels, for --cells and --path alike.\n\n klad pixel sprite.klad l1 --color '#2b2d42' --cells '3-12,4 3,5-9 12,5-9 3-12,10'\n klad pixel sprite.klad l1 --color '#2b2d42' --path 'M3.5 20.5 C 10 4 22 4 28.5 20.5'\n klad pixel sprite.klad l1 --erase --size 3 --path 'M4.5 4.5 L12.5 12.5'\n klad pixel sprite.klad l1 --color skin --cells '4-11,5-9'\n klad pixel sprite.klad l1 --erase --cells '7,7 8,7'\n\nAlso a pixel op in klad apply: {\"op\":\"pixel\",\"layer\":\"l1\",\"color\":\"skin\",\"cells\":[[4,5],[5,5]]}, with \"path\":\"M3.5 3.5 L9.5 3.5\" in place of cells, \"size\":2, or \"erase\":true."
)]
Pixel {
bundle: PathBuf,
layer: String,
#[arg(
long,
+ required_unless_present = "path",
help = "The pixels: x,y, a row run x0-x1,y, a column run x,y0-y1 or a block x0-x1,y0-y1, separated by spaces"
)]
- cells: String,
+ cells: Option<String>,
+ #[arg(
+ long,
+ conflicts_with = "cells",
+ help = "SVG path data drawn as a line of pixels, one pixel wide with no doubled corners on curves: 'M3.5 20.5 C 10 4 22 4 28.5 20.5'"
+ )]
+ path: Option<String>,
+ #[arg(
+ long,
+ default_value_t = 1,
+ help = "The pencil's size: a square of this many pixels a side (1 to 64)"
+ )]
+ size: u32,
#[arg(long, conflicts_with = "erase", help = "A palette name, a palette index or #rrggbb")]
color: Option<String>,
#[arg(long, help = "Clear these pixels instead of colouring them")]
@@ -2817,19 +2830,25 @@ fn run() -> Result<()> {
bundle,
layer,
cells,
+ path,
+ size,
color,
erase,
frame,
part,
flags,
} => {
+ let layer = Bundle::open(&bundle)?.doc.find_layer(&layer)?.id.clone();
let spec = PixelSpec {
layer,
frame,
color,
erase,
- cells: parse_cells(&cells)?,
+ cells: cells.as_deref().map(parse_cells).transpose()?.unwrap_or_default(),
+ path,
+ size,
part,
+ by_hand: false,
};
agent::edit(&bundle, &[Op::Pixel(spec)], &output(&flags, frame))?;
}
diff --git a/crates/cli/tests/binary.rs b/crates/cli/tests/binary.rs
index 3b470a4..aeb9acc 100644
--- a/crates/cli/tests/binary.rs
+++ b/crates/cli/tests/binary.rs
@@ -575,6 +575,57 @@ fn a_pixel_drawing_is_made_drawn_listed_and_edited_from_the_command_line() {
assert!(String::from_utf8_lossy(&refused.stderr).contains("pixel layer"));
let bad = run(&["pixel", path, &layer, "--color", "skin", "--cells", "3;4"]);
assert!(String::from_utf8_lossy(&bad.stderr).contains("is not x,y"));
+ let added = draw(&["add", path, "layer", "pixel", "name=lines"]);
+ let lines_id = added
+ .lines()
+ .find_map(|line| line.strip_prefix("added "))
+ .unwrap_or_else(|| panic!("an id in: {added}"))
+ .to_string();
+ draw(&[
+ "pixel",
+ path,
+ "lines",
+ "--color",
+ "skin",
+ "--path",
+ "M0.5 11.5 C 4 2 11 2 15.5 11.5",
+ ]);
+ draw(&[
+ "pixel",
+ path,
+ &lines_id,
+ "--color",
+ "skin",
+ "--path",
+ "M1.5 1.5 L5.5 1.5 L5.5 4.5",
+ ]);
+ draw(&["pixel", path, &lines_id, "--erase", "--size", "3", "--cells", "5,1"]);
+ let lines = json(&["strokes", path, &lines_id, "--json"]);
+ let cells = |at: usize| -> Vec<(i64, i64)> {
+ lines["fills"][at]["cells"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|c| (c[0].as_i64().unwrap(), c[1].as_i64().unwrap()))
+ .collect()
+ };
+ let curve = cells(0);
+ assert!(curve.contains(&(0, 11)) && curve.contains(&(15, 11)), "{curve:?}");
+ let doubled = curve.iter().any(|&(x, y)| {
+ let has = |dx: i64, dy: i64| curve.contains(&(x + dx, y + dy));
+ (has(1, 0) || has(-1, 0))
+ && (has(0, 1) || has(0, -1))
+ && !(has(1, 0) && has(-1, 0))
+ && !(has(0, 1) && has(0, -1))
+ });
+ assert!(!doubled, "a curve is one pixel thin with no corner doubled: {curve:?}");
+ assert_eq!(cells(1).len(), 8, "a path's own corner is kept");
+ assert_eq!(cells(2).len(), 9, "a size is a square of whole pixels");
+ draw(&["rm", path, &lines_id]);
+ let wide = run(&[
+ "pixel", path, &layer, "--color", "skin", "--cells", "1,1", "--size", "99",
+ ]);
+ assert!(String::from_utf8_lossy(&wide.stderr).contains("from 1 to 64"));
let shown = run(&["render", path]);
assert!(
String::from_utf8_lossy(&shown.stderr).contains("512x384"),
diff --git a/crates/core/src/bundle.rs b/crates/core/src/bundle.rs
index 695d53f..c281b08 100644
--- a/crates/core/src/bundle.rs
+++ b/crates/core/src/bundle.rs
@@ -655,8 +655,8 @@ pub fn summarize(ops: &[Op]) -> String {
like: Some(cel), layer, ..
}) => format!("fills on {layer} like {cel}"),
Op::Fill(spec) => format!("fill on {}", spec.layer),
- Op::Pixel(spec) if spec.erase => format!("erase {} pixels on {}", spec.cells.len(), spec.layer),
- Op::Pixel(spec) => format!("{} pixels on {}", spec.cells.len(), spec.layer),
+ Op::Pixel(spec) if spec.erase => format!("erase pixels on {}", spec.layer),
+ Op::Pixel(spec) => format!("pixels on {}", spec.layer),
Op::Palette(_) => "palette".to_string(),
Op::Transform { ids, .. } => format!("transform {}", ids.join(" ")),
Op::Detach { ids } => format!("detach {}", ids.join(" ")),
diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs
index 1681c5c..4fdbf54 100644
--- a/crates/core/src/lib.rs
+++ b/crates/core/src/lib.rs
@@ -19,6 +19,7 @@ pub mod palettes;
pub mod patch;
pub mod path;
pub mod pathedit;
+pub mod pixel;
pub mod repair;
pub mod retime;
pub mod rig;
diff --git a/crates/core/src/ops.rs b/crates/core/src/ops.rs
index f990279..075047e 100644
--- a/crates/core/src/ops.rs
+++ b/crates/core/src/ops.rs
@@ -288,9 +288,20 @@ pub struct PixelSpec {
pub color: Option<String>,
#[serde(default)]
pub erase: bool,
+ #[serde(default)]
pub cells: Vec<[i64; 2]>,
#[serde(default)]
+ pub path: Option<String>,
+ #[serde(default = "one_pixel")]
+ pub size: u32,
+ #[serde(default)]
pub part: Option<String>,
+ #[serde(skip)]
+ pub by_hand: bool,
+}
+
+fn one_pixel() -> u32 {
+ 1
}
impl PixelSpec {
@@ -300,22 +311,40 @@ impl PixelSpec {
(None, false) => bail!("pixel needs a color (a palette name or #rrggbb) or \"erase\":true"),
_ => {}
}
- if self.cells.is_empty() {
- bail!("pixel needs cells: a list of [x, y] in canvas pixels");
+ match (self.cells.is_empty(), &self.path) {
+ (true, None) => bail!(
+ "pixel needs cells (a list of [x, y] in canvas pixels) or a path (SVG path data, drawn as a line of pixels)"
+ ),
+ (false, Some(_)) => bail!("pixel takes cells or a path, not both"),
+ _ => {}
+ }
+ if !(1..=crate::pixel::MAX_SIZE).contains(&self.size) {
+ bail!(
+ "a pixel size is a whole number of pixels from 1 to {}, not {}",
+ crate::pixel::MAX_SIZE,
+ self.size
+ );
}
Ok(())
}
+ pub fn drawn(&self) -> Result<Vec<[i64; 2]>> {
+ match &self.path {
+ Some(d) => Ok(crate::pixel::drawn(&crate::pixel::of_path(d)?, self.size)),
+ None => Ok(crate::pixel::stamp(&self.cells, self.size)),
+ }
+ }
+
pub fn coverage(&self, doc: &Document) -> Result<Coverage> {
let (w, h) = (doc.canvas.width as i64, doc.canvas.height as i64);
- let inside: Vec<[u32; 2]> = self
- .cells
+ let drawn = self.drawn()?;
+ let inside: Vec<[u32; 2]> = drawn
.iter()
.filter(|c| c[0] >= 0 && c[1] >= 0 && c[0] < w && c[1] < h)
.map(|c| [c[0] as u32, c[1] as u32])
.collect();
if inside.is_empty() {
- bail!("none of the {} cells is on the {w}x{h} canvas", self.cells.len());
+ bail!("none of the {} cells is on the {w}x{h} canvas", drawn.len());
}
Ok(Coverage::from_cells(&inside))
}
@@ -3765,7 +3794,10 @@ pub fn apply(doc: &mut Document, op: &Op, out: &mut Applied) -> Result<()> {
}
None => Fill::cells(0, [0.0, 0.0, 0.0, 1.0], "", true, coverage),
}
- .by(Author::Agent);
+ .by(match spec.by_hand {
+ true => Author::Human,
+ false => Author::Agent,
+ });
fill.lock = !fill.erases() && locks_alpha(doc, &spec.layer);
let cel = paint_cel_at(doc, &spec.layer, spec.frame, out)?;
out.push(&spec.layer, &cel, MarkChange::Add(vec![Mark::Fill(fill)]));
diff --git a/crates/core/src/pixel.rs b/crates/core/src/pixel.rs
new file mode 100644
index 0000000..1962e3a
--- /dev/null
+++ b/crates/core/src/pixel.rs
@@ -0,0 +1,223 @@
+use crate::path;
+use anyhow::{Result, bail};
+use std::collections::BTreeSet;
+
+pub type Cell = [i64; 2];
+
+pub const MAX_SIZE: u32 = 64;
+
+pub fn line(from: Cell, to: Cell) -> Vec<Cell> {
+ let (dx, dy) = ((to[0] - from[0]).abs(), (to[1] - from[1]).abs());
+ let (sx, sy) = ((to[0] - from[0]).signum(), (to[1] - from[1]).signum());
+ let mut at = from;
+ let mut error = dx - dy;
+ let mut out = Vec::with_capacity((dx.max(dy) + 1) as usize);
+ loop {
+ out.push(at);
+ if at == to {
+ return out;
+ }
+ let twice = 2 * error;
+ if twice > -dy {
+ error -= dy;
+ at[0] += sx;
+ }
+ if twice < dx {
+ error += dx;
+ at[1] += sy;
+ }
+ }
+}
+
+pub fn cell_at(x: f32, y: f32) -> Cell {
+ [x.floor() as i64, y.floor() as i64]
+}
+
+pub fn trace(points: &[(f32, f32)]) -> Vec<Cell> {
+ let cells: Vec<Cell> = points.iter().map(|p| cell_at(p.0, p.1)).collect();
+ let Some(&first) = cells.first() else {
+ return Vec::new();
+ };
+ cells.windows(2).fold(vec![first], |mut out, pair| {
+ out.extend(line(pair[0], pair[1]).into_iter().skip(1));
+ out
+ })
+}
+
+pub fn extend(run: &mut Vec<Cell>, to: Cell) {
+ match run.last().copied() {
+ None => run.push(to),
+ Some(last) if last == to => {}
+ Some(last) => run.extend(line(last, to).into_iter().skip(1)),
+ }
+}
+
+pub fn perfect(run: &[Cell]) -> Vec<Cell> {
+ perfect_keeping(run, &BTreeSet::new())
+}
+
+pub fn perfect_keeping(run: &[Cell], keep: &BTreeSet<usize>) -> Vec<Cell> {
+ let mut out: Vec<Cell> = Vec::with_capacity(run.len());
+ let mut i = 0;
+ while i < run.len() {
+ let corner = i > 0 && i + 1 < run.len() && !keep.contains(&i) && {
+ let (before, at, after) = (out[out.len() - 1], run[i], run[i + 1]);
+ let touches = |a: Cell, b: Cell| (a[0] == b[0]) != (a[1] == b[1]);
+ touches(before, at) && touches(after, at) && before[0] != after[0] && before[1] != after[1]
+ };
+ if !corner {
+ out.push(run[i]);
+ }
+ i += 1;
+ }
+ out
+}
+
+fn turns(points: &[(f32, f32)], at: usize) -> bool {
+ if at == 0 || at + 1 >= points.len() {
+ return false;
+ }
+ let (a, b, c) = (points[at - 1], points[at], points[at + 1]);
+ let (ux, uy, vx, vy) = (b.0 - a.0, b.1 - a.1, c.0 - b.0, c.1 - b.1);
+ let (lu, lv) = (libm::sqrtf(ux * ux + uy * uy), libm::sqrtf(vx * vx + vy * vy));
+ lu > 1e-6 && lv > 1e-6 && (ux * vx + uy * vy) / (lu * lv) < 0.8
+}
+
+pub struct Run {
+ pub cells: Vec<Cell>,
+ pub corners: BTreeSet<usize>,
+}
+
+pub fn run_of(points: &[(f32, f32)]) -> Run {
+ let cells: Vec<Cell> = points.iter().map(|p| cell_at(p.0, p.1)).collect();
+ let Some(&first) = cells.first() else {
+ return Run {
+ cells: Vec::new(),
+ corners: BTreeSet::new(),
+ };
+ };
+ let mut corners = BTreeSet::new();
+ let traced = cells.windows(2).enumerate().fold(vec![first], |mut out, (i, pair)| {
+ out.extend(line(pair[0], pair[1]).into_iter().skip(1));
+ if turns(points, i + 1) {
+ corners.insert(out.len() - 1);
+ }
+ out
+ });
+ Run { cells: traced, corners }
+}
+
+pub fn stamp(run: &[Cell], size: u32) -> Vec<Cell> {
+ let size = size.clamp(1, MAX_SIZE) as i64;
+ let low = (size - 1) / 2;
+ let mut seen = BTreeSet::new();
+ run.iter()
+ .flat_map(|c| (0..size).flat_map(move |j| (0..size).map(move |i| [c[0] - low + i, c[1] - low + j])))
+ .filter(|c| seen.insert(*c))
+ .collect()
+}
+
+pub fn of_path(d: &str) -> Result<Vec<Run>> {
+ let lines = path::flatten(d)?;
+ let runs: Vec<Run> = lines
+ .iter()
+ .map(|line| run_of(&line.iter().map(|p| (p[0], p[1])).collect::<Vec<_>>()))
+ .filter(|run| !run.cells.is_empty())
+ .collect();
+ if runs.is_empty() {
+ bail!("the path has no points");
+ }
+ Ok(runs)
+}
+
+pub fn drawn(runs: &[Run], size: u32) -> Vec<Cell> {
+ let mut seen = BTreeSet::new();
+ runs.iter()
+ .map(|run| match size > 1 {
+ true => run.cells.clone(),
+ false => perfect_keeping(&run.cells, &run.corners),
+ })
+ .flat_map(|run| stamp(&run, size))
+ .filter(|c| seen.insert(*c))
+ .collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn lines_step_one_pixel_at_a_time_and_end_where_they_are_told() {
+ assert_eq!(line([0, 0], [3, 0]), [[0, 0], [1, 0], [2, 0], [3, 0]]);
+ assert_eq!(line([2, 2], [2, 2]), [[2, 2]]);
+ assert_eq!(line([0, 0], [3, 3]), [[0, 0], [1, 1], [2, 2], [3, 3]]);
+ let shallow = line([0, 0], [6, 2]);
+ assert_eq!(shallow.len(), 7, "one pixel per column: {shallow:?}");
+ assert_eq!((shallow[0], shallow[6]), ([0, 0], [6, 2]));
+ assert!(
+ shallow
+ .windows(2)
+ .all(|w| (w[1][0] - w[0][0]).abs() <= 1 && (w[1][1] - w[0][1]).abs() <= 1)
+ );
+ let back = line([6, 2], [0, 0]);
+ assert_eq!(back.len(), 7);
+ assert_eq!(back[6], [0, 0]);
+ }
+
+ #[test]
+ fn a_traced_hand_drops_the_corner_pixels_that_double_a_line() {
+ let run = trace(&[(0.5, 0.5), (1.5, 0.6), (1.4, 1.5), (2.5, 1.5), (2.5, 2.5)]);
+ assert_eq!(
+ run,
+ [[0, 0], [1, 0], [1, 1], [2, 1], [2, 2]],
+ "every step a pixel, corners and all"
+ );
+ assert_eq!(
+ perfect(&run),
+ [[0, 0], [1, 1], [2, 2]],
+ "the L corners go, the diagonal stays"
+ );
+ let straight = [[0, 0], [1, 0], [2, 0], [2, 1], [2, 2]];
+ assert_eq!(
+ perfect(&straight),
+ [[0, 0], [1, 0], [2, 1], [2, 2]],
+ "one corner of a real turn goes"
+ );
+ assert_eq!(perfect(&[[4, 4]]), [[4, 4]]);
+ assert_eq!(perfect(&[]), Vec::<Cell>::new());
+ let mut live = Vec::new();
+ [[0, 0], [0, 0], [3, 1]].iter().for_each(|c| extend(&mut live, *c));
+ assert_eq!(live, [[0, 0], [1, 0], [2, 1], [3, 1]], "a fast pen leaves no holes");
+ }
+
+ #[test]
+ fn a_size_is_a_square_of_whole_pixels_and_paths_become_pixels() {
+ assert_eq!(stamp(&[[5, 5]], 1), [[5, 5]]);
+ assert_eq!(stamp(&[[5, 5]], 2), [[5, 5], [6, 5], [5, 6], [6, 6]]);
+ let three = stamp(&[[5, 5]], 3);
+ assert_eq!(three.len(), 9);
+ assert!(three.contains(&[4, 4]) && three.contains(&[6, 6]));
+ assert_eq!(
+ stamp(&[[0, 0], [1, 0]], 2).len(),
+ 6,
+ "pixels two stamps share are kept once"
+ );
+ let runs = of_path("M1.5 1.5 L5.5 1.5 M0.5 3.5 L0.5 5.5").unwrap();
+ assert_eq!(runs.len(), 2);
+ assert_eq!(runs[0].cells, [[1, 1], [2, 1], [3, 1], [4, 1], [5, 1]]);
+ assert_eq!(drawn(&runs, 1).len(), 8);
+ let corner = of_path("M0.5 0.5 L3.5 0.5 L3.5 3.5").unwrap();
+ assert_eq!(drawn(&corner, 1).len(), 7, "the corner a path asks for is kept");
+ let curve = of_path("M0.5 8.5 C 3 8.5 8.5 3 8.5 0.5").unwrap();
+ let cells = drawn(&curve, 1);
+ assert_eq!((cells[0], cells[cells.len() - 1]), ([0, 8], [8, 0]));
+ assert!(
+ cells.windows(3).all(|w| {
+ let side = |a: Cell, b: Cell| (a[0] == b[0]) != (a[1] == b[1]);
+ !(side(w[0], w[1]) && side(w[2], w[1]) && w[0][0] != w[2][0] && w[0][1] != w[2][1])
+ }),
+ "a curve has no doubled corners: {cells:?}"
+ );
+ assert!(of_path("").is_err());
+ }
+}
diff --git a/docs/DESIGN.md b/docs/DESIGN.md
index b602aae..24a81b2 100644
--- a/docs/DESIGN.md
+++ b/docs/DESIGN.md
@@ -1,4 +1,4 @@
-_Last updated: 2026-11-11 17:20_
+_Last updated: 2026-11-11 18:30_
# 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, shapes, 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. Shapes, 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 0f08dc0..8fee008 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -1650,13 +1650,17 @@ Put whole pixels of one palette colour on a pixel layer, or erase them. A pixel
--cells lists them: x,y for one pixel, x0-x1,y for a run along a row, x,y0-y1 for a run down a column and x0-x1,y0-y1 for a block. --color is a palette name, a palette index or #rrggbb; a colour the palette does not have yet is added to it. The pixels become one mark bound to that palette entry, so it can be recoloured (klad set <cel>:s<id> color=...), moved (klad transform) or removed (klad rm) later, and klad strokes lists it. --erase clears the pixels under it instead.
+--path draws SVG path data as a line of pixels: a pixel is the square from x,y to x+1,y+1, so aim at pixel middles (3.5, not 3). Straight segments keep the corners they are given; curves are cleaned so no corner is doubled. --size makes the pencil a square of that many pixels, for --cells and --path alike.
+
klad pixel sprite.klad l1 --color '#2b2d42' --cells '3-12,4 3,5-9 12,5-9 3-12,10'
+ klad pixel sprite.klad l1 --color '#2b2d42' --path 'M3.5 20.5 C 10 4 22 4 28.5 20.5'
+ klad pixel sprite.klad l1 --erase --size 3 --path 'M4.5 4.5 L12.5 12.5'
klad pixel sprite.klad l1 --color skin --cells '4-11,5-9'
klad pixel sprite.klad l1 --erase --cells '7,7 8,7'
-Also a pixel op in klad apply: {"op":"pixel","layer":"l1","color":"skin","cells":[[4,5],[5,5]]} or with "erase":true.
+Also a pixel op in klad apply: {"op":"pixel","layer":"l1","color":"skin","cells":[[4,5],[5,5]]}, with "path":"M3.5 3.5 L9.5 3.5" in place of cells, "size":2, or "erase":true.
-Usage: klad pixel [OPTIONS] --cells <CELLS> <BUNDLE> <LAYER>
+Usage: klad pixel [OPTIONS] <BUNDLE> <LAYER>
Arguments:
<BUNDLE>
@@ -1669,6 +1673,14 @@ Options:
--cells <CELLS>
The pixels: x,y, a row run x0-x1,y, a column run x,y0-y1 or a block x0-x1,y0-y1, separated by spaces
+ --path <PATH>
+ SVG path data drawn as a line of pixels, one pixel wide with no doubled corners on curves: 'M3.5 20.5 C 10 4 22 4 28.5 20.5'
+
+ --size <SIZE>
+ The pencil's size: a square of this many pixels a side (1 to 64)
+
+ [default: 1]
+
--color <COLOR>
A palette name, a palette index or #rrggbb
diff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.md
index 3fe7333..0beff7c 100644
--- a/docs/skill/SKILL.md
+++ b/docs/skill/SKILL.md
@@ -107,12 +107,14 @@ klad add art.klad layer pixel name=sprite a pixel layer in any dra
klad pixel sprite.klad l1 --color '#2b2d42' --cells '3-12,2 3,3-8 12,3-8 3-12,9'
klad pixel sprite.klad l1 --color skin --cells '4-11,3-8'
klad pixel sprite.klad l1 --erase --cells '7,5 8,5'
+klad pixel sprite.klad l1 --color '#2b2d42' --path 'M3.5 20.5 C 10 4 22 4 28.5 20.5' a curve, one pixel thin
klad render sprite.klad --overlay grid enlarged, with numbered pixel lines
klad export sprite.klad --scale 8 -o [email protected] square pixels, to keep
```
- A pixel layer is a grid with no soft edges, and one pixel is one canvas pixel: a 32x32 sprite is a 32x32 drawing. Size the drawing in pixels of the art, not of the screen; `klad ls` shows the layer as `pixel`.
- `--cells` takes `x,y` for one pixel, `x0-x1,y` for a run along a row, `x,y0-y1` for a run down a column and `x0-x1,y0-y1` for a block, separated by spaces. Pixels off the canvas are dropped.
+- `--path` draws SVG path data as a line of pixels, for outlines and curves that would be tedious as cells. A pixel is the square from `x,y` to `x+1,y+1`, so aim at pixel middles (`3.5`, not `3`). Straight segments keep the corners they are given; curves come out one pixel thin with no doubled corners. `--size 2` (1 to 64) makes the pencil a square of that many pixels, for `--cells` and `--path` alike. In `apply`: `"path":"M3.5 3.5 L9.5 3.5"` in place of `cells`, and `"size":2`.
- `--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, sweetie-16, dawnbringer-16, dawnbringer-32, endesga-32, resurrect-64, aap-64, gameboy, 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.
- Each call makes one mark, `<cel>:s<id>`, that 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`.