Skip to content

armgit / klad

Public Imported from GitHub
0

A drawing app built for agent/human collaboration

Rust

Sprites as text for agents: a grid of characters draws a pixel layer and reads it back

Indicode BVa6ae65b8f8b9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 88109b6..d50b7ff 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.
+- Sprites as text, for agents. `klad pixel sprite.klad l1 --grid sprite.txt` draws a sprite from a legend (`i = ink`) and rows of characters, one per pixel, each character becoming one mark bound to its palette colour; `klad pixels sprite.klad l1` reads a pixel layer back the same way, with its legend and numbered rows and columns (`--plain` in the form `--grid` reads, `--json`).
- The pixel pencil and eraser. On a pixel layer the brush tool (**B**) draws whole pixels in the current colour, which joins the palette, and the eraser (**E**, or the pen's eraser end) clears them; each drag is one mark. A one-pixel line is pixel perfect (no doubled corners), the size is a square of whole pixels (**[** and **]**), and shift click draws a straight line from the last pixel. From the command line, `klad pixel` takes `--path` (SVG path data as a line of pixels) and `--size`.
- The palette of a pixel drawing. Changing a palette colour changes every pixel painted with it: click the colour in the palette, change it, and press **update** (or `klad palette art.klad --recolour skin --to '#e8b796'`). **palettes** adds the colours of a palette that comes with klad (PICO-8, Sweetie 16, DawnBringer 16 and 32, Endesga 32, Resurrect 64, AAP-64, Game Boy, 1-bit; `klad palettes` lists them) or of a palette file, a list of hex colours or a GIMP palette (`klad palette art.klad --load pico-8`). **ramp** adds five steps of the current colour, from dark and cool to light and warm (`klad palette art.klad --ramp wood --base '#8b5a2b'`), and `--ramp skin --of skin-dark,skin,skin-light` groups colours the palette has.
- A sharp view for pixel drawings. In the editor the zoom steps in whole pixels, so every pixel is the same size; a grid shows between the pixels once you are zoomed in (**View > Pixel grid**), the pixel under the pointer is outlined and its position shows in the status line, and the **Real size** panel shows the drawing as the player sees it, at 1x, 2x or 4x. `klad render` enlarges a pixel drawing to about 512 px, and `--overlay grid` numbers its pixels along the top and the left.
diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs
index f8c8736..a4fa318 100644
--- a/crates/cli/src/main.rs
+++ b/crates/cli/src/main.rs
@@ -869,17 +869,33 @@ enum Command {
},
#[command(
about = "Put whole pixels of one palette colour on a pixel layer, or erase them",
- long_about = "Put whole pixels of one palette colour on a pixel layer, or erase them. A pixel layer is a grid with no anti-aliasing where one pixel is one canvas pixel; make a pixel drawing with klad new --pixel 64x64, or add a layer with klad add <bundle> layer pixel.\n\n--cells lists them: x,y for one pixel, x0-x1,y for a run along a row, x,y0-y1 for a run down a column and x0-x1,y0-y1 for a block. --color is a palette name, a palette index or #rrggbb; a colour the palette does not have yet is added to it. The pixels become one mark bound to that palette entry, so it can be recoloured (klad set <cel>:s<id> color=...), moved (klad transform) or removed (klad rm) later, and klad strokes lists it. --erase clears the pixels under it instead.\n\n--path draws SVG path data as a line of pixels: a pixel is the square from x,y to x+1,y+1, so aim at pixel middles (3.5, not 3). Straight segments keep the corners they are given; curves are cleaned so no corner is doubled. --size makes the pencil a square of that many pixels, for --cells and --path alike.\n\n klad pixel sprite.klad l1 --color '#2b2d42' --cells '3-12,4 3,5-9 12,5-9 3-12,10'\n klad pixel sprite.klad l1 --color '#2b2d42' --path 'M3.5 20.5 C 10 4 22 4 28.5 20.5'\n klad pixel sprite.klad l1 --erase --size 3 --path 'M4.5 4.5 L12.5 12.5'\n klad pixel sprite.klad l1 --color skin --cells '4-11,5-9'\n klad pixel sprite.klad l1 --erase --cells '7,7 8,7'\n\nAlso a pixel op in klad apply: {\"op\":\"pixel\",\"layer\":\"l1\",\"color\":\"skin\",\"cells\":[[4,5],[5,5]]}, with \"path\":\"M3.5 3.5 L9.5 3.5\" in place of cells, \"size\":2, or \"erase\":true."
+ long_about = "Put whole pixels of one palette colour on a pixel layer, or erase them. A pixel layer is a grid with no anti-aliasing where one pixel is one canvas pixel; make a pixel drawing with klad new --pixel 64x64, or add a layer with klad add <bundle> layer pixel.\n\n--cells lists them: x,y for one pixel, x0-x1,y for a run along a row, x,y0-y1 for a run down a column and x0-x1,y0-y1 for a block. --color is a palette name, a palette index or #rrggbb; a colour the palette does not have yet is added to it. The pixels become one mark bound to that palette entry, so it can be recoloured (klad set <cel>:s<id> color=...), moved (klad transform) or removed (klad rm) later, and klad strokes lists it. --erase clears the pixels under it instead.\n\n--path draws SVG path data as a line of pixels: a pixel is the square from x,y to x+1,y+1, so aim at pixel middles (3.5, not 3). Straight segments keep the corners they are given; curves are cleaned so no corner is doubled. --size makes the pencil a square of that many pixels, for --cells and --path alike.\n\n klad pixel sprite.klad l1 --color '#2b2d42' --cells '3-12,4 3,5-9 12,5-9 3-12,10'\n klad pixel sprite.klad l1 --color '#2b2d42' --path 'M3.5 20.5 C 10 4 22 4 28.5 20.5'\n klad pixel sprite.klad l1 --erase --size 3 --path 'M4.5 4.5 L12.5 12.5'\n klad pixel sprite.klad l1 --color skin --cells '4-11,5-9'\n klad pixel sprite.klad l1 --erase --cells '7,7 8,7'\n\n--grid draws a whole sprite from text, the way klad pixels --plain prints one: legend lines (one character, =, a palette name, a colour, erase or empty), a blank line, then a row of characters per row of pixels. . is empty unless the legend says otherwise. Each character becomes one mark bound to its colour; --at x,y moves the grid's top left.\n\n klad pixel sprite.klad l1 --grid - <<'GRID'\n i = ink\n b = body\n\n ..iiii..\n .ibbbbi.\n .ibbbbi.\n ..iiii..\n GRID\n\nAlso a pixel op in klad apply: {\"op\":\"pixel\",\"layer\":\"l1\",\"color\":\"skin\",\"cells\":[[4,5],[5,5]]}, with \"path\":\"M3.5 3.5 L9.5 3.5\" in place of cells, \"size\":2, or \"erase\":true; and as a grid {\"op\":\"pixel\",\"layer\":\"l1\",\"rows\":[\"..ii..\",\".ibbi.\"],\"legend\":{\"i\":\"ink\",\"b\":\"body\"},\"at\":[0,0]}."
)]
Pixel {
bundle: PathBuf,
layer: String,
#[arg(
long,
- required_unless_present = "path",
+ required_unless_present_any = ["path", "grid"],
help = "The pixels: x,y, a row run x0-x1,y, a column run x,y0-y1 or a block x0-x1,y0-y1, separated by spaces"
)]
cells: Option<String>,
+ #[arg(
+ long,
+ value_name = "FILE",
+ conflicts_with_all = ["cells", "path", "color", "erase"],
+ help = "Draw a grid of characters from a file (- reads stdin): a legend (i = ink), a blank line, then one row of characters per row of pixels"
+ )]
+ grid: Option<String>,
+ #[arg(
+ long,
+ requires = "grid",
+ value_parser = parse_cell,
+ allow_hyphen_values = true,
+ default_value = "0,0",
+ help = "Where the grid's top left pixel goes: x,y"
+ )]
+ at: [i64; 2],
#[arg(
long,
conflicts_with = "cells",
@@ -1686,6 +1702,24 @@ enum Command {
#[command(flatten)]
flags: EditFlags,
},
+ #[command(
+ about = "Read a pixel layer as a grid of characters, one per pixel, with a legend of its palette colours",
+ long_about = "Read a pixel layer as a grid of characters, one per pixel, with a legend of its palette colours. It is what the layer shows at the frame: later marks over earlier ones, erased pixels empty. Each colour gets a character (the first letter of its palette name where that is free), . is an empty pixel, and the numbers along the top and the left count the pixels.\n\n klad pixels sprite.klad l1\n klad pixels sprite.klad l1 --plain > sprite.txt (the form klad pixel --grid reads back)\n klad pixels sprite.klad l1 --json\n\nTo draw from such a text: klad pixel sprite.klad l1 --grid sprite.txt. Each character of the legend becomes one mark bound to its colour."
+ )]
+ Pixels {
+ bundle: PathBuf,
+ layer: String,
+ #[arg(long, default_value_t = 0)]
+ frame: u32,
+ #[arg(
+ long,
+ conflicts_with = "json",
+ help = "Only the legend and the rows, as klad pixel --grid reads them"
+ )]
+ plain: bool,
+ #[arg(long)]
+ json: bool,
+ },
#[command(about = "The palettes that come with klad, to load with klad palette <bundle> --load <name>")]
Palettes {
#[arg(long)]
@@ -2111,6 +2145,17 @@ fn parse_cells(text: &str) -> Result<Vec<[i64; 2]>> {
Ok(cells)
}
+fn parse_cell(text: &str) -> Result<[i64; 2]> {
+ let parts: Vec<i64> = text
+ .split(',')
+ .map(|part| part.trim().parse::<i64>())
+ .collect::<std::result::Result<_, _>>()
+ .map_err(|_| anyhow!("{text:?} is not x,y in whole pixels"))?;
+ parts
+ .try_into()
+ .map_err(|_| anyhow!("{text:?} is not x,y in whole pixels"))
+}
+
fn parse_origin(text: &str) -> Result<Option<[f32; 2]>> {
match text {
"centre" | "center" => Ok(None),
@@ -2830,6 +2875,8 @@ fn run() -> Result<()> {
bundle,
layer,
cells,
+ grid,
+ at,
path,
size,
color,
@@ -2839,6 +2886,23 @@ fn run() -> Result<()> {
flags,
} => {
let layer = Bundle::open(&bundle)?.doc.find_layer(&layer)?.id.clone();
+ if let Some(source) = grid {
+ let text = match source.as_str() {
+ "-" => std::io::read_to_string(std::io::stdin()).context("reading the grid from stdin")?,
+ file => std::fs::read_to_string(file).with_context(|| format!("reading {file}"))?,
+ };
+ let (legend, rows) = klad_core::pixel::parse_text(&text)?;
+ let spec = klad_core::ops::GridSpec {
+ layer,
+ frame,
+ rows,
+ legend,
+ at,
+ part,
+ };
+ spec.check()?;
+ return agent::edit(&bundle, &[Op::PixelGrid(spec)], &output(&flags, frame));
+ }
let spec = PixelSpec {
layer,
frame,
@@ -3660,6 +3724,13 @@ fn run() -> Result<()> {
}
}
Command::Palettes { json } => palettes(json),
+ Command::Pixels {
+ bundle,
+ layer,
+ frame,
+ plain,
+ json,
+ } => pixels(&bundle, &layer, frame, plain, json)?,
Command::Export {
bundle,
png: _,
@@ -4352,6 +4423,64 @@ fn palette(path: &Path, as_json: bool) -> Result<()> {
Ok(())
}
+fn pixels(path: &Path, layer: &str, frame: u32, plain: bool, as_json: bool) -> Result<()> {
+ let bundle = Bundle::open(path)?;
+ let doc = &bundle.doc;
+ let owner = doc.find_layer(layer)?;
+ if !owner.pixel() {
+ bail!(
+ "{} is a {} layer: klad pixels reads pixel layers (klad strokes lists what a paint layer holds)",
+ owner.id,
+ owner.kind_name()
+ );
+ }
+ let marks = match owner.content_at(frame) {
+ Some(cel) => bundle.read_marks(&owner.id, &cel.id)?,
+ None => Vec::new(),
+ };
+ let grid = klad_core::pixel::grid_of(&marks, doc.canvas.width, doc.canvas.height);
+ let legend = klad_core::pixel::legend(doc, &grid);
+ if as_json {
+ let named: serde_json::Map<String, serde_json::Value> = legend
+ .iter()
+ .map(|n| {
+ let bound = doc.entry(&n.key).is_some();
+ (
+ n.sign.to_string(),
+ serde_json::json!({
+ "name": n.name,
+ "color": n.color,
+ "entry": if bound { serde_json::json!(n.key) } else { serde_json::Value::Null },
+ }),
+ )
+ })
+ .collect();
+ println!(
+ "{}",
+ serde_json::json!({
+ "layer": owner.id,
+ "frame": frame,
+ "width": grid.width,
+ "height": grid.height,
+ "empty": klad_core::pixel::EMPTY.to_string(),
+ "legend": named,
+ "rows": klad_core::pixel::rows(&grid, &legend),
+ })
+ );
+ return Ok(());
+ }
+ if plain {
+ println!("{}", klad_core::pixel::plain(&grid, &legend));
+ return Ok(());
+ }
+ println!(
+ "{}x{} layer {} \"{}\" frame {frame}",
+ grid.width, grid.height, owner.id, owner.name
+ );
+ println!("{}", klad_core::pixel::ruled(&grid, &legend));
+ Ok(())
+}
+
fn palette_source(source: &str) -> Result<Vec<klad_core::doc::Swatch>> {
if let Some(shipped) = klad_core::palettes::shipped(source) {
return Ok(shipped.swatches());
diff --git a/crates/cli/tests/binary.rs b/crates/cli/tests/binary.rs
index aeb9acc..54961fe 100644
--- a/crates/cli/tests/binary.rs
+++ b/crates/cli/tests/binary.rs
@@ -707,6 +707,73 @@ fn the_palette_recolours_its_pixels_loads_palettes_and_groups_ramps_from_the_com
std::fs::remove_dir_all(&dir).unwrap();
}
+#[test]
+fn a_sprite_is_written_as_a_grid_of_characters_and_read_back_the_same() {
+ use std::io::Write;
+ use std::process::Stdio;
+ let dir = std::env::temp_dir().join(format!("draw-binary-grid-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ let bundle = dir.join("sprite.klad");
+ let path = bundle.to_str().unwrap();
+ let run = |args: &[&str]| Command::new(env!("CARGO_BIN_EXE_klad")).args(args).output().unwrap();
+ let draw = |args: &[&str]| {
+ let out = run(args);
+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
+ String::from_utf8_lossy(&out.stdout).to_string()
+ };
+ draw(&["new", path, "--pixel", "8x6"]);
+ draw(&["palette", path, "--add", "#22223b", "--name", "ink"]);
+ let text = "i = ink\nb = #f2c14e\n\n..iiii..\n.ibbbbi.\n.ibbbbi.\n..iiii..\n";
+ let mut child = Command::new(env!("CARGO_BIN_EXE_klad"))
+ .args(["pixel", path, "l1", "--grid", "-", "--at", "0,1"])
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()
+ .unwrap();
+ child.stdin.take().unwrap().write_all(text.as_bytes()).unwrap();
+ let made = child.wait_with_output().unwrap();
+ assert!(made.status.success(), "{}", String::from_utf8_lossy(&made.stderr));
+ assert!(String::from_utf8_lossy(&made.stdout).contains("pixel marks"));
+ let marks: serde_json::Value = serde_json::from_str(&draw(&["strokes", path, "l1", "--json"])).unwrap();
+ assert_eq!(
+ marks["fills"].as_array().unwrap().len(),
+ 2,
+ "one mark for each colour of the grid"
+ );
+ let plain = draw(&["pixels", path, "l1", "--plain"]);
+ assert_eq!(
+ plain.trim_end(),
+ ". = empty\ni = ink\na = #f2c14e\n\n........\n..iiii..\n.iaaaai.\n.iaaaai.\n..iiii..\n........"
+ );
+ let ruled = draw(&["pixels", path, "l1"]);
+ assert!(ruled.contains("8x6") && ruled.contains(" 1 ..iiii.."), "{ruled}");
+ let read: serde_json::Value = serde_json::from_str(&draw(&["pixels", path, "l1", "--json"])).unwrap();
+ assert_eq!(read["rows"][2], ".iaaaai.");
+ assert_eq!(read["legend"]["i"]["name"], "ink");
+ assert_eq!((read["width"].as_u64(), read["height"].as_u64()), (Some(8), Some(6)));
+ let copy = dir.join("copy.klad");
+ let copy_path = copy.to_str().unwrap();
+ draw(&["new", copy_path, "--pixel", "8x6"]);
+ draw(&["palette", copy_path, "--add", "#22223b", "--name", "ink"]);
+ let saved = dir.join("sprite.txt");
+ std::fs::write(&saved, &plain).unwrap();
+ draw(&["pixel", copy_path, "l1", "--grid", saved.to_str().unwrap()]);
+ assert_eq!(
+ draw(&["hash", copy_path]),
+ draw(&["hash", path]),
+ "what klad pixels prints draws the same picture again"
+ );
+ std::fs::write(&saved, "i = ink\n\n..q..\n").unwrap();
+ let unknown = run(&["pixel", path, "l1", "--grid", saved.to_str().unwrap()]);
+ assert!(String::from_utf8_lossy(&unknown.stderr).contains("the legend does not name"));
+ draw(&["add", path, "layer", "paint", "name=paint"]);
+ let wrong = run(&["pixels", path, "paint"]);
+ assert!(String::from_utf8_lossy(&wrong.stderr).contains("reads pixel layers"));
+ std::fs::remove_dir_all(&dir).unwrap();
+}
+
#[test]
fn recolour_moves_strokes_together_and_keeps_their_shades() {
let dir = std::env::temp_dir().join(format!("draw-binary-recolour-{}", std::process::id()));
diff --git a/crates/core/src/bundle.rs b/crates/core/src/bundle.rs
index c281b08..faad919 100644
--- a/crates/core/src/bundle.rs
+++ b/crates/core/src/bundle.rs
@@ -657,6 +657,7 @@ pub fn summarize(ops: &[Op]) -> String {
Op::Fill(spec) => format!("fill on {}", spec.layer),
Op::Pixel(spec) if spec.erase => format!("erase pixels on {}", spec.layer),
Op::Pixel(spec) => format!("pixels on {}", spec.layer),
+ Op::PixelGrid(grid) => format!("pixel grid on {}", grid.layer),
Op::Palette(_) => "palette".to_string(),
Op::Transform { ids, .. } => format!("transform {}", ids.join(" ")),
Op::Detach { ids } => format!("detach {}", ids.join(" ")),
diff --git a/crates/core/src/ops.rs b/crates/core/src/ops.rs
index 075047e..33d6b1d 100644
--- a/crates/core/src/ops.rs
+++ b/crates/core/src/ops.rs
@@ -121,6 +121,7 @@ pub enum Op {
Stroke(StrokeSpec),
Fill(FillSpec),
Pixel(PixelSpec),
+ PixelGrid(GridSpec),
Palette(PaletteEdit),
Transform {
ids: Vec<String>,
@@ -304,6 +305,58 @@ fn one_pixel() -> u32 {
1
}
+#[derive(Clone, Debug, PartialEq, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct GridSpec {
+ pub layer: String,
+ #[serde(default)]
+ pub frame: u32,
+ pub rows: Vec<String>,
+ #[serde(default)]
+ pub legend: BTreeMap<String, String>,
+ #[serde(default)]
+ pub at: [i64; 2],
+ #[serde(default)]
+ pub part: Option<String>,
+}
+
+impl GridSpec {
+ pub fn check(&self) -> Result<()> {
+ if self.rows.iter().all(|row| row.is_empty()) {
+ bail!("a pixel grid needs rows: a list of strings, one character per pixel");
+ }
+ if let Some(sign) = self.legend.keys().find(|k| k.chars().count() != 1) {
+ bail!("a legend names single characters, not {sign:?}");
+ }
+ Ok(())
+ }
+
+ pub fn specs(&self) -> Result<Vec<PixelSpec>> {
+ self.check()?;
+ let placed = crate::pixel::placed(&self.rows, &self.legend, self.at)?;
+ if placed.is_empty() {
+ bail!("every character of the grid is empty: nothing to draw");
+ }
+ Ok(placed
+ .into_iter()
+ .map(|(_, meaning, cells)| PixelSpec {
+ layer: self.layer.clone(),
+ frame: self.frame,
+ color: match &meaning {
+ crate::pixel::Sign::Colour(value) => Some(value.clone()),
+ _ => None,
+ },
+ erase: matches!(meaning, crate::pixel::Sign::Erase),
+ cells,
+ path: None,
+ size: 1,
+ part: self.part.clone(),
+ by_hand: false,
+ })
+ .collect())
+ }
+}
+
impl PixelSpec {
pub fn check(&self) -> Result<()> {
match (&self.color, self.erase) {
@@ -1555,6 +1608,11 @@ impl Op {
spec.check()?;
Op::Fill(spec)
}
+ "pixel" if map.contains_key("rows") => {
+ let grid: GridSpec = serde_json::from_value(Value::Object(std::mem::take(&mut map)))?;
+ grid.check()?;
+ Op::PixelGrid(grid)
+ }
"pixel" => {
let spec: PixelSpec = serde_json::from_value(Value::Object(std::mem::take(&mut map)))?;
spec.check()?;
@@ -3769,50 +3827,12 @@ pub fn apply(doc: &mut Document, op: &Op, out: &mut Applied) -> Result<()> {
Ok::<_, anyhow::Error>(())
})?;
}
- Op::Pixel(spec) => {
- spec.check().with_context(|| format!("pixel on {}", spec.layer))?;
- let path = layer_path(doc, &spec.layer)?;
- let target = doc.layer_at(&path);
- if !target.pixel() {
- bail!(
- "{} is a {} layer; pixels go into pixel layers (klad add <bundle> layer pixel)",
- spec.layer,
- target.kind().name()
- );
- }
- let coverage = spec.coverage(doc).with_context(|| format!("pixel on {}", spec.layer))?;
- let mut fill = match &spec.color {
- Some(color) => {
- let before = doc.palette.clone();
- let (entry, hex) = doc
- .bind_swatch(color)
- .with_context(|| format!("pixel on {}", spec.layer))?;
- if doc.palette != before && !out.changed.iter().any(|c| c == "palette") {
- out.changed.push("palette".into());
- }
- Fill::cells(0, parse_hex(&hex)?, &entry, false, coverage)
- }
- None => Fill::cells(0, [0.0, 0.0, 0.0, 1.0], "", true, coverage),
- }
- .by(match spec.by_hand {
- true => Author::Human,
- false => Author::Agent,
- });
- fill.lock = !fill.erases() && locks_alpha(doc, &spec.layer);
- let cel = paint_cel_at(doc, &spec.layer, spec.frame, out)?;
- out.push(&spec.layer, &cel, MarkChange::Add(vec![Mark::Fill(fill)]));
- if let Some(name) = &spec.part {
- out.push(
- &spec.layer,
- &cel,
- MarkChange::Part {
- name: name.clone(),
- count: 1,
- ids: Vec::new(),
- },
- );
- }
- }
+ Op::Pixel(spec) => put_pixels(doc, spec, out)?,
+ Op::PixelGrid(grid) => grid
+ .specs()
+ .with_context(|| format!("pixel grid on {}", grid.layer))?
+ .iter()
+ .try_for_each(|spec| put_pixels(doc, spec, out))?,
Op::Fill(spec) => {
off_the_grid(doc, &spec.layer, "flood and lasso fills")?;
let mut fill = spec.build(doc).with_context(|| format!("fill on {}", spec.layer))?;
@@ -3963,6 +3983,52 @@ fn edit_path(doc: &mut Document, id: &str, edit: &PathEdit) -> Result<()> {
Ok(())
}
+fn put_pixels(doc: &mut Document, spec: &PixelSpec, out: &mut Applied) -> Result<()> {
+ spec.check().with_context(|| format!("pixel on {}", spec.layer))?;
+ let path = layer_path(doc, &spec.layer)?;
+ let target = doc.layer_at(&path);
+ if !target.pixel() {
+ bail!(
+ "{} is a {} layer; pixels go into pixel layers (klad add <bundle> layer pixel)",
+ spec.layer,
+ target.kind().name()
+ );
+ }
+ let coverage = spec.coverage(doc).with_context(|| format!("pixel on {}", spec.layer))?;
+ let mut fill = match &spec.color {
+ Some(color) => {
+ let before = doc.palette.clone();
+ let (entry, hex) = doc
+ .bind_swatch(color)
+ .with_context(|| format!("pixel on {}", spec.layer))?;
+ if doc.palette != before && !out.changed.iter().any(|c| c == "palette") {
+ out.changed.push("palette".into());
+ }
+ Fill::cells(0, parse_hex(&hex)?, &entry, false, coverage)
+ }
+ None => Fill::cells(0, [0.0, 0.0, 0.0, 1.0], "", true, coverage),
+ }
+ .by(match spec.by_hand {
+ true => Author::Human,
+ false => Author::Agent,
+ });
+ fill.lock = !fill.erases() && locks_alpha(doc, &spec.layer);
+ let cel = paint_cel_at(doc, &spec.layer, spec.frame, out)?;
+ out.push(&spec.layer, &cel, MarkChange::Add(vec![Mark::Fill(fill)]));
+ if let Some(name) = &spec.part {
+ out.push(
+ &spec.layer,
+ &cel,
+ MarkChange::Part {
+ name: name.clone(),
+ count: 1,
+ ids: Vec::new(),
+ },
+ );
+ }
+ Ok(())
+}
+
fn off_the_grid(doc: &Document, layer: &str, what: &str) -> Result<()> {
if doc.layer(layer).is_some_and(Layer::pixel) {
bail!("{layer} is a pixel layer: it takes whole pixels (klad pixel), not {what}");
diff --git a/crates/core/src/pixel.rs b/crates/core/src/pixel.rs
index 1962e3a..0f45313 100644
--- a/crates/core/src/pixel.rs
+++ b/crates/core/src/pixel.rs
@@ -1,6 +1,8 @@
+use crate::doc::Document;
use crate::path;
+use crate::stroke::Mark;
use anyhow::{Result, bail};
-use std::collections::BTreeSet;
+use std::collections::{BTreeMap, BTreeSet};
pub type Cell = [i64; 2];
@@ -142,6 +144,252 @@ pub fn drawn(runs: &[Run], size: u32) -> Vec<Cell> {
.collect()
}
+pub const EMPTY: char = '.';
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Grid {
+ pub width: u32,
+ pub height: u32,
+ pub cells: Vec<Option<String>>,
+}
+
+impl Grid {
+ pub fn at(&self, x: u32, y: u32) -> Option<&str> {
+ self.cells.get((y * self.width + x) as usize)?.as_deref()
+ }
+
+ pub fn keys(&self) -> Vec<&str> {
+ let mut seen = BTreeSet::new();
+ self.cells
+ .iter()
+ .flatten()
+ .map(String::as_str)
+ .filter(|k| seen.insert(*k))
+ .collect()
+ }
+}
+
+pub fn grid_of(marks: &[Mark], width: u32, height: u32) -> Grid {
+ let mut cells: Vec<Option<String>> = vec![None; width as usize * height as usize];
+ crate::stroke::fills_of(marks).filter(|f| f.on_grid()).for_each(|fill| {
+ let key = match fill.entry() {
+ Some(entry) => entry.to_string(),
+ None => crate::color::to_hex(fill.color()),
+ };
+ fill.coverage
+ .cells()
+ .filter(|c| c[0] < width && c[1] < height)
+ .filter(|c| crate::cut::keeps(&fill.cuts, (c[0] as f32 + 0.5, c[1] as f32 + 0.5)))
+ .for_each(|c| {
+ let at = (c[1] * width + c[0]) as usize;
+ match (fill.erases(), fill.lock) {
+ (true, _) => cells[at] = None,
+ (false, true) if cells[at].is_none() => {}
+ (false, _) => cells[at] = Some(key.clone()),
+ }
+ });
+ });
+ Grid { width, height, cells }
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Named {
+ pub sign: char,
+ pub key: String,
+ pub name: String,
+ pub color: String,
+}
+
+const SIGNS: &str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#@%&*+=~^:;!?$";
+
+pub fn legend(doc: &Document, grid: &Grid) -> Vec<Named> {
+ let used: BTreeSet<&str> = grid.keys().into_iter().collect();
+ let entries: Vec<(String, String, String)> = doc
+ .palette
+ .iter()
+ .filter(|s| !s.id.is_empty() && used.contains(s.id.as_str()))
+ .map(|s| (s.id.clone(), s.name.clone(), s.color.clone()))
+ .chain(
+ grid.keys()
+ .into_iter()
+ .filter(|k| doc.entry(k).is_none())
+ .map(|k| (k.to_string(), String::new(), k.to_string())),
+ )
+ .collect();
+ let mut taken: BTreeSet<char> = BTreeSet::new();
+ entries
+ .into_iter()
+ .map(|(key, name, color)| {
+ let wished = name.chars().find(|c| c.is_ascii_alphanumeric());
+ let sign = wished
+ .into_iter()
+ .chain(wished.map(|c| c.to_ascii_uppercase()))
+ .chain(SIGNS.chars())
+ .find(|c| !taken.contains(c))
+ .unwrap_or('?');
+ taken.insert(sign);
+ Named { sign, key, name, color }
+ })
+ .collect()
+}
+
+pub fn rows(grid: &Grid, legend: &[Named]) -> Vec<String> {
+ (0..grid.height)
+ .map(|y| {
+ (0..grid.width)
+ .map(|x| match grid.at(x, y) {
+ Some(key) => legend.iter().find(|n| n.key == key).map_or('?', |n| n.sign),
+ None => EMPTY,
+ })
+ .collect()
+ })
+ .collect()
+}
+
+pub fn plain(grid: &Grid, legend: &[Named]) -> String {
+ let lines = legend.iter().map(|n| {
+ let value = match n.name.is_empty() {
+ true => n.color.as_str(),
+ false => n.name.as_str(),
+ };
+ format!("{} = {value}", n.sign)
+ });
+ std::iter::once(format!("{EMPTY} = empty"))
+ .chain(lines)
+ .chain(std::iter::once(String::new()))
+ .chain(rows(grid, legend))
+ .collect::<Vec<_>>()
+ .join("\n")
+}
+
+pub fn ruled(grid: &Grid, legend: &[Named]) -> String {
+ let pad = grid.height.saturating_sub(1).to_string().len().max(2);
+ let tens: String = (0..grid.width)
+ .map(|x| match x % 10 {
+ 0 => char::from_digit((x / 10) % 10, 10).unwrap_or(' '),
+ _ => ' ',
+ })
+ .collect();
+ let ones: String = (0..grid.width)
+ .map(|x| char::from_digit(x % 10, 10).unwrap_or(' '))
+ .collect();
+ let lines = legend.iter().map(|n| {
+ format!(
+ " {} {}",
+ n.sign,
+ [n.name.as_str(), n.color.as_str(), n.key.as_str()]
+ .iter()
+ .filter(|part| !part.is_empty())
+ .fold(Vec::<&str>::new(), |mut kept, part| {
+ if !kept.contains(part) {
+ kept.push(part);
+ }
+ kept
+ })
+ .join(" ")
+ )
+ });
+ std::iter::once(format!(" {EMPTY} empty"))
+ .chain(lines)
+ .chain([
+ String::new(),
+ format!("{:pad$} {}", "", tens.trim_end()),
+ format!("{:pad$} {ones}", ""),
+ ])
+ .chain(
+ rows(grid, legend)
+ .into_iter()
+ .enumerate()
+ .map(|(y, row)| format!("{y:>pad$} {row}")),
+ )
+ .collect::<Vec<_>>()
+ .join("\n")
+}
+
+pub fn parse_text(text: &str) -> Result<(BTreeMap<String, String>, Vec<String>)> {
+ let lines: Vec<&str> = text.lines().map(str::trim_end).collect();
+ let first = lines.iter().position(|l| !l.trim().is_empty()).unwrap_or(lines.len());
+ let lines = &lines[first..];
+ let Some(gap) = lines.iter().position(|l| l.trim().is_empty()) else {
+ bail!(
+ "a pixel grid is a legend, a blank line, then the rows: lines like \"i = ink\" first, then rows like \"..iiii..\""
+ );
+ };
+ let legend = lines[..gap]
+ .iter()
+ .map(|line| {
+ let line = line.trim();
+ let sign = line.chars().next().unwrap_or(' ');
+ let rest = line[sign.len_utf8()..].trim_start();
+ match rest.strip_prefix('=') {
+ Some(value) if !sign.is_whitespace() && !value.trim().is_empty() => {
+ Ok((sign.to_string(), value.trim().to_string()))
+ }
+ _ => bail!(
+ "{line:?} is not a legend line: one character, =, then a palette name, a colour, erase or empty"
+ ),
+ }
+ })
+ .collect::<Result<BTreeMap<_, _>>>()?;
+ let rows: Vec<String> = lines[gap..]
+ .iter()
+ .skip_while(|l| l.trim().is_empty())
+ .map(|l| l.trim().to_string())
+ .collect();
+ let rows: Vec<String> = rows
+ .iter()
+ .take(rows.iter().rposition(|r| !r.is_empty()).map_or(0, |last| last + 1))
+ .cloned()
+ .collect();
+ if rows.is_empty() {
+ bail!("the pixel grid has a legend but no rows after the blank line");
+ }
+ Ok((legend, rows))
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum Sign {
+ Empty,
+ Erase,
+ Colour(String),
+}
+
+pub fn meaning(legend: &BTreeMap<String, String>, sign: char) -> Option<Sign> {
+ match legend.get(&sign.to_string()).map(|v| v.trim()) {
+ Some("empty" | "skip") => Some(Sign::Empty),
+ Some("erase") => Some(Sign::Erase),
+ Some(value) => Some(Sign::Colour(value.to_string())),
+ None if sign == EMPTY => Some(Sign::Empty),
+ None => None,
+ }
+}
+
+pub fn placed(rows: &[String], legend: &BTreeMap<String, String>, at: Cell) -> Result<Vec<(char, Sign, Vec<Cell>)>> {
+ let mut found: Vec<(char, Sign, Vec<Cell>)> = Vec::new();
+ rows.iter().enumerate().try_for_each(|(y, row)| {
+ row.chars().enumerate().try_for_each(|(x, sign)| {
+ let cell = [at[0] + x as i64, at[1] + y as i64];
+ match found.iter_mut().find(|(s, _, _)| *s == sign) {
+ Some((_, _, cells)) => cells.push(cell),
+ None => {
+ let Some(meaning) = meaning(legend, sign) else {
+ bail!(
+ "row {y}, column {x} holds {sign:?}, which the legend does not name: it has {}",
+ legend.keys().map(String::as_str).collect::<Vec<_>>().join(" ")
+ );
+ };
+ found.push((sign, meaning, vec![cell]));
+ }
+ }
+ Ok(())
+ })
+ })?;
+ Ok(found
+ .into_iter()
+ .filter(|(_, meaning, _)| !matches!(meaning, Sign::Empty))
+ .collect())
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -220,4 +468,112 @@ mod tests {
);
assert!(of_path("").is_err());
}
+
+ #[test]
+ fn a_layer_reads_as_a_grid_of_signs_and_a_grid_text_reads_back_as_the_same_pixels() {
+ use crate::doc::Swatch;
+ use crate::fill::{Coverage, Fill};
+ let swatch = |color: &str, name: &str, id: &str| Swatch {
+ color: color.into(),
+ name: name.into(),
+ id: id.into(),
+ ramp: String::new(),
+ };
+ let mut doc = Document::new(6, 4);
+ doc.palette = vec![
+ swatch("#22223b", "ink", "p1"),
+ swatch("#f2c14e", "iris", "p2"),
+ swatch("#ffffff", "", "p3"),
+ swatch("#000000", "unused", "p4"),
+ ];
+ let cells = |list: &[[u32; 2]]| Coverage::from_cells(list);
+ let colour = |hex: &str| crate::color::parse_hex(hex).unwrap();
+ let mut locked = Fill::cells(4, colour("#ffffff"), "p3", false, cells(&[[1, 1], [5, 3]]));
+ locked.lock = true;
+ let mut cut = Fill::cells(6, colour("#f2c14e"), "p2", false, cells(&[[0, 3], [1, 3], [2, 3]]));
+ cut.cuts = vec![crate::cut::Cut {
+ keep: crate::cut::Keep::Inside,
+ polygon: vec![[0.0, 2.9], [2.0, 2.9], [2.0, 4.1], [0.0, 4.1]],
+ }];
+ let marks: Vec<Mark> = vec![
+ Fill::cells(
+ 1,
+ colour("#22223b"),
+ "p1",
+ false,
+ cells(&[[0, 0], [1, 0], [2, 0], [1, 1]]),
+ )
+ .into(),
+ Fill::cells(2, colour("#f2c14e"), "p2", false, cells(&[[2, 0], [3, 0]])).into(),
+ Fill::cells(3, colour("#000000"), "", true, cells(&[[0, 0], [4, 2]])).into(),
+ locked.into(),
+ Fill::cells(5, colour("#ff00ff"), "", false, cells(&[[5, 0]])).into(),
+ cut.into(),
+ ];
+ let grid = grid_of(&marks, 6, 4);
+ assert_eq!(grid.at(0, 0), None, "an erased pixel is empty");
+ assert_eq!(grid.at(2, 0), Some("p2"), "a later mark covers an earlier one");
+ assert_eq!(grid.at(1, 1), Some("p3"), "a locked mark paints where there is paint");
+ assert_eq!(grid.at(5, 3), None, "and nowhere else");
+ assert_eq!(
+ grid.at(5, 0),
+ Some("#ff00ff"),
+ "a mark bound to nothing shows by its colour"
+ );
+ assert_eq!(
+ (grid.at(1, 3), grid.at(2, 3)),
+ (Some("p2"), None),
+ "a cut mark shows only its kept side"
+ );
+ let named = legend(&doc, &grid);
+ let signs: Vec<(char, &str)> = named.iter().map(|n| (n.sign, n.key.as_str())).collect();
+ assert_eq!(
+ signs,
+ [('i', "p1"), ('I', "p2"), ('a', "p3"), ('b', "#ff00ff")],
+ "the first letter of the name, its capital when taken, then the next free sign; unused colours get none"
+ );
+ assert_eq!(rows(&grid, &named), [".iII.b", ".a....", "......", "II...."]);
+ let text = plain(&grid, &named);
+ assert_eq!(
+ text,
+ ". = empty\ni = ink\nI = iris\na = #ffffff\nb = #ff00ff\n\n.iII.b\n.a....\n......\nII...."
+ );
+ let ruled = ruled(&grid, &named);
+ assert!(
+ ruled.contains(" i ink #22223b p1") && ruled.contains(" 0 .iII.b"),
+ "{ruled}"
+ );
+ let (read_legend, read_rows) = parse_text(&format!("\n{text}\n\n")).unwrap();
+ assert_eq!(read_rows, rows(&grid, &named));
+ let placed = placed(&read_rows, &read_legend, [10, 20]).unwrap();
+ let drawn: Vec<(char, usize)> = placed.iter().map(|(sign, _, cells)| (*sign, cells.len())).collect();
+ assert_eq!(drawn, [('i', 1), ('I', 4), ('b', 1), ('a', 1)]);
+ assert_eq!(placed[0].2, [[11, 20]], "the grid lands where it is put");
+ let erasing: BTreeMap<String, String> = [("x", "erase"), ("o", "ink")]
+ .iter()
+ .map(|(k, v)| (k.to_string(), v.to_string()))
+ .collect();
+ let both = super::placed(&["xo.".to_string()], &erasing, [0, 0]).unwrap();
+ assert!(matches!(both[0].1, Sign::Erase) && matches!(&both[1].1, Sign::Colour(c) if c == "ink"));
+ let unnamed = super::placed(&["o?".to_string()], &erasing, [0, 0])
+ .unwrap_err()
+ .to_string();
+ assert!(
+ unnamed.contains("row 0, column 1") && unnamed.contains("'?'"),
+ "{unnamed}"
+ );
+ assert!(
+ parse_text("i = ink\n..ii..")
+ .unwrap_err()
+ .to_string()
+ .contains("a blank line")
+ );
+ assert!(
+ parse_text("ink\n\n..ii..")
+ .unwrap_err()
+ .to_string()
+ .contains("not a legend line")
+ );
+ assert!(parse_text("i = ink\n\n\n").unwrap_err().to_string().contains("no rows"));
+ }
}
diff --git a/docs/DESIGN.md b/docs/DESIGN.md
index 24a81b2..eecb48b 100644
--- a/docs/DESIGN.md
+++ b/docs/DESIGN.md
@@ -1,4 +1,4 @@
-_Last updated: 2026-11-11 18:30_
+_Last updated: 2026-11-11 19:40_
# klad: design
@@ -232,7 +232,7 @@ Unknown keys are errors that list the valid ones, so a typo never passes silentl
Every layer has `blend`, `opacity`, `visible`, `locked`, optional `mask`, `clip` and (M5, format 8) `effects`. Effects are layer settings, not a layer kind: the planned `filter` kind became them.
-- **Pixel layers (M9).** A pixel layer is a paint layer flagged `pixel`, so it shares cels, masks, clipping, lock alpha, effects, the timeline and every export with paint layers. One pixel is one canvas pixel: a 64x64 sprite is a 64x64 drawing shown enlarged, and a drawing never mixes pixel sizes. Its marks stay data, as strokes do: a pixel mark is a fill record whose source is cells (`FillSource::Cells`), a set of whole pixels (coverage 0 or 255) with the id of the palette swatch it was drawn with, or a set of pixels to erase. So the same addresses, `set`, `rm`, `transform`, lasso, copy and history work on them; scaling, flipping and turning sample the nearest pixel (`markedit::resampled` with `hard`), which also makes an export above full size hard-edged. Colours are palette entries: `Document::bind_swatch` finds or adds the swatch and gives it an `id` the first time a mark uses it, and `set color=` on a pixel mark binds it to the new entry. The `pixel` op (`klad pixel`) is the first way to make marks; brush strokes and flood or lasso fills are refused on a pixel layer (`ops::off_the_grid`). A drawing with a pixel layer (`Document::pixel_art`) gets a sharp view on both sides. In the editor the zoom moves in whole screen pixels per pixel above real size (`View::whole`, `View::fit_whole`; free below it), a pixel grid shows from 8 screen pixels per pixel (a dark line with light dashes, so it reads on any colour; View > Pixel grid), the pixel under the pointer is outlined on a pixel layer and named in the status line, and the Real size pane (`Pane::Preview`, opened the first time a pixel drawing is opened) shows the composed frame at 1, 2 or 4 screen pixels per pixel for drawings up to 512 px. In the CLI, `klad render` and edit previews enlarge by a whole number to about 512 px (`agent::pixel_scale`), and `--overlay grid` draws the same lines with the pixel numbers along the top and left (`overlay::draw_cells`). The palette is what a pixel drawing is bound to. A mark stores its swatch's id and its colour, so every reader of a stroke file draws it without the palette; when a palette edit changes a swatch's colour, `ops::follow_palette` adds a `MarkChange::Entry` for every pixel drawing, which rewrites the colour of the marks bound to that swatch in the same transaction (one undo step), and a removed swatch unbinds its marks. A palette rewritten without ids keeps them by name, then by colour (`carry_ids`). Swatches carry an optional `ramp` name: a ramp is the swatches sharing it, in palette order, dark to light (`palettes::ramp` makes one from a base colour with `color::value_step`, darker and cooler to lighter and warmer). Palettes that come with klad are colour lists in `core/src/palettes.rs` (`klad palettes`), and `palettes::parse` reads a list of hex colours or a GIMP palette. The pencil is grid geometry in `core/src/pixel.rs`, shared by both hands: `line` (Bresenham), `extend` (a run that follows the pen with no holes), `perfect` (drops the corner pixel of an L, so a hand-drawn line stays one pixel thin), `stamp` (a size is a square of whole pixels) and `of_path` (SVG path data flattened and traced; corners the path asks for are kept, the corners that flattening a curve leaves are not). The `pixel` op takes `cells` or a `path`, and a `size`. In the editor the brush tool on a pixel layer is the pencil (the eraser command and the pen's eraser end erase): the run is drawn over the canvas as it grows and committed on release as one `pixel` op marked as made by hand, so the palette binding, history and sync are the op's. Shift click draws a straight line from the last pixel; `[` and `]` change the size. Shapes, shading, sharp exports and Aseprite files follow in the milestone's later stories.
+- **Pixel layers (M9).** A pixel layer is a paint layer flagged `pixel`, so it shares cels, masks, clipping, lock alpha, effects, the timeline and every export with paint layers. One pixel is one canvas pixel: a 64x64 sprite is a 64x64 drawing shown enlarged, and a drawing never mixes pixel sizes. Its marks stay data, as strokes do: a pixel mark is a fill record whose source is cells (`FillSource::Cells`), a set of whole pixels (coverage 0 or 255) with the id of the palette swatch it was drawn with, or a set of pixels to erase. So the same addresses, `set`, `rm`, `transform`, lasso, copy and history work on them; scaling, flipping and turning sample the nearest pixel (`markedit::resampled` with `hard`), which also makes an export above full size hard-edged. Colours are palette entries: `Document::bind_swatch` finds or adds the swatch and gives it an `id` the first time a mark uses it, and `set color=` on a pixel mark binds it to the new entry. The `pixel` op (`klad pixel`) is the first way to make marks; brush strokes and flood or lasso fills are refused on a pixel layer (`ops::off_the_grid`). A drawing with a pixel layer (`Document::pixel_art`) gets a sharp view on both sides. In the editor the zoom moves in whole screen pixels per pixel above real size (`View::whole`, `View::fit_whole`; free below it), a pixel grid shows from 8 screen pixels per pixel (a dark line with light dashes, so it reads on any colour; View > Pixel grid), the pixel under the pointer is outlined on a pixel layer and named in the status line, and the Real size pane (`Pane::Preview`, opened the first time a pixel drawing is opened) shows the composed frame at 1, 2 or 4 screen pixels per pixel for drawings up to 512 px. In the CLI, `klad render` and edit previews enlarge by a whole number to about 512 px (`agent::pixel_scale`), and `--overlay grid` draws the same lines with the pixel numbers along the top and left (`overlay::draw_cells`). The palette is what a pixel drawing is bound to. A mark stores its swatch's id and its colour, so every reader of a stroke file draws it without the palette; when a palette edit changes a swatch's colour, `ops::follow_palette` adds a `MarkChange::Entry` for every pixel drawing, which rewrites the colour of the marks bound to that swatch in the same transaction (one undo step), and a removed swatch unbinds its marks. A palette rewritten without ids keeps them by name, then by colour (`carry_ids`). Swatches carry an optional `ramp` name: a ramp is the swatches sharing it, in palette order, dark to light (`palettes::ramp` makes one from a base colour with `color::value_step`, darker and cooler to lighter and warmer). Palettes that come with klad are colour lists in `core/src/palettes.rs` (`klad palettes`), and `palettes::parse` reads a list of hex colours or a GIMP palette. The pencil is grid geometry in `core/src/pixel.rs`, shared by both hands: `line` (Bresenham), `extend` (a run that follows the pen with no holes), `perfect` (drops the corner pixel of an L, so a hand-drawn line stays one pixel thin), `stamp` (a size is a square of whole pixels) and `of_path` (SVG path data flattened and traced; corners the path asks for are kept, the corners that flattening a curve leaves are not). The `pixel` op takes `cells` or a `path`, and a `size`. In the editor the brush tool on a pixel layer is the pencil (the eraser command and the pen's eraser end erase): the run is drawn over the canvas as it grows and committed on release as one `pixel` op marked as made by hand, so the palette binding, history and sync are the op's. Shift click draws a straight line from the last pixel; `[` and `]` change the size. 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, shading, sharp exports and Aseprite files follow in the milestone's later stories.
- **Blend modes.** `normal`, `multiply`, `screen`, `overlay`, `add`, and since M5 `color-dodge`, `soft-light`, `hard-light`, `lighten`, `darken`, `color`, `luminosity`, all as in the W3C compositing spec (Skia's modes; `look::blend_rgb` and `look::composite` hold the formulas the tests check them against).
- **Effects (M5).** `"effects": [{"glow": {...}}, {"outline": {...}}]`, applied in order to the layer's content (after its mask; for a clip base, to the base and its clipped layers together) before its opacity and blend: `blur` (radius, a Gaussian sigma), `glow` (radius, strength, threshold: 0 glows from every pixel, higher only from the bright ones; color: a tint; blend: how the glow mixes with what is under the layer, screen by default, normal lays it like paint under the layer), `outline` (width, color, inside), `shadow` (x, y, radius, color, laid under the layer), `noise` (amount, size, seed, mono: a grain fixed to the canvas), `displace` (amount, size, seed, by: smooth waves, or a layer whose red pushes across and green down), `relief` (strength, light, highlight, shade, softness: lights the paint height of the layer's drawings, below). Each effect knows its reach (`look::reach`), so a tile is composed from its content within the tile plus that margin and tiles meet without seams (noise and haze read only their own pixel and add no margin, so they cost no neighbouring tiles); a tile skips a clip stack or group that puts no pixel in it (none of its rasters, live tiles or onion ghosts has a tile in the tile grown by its effects' margin; layers moved by keys, adjustment layers and vector layers drawn from their nodes always count), which leaves the tile the same since every blend leaves the pixels under a transparent layer as they are; the pixels are computed in Rust (`klad-render/effects.rs`) on f32 with absolute coordinates, so a tile equals the same pixels of the whole image byte for byte (tested). Blurs use a direct kernel, below a sigma of 2 at full size and above it on a grid of 2, 4, ... px blocks anchored to the canvas, then sampled back.
- **Adjustment layers (M5).** An `adjust` layer changes what is under it in its list: the layers below it in its group, or, clipped, its base. A group holding an adjustment is composed apart, so the adjustment stays inside it. The colour math is on unpremultiplied sRGB values with alpha kept: `hsl` (hue in degrees, saturation and lightness -1..1), `levels` (black, white, gamma, low, high), `curves` (points, and red, green, blue applied before them; monotone cubic, no overshoot), `balance` (shadows, midtones, highlights: cyan to red, magenta to green, yellow to blue, keepLight), `gradient-map` (stops by brightness). The layer's opacity, blend and mask decide how much of the adjusted colour replaces the colour under it. `fill` (a solid or gradient paint) is drawn like a content layer instead, with the layer's blend.
diff --git a/docs/cli.md b/docs/cli.md
index 8fee008..329ae9a 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -62,6 +62,7 @@ This reference is licensed under the MIT License (`LICENSE-MIT`), unlike klad it
- [`klad gaps`](#klad-gaps): List closed regions of the lines that no fill on the layer covers
- [`klad refill`](#klad-refill): Recompute the flood fills of a paint cel after the lines they were made from changed
- [`klad palette`](#klad-palette): The document palette: list it, --add or --rm a colour, --recolour one, --load a palette, or group colours in a --ramp
+- [`klad pixels`](#klad-pixels): Read a pixel layer as a grid of characters, one per pixel, with a legend of its palette colours
- [`klad palettes`](#klad-palettes): The palettes that come with klad, to load with klad palette <bundle> --load <name>
- [`klad export`](#klad-export): Export PNGs, sprite sheets, numbered frames or a Godot SpriteFrames and scene
- [`klad brushes`](#klad-brushes): List brushes: the library, and with a bundle the ones it embeds
@@ -1658,7 +1659,19 @@ Put whole pixels of one palette colour on a pixel layer, or erase them. A pixel
klad pixel sprite.klad l1 --color skin --cells '4-11,5-9'
klad pixel sprite.klad l1 --erase --cells '7,7 8,7'
-Also a pixel op in klad apply: {"op":"pixel","layer":"l1","color":"skin","cells":[[4,5],[5,5]]}, with "path":"M3.5 3.5 L9.5 3.5" in place of cells, "size":2, or "erase":true.
+--grid draws a whole sprite from text, the way klad pixels --plain prints one: legend lines (one character, =, a palette name, a colour, erase or empty), a blank line, then a row of characters per row of pixels. . is empty unless the legend says otherwise. Each character becomes one mark bound to its colour; --at x,y moves the grid's top left.
+
+ klad pixel sprite.klad l1 --grid - <<'GRID'
+ i = ink
+ b = body
+
+ ..iiii..
+ .ibbbbi.
+ .ibbbbi.
+ ..iiii..
+ GRID
+
+Also a pixel op in klad apply: {"op":"pixel","layer":"l1","color":"skin","cells":[[4,5],[5,5]]}, with "path":"M3.5 3.5 L9.5 3.5" in place of cells, "size":2, or "erase":true; and as a grid {"op":"pixel","layer":"l1","rows":["..ii..",".ibbi."],"legend":{"i":"ink","b":"body"},"at":[0,0]}.
Usage: klad pixel [OPTIONS] <BUNDLE> <LAYER>
@@ -1673,6 +1686,14 @@ Options:
--cells <CELLS>
The pixels: x,y, a row run x0-x1,y, a column run x,y0-y1 or a block x0-x1,y0-y1, separated by spaces
+ --grid <FILE>
+ Draw a grid of characters from a file (- reads stdin): a legend (i = ink), a blank line, then one row of characters per row of pixels
+
+ --at <AT>
+ Where the grid's top left pixel goes: x,y
+
+ [default: 0,0]
+
--path <PATH>
SVG path data drawn as a line of pixels, one pixel wide with no doubled corners on curves: 'M3.5 20.5 C 10 4 22 4 28.5 20.5'
@@ -3146,6 +3167,40 @@ Options:
Print help (see a summary with '-h')
```
+## klad pixels
+
+```text
+Read a pixel layer as a grid of characters, one per pixel, with a legend of its palette colours. It is what the layer shows at the frame: later marks over earlier ones, erased pixels empty. Each colour gets a character (the first letter of its palette name where that is free), . is an empty pixel, and the numbers along the top and the left count the pixels.
+
+ klad pixels sprite.klad l1
+ klad pixels sprite.klad l1 --plain > sprite.txt (the form klad pixel --grid reads back)
+ klad pixels sprite.klad l1 --json
+
+To draw from such a text: klad pixel sprite.klad l1 --grid sprite.txt. Each character of the legend becomes one mark bound to its colour.
+
+Usage: klad pixels [OPTIONS] <BUNDLE> <LAYER>
+
+Arguments:
+ <BUNDLE>
+
+
+ <LAYER>
+
+
+Options:
+ --frame <FRAME>
+ [default: 0]
+
+ --plain
+ Only the legend and the rows, as klad pixel --grid reads them
+
+ --json
+
+
+ -h, --help
+ Print help (see a summary with '-h')
+```
+
## klad palettes
```text
diff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.md
index 0beff7c..f6b75f0 100644
--- a/docs/skill/SKILL.md
+++ b/docs/skill/SKILL.md
@@ -104,23 +104,35 @@ klad lasso art.klad l4 --polygon '...' --cut --rm
```
klad new sprite.klad --pixel 32x32 a pixel drawing: one pixel layer, l1
klad add art.klad layer pixel name=sprite a pixel layer in any drawing
-klad pixel sprite.klad l1 --color '#2b2d42' --cells '3-12,2 3,3-8 12,3-8 3-12,9'
-klad pixel sprite.klad l1 --color skin --cells '4-11,3-8'
-klad pixel sprite.klad l1 --erase --cells '7,5 8,5'
-klad pixel sprite.klad l1 --color '#2b2d42' --path 'M3.5 20.5 C 10 4 22 4 28.5 20.5' a curve, one pixel thin
+klad palette sprite.klad --add '#22223b' --name ink name the colours first
+klad pixel sprite.klad l1 --grid - <<'GRID' a sprite as text: a legend, a blank line, the rows
+i = ink
+b = body
+
+..iiii..
+.ibbbbi.
+.ibbbbi.
+..iiii..
+GRID
+klad pixels sprite.klad l1 read the layer back as text, with numbered rows and columns
klad render sprite.klad --overlay grid enlarged, with numbered pixel lines
+klad pixel sprite.klad l1 --color ink --cells '3-12,2 3,3-8' single pixels, runs and blocks
+klad pixel sprite.klad l1 --color ink --path 'M3.5 20.5 C 10 4 22 4 28.5 20.5' a curve, one pixel thin
+klad pixel sprite.klad l1 --erase --cells '7,5 8,5'
klad export sprite.klad --scale 8 -o [email protected] square pixels, to keep
```
- A pixel layer is a grid with no soft edges, and one pixel is one canvas pixel: a 32x32 sprite is a 32x32 drawing. Size the drawing in pixels of the art, not of the screen; `klad ls` shows the layer as `pixel`.
-- `--cells` takes `x,y` for one pixel, `x0-x1,y` for a run along a row, `x,y0-y1` for a run down a column and `x0-x1,y0-y1` for a block, separated by spaces. Pixels off the canvas are dropped.
+- Draw a sprite as a grid of characters: `klad pixel <bundle> <layer> --grid <file>` (`-` reads stdin). Legend lines come first (one character, `=`, then a palette name, a colour, `erase` or `empty`), then a blank line, then one row of characters per row of pixels. `.` is empty (it leaves what is there) unless the legend says otherwise; a character the legend does not name is an error that says where. `--at x,y` puts the grid's top left pixel elsewhere, so a part (an eye, a hand) can be a small grid of its own. Each character becomes one mark bound to its colour, so a whole sprite is a handful of marks you can recolour or move.
+- Read before you change: `klad pixels <bundle> <layer>` prints what the layer shows as the same kind of grid, with a legend (each colour's character, name, hex and id) and the pixel numbers along the top and the left. `--plain` prints only the legend and rows, in the form `--grid` reads, so a sprite can be read, edited as text and written to an empty layer or frame; `--json` gives `rows` and `legend`. Reading the text is exact; the picture is for judging how it looks.
+- For a few pixels use `--cells`: `x,y` for one pixel, `x0-x1,y` for a run along a row, `x,y0-y1` for a run down a column and `x0-x1,y0-y1` for a block, separated by spaces. Pixels off the canvas are dropped.
- `--path` draws SVG path data as a line of pixels, for outlines and curves that would be tedious as cells. A pixel is the square from `x,y` to `x+1,y+1`, so aim at pixel middles (`3.5`, not `3`). Straight segments keep the corners they are given; curves come out one pixel thin with no doubled corners. `--size 2` (1 to 64) makes the pencil a square of that many pixels, for `--cells` and `--path` alike. In `apply`: `"path":"M3.5 3.5 L9.5 3.5"` in place of `cells`, and `"size":2`.
- `--color` is a palette name, a palette index or `#rrggbb`. Every pixel mark is bound to a palette entry: a colour the palette lacks is added to it, so name the colours first (`klad palette sprite.klad --add '#f0c8a0' --name skin`) and draw with the names. `klad palette` lists the entries with their ids.
- The palette is the drawing's colours, and changing one changes the picture: `klad palette sprite.klad --recolour skin --to '#e8b796'` (a name, a colour, an index or an id) recolours every pixel mark drawn with it, on every frame. So fix a colour in the palette, not mark by mark. `klad palette sprite.klad --load pico-8` adds a palette that comes with klad (`klad palettes` lists them: pico-8, sweetie-16, dawnbringer-16, dawnbringer-32, endesga-32, resurrect-64, aap-64, gameboy, 1-bit) or a file (`.hex`, one colour per line, or a GIMP `.gpl`); colours the palette holds are not added twice. A ramp is a row of colours for one material, dark to light: `klad palette sprite.klad --ramp wood --base '#8b5a2b' --steps 5` makes `wood-1` (dark, cooler) to `wood-5` (light, warmer) around the base, and `--ramp skin --of skin-dark,skin,skin-light` groups colours it has. Shade a form with the steps of its ramp, not with new colours.
-- Each call makes one mark, `<cel>:s<id>`, that stays editable: `klad set sprite.klad c2:s1 color=shadow` recolours it (and binds it to that entry), `klad transform ... --move 2,0` moves it by whole pixels, `--flip h` and `--rotate 90` keep it hard, `klad rm` removes it. `klad strokes sprite.klad l1` lists the marks with their entry and cell count; `--json` gives each one's `cells`.
-- Later marks cover earlier ones; `--erase` makes a mark that clears what was drawn before it at those pixels (remove that mark and the pixels come back).
+- Each mark, `<cel>:s<id>`, stays editable: `klad set sprite.klad c2:s1 color=shadow` recolours it (and binds it to that entry), `klad transform ... --move 2,0` moves it by whole pixels, `--flip h` and `--rotate 90` keep it hard, `klad rm` removes it. `klad strokes sprite.klad l1` lists the marks with their entry and cell count; `--json` gives each one's `cells`.
+- Later marks cover earlier ones; `--erase` (or `erase` in a grid's legend) makes a mark that clears what was drawn before it at those pixels (remove that mark and the pixels come back).
- Looking: `klad render` and the `--render` preview of an edit enlarge a pixel drawing by a whole number to about 512 px, so every pixel is a square you can see (`--scale 1` gives the real size, which is how the player sees it: check there too). `--overlay grid` draws a line between pixels and numbers them along the top and the left, so a pixel's `x,y` can be read off the picture: the number is on the line where that column or row starts. `klad export --scale 8` (whole numbers) writes the enlarged PNG to keep.
-- In `apply`: `{"op":"pixel","layer":"l1","color":"skin","cells":[[4,5],[5,5]]}` or `"erase":true`. Brush strokes (`klad stroke`, `ink`, `paint`, ...) and `klad fill` are refused on a pixel layer.
+- In `apply`: `{"op":"pixel","layer":"l1","color":"skin","cells":[[4,5],[5,5]]}`, with `"erase":true`, or a grid: `{"op":"pixel","layer":"l1","rows":["..ii..",".ibbi."],"legend":{"i":"ink","b":"body"},"at":[0,0]}`. Brush strokes (`klad stroke`, `ink`, `paint`, ...) and `klad fill` are refused on a pixel layer.
## Masks, clipping and lock alpha