Skip to content

armgit / klad

Public Imported from GitHub
0

A drawing app built for agent/human collaboration

Rust

Pictures to pixels: a picture onto the palette, and a pixel drawing of a painted layer

Indicode BVcebfa961cbfb
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 337ee83..c0ae3f1 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.
+- Pictures to pixels. **File > Pixels of a picture…** turns a PNG or JPEG into pixels on the pixel layer you are on, in the palette's colours, or makes a pixel drawing of the layer you are on or of the whole picture at a size you choose. From the command line: `klad pixelize sprite.klad --image ref.png --to l1`, `klad pixelize hero.klad --size 64`, and `klad import ref.png` for a new pixel drawing from a picture. Each pixel becomes part of a mark bound to a palette colour, so the result is edited like any pixel drawing.
- Aseprite files in and out. `klad import hero.aseprite` opens an Aseprite file as a klad drawing: its layers and groups, every frame's drawing, linked cels, the palette and its tags as clips. In the editor, **Choose an Aseprite file...** in the start window (or its path pasted there) does the same and opens the drawing it made. `klad export hero.klad --aseprite`, or **Aseprite** in the export window, writes a drawing's pixel layers back to an Aseprite file. klad says what it leaves out each way.
- Palette variants. A drawing can hold other colours for the same sprite, like a blue team beside a red one. In the Colour panel **new variant** makes one and shows it; colours you change while it is shown are its own, and the palette itself keeps its colours. Pick **base** or a variant under the palette to show it. The export window exports what is shown, one variant, or **every variant** in one go. From the command line: `klad palette --new-variant blue`, `--variant base`, `--rename-variant`, `--rm-variant`, and `klad export --variant blue` or `--variants`.
- Exports that stay sharp, and GIFs. A pixel drawing exports at whole-number sizes only, up to 64 times (`klad export sprite.klad --scale 8`), enlarged pixel for pixel; the export window shows **times real size** and the size in pixels. Sheets, numbered frames and Godot exports follow the same rule, and the Godot scenes of a pixel drawing turn texture filtering off. New for every drawing: `klad export art.klad --gif` and **GIF** in the export window write an animated GIF for each clip, or one of the whole timeline, with each frame's own duration. A GIF holds 255 colours: `--dither` (the **dither** box) mixes them in a fine pattern so the soft gradients of a painting do not band.
diff --git a/crates/app/src/commands.rs b/crates/app/src/commands.rs
index 22a7951..75d9ee4 100644
--- a/crates/app/src/commands.rs
+++ b/crates/app/src/commands.rs
@@ -18,6 +18,7 @@ pub enum Cmd {
MakeMirror,
Unwrap,
ImportPicture,
+ Pixelize,
Shapes,
Strokes,
Points,
@@ -521,7 +522,7 @@ use Repeat as R;
use Trigger as T;
impl Cmd {
- pub const ALL: [Cmd; 194] = [
+ pub const ALL: [Cmd; 195] = [
Cmd::Brush,
Cmd::Eraser,
Cmd::Fill,
@@ -536,6 +537,7 @@ impl Cmd {
Cmd::MakeMirror,
Cmd::Unwrap,
Cmd::ImportPicture,
+ Cmd::Pixelize,
Cmd::Shapes,
Cmd::Strokes,
Cmd::Points,
@@ -864,6 +866,15 @@ impl Cmd {
R::No,
"place a PNG or JPEG on a new layer to trace over or paint from (dropping the file works too)",
),
+ Cmd::Pixelize => spec(
+ "layer.pixelize",
+ "pixels of a picture",
+ icon::PIXELS,
+ G::Layers,
+ T::None,
+ R::No,
+ "turn a PNG or JPEG into pixels on the pixel layer you are on, or make a pixel drawing of this layer or of the whole picture, as klad pixelize does",
+ ),
Cmd::Points => spec(
"tool.points",
"edit points",
@@ -2484,6 +2495,7 @@ impl Cmd {
Cmd::MakeMirror => "Mirror",
Cmd::Unwrap => "Take shapes out",
Cmd::ImportPicture => "Import picture…",
+ Cmd::Pixelize => "Pixels of a picture…",
Cmd::Shapes => "Select and move",
Cmd::Strokes => "Select strokes",
Cmd::Points => "Edit points",
@@ -2699,6 +2711,7 @@ pub const MENUS: [Menu; 9] = [
Run(Cmd::CloseDocument),
Line,
Run(Cmd::ImportPicture),
+ Run(Cmd::Pixelize),
Run(Cmd::AddFont),
Line,
Run(Cmd::Export),
diff --git a/crates/app/src/editor.rs b/crates/app/src/editor.rs
index d3fef74..145936d 100644
--- a/crates/app/src/editor.rs
+++ b/crates/app/src/editor.rs
@@ -20,6 +20,7 @@ mod options;
mod paintover;
mod panels;
mod pins;
+mod pixels;
mod prefs;
mod selection;
mod shift;
@@ -606,6 +607,7 @@ struct Windows {
palettes: bool,
about: bool,
export: bool,
+ pixels: bool,
report: bool,
font: bool,
paintover: bool,
@@ -713,6 +715,7 @@ pub(crate) struct Editor {
between: between::Between,
checks: checks::Checks,
export: export::Form,
+ pixels: pixels::Form,
paintover: paintover::Form,
compare: Option<compare::Compared>,
bones: bones::BoneTool,
@@ -914,6 +917,7 @@ impl Editor {
between: between::Between::default(),
checks: checks::Checks::default(),
export: export::Form::default(),
+ pixels: pixels::Form::default(),
paintover: paintover::Form::default(),
compare: None,
bones: bones::BoneTool::default(),
diff --git a/crates/app/src/editor/commands.rs b/crates/app/src/editor/commands.rs
index be1a6e2..9001dc6 100644
--- a/crates/app/src/editor/commands.rs
+++ b/crates/app/src/editor/commands.rs
@@ -493,6 +493,7 @@ impl Editor {
Cmd::About => self.windows.about,
Cmd::ReportProblem => self.windows.report,
Cmd::Export => self.windows.export,
+ Cmd::Pixelize => self.windows.pixels,
Cmd::AddFont => self.windows.font,
Cmd::PaintOver => self.windows.paintover,
Cmd::CompareReference => self.windows.compare,
@@ -603,6 +604,7 @@ impl Editor {
Cmd::MakeMirror => self.wrap("mirror")?,
Cmd::Unwrap => self.unwrap()?,
Cmd::ImportPicture => self.windows.import = !self.windows.import,
+ Cmd::Pixelize => self.windows.pixels = !self.windows.pixels,
Cmd::LoadPalette => self.windows.palettes = !self.windows.palettes,
Cmd::NewVariant => {
let typed = self.swatch_name.trim().to_string();
diff --git a/crates/app/src/editor/panels.rs b/crates/app/src/editor/panels.rs
index 53d88c5..ff8b56a 100644
--- a/crates/app/src/editor/panels.rs
+++ b/crates/app/src/editor/panels.rs
@@ -1020,6 +1020,17 @@ impl Editor {
);
self.windows.export &= open;
}
+ if self.windows.pixels {
+ let mut open = true;
+ Self::window(
+ ctx,
+ "pixels",
+ (format!("{} Pixels of a picture", icon::PIXELS), near_timeline),
+ &mut open,
+ |ui| self.check(|e| e.pixels_window(ui)),
+ );
+ self.windows.pixels &= open;
+ }
if self.windows.paintover {
let mut open = true;
Self::window(
diff --git a/crates/app/src/editor/pixels.rs b/crates/app/src/editor/pixels.rs
new file mode 100644
index 0000000..7d45a9e
--- /dev/null
+++ b/crates/app/src/editor/pixels.rs
@@ -0,0 +1,226 @@
+use super::Editor;
+use crate::jobs::{Spec, Tag};
+use crate::theme::Hint;
+use anyhow::{Result, bail};
+use std::path::PathBuf;
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub(super) enum Source {
+ #[default]
+ File,
+ Layer,
+ Whole,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub(super) struct Form {
+ pub source: Source,
+ pub path: String,
+ pub size: u32,
+ pub colors: u32,
+}
+
+impl Default for Form {
+ fn default() -> Self {
+ Self {
+ source: Source::File,
+ path: String::new(),
+ size: 64,
+ colors: 0,
+ }
+ }
+}
+
+pub(super) fn args(bundle: &str, layer: &str, frame: u32, form: &Form) -> Vec<String> {
+ let mut args = vec!["pixelize".to_string(), bundle.to_string()];
+ let mut push = |flag: &str, value: String| {
+ args.push(flag.to_string());
+ args.push(value);
+ };
+ match form.source {
+ Source::File => {
+ push("--image", form.path.trim().to_string());
+ push("--to", layer.to_string());
+ push("--frame", frame.to_string());
+ if form.size > 0 {
+ push("--size", form.size.to_string());
+ }
+ }
+ Source::Layer => {
+ push("--layer", layer.to_string());
+ push("--size", form.size.max(1).to_string());
+ }
+ Source::Whole => push("--size", form.size.max(1).to_string()),
+ }
+ if form.colors >= 2 {
+ push("--colors", form.colors.to_string());
+ }
+ args
+}
+
+fn made(out: &str, err: &str) -> String {
+ let drawing = out.lines().map(str::trim).rfind(|l| l.ends_with(".klad"));
+ let notes: Vec<&str> = err.lines().filter_map(|l| l.trim().strip_prefix("note: ")).collect();
+ match drawing {
+ Some(path) => format!("made {path}: open it from File > Open"),
+ None => notes.first().map_or(String::new(), |n| n.to_string()),
+ }
+}
+
+impl Editor {
+ pub(super) fn make_pixels(&mut self) -> Result<()> {
+ let form = self.pixels.clone();
+ let layer = self
+ .scene
+ .active_layer()
+ .map(|l| (l.id.clone(), l.name.clone(), l.pixel()));
+ let name = match (form.source, &layer) {
+ (Source::File, _) if form.path.trim().is_empty() => {
+ bail!("type the path of a PNG or JPEG file first")
+ }
+ (Source::File, Some((_, name, true))) => format!("pixels of the picture on {name}"),
+ (Source::File, _) => {
+ bail!("pick a pixel layer first: the picture's pixels go on it (Layer > New pixel layer)")
+ }
+ (Source::Layer, Some((_, name, _))) => format!("a pixel drawing of {name}"),
+ (Source::Layer, None) => bail!("pick the layer to make pixels of first"),
+ (Source::Whole, _) => "a pixel drawing of the picture".to_string(),
+ };
+ let layer_id = layer.map_or(String::new(), |(id, _, _)| id);
+ let args = args(
+ &self.scene.bundle.root.to_string_lossy(),
+ &layer_id,
+ self.scene.frame,
+ &form,
+ );
+ self.start_job(Spec {
+ tag: Tag::Edit,
+ name,
+ exe: PathBuf::new(),
+ args,
+ env: Vec::new(),
+ reruns: 3,
+ summary: made,
+ failure: |_, err| super::tweens::failure(err),
+ });
+ Ok(())
+ }
+
+ pub(super) fn pixels_window(&mut self, ui: &mut egui::Ui) -> Result<()> {
+ let on_pixels = self.scene.active_layer().is_some_and(|l| l.pixel());
+ let form = &mut self.pixels;
+ ui.horizontal(|ui| {
+ ui.selectable_value(&mut form.source, Source::File, "a picture file")
+ .hint("a PNG or JPEG becomes pixels on the pixel layer you are on, in the palette's colours");
+ ui.selectable_value(&mut form.source, Source::Layer, "this layer")
+ .hint("a new pixel drawing of the layer you are on, every frame of it; this drawing is not changed");
+ ui.selectable_value(&mut form.source, Source::Whole, "the whole picture")
+ .hint("a new pixel drawing of everything that shows, every frame of it; this drawing is not changed");
+ });
+ let mut choose = false;
+ if form.source == Source::File {
+ ui.horizontal(|ui| {
+ let label = ui.label("file");
+ ui.add(
+ egui::TextEdit::singleline(&mut form.path)
+ .desired_width(240.0)
+ .hint_text("/path/to/picture.png"),
+ )
+ .labelled_by(label.id)
+ .hint("a PNG or JPEG file");
+ if crate::picker::NATIVE {
+ choose = ui.button("choose...").hint("pick the picture").clicked();
+ }
+ });
+ if !on_pixels {
+ ui.weak("pick a pixel layer first: the pixels go on the layer you are on");
+ }
+ }
+ let least = match form.source {
+ Source::File => 0,
+ _ => 1,
+ };
+ form.size = form.size.clamp(least, 512);
+ ui.add(egui::Slider::new(&mut form.size, least..=512).text("longest side px"))
+ .hint(match form.source {
+ Source::File => "the picture's longest side once it is pixels; 0 keeps its own size (up to 512 px)",
+ _ => "the longest side of the pixel drawing: 64 for a 64 px sprite",
+ });
+ ui.add(egui::Slider::new(&mut form.colors, 0..=64).text("colours"))
+ .hint("0: every pixel takes the nearest colour of the palette (or the picture's own colours when the palette is empty); from 2: that many colours are made from the picture");
+ if form.colors == 1 {
+ form.colors = 2;
+ }
+ let run = ui.button("make pixels").hint("as klad pixelize does").clicked();
+ if choose && let Some(path) = crate::picker::choose_file(None, "Choose") {
+ self.pixels.path = path.display().to_string();
+ }
+ if run {
+ self.make_pixels()?;
+ }
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn the_window_builds_the_cli_call() {
+ let file = Form {
+ path: " /p/ref.png ".into(),
+ size: 0,
+ colors: 0,
+ ..Form::default()
+ };
+ assert_eq!(
+ args("/w/art.klad", "l3", 2, &file).join(" "),
+ "pixelize /w/art.klad --image /p/ref.png --to l3 --frame 2"
+ );
+ let sized = Form {
+ path: "/p/ref.png".into(),
+ size: 48,
+ colors: 12,
+ ..Form::default()
+ };
+ assert_eq!(
+ args("/w/art.klad", "l3", 0, &sized).join(" "),
+ "pixelize /w/art.klad --image /p/ref.png --to l3 --frame 0 --size 48 --colors 12"
+ );
+ let layer = Form {
+ source: Source::Layer,
+ size: 64,
+ colors: 1,
+ ..Form::default()
+ };
+ assert_eq!(
+ args("/w/art.klad", "l3", 5, &layer).join(" "),
+ "pixelize /w/art.klad --layer l3 --size 64"
+ );
+ let whole = Form {
+ source: Source::Whole,
+ size: 32,
+ colors: 8,
+ ..Form::default()
+ };
+ assert_eq!(
+ args("/w/art.klad", "l3", 5, &whole).join(" "),
+ "pixelize /w/art.klad --size 32 --colors 8"
+ );
+ assert_eq!(
+ made(
+ "/w/art-pixel.klad\n",
+ "64x64, 28 frames\nnote: every pixel took the nearest\n"
+ ),
+ "made /w/art-pixel.klad: open it from File > Open"
+ );
+ assert_eq!(
+ made(
+ "rev 9\n",
+ "note: 6x5 pixels in 1 colour on pixel 1\nnote: every pixel\n"
+ ),
+ "6x5 pixels in 1 colour on pixel 1"
+ );
+ }
+}
diff --git a/crates/app/src/editor/ui_tests.rs b/crates/app/src/editor/ui_tests.rs
index ef943a9..8a5aa45 100644
--- a/crates/app/src/editor/ui_tests.rs
+++ b/crates/app/src/editor/ui_tests.rs
@@ -2279,6 +2279,18 @@ fn the_pixel_pencil_mirrors_across_a_line_and_wraps_on_a_tile() {
"a GIF has no 16-bit form"
);
h.state_mut().windows.export = false;
+ h.state_mut().invoke(Cmd::Pixelize).unwrap();
+ h.run_steps(3);
+ assert_eq!(h.state().is_on(Cmd::Pixelize), Some(true));
+ assert!(
+ h.query_by_label("a picture file").is_some() && h.query_by_label("this layer").is_some(),
+ "the window offers a picture file or a layer of this drawing"
+ );
+ h.get_by_label("make pixels").click();
+ h.run_steps(3);
+ let said = h.state().messages.latest().map(|m| m.text.clone()).unwrap_or_default();
+ assert!(said.contains("type the path of a PNG or JPEG file first"), "{said}");
+ h.state_mut().invoke(Cmd::Pixelize).unwrap();
h.run_steps(2);
assert_eq!(h.state().is_on(Cmd::Symmetry), Some(false));
h.state_mut().invoke(Cmd::Symmetry).unwrap();
diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs
index c0f41d0..f404b18 100644
--- a/crates/cli/src/main.rs
+++ b/crates/cli/src/main.rs
@@ -20,6 +20,7 @@ mod looks;
mod marks;
mod paintover;
mod paths;
+mod pixelise;
mod rig;
mod scene;
mod shapes;
@@ -131,11 +132,22 @@ impl Where {
#[derive(Subcommand)]
enum Command {
#[command(
- about = "Open an Aseprite file as a klad drawing",
- long_about = "Make a klad drawing from an Aseprite file (.aseprite or .ase): its layers and groups, the drawing of every frame, its palette and its tags. The drawing is written next to the file (hero.aseprite makes hero.klad) unless -o names it, and its path is printed.\n\n klad import hero.aseprite\n klad import hero.ase -o sprites/hero.klad\n\nWhat comes over: image layers as pixel layers with their name, visibility, opacity and blend mode, groups as groups, every cel as a drawing on its frame (linked cels stay linked), the palette with its names, and tags as clips. Frame times become whole frames: a file of 100 ms frames is 10 frames a second, and a frame shown for 300 ms holds for three. Indexed, grey and RGBA files all open; every pixel is bound to its palette colour, and colours a file uses outside its palette are added to it.\n\nWhat does not: tilemap layers, tilesets and slices are left out, a tag that plays backwards or back and forth becomes a clip that plays forwards, and blend modes klad does not have blend as normal. Each of these is said when it happens.\n\nklad export art.klad --aseprite writes a drawing's pixel layers back to an Aseprite file."
+ about = "Open an Aseprite file or a picture as a klad pixel drawing",
+ long_about = "Make a klad drawing from an Aseprite file (.aseprite or .ase), or a pixel drawing from a picture (.png, .jpg). The drawing is written next to the file (hero.aseprite makes hero.klad) unless -o names it, and its path is printed.\n\n klad import hero.aseprite\n klad import hero.ase -o sprites/hero.klad\n klad import sprite.png (a picture of 512 px or less a side, at its own size)\n klad import [email protected] --size 32 (shrunk to 32 px on its longest side)\n klad import photo.jpg --size 64 --colors 16\n\nA picture becomes one pixel layer: every solid pixel takes a palette colour, and the palette is the picture's own colours when it has 256 or fewer, else 32 made from it, or --colors N. klad pixelize puts a picture on a layer of a drawing you have, in that drawing's palette.\n\nFrom an Aseprite file, what comes over: image layers as pixel layers with their name, visibility, opacity and blend mode, groups as groups, every cel as a drawing on its frame (linked cels stay linked), the palette with its names, and tags as clips. Frame times become whole frames: a file of 100 ms frames is 10 frames a second, and a frame shown for 300 ms holds for three. Indexed, grey and RGBA files all open; every pixel is bound to its palette colour, and colours a file uses outside its palette are added to it.\n\nWhat does not: tilemap layers, tilesets and slices are left out, a tag that plays backwards or back and forth becomes a clip that plays forwards, and blend modes klad does not have blend as normal. Each of these is said when it happens.\n\nklad export art.klad --aseprite writes a drawing's pixel layers back to an Aseprite file."
)]
Import {
file: PathBuf,
+ #[arg(
+ long,
+ help = "A picture: its longest side in pixels once it is pixel art, 1 to 512 (needed when the picture is larger)"
+ )]
+ size: Option<u32>,
+ #[arg(
+ long,
+ alias = "colours",
+ help = "A picture: reduce it to this many colours, 2 to 256 (default: its own colours when it has 256 or fewer, else 32)"
+ )]
+ colors: Option<usize>,
#[arg(
short,
long,
@@ -143,6 +155,53 @@ enum Command {
)]
out: Option<PathBuf>,
},
+ #[command(
+ about = "Make pixels of a picture or of a painted or vector layer",
+ long_about = "Turn a picture into pixel art. Each pixel takes one palette colour and becomes part of a pixel mark, so the result is edited like any pixel drawing: recolour a palette colour, move marks, shade along ramps.\n\nA picture file onto a pixel layer of this drawing:\n\n klad pixelize sprite.klad --image ref.png --to l1 (at its own size, top left)\n klad pixelize sprite.klad --image photo.jpg --to l1 --size 48 --at 8,8\n\nEvery pixel takes the nearest colour of the drawing's palette, so the picture lands in the colours the sprite already has. --colors N makes N colours from the picture instead and adds them to the palette. --size is the picture's longest side in pixels once it is shrunk (each pixel is the average of the area it covers; a picture enlarged by a whole number comes back exact). Pixels less than half solid are left empty.\n\nA painted or vector layer, or the whole picture, as a new pixel drawing:\n\n klad pixelize hero.klad --size 64 (the whole picture, 64 px on its longest side: hero-pixel.klad)\n klad pixelize hero.klad --layer body --size 48 --colors 12 -o body.klad\n\nEvery frame is pixelised with one set of colours, frames that come out the same hold, and clips are kept. Without --colors the drawing's own palette is used when it has one, else 16 colours are made from the picture. The drawing itself is not changed.\n\nklad import ref.png makes a new pixel drawing straight from a picture file."
+ )]
+ Pixelize {
+ bundle: PathBuf,
+ #[arg(
+ long,
+ requires = "to",
+ conflicts_with = "layer",
+ help = "A PNG or JPEG file to put on a pixel layer"
+ )]
+ image: Option<PathBuf>,
+ #[arg(
+ long,
+ requires = "image",
+ help = "With --image: the pixel layer it goes on (an id or a name)"
+ )]
+ to: Option<String>,
+ #[arg(
+ long,
+ requires = "image",
+ allow_hyphen_values = true,
+ help = "With --image: the canvas pixel of its top left corner, x,y"
+ )]
+ at: Option<String>,
+ #[arg(long, default_value_t = 0, help = "With --image: the frame it is drawn on")]
+ frame: u32,
+ #[arg(
+ long,
+ help = "Without --image: the layer or group to pixelise (default: the whole picture)"
+ )]
+ layer: Option<String>,
+ #[arg(long, help = "The longest side in pixels, 1 to 512")]
+ size: Option<u32>,
+ #[arg(long, alias = "colours", help = "Make this many colours from the picture, 2 to 256")]
+ colors: Option<usize>,
+ #[arg(
+ short,
+ long,
+ conflicts_with = "image",
+ help = "Without --image: the pixel drawing to make"
+ )]
+ out: Option<PathBuf>,
+ #[command(flatten)]
+ flags: EditFlags,
+ },
#[command(about = "Create an empty bundle with paint layers")]
New {
bundle: PathBuf,
@@ -2489,14 +2548,67 @@ fn pixel_size(text: &str) -> Result<(u32, u32)> {
fn run() -> Result<()> {
match Cli::parse().command {
- Command::Import { file, out } => {
- if !aseprite::is_file(&file) {
- return Err(anyhow!(
- "klad import opens Aseprite files (.aseprite or .ase): {} is something else. A picture goes on a layer with klad add <bundle> layer image src=<file>",
- file.display()
- ));
+ Command::Import {
+ file,
+ size,
+ colors,
+ out,
+ } => {
+ let made = match (aseprite::is_file(&file), pixelise::is_picture(&file)) {
+ (true, _) if size.is_some() || colors.is_some() => {
+ return Err(anyhow!(
+ "--size and --colors are for pictures: an Aseprite file comes in as it is"
+ ));
+ }
+ (true, _) => aseprite::import(&file, out)?,
+ (_, true) => pixelise::import(&file, &pixelise::Ask { size, colors }, out)?,
+ _ => {
+ return Err(anyhow!(
+ "klad import opens Aseprite files (.aseprite, .ase) and pictures (.png, .jpg) as pixel drawings: {} is something else. A picture to trace or paint over goes on a layer with klad add <bundle> layer image src=<file>",
+ file.display()
+ ));
+ }
+ };
+ println!("{}", made.display());
+ }
+ Command::Pixelize {
+ bundle,
+ image,
+ to,
+ at,
+ frame,
+ layer,
+ size,
+ colors,
+ out,
+ flags,
+ } => {
+ let ask = pixelise::Ask { size, colors };
+ match (image, to) {
+ (Some(file), Some(to)) => {
+ let at = match at.as_deref().map(|text| {
+ text.split(',')
+ .map(|part| part.trim().parse::<i64>())
+ .collect::<std::result::Result<Vec<_>, _>>()
+ }) {
+ None => [0, 0],
+ Some(Ok(v)) if v.len() == 2 => [v[0], v[1]],
+ _ => {
+ return Err(anyhow!(
+ "--at takes x,y: the canvas pixel of the picture's top left corner"
+ ));
+ }
+ };
+ let doc = Bundle::open(&bundle)?.doc;
+ let (ops, notes) = pixelise::placed(&doc, &file, &to, frame, at, &ask)?;
+ agent::edit(&bundle, &ops, &output(&flags, frame))?;
+ notes.iter().for_each(|note| eprintln!("note: {note}"));
+ }
+ _ => println!(
+ "{}",
+ pixelise::pixelize(&bundle, layer.as_deref(), &ask, out)?.display()
+ ),
}
- println!("{}", aseprite::import(&file, out)?.display());
}
Command::New {
bundle,
diff --git a/crates/cli/src/pixelise.rs b/crates/cli/src/pixelise.rs
new file mode 100644
index 0000000..a328f89
--- /dev/null
+++ b/crates/cli/src/pixelise.rs
@@ -0,0 +1,367 @@
+use crate::layers;
+use crate::sprites::{bundle_dir, bundle_stem, file_safe};
+use anyhow::{Context, Result, bail};
+use klad_brush::BrushSet;
+use klad_core::bundle::{Blank, Bundle};
+use klad_core::color::parse_hex;
+use klad_core::doc::{Document, Swatch};
+use klad_core::ops::{ClipEdit, Op, PaletteEdit, PixelSpec};
+use klad_render::export::{Options, Target, detail_of, dither8, render};
+use klad_render::pixelise::{MOST_COLOURS, MOST_SIDE, Picture, colours, counted, decode, fitted, mapped, shrunk};
+use serde_json::json;
+use std::collections::BTreeMap;
+use std::fs;
+use std::path::{Path, PathBuf};
+
+const UNASKED: usize = 32;
+const FROM_PAINT: usize = 16;
+
+#[derive(Clone, Copy, Debug, Default)]
+pub struct Ask {
+ pub size: Option<u32>,
+ pub colors: Option<usize>,
+}
+
+pub fn is_picture(path: &Path) -> bool {
+ path.extension()
+ .and_then(|e| e.to_str())
+ .is_some_and(|e| ["png", "jpg", "jpeg"].iter().any(|known| e.eq_ignore_ascii_case(known)))
+}
+
+fn read(file: &Path) -> Result<Picture> {
+ let bytes = fs::read(file).with_context(|| format!("reading {}", file.display()))?;
+ decode(&bytes).with_context(|| file.display().to_string())
+}
+
+fn sized(picture: &Picture, ask: &Ask) -> Result<Picture> {
+ let longest = picture.width.max(picture.height);
+ let (width, height) = match ask.size {
+ Some(0) => bail!("--size is the longest side in pixels, from 1 to {MOST_SIDE}"),
+ Some(size) if size > MOST_SIDE => {
+ bail!("--size {size} is past {MOST_SIDE}: a pixel drawing that large is a painting")
+ }
+ Some(size) => fitted(picture.width, picture.height, size),
+ None if longest <= MOST_SIDE => (picture.width, picture.height),
+ None => bail!(
+ "the picture is {}x{}: give --size, its longest side in pixels once it is pixel art (at most {MOST_SIDE})",
+ picture.width,
+ picture.height
+ ),
+ };
+ Ok(shrunk(picture, width, height))
+}
+
+fn checked(ask: &Ask) -> Result<()> {
+ match ask.colors {
+ Some(n) if !(2..=MOST_COLOURS).contains(&n) => bail!("--colors takes 2 to {MOST_COLOURS}, not {n}"),
+ _ => Ok(()),
+ }
+}
+
+fn hex(colour: [u8; 3]) -> String {
+ format!("#{:02x}{:02x}{:02x}", colour[0], colour[1], colour[2])
+}
+
+fn own_palette(palette: &[Swatch]) -> Vec<(String, [u8; 3])> {
+ palette
+ .iter()
+ .enumerate()
+ .filter_map(|(index, swatch)| {
+ let c = parse_hex(&swatch.color).ok()?;
+ (c[3] >= 1.0).then(|| {
+ let rgb = [c[0], c[1], c[2]].map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8);
+ (index.to_string(), rgb)
+ })
+ })
+ .collect()
+}
+
+fn chosen(
+ palette: &[Swatch],
+ pictures: &[&Picture],
+ ask: &Ask,
+ unasked: usize,
+ notes: &mut Vec<String>,
+) -> Vec<(String, [u8; 3])> {
+ let made = |count: usize| -> Vec<(String, [u8; 3])> {
+ colours(pictures, count)
+ .into_iter()
+ .map(|colour| (hex(colour), colour))
+ .collect()
+ };
+ let own = own_palette(palette);
+ match (ask.colors, own.len() >= 2) {
+ (Some(count), _) => made(count),
+ (None, true) => {
+ notes.push(format!(
+ "every pixel took the nearest of the palette's {} colours (--colors N makes colours from the picture instead)",
+ own.len()
+ ));
+ own
+ }
+ (None, false) => match counted(pictures).len() <= MOST_COLOURS {
+ true => made(MOST_COLOURS),
+ false => {
+ notes.push(format!(
+ "the picture has more than {MOST_COLOURS} colours: it was reduced to {unasked} (--colors N for another number)"
+ ));
+ made(unasked)
+ }
+ },
+ }
+}
+
+fn marks(
+ layer: &str,
+ frame: u32,
+ at: [i64; 2],
+ picture: &Picture,
+ keys: &[(String, [u8; 3])],
+ canvas: (u32, u32),
+) -> Vec<Op> {
+ let table: Vec<[u8; 3]> = keys.iter().map(|(_, colour)| *colour).collect();
+ let mut by_colour: BTreeMap<usize, Vec<[i64; 2]>> = BTreeMap::new();
+ mapped(picture, &table).into_iter().enumerate().for_each(|(i, index)| {
+ let (x, y) = (
+ at[0] + (i as u32 % picture.width) as i64,
+ at[1] + (i as u32 / picture.width) as i64,
+ );
+ if let Some(index) = index
+ && x >= 0
+ && y >= 0
+ && x < canvas.0 as i64
+ && y < canvas.1 as i64
+ {
+ by_colour.entry(index).or_default().push([x, y]);
+ }
+ });
+ by_colour
+ .into_iter()
+ .map(|(index, cells)| {
+ Op::Pixel(PixelSpec {
+ layer: layer.to_string(),
+ frame,
+ color: Some(keys[index].0.clone()),
+ cells,
+ ..PixelSpec::default()
+ })
+ })
+ .collect()
+}
+
+pub fn placed(
+ doc: &Document,
+ file: &Path,
+ layer: &str,
+ frame: u32,
+ at: [i64; 2],
+ ask: &Ask,
+) -> Result<(Vec<Op>, Vec<String>)> {
+ checked(ask)?;
+ let owner = doc.find_layer(layer)?;
+ if !owner.pixel() {
+ bail!(
+ "{} is a {} layer: a picture's pixels go on a pixel layer (klad add <bundle> layer pixel)",
+ owner.name,
+ owner.kind_name()
+ );
+ }
+ let picture = sized(&read(file)?, ask)?;
+ let mut notes = Vec::new();
+ let keys = chosen(&doc.palette, &[&picture], ask, UNASKED, &mut notes);
+ let ops = marks(
+ &owner.id,
+ frame,
+ at,
+ &picture,
+ &keys,
+ (doc.canvas.width, doc.canvas.height),
+ );
+ if ops.is_empty() {
+ bail!(
+ "the picture has no solid pixels inside the canvas at {},{}",
+ at[0],
+ at[1]
+ );
+ }
+ notes.insert(
+ 0,
+ format!(
+ "{}x{} pixels in {} on {}",
+ picture.width,
+ picture.height,
+ match ops.len() {
+ 1 => "1 colour".to_string(),
+ n => format!("{n} colours"),
+ },
+ owner.name
+ ),
+ );
+ Ok((ops, notes))
+}
+
+fn fresh(target: &Path) -> Result<()> {
+ match target.exists() {
+ true => bail!(
+ "{} is there already: give the drawing another name with -o",
+ target.display()
+ ),
+ false => Ok(()),
+ }
+}
+
+fn finished(mut bundle: Bundle, ops: &[Op], target: &Path, what: &str) -> Result<Bundle> {
+ let applied = bundle.apply(ops).and_then(|_| bundle.stamp("cli"));
+ match applied {
+ Ok(_) => Ok(bundle),
+ Err(error) => {
+ let _ = fs::remove_dir_all(target);
+ Err(error.context(what.to_string()))
+ }
+ }
+}
+
+pub fn import(file: &Path, ask: &Ask, out: Option<PathBuf>) -> Result<PathBuf> {
+ checked(ask)?;
+ let target = out.unwrap_or_else(|| file.with_extension("klad"));
+ fresh(&target)?;
+ let picture = sized(&read(file)?, ask)?;
+ let mut notes = Vec::new();
+ let keys = chosen(&[], &[&picture], ask, UNASKED, &mut notes);
+ let bundle = Bundle::blank(
+ &target,
+ &Blank {
+ width: picture.width,
+ height: picture.height,
+ pixel: true,
+ ..Blank::default()
+ },
+ "cli",
+ )?;
+ let layer = bundle.doc.layers[0].id.clone();
+ let ops = marks(&layer, 0, [0, 0], &picture, &keys, (picture.width, picture.height));
+ let bundle = finished(bundle, &ops, &target, &format!("bringing in {}", file.display()))?;
+ eprintln!(
+ "{}x{}, {} palette colours",
+ bundle.doc.canvas.width,
+ bundle.doc.canvas.height,
+ bundle.doc.palette.len()
+ );
+ notes.iter().for_each(|note| eprintln!("note: {note}"));
+ Ok(target)
+}
+
+pub fn pixelize(path: &Path, layer: Option<&str>, ask: &Ask, out: Option<PathBuf>) -> Result<PathBuf> {
+ checked(ask)?;
+ let bundle = Bundle::open(path)?;
+ let doc = &bundle.doc;
+ let source = layer.map(|key| doc.find_layer(key)).transpose()?;
+ let Some(size) = ask.size else {
+ bail!("give --size: the longest side of the pixel drawing, in pixels (64 for a 64 px sprite)");
+ };
+ if size == 0 || size > MOST_SIDE {
+ bail!("--size is the longest side in pixels, from 1 to {MOST_SIDE}");
+ }
+ let name = source.map(|l| match l.name.is_empty() {
+ true => l.id.clone(),
+ false => l.name.clone(),
+ });
+ let target = out.unwrap_or_else(|| {
+ let part = name.as_ref().map_or(String::new(), |n| format!("-{}", file_safe(n)));
+ bundle_dir(&bundle).join(format!("{}{part}-pixel.klad", bundle_stem(&bundle)))
+ });
+ fresh(&target)?;
+ let (width, height) = (doc.canvas.width, doc.canvas.height);
+ let (to_width, to_height) = fitted(width, height, size);
+ let scale = match doc.pixel_art() {
+ true => 1.0,
+ false => (size as f32 / width.max(height) as f32).clamp(1.0 / 16.0, 1.0),
+ };
+ let detail = detail_of(doc, scale);
+ let brushes = BrushSet::for_bundle(&bundle)?;
+ let aim = source.map_or(Target::Frame, Target::Layer);
+ let options = Options {
+ scale,
+ background: false,
+ references: false,
+ detail,
+ };
+ let frames: Vec<Picture> = (0..doc.timeline.frames)
+ .map(|frame| {
+ let rasters = layers::load_at(&bundle, frame, &brushes, detail)?;
+ let image = render(doc, frame, &rasters, &aim, options)?;
+ let shown = Picture {
+ width: image.width() as u32,
+ height: image.height() as u32,
+ rgba: dither8(&image)?,
+ };
+ Ok(shrunk(&shown, to_width, to_height))
+ })
+ .collect::<Result<_>>()?;
+ let all: Vec<&Picture> = frames.iter().collect();
+ let mut notes = Vec::new();
+ let keys = chosen(&doc.palette, &all, ask, FROM_PAINT, &mut notes);
+ let made = Bundle::blank(
+ &target,
+ &Blank {
+ width: to_width,
+ height: to_height,
+ fps: doc.timeline.fps,
+ frames: doc.timeline.frames,
+ pixel: true,
+ ..Blank::default()
+ },
+ "cli",
+ )?;
+ let to = made.doc.layers[0].id.clone();
+ let uses_own = ask.colors.is_none() && keys.iter().all(|(key, _)| !key.starts_with('#'));
+ let palette = uses_own.then(|| {
+ Op::Palette(PaletteEdit::Set {
+ swatches: doc
+ .palette
+ .iter()
+ .map(|s| Swatch {
+ id: String::new(),
+ ..s.clone()
+ })
+ .collect(),
+ })
+ });
+ let named = Op::parse(json!({ "op": "set", "id": to, "name": name.clone().unwrap_or_else(|| "pixels".into()) }))?;
+ let drawn: Vec<Op> = frames
+ .iter()
+ .enumerate()
+ .filter(|(at, picture)| *at == 0 || frames[at - 1] != **picture)
+ .map(|(at, picture)| {
+ let cel = (at > 0)
+ .then(|| Op::parse(json!({ "op": "add", "cel": { "frame": at }, "in": to })))
+ .transpose()?;
+ Ok(cel
+ .into_iter()
+ .chain(marks(&to, at as u32, [0, 0], picture, &keys, (to_width, to_height)))
+ .collect::<Vec<_>>())
+ })
+ .collect::<Result<Vec<_>>>()?
+ .into_iter()
+ .flatten()
+ .collect();
+ let clips = doc
+ .timeline
+ .clips
+ .iter()
+ .map(|clip| Op::Clip(ClipEdit::Add(clip.clone())));
+ let ops: Vec<Op> = palette.into_iter().chain([named]).chain(drawn).chain(clips).collect();
+ let made = finished(made, &ops, &target, &format!("making pixels of {}", path.display()))?;
+ let drawings = made.doc.layers[0].cels().len();
+ eprintln!(
+ "{to_width}x{to_height}, {} frames ({}), {} palette colours",
+ made.doc.timeline.frames,
+ match drawings {
+ 1 => "1 drawing".to_string(),
+ n => format!("{n} drawings"),
+ },
+ made.doc.palette.len()
+ );
+ notes.iter().for_each(|note| eprintln!("note: {note}"));
+ Ok(target)
+}
diff --git a/crates/cli/tests/binary.rs b/crates/cli/tests/binary.rs
index 053bd9a..04308aa 100644
--- a/crates/cli/tests/binary.rs
+++ b/crates/cli/tests/binary.rs
@@ -1564,6 +1564,250 @@ fn a_pixel_drawing_goes_out_to_an_aseprite_file_and_comes_back_the_same() {
std::fs::remove_dir_all(&dir).unwrap();
}
+#[test]
+fn pictures_and_painted_layers_become_pixels_on_the_palette() {
+ let dir = std::env::temp_dir().join(format!("draw-binary-pixelize-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ let bundle = dir.join("hop.klad");
+ let path = bundle.to_str().unwrap();
+ let run = |args: &[&str]| Command::new(env!("CARGO_BIN_EXE_klad")).args(args).output().unwrap();
+ let both = |args: &[&str]| {
+ let out = run(args);
+ assert!(
+ out.status.success(),
+ "{args:?}: {}",
+ String::from_utf8_lossy(&out.stderr)
+ );
+ (
+ String::from_utf8_lossy(&out.stdout).to_string(),
+ String::from_utf8_lossy(&out.stderr).to_string(),
+ )
+ };
+ let draw = |args: &[&str]| both(args).0;
+ let refused = |args: &[&str]| {
+ let out = run(args);
+ assert!(!out.status.success(), "{args:?} went through");
+ String::from_utf8_lossy(&out.stderr).to_string()
+ };
+ let rows = |drawing: &str, layer: &str| -> Vec<String> {
+ draw(&["pixels", drawing, layer, "--plain"])
+ .lines()
+ .skip_while(|line| !line.is_empty())
+ .skip(1)
+ .map(String::from)
+ .collect()
+ };
+ draw(&["new", path, "--pixel", "16x12"]);
+ draw(&["palette", path, "--add", "#22223b", "--name", "ink"]);
+ draw(&["palette", path, "--add", "#ef233c", "--name", "red"]);
+ draw(&["pixel", path, "l1", "--color", "ink", "--rect", "2,6,4,4", "--filled"]);
+ draw(&["pixel", path, "l1", "--color", "red", "--cells", "3,7 4,7"]);
+ let png = dir.join("[email protected]");
+ draw(&["export", path, "--scale", "8", "-o", png.to_str().unwrap()]);
+
+ let back = dir.join("back.klad");
+ let (named, told) = both(&[
+ "import",
+ png.to_str().unwrap(),
+ "--size",
+ "16",
+ "-o",
+ back.to_str().unwrap(),
+ ]);
+ assert_eq!(named.trim(), back.to_str().unwrap());
+ assert!(told.contains("16x12, 2 palette colours"), "{told}");
+ let again = back.to_str().unwrap();
+ let swapped =
+ |rows: Vec<String>| -> Vec<String> { rows.iter().map(|r| r.replace('a', "i").replace('b', "r")).collect() };
+ assert_eq!(
+ swapped(rows(again, "l1")),
+ rows(path, "l1"),
+ "a picture enlarged eight times comes back exact"
+ );
+ let own = draw(&["import", png.to_str().unwrap()]);
+ assert!(own.trim().ends_with("[email protected]"));
+ assert!(
+ draw(&["info", own.trim()]).contains("128x96"),
+ "without --size a small picture keeps its size"
+ );
+ assert!(refused(&["import", png.to_str().unwrap(), "-o", again]).contains("is there already"));
+ assert!(
+ refused(&[
+ "import",
+ png.to_str().unwrap(),
+ "--size",
+ "900",
+ "-o",
+ dir.join("x.klad").to_str().unwrap()
+ ])
+ .contains("past 512")
+ );
+ assert!(refused(&["import", dir.join("notes.txt").to_str().unwrap()]).contains("Aseprite files"));
+
+ let (_, told) = both(&[
+ "pixelize",
+ path,
+ "--image",
+ png.to_str().unwrap(),
+ "--to",
+ "l1",
+ "--size",
+ "8",
+ "--at",
+ "8,0",
+ ]);
+ assert!(
+ told.contains("8x6 pixels in 1 colour on") && told.contains("nearest of the palette's 2 colours"),
+ "at half the size the two red pixels are a quarter of their blocks, so the blocks are ink: {told}"
+ );
+ let placed = rows(path, "l1");
+ assert_eq!(
+ (placed[3].as_str(), placed[4].as_str(), placed[6].as_str()),
+ (".........ii.....", ".........ii.....", "..iiii.........."),
+ "the small copy sits beside the first, in the same palette colour"
+ );
+ assert_eq!(
+ draw(&["palette", path]).lines().count(),
+ 2,
+ "nothing was added to the palette"
+ );
+ let (_, told) = both(&[
+ "pixelize",
+ path,
+ "--image",
+ png.to_str().unwrap(),
+ "--to",
+ "l1",
+ "--size",
+ "8",
+ "--colors",
+ "2",
+ "--at",
+ "0,0",
+ ]);
+ assert!(
+ told.contains("8x6 pixels in 2 colours"),
+ "with colours made from the picture, the blocks that held a red pixel keep their own mix: {told}"
+ );
+ assert_eq!(
+ draw(&["palette", path]).lines().count(),
+ 3,
+ "the mixed colour joined the palette; ink was there already"
+ );
+ let quarter = refused(&[
+ "pixelize",
+ path,
+ "--image",
+ png.to_str().unwrap(),
+ "--to",
+ "l1",
+ "--size",
+ "4",
+ ]);
+ assert!(
+ quarter.contains("no solid pixels"),
+ "at a quarter of the size no block is half covered: {quarter}"
+ );
+ assert!(
+ refused(&[
+ "pixelize",
+ path,
+ "--image",
+ png.to_str().unwrap(),
+ "--to",
+ "l1",
+ "--at",
+ "40,40"
+ ])
+ .contains("no solid pixels")
+ );
+ assert!(
+ refused(&[
+ "pixelize",
+ path,
+ "--image",
+ png.to_str().unwrap(),
+ "--to",
+ "l1",
+ "--colors",
+ "1"
+ ])
+ .contains("2 to 256")
+ );
+
+ let painting = dir.join("sign.klad");
+ let sign = painting.to_str().unwrap();
+ draw(&[
+ "new", sign, "--width", "320", "--height", "160", "--frames", "3", "--fps", "6",
+ ]);
+ draw(&["add", sign, "layer", "vector", "name=board"]);
+ let board = draw(&["ls", sign])
+ .lines()
+ .find(|l| l.contains("board"))
+ .unwrap()
+ .split_whitespace()
+ .next()
+ .unwrap()
+ .to_string();
+ draw(&[
+ "add",
+ sign,
+ "rect",
+ "--in",
+ &board,
+ "x=40",
+ "y=40",
+ "w=240",
+ "h=80",
+ "fill=#8b5a2b",
+ ]);
+ draw(&[
+ "add",
+ sign,
+ "ellipse",
+ "--in",
+ &board,
+ "cx=160",
+ "cy=80",
+ "rx=30",
+ "ry=30",
+ "fill=#f0c8a0",
+ ]);
+ draw(&["clip", sign, "--add", "sway", "--from", "0", "--to", "2", "--loop"]);
+ assert!(refused(&["pixelize", sign]).contains("give --size"));
+ let (named, told) = both(&["pixelize", sign, "--layer", "board", "--size", "32"]);
+ let made = named.trim().to_string();
+ assert!(made.ends_with("sign-board-pixel.klad"), "{made}");
+ assert!(told.contains("32x16, 3 frames (1 drawing)"), "{told}");
+ let pixels = rows(&made, "board");
+ assert_eq!(pixels.len(), 16);
+ assert_eq!(
+ pixels[4],
+ format!("....{}....", pixels[4][4..5].repeat(24)),
+ "the board is one colour across, from 40 to 280 of 320"
+ );
+ assert_ne!(
+ pixels[8].chars().nth(16),
+ pixels[8].chars().nth(5),
+ "with the disc in another colour"
+ );
+ assert!(
+ pixels[0].chars().all(|c| c == '.'),
+ "and nothing where the layer is clear"
+ );
+ let timeline = draw(&["frames", &made]);
+ assert!(
+ timeline.contains("3 frames at 6 fps") && timeline.contains("clip sway"),
+ "{timeline}"
+ );
+ assert!(
+ draw(&["ls", sign]).contains("board"),
+ "the painting itself is unchanged"
+ );
+ 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/render/src/gif.rs b/crates/render/src/gif.rs
index 1485b5e..f2bb7bb 100644
--- a/crates/render/src/gif.rs
+++ b/crates/render/src/gif.rs
@@ -21,7 +21,7 @@ fn colours(shots: &[Shot]) -> BTreeMap<[u8; 3], usize> {
seen
}
-fn median_cut(counts: &BTreeMap<[u8; 3], usize>, room: usize) -> Vec<[u8; 3]> {
+pub(crate) fn median_cut(counts: &BTreeMap<[u8; 3], usize>, room: usize) -> Vec<[u8; 3]> {
let mut boxes: Vec<Vec<([u8; 3], usize)>> = vec![counts.iter().map(|(c, n)| (*c, *n)).collect()];
while boxes.len() < room {
let widest = boxes
diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs
index fb57351..1265f4f 100644
--- a/crates/render/src/lib.rs
+++ b/crates/render/src/lib.rs
@@ -8,6 +8,7 @@ pub mod form;
pub mod gif;
pub mod onion;
pub mod overlay;
+pub mod pixelise;
pub mod pngwrite;
pub mod shapes;
pub mod sheet;
diff --git a/crates/render/src/pixelise.rs b/crates/render/src/pixelise.rs
new file mode 100644
index 0000000..9811abf
--- /dev/null
+++ b/crates/render/src/pixelise.rs
@@ -0,0 +1,239 @@
+use anyhow::{Result, anyhow, bail};
+use klad_core::color::to_oklab;
+use skia_safe::{AlphaType, ColorType, Data, Image, ImageInfo, image::CachingHint};
+use std::collections::BTreeMap;
+
+pub const SOLID: u8 = 128;
+pub const MOST_SIDE: u32 = 512;
+pub const MOST_COLOURS: usize = 256;
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Picture {
+ pub width: u32,
+ pub height: u32,
+ pub rgba: Vec<u8>,
+}
+
+pub fn decode(bytes: &[u8]) -> Result<Picture> {
+ let image = Image::from_encoded(Data::new_copy(bytes))
+ .ok_or_else(|| anyhow!("this is not a picture klad can read: it reads PNG and JPEG files"))?;
+ let (width, height) = (image.width() as u32, image.height() as u32);
+ let info = ImageInfo::new(
+ (width as i32, height as i32),
+ ColorType::RGBA8888,
+ AlphaType::Unpremul,
+ None,
+ );
+ let mut rgba = vec![0u8; width as usize * height as usize * 4];
+ if !image.read_pixels(&info, &mut rgba, width as usize * 4, (0, 0), CachingHint::Allow) {
+ bail!("the picture's pixels cannot be read");
+ }
+ Ok(Picture { width, height, rgba })
+}
+
+pub fn fitted(width: u32, height: u32, longest: u32) -> (u32, u32) {
+ let side = width.max(height).max(1) as f64;
+ let scale = longest as f64 / side;
+ (
+ ((width as f64 * scale).round() as u32).max(1),
+ ((height as f64 * scale).round() as u32).max(1),
+ )
+}
+
+pub fn shrunk(picture: &Picture, width: u32, height: u32) -> Picture {
+ if (width, height) == (picture.width, picture.height) {
+ return picture.clone();
+ }
+ let (sw, sh) = (picture.width as usize, picture.height as usize);
+ let edge = |at: u32, of: u32, source: usize| -> (usize, usize) {
+ let from = at as usize * source / of as usize;
+ let to = ((at as usize + 1) * source).div_ceil(of as usize);
+ (from.min(source - 1), to.clamp(from + 1, source))
+ };
+ let rgba = (0..height)
+ .flat_map(|y| (0..width).map(move |x| (x, y)))
+ .flat_map(|(x, y)| {
+ let ((x0, x1), (y0, y1)) = (edge(x, width, sw), edge(y, height, sh));
+ let mut sums = [0u64; 4];
+ (y0..y1).for_each(|sy| {
+ (x0..x1).for_each(|sx| {
+ let px = &picture.rgba[(sy * sw + sx) * 4..][..4];
+ let alpha = px[3] as u64;
+ (0..3).for_each(|ch| sums[ch] += px[ch] as u64 * alpha);
+ sums[3] += alpha;
+ });
+ });
+ let count = ((x1 - x0) * (y1 - y0)) as u64;
+ match sums[3] {
+ 0 => [0, 0, 0, 0],
+ alpha => [
+ ((sums[0] + alpha / 2) / alpha) as u8,
+ ((sums[1] + alpha / 2) / alpha) as u8,
+ ((sums[2] + alpha / 2) / alpha) as u8,
+ ((alpha + count / 2) / count) as u8,
+ ],
+ }
+ })
+ .collect();
+ Picture { width, height, rgba }
+}
+
+pub fn counted(pictures: &[&Picture]) -> BTreeMap<[u8; 3], usize> {
+ let mut seen: BTreeMap<[u8; 3], usize> = BTreeMap::new();
+ pictures.iter().for_each(|picture| {
+ picture
+ .rgba
+ .as_chunks::<4>()
+ .0
+ .iter()
+ .filter(|px| px[3] >= SOLID)
+ .for_each(|px| *seen.entry([px[0], px[1], px[2]]).or_default() += 1);
+ });
+ seen
+}
+
+pub fn colours(pictures: &[&Picture], most: usize) -> Vec<[u8; 3]> {
+ let counts = counted(pictures);
+ match counts.len() <= most.max(1) {
+ true => {
+ let mut by_use: Vec<([u8; 3], usize)> = counts.into_iter().collect();
+ by_use.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
+ by_use.into_iter().map(|(colour, _)| colour).collect()
+ }
+ false => {
+ let mut cut = crate::gif::median_cut(&counts, most.max(1));
+ cut.sort_by(|a, b| {
+ let light =
+ |c: &[u8; 3]| to_oklab([c[0] as f32 / 255.0, c[1] as f32 / 255.0, c[2] as f32 / 255.0, 1.0])[0];
+ light(a).total_cmp(&light(b)).then(a.cmp(b))
+ });
+ cut.dedup();
+ cut
+ }
+ }
+}
+
+pub fn mapped(picture: &Picture, palette: &[[u8; 3]]) -> Vec<Option<usize>> {
+ let lab = |c: [u8; 3]| to_oklab([c[0] as f32 / 255.0, c[1] as f32 / 255.0, c[2] as f32 / 255.0, 1.0]);
+ let labs: Vec<[f32; 3]> = palette.iter().map(|c| lab(*c)).collect();
+ let mut found: BTreeMap<[u8; 3], usize> = palette.iter().enumerate().rev().map(|(i, c)| (*c, i)).collect();
+ picture
+ .rgba
+ .as_chunks::<4>()
+ .0
+ .iter()
+ .map(|px| {
+ if px[3] < SOLID || palette.is_empty() {
+ return None;
+ }
+ let colour = [px[0], px[1], px[2]];
+ Some(*found.entry(colour).or_insert_with(|| {
+ let at = lab(colour);
+ labs.iter()
+ .enumerate()
+ .min_by(|a, b| {
+ let far = |l: &[f32; 3]| (0..3).map(|i| (l[i] - at[i]).powi(2)).sum::<f32>();
+ far(a.1).total_cmp(&far(b.1))
+ })
+ .map_or(0, |(i, _)| i)
+ }))
+ })
+ .collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn picture(width: u32, height: u32, at: impl Fn(u32, u32) -> [u8; 4]) -> Picture {
+ Picture {
+ width,
+ height,
+ rgba: (0..height)
+ .flat_map(|y| (0..width).map(move |x| (x, y)))
+ .flat_map(|(x, y)| at(x, y))
+ .collect(),
+ }
+ }
+
+ #[test]
+ fn a_picture_enlarged_by_whole_numbers_shrinks_back_to_its_pixels() {
+ let small = picture(5, 3, |x, y| match (x + y) % 3 {
+ 0 => [0, 0, 0, 0],
+ 1 => [239, 35, 60, 255],
+ _ => [34, 34, 59, 255],
+ });
+ let big = picture(40, 24, |x, y| {
+ let at = ((y / 8) * 5 + x / 8) as usize * 4;
+ small.rgba[at..at + 4].try_into().unwrap()
+ });
+ assert_eq!(shrunk(&big, 5, 3), small);
+ assert_eq!(shrunk(&small, 5, 3), small);
+ assert_eq!(fitted(40, 24, 5), (5, 3));
+ assert_eq!(fitted(1000, 10, 64), (64, 1));
+ let half = shrunk(&picture(2, 1, |x, _| [200, 100, 0, if x == 0 { 255 } else { 0 }]), 1, 1);
+ assert_eq!(
+ half.rgba,
+ [200, 100, 0, 128],
+ "a clear pixel takes no part in the colour, only in the alpha"
+ );
+ }
+
+ #[test]
+ fn colours_are_the_pictures_own_when_few_and_cut_down_when_many() {
+ let few = picture(4, 1, |x, _| match x {
+ 0 => [10, 10, 10, 255],
+ 1 | 2 => [200, 30, 30, 255],
+ _ => [1, 2, 3, 40],
+ });
+ assert_eq!(
+ colours(&[&few], 16),
+ [[200, 30, 30], [10, 10, 10]],
+ "most used first, clear pixels left out"
+ );
+ let many = picture(64, 64, |x, y| [(x * 4) as u8, (y * 4) as u8, 128, 255]);
+ let cut = colours(&[&many], 8);
+ assert!(cut.len() <= 8 && cut.len() >= 6, "{}", cut.len());
+ let lights: Vec<f32> = cut
+ .iter()
+ .map(|c| to_oklab([c[0] as f32 / 255.0, c[1] as f32 / 255.0, c[2] as f32 / 255.0, 1.0])[0])
+ .collect();
+ assert!(lights.windows(2).all(|w| w[0] <= w[1]), "dark to light: {lights:?}");
+ }
+
+ #[test]
+ fn every_solid_pixel_takes_the_nearest_palette_colour() {
+ let palette = [[0, 0, 0], [255, 255, 255], [220, 40, 40], [40, 60, 200]];
+ let shown = picture(5, 1, |x, _| match x {
+ 0 => [250, 245, 240, 255],
+ 1 => [200, 60, 50, 255],
+ 2 => [30, 30, 90, 200],
+ 3 => [20, 20, 20, 100],
+ _ => [40, 60, 200, 255],
+ });
+ assert_eq!(mapped(&shown, &palette), [Some(1), Some(2), Some(3), None, Some(3)]);
+ assert!(mapped(&shown, &[]).iter().all(Option::is_none));
+ }
+
+ #[test]
+ fn a_png_is_read_with_its_alpha() {
+ let image = {
+ let info = ImageInfo::new((2, 1), ColorType::RGBA8888, AlphaType::Unpremul, None);
+ let pixels = [255u8, 0, 0, 255, 0, 0, 255, 0];
+ skia_safe::images::raster_from_data(&info, Data::new_copy(&pixels), 8).unwrap()
+ };
+ let png = image
+ .encode(None, skia_safe::EncodedImageFormat::PNG, None)
+ .expect("Skia writes a PNG");
+ let read = decode(png.as_bytes()).unwrap();
+ assert_eq!((read.width, read.height), (2, 1));
+ assert_eq!(read.rgba[..4], [255, 0, 0, 255]);
+ assert_eq!(read.rgba[7], 0);
+ assert!(
+ decode(b"not a picture")
+ .unwrap_err()
+ .to_string()
+ .contains("PNG and JPEG")
+ );
+ }
+}
diff --git a/docs/DESIGN.md b/docs/DESIGN.md
index 8169a8a..bd1fe35 100644
--- a/docs/DESIGN.md
+++ b/docs/DESIGN.md
@@ -1,4 +1,4 @@
-_Last updated: 2026-11-12 14:00_
+_Last updated: 2026-11-12 17:00_
# 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. 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 builds on ramps. `shade` (a number of ramp steps) is a way to colour, not a source: for the pixels of any source, `Bundle::settled` reads what the layer shows and makes one mark per target colour, each pixel taking the swatch `Document::ramp_step` gives for its own (pixels in no ramp, or at its end, are left). `dither` keeps the pixels a 4x4 Bayer pattern fixed to the canvas turns on for that share (`pixel::dithered`), and `second` gives the rest another colour, as a second mark. `outline` is a source: the empty pixels that touch a drawn one (or, `inside`, the drawn ones that touch an empty one) on the grid of this layer, another or all (`pixel::outline`). All three need the drawing, so they are settled in the bundle with `fill`, and `settle_pixels` may return more ops than it was given. Mark by mark, `klad recolour --step` and the selection bar's Lighter and Darker move a mark to the next swatch of its ramp, and `klad recolour --from` rebinds every mark of one colour. A colour's character in the text view is fixed by its place in the palette, not by which colours are in use. Two things multiply what is drawn. A mirror (`mirrorX`, `mirrorY` on the `pixel` op; the editor's mirror line) adds each pixel's twin across a line that stands between two pixels or through a column (`pixel::mirrored`); it is part of the op, so the mark holds both halves. Wrap is a property of the canvas (`canvas.wrap`, set by the `canvas` op): the drawing is a tile, so `PixelSpec::coverage` brings pixels past an edge back in on the other side (`pixel::wrapped`) instead of dropping them, and floods and outlines take their neighbours round the edges. It changes what is drawn, never how the drawing renders; to see the repeat, the editor draws the canvas quad three times across and down with the copies dimmed (the shader repeats the texture when the view's uniform says so) and `klad render --repeat N` tiles the finished picture. Transforms of marks do not wrap. Animation on pixel layers is the timeline as it is: drawings on frames, holds, links, clips and onion skins need nothing new, since a pixel layer is a paint layer. Two things differ. A keyed layer or group that holds only pixel layers (`Layer::grid_only`) is drawn at its key's position rounded to whole pixels and sampled nearest (`render::draw_content`), so a keyed move never softens a sprite. And the ops that move points refuse pixel layers with the reason and what to do instead (`ops::grid_refusal`, checked in `ops::apply` and before the CLI resolves anything): `inbetween`, `pose`, `weights` and attaching to bones. Exports of a pixel drawing take whole-number scales only (`export::check_scale`: 1 to `PIXEL_MAX_SCALE` 64, no side past 16384 px, checked before anything is drawn): the frame is drawn at its real size and enlarged with nearest sampling (`export::render`, the same `resample` the preview uses), so the detail of the rasters stays 1 (`export::detail_of`) and every export path (a frame, sheets, numbered frames, GIF, Godot) is sharp by the same code. Fractional scales are refused, not rounded, because a rounded scale would silently change the size asked for. The Godot scenes of a pixel drawing set `texture_filter = 1` (nearest) on the sprite, or on the root of a parallax scene, so nothing depends on the project's default filter. `render/src/gif.rs` writes animated GIFs (`klad export --gif`, the export window's GIF choice) with no new dependency: one global table of up to 255 colours plus a clear index, exact when the frames hold 255 colours or fewer (always, for palette art), median cut otherwise, each pixel then taking the nearest entry, or with `--dither` (the export window's dither box) the nearest entry of the colour moved by an 8x8 ordered pattern, offset per channel, as far as the table's entries lie apart on average (`gif::Pattern`, `spacing`); ordered and not error diffusion, so the pattern holds still from frame to frame; it is an option and off by default because flat art is cleaner without it, and it does nothing when nothing was reduced; LZW with a table reset at 4096 codes; each run of equal pictures is one frame whose delay is its duration in hundredths with the rounding error carried to the next, so the total stays right; frames replace each other (disposal 2) since they are whole pictures with clear pixels. A test reads the result back with Skia's decoder. Palette variants (`doc.variants`, S9.12) are named sets of colour overrides by swatch id. The drawing always is in one variant: the palette and the marks hold the shown variant's colours, `variants.base` keeps the base colours that variant overrides, and showing another one is an ordinary palette edit (`PaletteEdit::Variant`, through `follow_palette`), so the editor, the previews, undo and every reader of the file need nothing new and a variant can never be seen half applied. A view-only variant was the alternative; it would have needed a second set of rasters in the editor's compositor and would have left the question of which variant an edit belongs to. Here the rule is simple: a colour changed while a variant is shown is that variant's (`ops::keep_variant` records it, and drops it again when it is set back to the base colour); a variant follows the base wherever it has no colour of its own. Exports of a variant that is not shown do not touch the drawing: `Document::dress(name)` gives the colours that differ from what is shown, and `layers::dressed` replays the pixel drawings that use them with those colours (`klad export --variant`, `--variants`; file names take the variant after the drawing's name). Both paths rest on `Document::variant_colours`. Aseprite files (S9.13): `render/src/aseprite.rs` reads and writes the published binary format into a plain `Sprite` (layers with their nesting level, cels with a picture or a link, per-frame durations, tags, palette); reading turns indexed and grey pixels into RGBA (the transparent index is clear except on a background layer) and lists what it drops, writing is always RGBA with zlib cels. It was checked against files made by Aseprite itself (its public test sprites, not in the repository) and, for the writer, against an independent dump of the chunks. `cli/src/aseprite.rs` maps a sprite to a drawing and back. In: one `add layer` op per top-level layer with its children and cels (explicit cel ids, so linked cels become klad links and a cel followed by an empty frame gets a `hold`), then one pixel op per colour per cel, bound to the palette entry with that colour (file palette first, other colours added, at most 1024), tags as clips; frame times become whole frames at the lowest fps from 1 to 120 with the least error (`timing`), said when it is not exact. Out: pixel layers and groups only (others are named in a note), one file frame per stretch of timeline in which no layer starts or ends a drawing and no clip starts or ends, so holds do not multiply frames and a file that came in goes out with the frames it had; a drawing shown again is a linked cel; a pixel layer's own keyed x, y and opacity go into the cel's position and opacity (every frame is then its own). `klad import` makes the drawing, `klad export --aseprite` the file; the editor opens an Aseprite file by running `klad import` (`start::brought_in`, used by `Home::open`, so the start window, a path given at launch and the system's open all work) and has an Aseprite choice in the export window. Indexed output and tag directions are not kept on the way out.
+- **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 builds on ramps. `shade` (a number of ramp steps) is a way to colour, not a source: for the pixels of any source, `Bundle::settled` reads what the layer shows and makes one mark per target colour, each pixel taking the swatch `Document::ramp_step` gives for its own (pixels in no ramp, or at its end, are left). `dither` keeps the pixels a 4x4 Bayer pattern fixed to the canvas turns on for that share (`pixel::dithered`), and `second` gives the rest another colour, as a second mark. `outline` is a source: the empty pixels that touch a drawn one (or, `inside`, the drawn ones that touch an empty one) on the grid of this layer, another or all (`pixel::outline`). All three need the drawing, so they are settled in the bundle with `fill`, and `settle_pixels` may return more ops than it was given. Mark by mark, `klad recolour --step` and the selection bar's Lighter and Darker move a mark to the next swatch of its ramp, and `klad recolour --from` rebinds every mark of one colour. A colour's character in the text view is fixed by its place in the palette, not by which colours are in use. Two things multiply what is drawn. A mirror (`mirrorX`, `mirrorY` on the `pixel` op; the editor's mirror line) adds each pixel's twin across a line that stands between two pixels or through a column (`pixel::mirrored`); it is part of the op, so the mark holds both halves. Wrap is a property of the canvas (`canvas.wrap`, set by the `canvas` op): the drawing is a tile, so `PixelSpec::coverage` brings pixels past an edge back in on the other side (`pixel::wrapped`) instead of dropping them, and floods and outlines take their neighbours round the edges. It changes what is drawn, never how the drawing renders; to see the repeat, the editor draws the canvas quad three times across and down with the copies dimmed (the shader repeats the texture when the view's uniform says so) and `klad render --repeat N` tiles the finished picture. Transforms of marks do not wrap. Animation on pixel layers is the timeline as it is: drawings on frames, holds, links, clips and onion skins need nothing new, since a pixel layer is a paint layer. Two things differ. A keyed layer or group that holds only pixel layers (`Layer::grid_only`) is drawn at its key's position rounded to whole pixels and sampled nearest (`render::draw_content`), so a keyed move never softens a sprite. And the ops that move points refuse pixel layers with the reason and what to do instead (`ops::grid_refusal`, checked in `ops::apply` and before the CLI resolves anything): `inbetween`, `pose`, `weights` and attaching to bones. Exports of a pixel drawing take whole-number scales only (`export::check_scale`: 1 to `PIXEL_MAX_SCALE` 64, no side past 16384 px, checked before anything is drawn): the frame is drawn at its real size and enlarged with nearest sampling (`export::render`, the same `resample` the preview uses), so the detail of the rasters stays 1 (`export::detail_of`) and every export path (a frame, sheets, numbered frames, GIF, Godot) is sharp by the same code. Fractional scales are refused, not rounded, because a rounded scale would silently change the size asked for. The Godot scenes of a pixel drawing set `texture_filter = 1` (nearest) on the sprite, or on the root of a parallax scene, so nothing depends on the project's default filter. `render/src/gif.rs` writes animated GIFs (`klad export --gif`, the export window's GIF choice) with no new dependency: one global table of up to 255 colours plus a clear index, exact when the frames hold 255 colours or fewer (always, for palette art), median cut otherwise, each pixel then taking the nearest entry, or with `--dither` (the export window's dither box) the nearest entry of the colour moved by an 8x8 ordered pattern, offset per channel, as far as the table's entries lie apart on average (`gif::Pattern`, `spacing`); ordered and not error diffusion, so the pattern holds still from frame to frame; it is an option and off by default because flat art is cleaner without it, and it does nothing when nothing was reduced; LZW with a table reset at 4096 codes; each run of equal pictures is one frame whose delay is its duration in hundredths with the rounding error carried to the next, so the total stays right; frames replace each other (disposal 2) since they are whole pictures with clear pixels. A test reads the result back with Skia's decoder. Palette variants (`doc.variants`, S9.12) are named sets of colour overrides by swatch id. The drawing always is in one variant: the palette and the marks hold the shown variant's colours, `variants.base` keeps the base colours that variant overrides, and showing another one is an ordinary palette edit (`PaletteEdit::Variant`, through `follow_palette`), so the editor, the previews, undo and every reader of the file need nothing new and a variant can never be seen half applied. A view-only variant was the alternative; it would have needed a second set of rasters in the editor's compositor and would have left the question of which variant an edit belongs to. Here the rule is simple: a colour changed while a variant is shown is that variant's (`ops::keep_variant` records it, and drops it again when it is set back to the base colour); a variant follows the base wherever it has no colour of its own. Exports of a variant that is not shown do not touch the drawing: `Document::dress(name)` gives the colours that differ from what is shown, and `layers::dressed` replays the pixel drawings that use them with those colours (`klad export --variant`, `--variants`; file names take the variant after the drawing's name). Both paths rest on `Document::variant_colours`. Aseprite files (S9.13): `render/src/aseprite.rs` reads and writes the published binary format into a plain `Sprite` (layers with their nesting level, cels with a picture or a link, per-frame durations, tags, palette); reading turns indexed and grey pixels into RGBA (the transparent index is clear except on a background layer) and lists what it drops, writing is always RGBA with zlib cels. It was checked against files made by Aseprite itself (its public test sprites, not in the repository) and, for the writer, against an independent dump of the chunks. `cli/src/aseprite.rs` maps a sprite to a drawing and back. In: one `add layer` op per top-level layer with its children and cels (explicit cel ids, so linked cels become klad links and a cel followed by an empty frame gets a `hold`), then one pixel op per colour per cel, bound to the palette entry with that colour (file palette first, other colours added, at most 1024), tags as clips; frame times become whole frames at the lowest fps from 1 to 120 with the least error (`timing`), said when it is not exact. Out: pixel layers and groups only (others are named in a note), one file frame per stretch of timeline in which no layer starts or ends a drawing and no clip starts or ends, so holds do not multiply frames and a file that came in goes out with the frames it had; a drawing shown again is a linked cel; a pixel layer's own keyed x, y and opacity go into the cel's position and opacity (every frame is then its own). `klad import` makes the drawing, `klad export --aseprite` the file; the editor opens an Aseprite file by running `klad import` (`start::brought_in`, used by `Home::open`, so the start window, a path given at launch and the system's open all work) and has an Aseprite choice in the export window. Indexed output and tag directions are not kept on the way out. Pictures to pixels (S9.14): `render/src/pixelise.rs` decodes a picture with Skia, shrinks it by area average on premultiplied colour (`shrunk`; exact for whole-number reductions of enlarged pixel art), picks colours (`colours`: the picture's own, most used first, when few enough, else the GIF encoder's median cut, dark to light) and maps every pixel at least half solid to the nearest colour in Oklab (`mapped`). `cli/src/pixelise.rs` turns that into ordinary pixel ops, one mark per colour, so nothing new is stored: a picture file onto a pixel layer in the drawing's palette (`klad pixelize --image --to`), a picture as a new pixel drawing (`klad import x.png`), and a painted or vector layer, or the whole picture, as a new pixel drawing with every frame rendered through the export path, shrunk, and held when it equals the frame before (`klad pixelize --size`). The palette rule is the same everywhere: `--colors N` makes colours from the picture, else an existing palette of two or more solid colours is used as it is, else the picture's own colours (32 when it has more than 256, 16 for a painting). No dithering and no outline repair: the result is a start to clean up. The editor has one window for it (File > Pixels of a picture…, `editor/pixels.rs`) that runs the same command.
- **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 e4548c5..362fc94 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -8,7 +8,8 @@ This reference is licensed under the MIT License (`LICENSE-MIT`), unlike klad it
## Commands
-- [`klad import`](#klad-import): Open an Aseprite file as a klad drawing
+- [`klad import`](#klad-import): Open an Aseprite file or a picture as a klad pixel drawing
+- [`klad pixelize`](#klad-pixelize): Make pixels of a picture or of a painted or vector layer
- [`klad new`](#klad-new): Create an empty bundle with paint layers
- [`klad canvas`](#klad-canvas): The canvas: its size and background, and whether it wraps at its edges
- [`klad frames`](#klad-frames): Exposure sheet: a row per frame, a column per layer (top first)
@@ -96,12 +97,17 @@ This reference is licensed under the MIT License (`LICENSE-MIT`), unlike klad it
## klad import
```text
-Make a klad drawing from an Aseprite file (.aseprite or .ase): its layers and groups, the drawing of every frame, its palette and its tags. The drawing is written next to the file (hero.aseprite makes hero.klad) unless -o names it, and its path is printed.
+Make a klad drawing from an Aseprite file (.aseprite or .ase), or a pixel drawing from a picture (.png, .jpg). The drawing is written next to the file (hero.aseprite makes hero.klad) unless -o names it, and its path is printed.
klad import hero.aseprite
klad import hero.ase -o sprites/hero.klad
+ klad import sprite.png (a picture of 512 px or less a side, at its own size)
+ klad import [email protected] --size 32 (shrunk to 32 px on its longest side)
+ klad import photo.jpg --size 64 --colors 16
-What comes over: image layers as pixel layers with their name, visibility, opacity and blend mode, groups as groups, every cel as a drawing on its frame (linked cels stay linked), the palette with its names, and tags as clips. Frame times become whole frames: a file of 100 ms frames is 10 frames a second, and a frame shown for 300 ms holds for three. Indexed, grey and RGBA files all open; every pixel is bound to its palette colour, and colours a file uses outside its palette are added to it.
+A picture becomes one pixel layer: every solid pixel takes a palette colour, and the palette is the picture's own colours when it has 256 or fewer, else 32 made from it, or --colors N. klad pixelize puts a picture on a layer of a drawing you have, in that drawing's palette.
+
+From an Aseprite file, what comes over: image layers as pixel layers with their name, visibility, opacity and blend mode, groups as groups, every cel as a drawing on its frame (linked cels stay linked), the palette with its names, and tags as clips. Frame times become whole frames: a file of 100 ms frames is 10 frames a second, and a frame shown for 300 ms holds for three. Indexed, grey and RGBA files all open; every pixel is bound to its palette colour, and colours a file uses outside its palette are added to it.
What does not: tilemap layers, tilesets and slices are left out, a tag that plays backwards or back and forth becomes a clip that plays forwards, and blend modes klad does not have blend as normal. Each of these is said when it happens.
@@ -114,6 +120,12 @@ Arguments:
Options:
+ --size <SIZE>
+ A picture: its longest side in pixels once it is pixel art, 1 to 512 (needed when the picture is larger)
+
+ --colors <COLORS>
+ A picture: reduce it to this many colours, 2 to 256 (default: its own colours when it has 256 or fewer, else 32)
+
-o, --out <OUT>
The drawing to make (default: the file's name with .klad, next to it)
@@ -121,6 +133,76 @@ Options:
Print help (see a summary with '-h')
```
+## klad pixelize
+
+```text
+Turn a picture into pixel art. Each pixel takes one palette colour and becomes part of a pixel mark, so the result is edited like any pixel drawing: recolour a palette colour, move marks, shade along ramps.
+
+A picture file onto a pixel layer of this drawing:
+
+ klad pixelize sprite.klad --image ref.png --to l1 (at its own size, top left)
+ klad pixelize sprite.klad --image photo.jpg --to l1 --size 48 --at 8,8
+
+Every pixel takes the nearest colour of the drawing's palette, so the picture lands in the colours the sprite already has. --colors N makes N colours from the picture instead and adds them to the palette. --size is the picture's longest side in pixels once it is shrunk (each pixel is the average of the area it covers; a picture enlarged by a whole number comes back exact). Pixels less than half solid are left empty.
+
+A painted or vector layer, or the whole picture, as a new pixel drawing:
+
+ klad pixelize hero.klad --size 64 (the whole picture, 64 px on its longest side: hero-pixel.klad)
+ klad pixelize hero.klad --layer body --size 48 --colors 12 -o body.klad
+
+Every frame is pixelised with one set of colours, frames that come out the same hold, and clips are kept. Without --colors the drawing's own palette is used when it has one, else 16 colours are made from the picture. The drawing itself is not changed.
+
+klad import ref.png makes a new pixel drawing straight from a picture file.
+
+Usage: klad pixelize [OPTIONS] <BUNDLE>
+
+Arguments:
+ <BUNDLE>
+
+
+Options:
+ --image <IMAGE>
+ A PNG or JPEG file to put on a pixel layer
+
+ --to <TO>
+ With --image: the pixel layer it goes on (an id or a name)
+
+ --at <AT>
+ With --image: the canvas pixel of its top left corner, x,y
+
+ --frame <FRAME>
+ With --image: the frame it is drawn on
+
+ [default: 0]
+
+ --layer <LAYER>
+ Without --image: the layer or group to pixelise (default: the whole picture)
+
+ --size <SIZE>
+ The longest side in pixels, 1 to 512
+
+ --colors <COLORS>
+ Make this many colours from the picture, 2 to 256
+
+ -o, --out <OUT>
+ Without --image: the pixel drawing to make
+
+ --render
+ Render a preview after the edit and print its path
+
+ --scale <SCALE>
+ Preview scale (default: longest side 1024 px)
+
+ --json
+ Print the result as JSON
+
+ --overlay <OVERLAY>
+ Draw on the preview: ids, bbox, grid or all (comma separated)
+
+ -h, --help
+ Print help (see a summary with '-h')
+```
+
## klad new
```text
diff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.md
index 966e96b..e9affbd 100644
--- a/docs/skill/SKILL.md
+++ b/docs/skill/SKILL.md
@@ -143,6 +143,7 @@ klad export sprite.klad --scale 8 -o [email protected] square pixels, to keep
- Animation is frame by frame: a pixel layer holds a drawing per frame like a paint layer (`klad add sprite.klad cel --in l1 frame=2`, then `klad pixel ... --frame 2`; `klad duplicate`, links, holds, clips and `--overlay onion` all work). To make the next frame, read the last one (`klad pixels sprite.klad l1 --frame 0 --plain`), change the text and write it to the new frame. Keying a pixel layer (`klad key sprite.klad l1 --frame 4 x=6`) moves it by whole pixels: positions in between are rounded, so a slow move steps a pixel at a time. `klad inbetween`, `klad pose`, `klad weights` and `klad attach` refuse pixel layers and say why: they move points and bend strokes, which would take pixels off the grid.
- Palette variants are other colours for the same sprite (teams, seasons, a hurt flash, day and night): `klad palette sprite.klad --new-variant blue` makes one and shows it, and every colour you change while it is shown (`--recolour team --to '#2a6fdb'`, `--add` with an existing name) is blue's own; the base palette keeps its colours, and a variant follows the base for every colour it has not changed. `--variant base` (or `--variant blue`) shows another one: the pixels stay the same marks, only their colours change, as one undo step. `klad palette sprite.klad` lists what is shown and each variant's own colours; `--rename-variant blue --to navy` and `--rm-variant navy` do what they say. Draw in the base palette and bind the parts that will change to their own palette colours (a `team` colour and its shades, not the same red that is also used for the mouth), or a variant changes more than you meant. Export without switching: `klad export sprite.klad --variant blue` renders that variant whatever is shown (file names get `-blue` after the drawing's name), and `--variants` exports the base and every variant in one go; both work with `--sheet`, `--frames`, `--gif` and `--godot`. Variants recolour pixel marks only: strokes on paint layers and vector shapes store their own colours.
- Exports stay sharp: a pixel drawing exports at whole-number scales only (`--scale 1` to 64, at most 16384 px a side), enlarged pixel for pixel, never smoothed; `--scale 2.5` is refused with the reason. That holds for `klad export` of a frame, `--sheet`, `--frames`, `--gif` and `--godot` (sheet cells and the Godot offset are scaled with it; the Godot scenes set `texture_filter` to nearest so the sprite stays sharp in the game). To show a sprite to someone, `klad export sprite.klad --gif --scale 8`; in a game, export at `--scale 1` and let the engine enlarge it.
+- Pictures to pixels. `klad pixelize sprite.klad --image ref.png --to l1` puts a PNG or JPEG on a pixel layer: every pixel takes the nearest colour of the drawing's palette (so it lands in the colours the sprite has; `--colors N` makes N colours from the picture and adds them instead), `--size 48` shrinks it to 48 px on its longest side first (each pixel the average of the area it covers; a picture enlarged by a whole number comes back exact; pixels less than half solid stay empty), `--at x,y` places its top left, `--frame` picks the drawing. `klad import ref.png [--size N] [--colors N]` makes a new pixel drawing from a picture, with the picture's own colours as its palette (reduced to 32 when it has more than 256). `klad pixelize hero.klad --size 64 [--layer body] [--colors 12] [-o out.klad]` makes a new pixel drawing (`hero-pixel.klad`) of a painted or vector layer or of the whole picture, every frame with one set of colours, frames that come out the same held, clips kept; the drawing itself is not changed. All three give marks bound to palette colours, one per colour, so the result is edited like anything else here. Treat it as a start, not a finish: shrinking blurs edges into in-between colours and breaks one-pixel outlines, so look at it at real size, then redraw the outline, and cut stray colours with `klad recolour --from a --to b`.
- Aseprite files: `klad import hero.aseprite` (or `.ase`; `-o` names the drawing) makes `hero.klad` next to the file: image layers as pixel layers with their name, visibility, opacity and blend mode, groups as groups, every cel as a drawing on its frame (linked cels stay links), the palette with its names, tags as clips. Frame times become whole frames at the slowest speed that fits (100 ms frames are 10 fps; a 300 ms frame holds for three). Indexed, grey and RGBA files all open, every pixel bound to its palette colour. It says what it leaves out: tilemap layers, tilesets, slices, tag directions other than forwards, blend modes klad lacks. `klad export hero.klad --aseprite` writes the pixel layers and groups back (RGBA; holds and links as linked cels, clips as tags, a pixel layer's keyed moves and opacity baked into its cels; `--variant` and `--variants` work); paint, vector and other layers are left out and named. Use it to hand work to someone who uses Aseprite, or to take over a sprite made there.
- 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).