Skip to content

armgit / klad

Public Imported from GitHub
0

A drawing app built for agent/human collaboration

Rust

Stroke files record what a modifier stroke is attached to: klad/6

Indicode BVe0110008f516
diff --git a/crates/brush/tests/edit_time.rs b/crates/brush/tests/edit_time.rs
new file mode 100644
index 0000000..4a33434
--- /dev/null
+++ b/crates/brush/tests/edit_time.rs
@@ -0,0 +1,48 @@
+use klad_brush::{BrushSet, CelReplay};
+use klad_core::bundle::Bundle;
+use klad_core::markedit::{self, MarkChange, MarkTransform};
+use std::time::Instant;
+
+#[test]
+#[ignore]
+fn edit_time() {
+ let Ok(path) = std::env::var("KLAD_EDIT_BUNDLE") else {
+ eprintln!("set KLAD_EDIT_BUNDLE, KLAD_EDIT_LAYER and KLAD_EDIT_MARK (an address like c8:s120)");
+ return;
+ };
+ let layer = std::env::var("KLAD_EDIT_LAYER").unwrap();
+ let mark = std::env::var("KLAD_EDIT_MARK").unwrap();
+ let (cel, id) = markedit::parse_address(&mark).unwrap();
+ let bundle = Bundle::open(&path).unwrap();
+ let brushes = BrushSet::for_bundle(&bundle).unwrap();
+ let marks = bundle.read_marks(&layer, cel).unwrap();
+ let (w, h) = (bundle.doc.canvas.width, bundle.doc.canvas.height);
+ let start = Instant::now();
+ let (mut replay, mut raster, _) = CelReplay::replay(w, h, marks.clone(), &brushes).unwrap();
+ println!("replay in order: {:.0} ms for {} marks", start.elapsed().as_secs_f64() * 1000.0, marks.len());
+ let mut current = marks;
+ let times: Vec<(f64, usize, bool)> = [6.0f32, -6.0, 6.0, -6.0, 6.0]
+ .iter()
+ .map(|dx| {
+ let mut change = MarkChange::Transform {
+ ids: vec![id],
+ transform: MarkTransform {
+ x: *dx,
+ ..Default::default()
+ },
+ };
+ markedit::apply(&mut current, &mut change, cel, bundle.doc.mark_ids(cel)).unwrap();
+ let start = Instant::now();
+ let updated = replay.update(&mut raster, current.clone(), &brushes).unwrap();
+ (start.elapsed().as_secs_f64() * 1000.0, updated.replayed, updated.full)
+ })
+ .collect();
+ let mut ms: Vec<f64> = times.iter().map(|t| t.0).collect();
+ ms.sort_by(f64::total_cmp);
+ println!(
+ "move {mark} by 6 px: median {:.1} ms, {} marks replayed, full rebuild {}",
+ ms[ms.len() / 2],
+ times[0].1,
+ times[0].2
+ );
+}
diff --git a/crates/core/src/doc.rs b/crates/core/src/doc.rs
index 45814df..b5f1b9c 100644
--- a/crates/core/src/doc.rs
+++ b/crates/core/src/doc.rs
@@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize};
use std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet};
-pub const FORMAT: &str = "klad/5";
+pub const FORMAT: &str = "klad/6";
pub const MAX_SIZE: u32 = 16384;
pub const MASK: usize = usize::MAX;
diff --git a/crates/core/src/migrate.rs b/crates/core/src/migrate.rs
index be25e6e..963f71d 100644
--- a/crates/core/src/migrate.rs
+++ b/crates/core/src/migrate.rs
@@ -10,7 +10,7 @@ pub fn migrate(value: Value) -> Result<Value> {
.to_string();
match format.as_str() {
FORMAT => Ok(value),
- "klad/4" => Ok(uncount(value)),
+ "klad/4" | "klad/5" => Ok(uncount(value)),
"klad/1" | "klad/2" | "klad/3" => {
let mut value = value;
if let Some(layers) = value.get_mut("layers").and_then(Value::as_array_mut) {
@@ -77,6 +77,11 @@ mod tests {
json!({"format": FORMAT, "layers": []}),
"klad/5 keeps no counters in doc.json: they live in the copy's .cache"
);
+ assert_eq!(
+ migrate(json!({"format": "klad/5", "layers": []})).unwrap(),
+ json!({"format": FORMAT, "layers": []}),
+ "klad/6 adds attachments to stroke files; a klad/5 drawing opens unchanged"
+ );
assert_eq!(
migrate(first).unwrap(),
moved,
diff --git a/crates/core/src/stroke.rs b/crates/core/src/stroke.rs
index 4e10d76..3796352 100644
--- a/crates/core/src/stroke.rs
+++ b/crates/core/src/stroke.rs
@@ -10,7 +10,8 @@ pub const TILT_STEPS: f32 = 127.0;
pub const ZSTD_LEVEL: i32 = 3;
const MAGIC: &[u8; 4] = b"KLST";
const OLD_MAGIC: &[u8; 4] = b"DAST";
-const VERSION: u8 = 1;
+const VERSION: u8 = 2;
+const READS: [u8; 2] = [1, 2];
const MARK_STROKE: u8 = 0;
const MARK_FILL: u8 = 1;
const HAS_TILT: u8 = 1;
@@ -19,6 +20,7 @@ const HAS_TAPER: u8 = 4;
const HAS_LOCK: u8 = 8;
const HAS_CUTS: u8 = 16;
const HAS_SECOND: u8 = 32;
+const HAS_ON: u8 = 64;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Sample {
@@ -85,6 +87,7 @@ pub struct Stroke {
pub lock: bool,
pub cuts: Vec<Cut>,
pub second: Option<[u16; 4]>,
+ pub on: Vec<u32>,
pub samples: Vec<Sample>,
}
@@ -103,6 +106,7 @@ impl Stroke {
lock: false,
cuts: Vec::new(),
second: None,
+ on: Vec::new(),
samples: Vec::new(),
}
}
@@ -160,6 +164,7 @@ impl Stroke {
(self.lock, HAS_LOCK),
(!self.cuts.is_empty(), HAS_CUTS),
(self.second.is_some(), HAS_SECOND),
+ (!self.on.is_empty(), HAS_ON),
]
.iter()
.filter(|(on, _)| *on)
@@ -214,6 +219,10 @@ fn encode_stroke(out: &mut Vec<u8>, stroke: &Stroke) {
if let Some(second) = stroke.second {
second.iter().for_each(|c| out.extend_from_slice(&c.to_le_bytes()));
}
+ if channels & HAS_ON != 0 {
+ varint::put(out, stroke.on.len() as u64);
+ put_column(out, stroke.on.iter().map(|&id| id as i64));
+ }
varint::put(out, stroke.samples.len() as u64);
let s = &stroke.samples;
put_column(out, s.iter().map(|v| v.x as i64));
@@ -259,6 +268,16 @@ fn decode_stroke(reader: &mut Reader) -> Result<Stroke> {
} else {
None
};
+ let on = match channels & HAS_ON != 0 {
+ true => {
+ let count = reader.varint()? as usize;
+ read_column(reader, count)?
+ .into_iter()
+ .map(|id| Ok(u32::try_from(id)?))
+ .collect::<Result<Vec<_>>>()?
+ }
+ false => Vec::new(),
+ };
let n = reader.varint()? as usize;
let xs = read_column(reader, n)?;
let ys = read_column(reader, n)?;
@@ -299,6 +318,7 @@ fn decode_stroke(reader: &mut Reader) -> Result<Stroke> {
lock,
cuts,
second,
+ on,
samples,
})
}
@@ -448,8 +468,8 @@ pub fn decode_raw(bytes: &[u8]) -> Result<Vec<Mark>> {
_ => bail!("not a stroke file"),
}
let version = reader.u8()?;
- if version != VERSION {
- bail!("stroke file version {version} is not {VERSION}");
+ if !READS.contains(&version) {
+ bail!("stroke file version {version} is not one of {READS:?}: made by a newer klad");
}
let count = reader.varint()? as usize;
let marks = (0..count)
@@ -498,6 +518,32 @@ mod tests {
assert_eq!(back, vec![Mark::Stroke(stroke)]);
}
+ #[test]
+ fn attachments_round_trip_change_the_fingerprint_and_version_1_files_still_read() {
+ let line = Stroke::new(1, "ink", [0.0, 0.0, 0.0, 1.0], 4.0, 1).with_points(&[(1.0, 1.0, 1.0), (9.0, 2.0, 0.5)], 0.0);
+ let free = Stroke::new(2, "eraser", [0.0, 0.0, 0.0, 1.0], 12.0, 2).with_points(&[(4.0, 0.0, 1.0), (4.0, 6.0, 1.0)], 0.0);
+ let attached = Stroke {
+ on: vec![1, 7 | (5 << 22), 3],
+ ..free.clone()
+ };
+ let marks: Vec<Mark> = vec![line.clone().into(), attached.clone().into()];
+ assert_eq!(decode_raw(&encode_raw(&marks)).unwrap(), marks);
+ assert_ne!(
+ fingerprint(&attached.clone().into()),
+ fingerprint(&free.clone().into()),
+ "attaching changes what a stroke draws, so caches must see it"
+ );
+ let mut old = encode_raw(&[line.clone().into(), free.clone().into()]);
+ old[4] = 1;
+ assert_eq!(
+ decode_raw(&old).unwrap(),
+ vec![Mark::Stroke(line), Mark::Stroke(free)],
+ "a version 1 file reads as strokes with nothing attached"
+ );
+ old[4] = 3;
+ assert!(decode_raw(&old).unwrap_err().to_string().contains("newer klad"));
+ }
+
#[test]
fn quantisation_is_stable_under_re_quantising() {
let s = Sample::quantize(10.37, -4.21, 0.333, (0.5, -0.25), 5.2);
@@ -518,7 +564,7 @@ mod tests {
bytes[..4].copy_from_slice(OLD_MAGIC);
assert!(decode_raw(&bytes).unwrap_err().to_string().contains("old .draw format"));
bytes[..4].copy_from_slice(MAGIC);
- bytes[4] = 2;
+ bytes[4] = VERSION + 1;
assert!(decode_raw(&bytes).is_err());
}
diff --git a/crates/core/src/tween.rs b/crates/core/src/tween.rs
index 05a1080..a23dff7 100644
--- a/crates/core/src/tween.rs
+++ b/crates/core/src/tween.rs
@@ -1664,6 +1664,7 @@ fn stroke_at(s: &StrokePlan, line: &[P], sim: Sim, t: f32) -> Stroke {
(Some(a), Some(b)) => Some(colour(a, b, t)),
(a, b) => a.or(b),
},
+ on: s.a.on.clone(),
samples,
}
}
diff --git a/docs/format.md b/docs/format.md
index 1beb05c..678f786 100644
--- a/docs/format.md
+++ b/docs/format.md
@@ -1,4 +1,4 @@
-_Last updated: 2026-11-09 (format `klad/5`, stroke files `KLST` version 1, brushes `klad-brush/1`)_
+_Last updated: 2026-11-09 18:00 (format `klad/6`, stroke files `KLST` version 2, brushes `klad-brush/1`)_
# The klad drawing format
@@ -32,13 +32,13 @@ Writers replace files atomically (write a temporary file, then rename), so a rea
- **Colours** are `"#rrggbb"` or `"#rrggbbaa"`: sRGB, straight (not premultiplied) alpha.
- **Ids** are unique across the whole document and use letters, digits, `-` and `_`. Ids are case sensitive. klad makes new ones from a prefix (`l` layer, `c` cel, `n` node), a number, and the tag of the copy that made them: `l48qa`. Each copy of a drawing (a clone, a git worktree: any folder without `.cache/copy.json`) picks a two-letter tag the first time klad opens it and keeps it in `.cache/copy.json`, with counters that only go up, so two copies edited apart never make the same id; the copy a drawing was made in has no tag (`l48`). A folder copied by hand with its `.cache/` keeps the tag: delete `.cache/` in the copy to give it its own. Ids already in a drawing never change. Writers that make their own ids should do the same or use a long random part. A drawing with an id used twice does not open; `klad repair` gives every later one a new id.
- **JSON** is UTF-8, written pretty with a stable key order. Keys at their default value are left out; readers must take the defaults listed below for missing keys. Most objects reject keys they do not know, so writers must not add their own.
-- **Versions.** `format` names the version of `doc.json` and everything it implies; this is `klad/5`. Each version opens the older `klad/` drawings and migrates them in memory (written back on the next change). A reader that meets a newer version than it knows should refuse to write the bundle. Drawings from before `klad/1` (`.draw` folders, formats `draw-anything/0` to `/9`) do not open.
+- **Versions.** `format` names the version of `doc.json` and everything it implies; this is `klad/6`. Each version opens the older `klad/` drawings and migrates them in memory (written back on the next change). A reader that meets a newer version than it knows should refuse to write the bundle. Drawings from before `klad/1` (`.draw` folders, formats `draw-anything/0` to `/9`) do not open.
## doc.json
```json
{
- "format": "klad/5",
+ "format": "klad/6",
"canvas": { "width": 2048, "height": 2048, "background": "#f4efe6" },
"timeline": { "fps": 12, "frames": 24, "origin": [1024, 1800],
"clips": [{ "name": "run", "from": 0, "to": 11, "loop": true, "fps": 24 }] },
@@ -60,7 +60,7 @@ Writers replace files atomically (write a temporary file, then rename), so a rea
| Key | Type | Default | Meaning |
|---|---|---|---|
-| `format` | string | | `"klad/5"` |
+| `format` | string | | `"klad/6"` |
| `canvas` | object | | `width`, `height` (px), `background` (a colour; none is transparent) |
| `timeline` | object | 12 fps, 1 frame | see below |
| `palette` | array | `[]` | swatches: `color`, optional `name` (unique, not starting with `#`) |
@@ -231,7 +231,7 @@ The file is one zstd frame (any level; klad uses 3). Inside:
| Bytes | What |
|---|---|
| 4 | `KLST` |
-| 1 | the version: 1 |
+| 1 | the version: 2 (version 1 files read as strokes with nothing attached) |
| varint | the number of marks |
| ... | each mark: a kind byte (0 stroke, 1 fill), then its record |
@@ -250,11 +250,12 @@ Numbers: a **varint** is an unsigned LEB128 integer (7 bits per byte, low bits f
| opacity | f32 | 0 to 1 |
| flow | f32 | 0 to 1 |
| seed | u32 | the seed of the brush's randomness, so a stroke replays the same |
-| channels | u8 | bits: 1 tilt, 2 time, 4 taper, 8 lock alpha, 16 cuts, 32 second colour |
+| channels | u8 | bits: 1 tilt, 2 time, 4 taper, 8 lock alpha, 16 cuts, 32 second colour, 64 attached |
| author | u8 | 0 a person, 1 an agent |
| taper | 2 f32 | if bit 4: px over which the start and end thin to a point, whatever the pressure |
| cuts | cuts | if bit 16 |
| second colour | colour | if bit 32: for brushes whose colour moves between two |
+| attached to | varint count, column | if bit 64: the ids of the marks in this drawing the stroke is attached to (see Attachments) |
| samples | varint | n, the number of samples |
| x, y | 2 columns | position in 1/16 px |
| pressure | column | 0 to 4095 |
@@ -263,6 +264,14 @@ Numbers: a **varint** is an unsigned LEB128 integer (7 bits per byte, low bits f
A **column** is n signed varints, each the difference from the previous value (the first from 0). Without the tilt or time bit those values are 0. Bit 8 has no data: it marks a stroke made with lock alpha on.
+### Attachments
+
+An eraser, smudge or blender stroke (a brush with `"blend": "erase"`, or a `paint` of `smudge` or `blend`) records the marks it changed when it was drawn: the earlier marks in its drawing with paint under it. It moves, turns, is copied and is deleted with them, and splits when only some of them move.
+
+An attached eraser erases only its marks' share of each pixel. Every way a mark lands is linear in the pixel under it (premultiplied colour: paint `c a + p (1 - a)`, lock alpha `c a u + p (1 - a)` on the colour with alpha kept, erase `p (1 - a)`), so a pixel is a sum of each mark's share, each covered by what came after it. From the eraser's first mark up to the eraser, klad keeps that sum for the eraser's marks alone (its marks add their paint, every other mark covers it; smudges and blenders move it as they move the pixels), and the eraser subtracts `a` times that share instead of scaling the whole pixel. Where two attached erasers overlap, the later one takes from the earlier one's share the part their marks have in common: all of it when one's marks hold the other's, none when they share no mark, and the smaller of the two shares otherwise. An eraser with a wet stroke (`paint` of `wet`) between its first mark and itself, on the same tiles, erases in order like an unattached one. Ids that no longer exist in the drawing are ignored, and an eraser with none left erases in order.
+
+A reader that ignores attachments draws every drawing as it was when its erasers were drawn, which is the same picture until something attached moves. Smudge and blender strokes always act on whatever is under them; their attachments only say what they move with.
+
### Fills
| Field | Encoding | Meaning |
@@ -335,3 +344,4 @@ Drawing a stroke: walk the samples, interpolate between them, stamp the tip ever
| `klad/3` | paint layers under a skeleton get `bone`, attaching them to one bone (2026-11-08). `klad/1` and `klad/2` drawings open unchanged. |
| `klad/4` | skeletons move to bones layers, and paint layers join one with `rig` (2026-11-08). Older drawings open without their bones, IK, weights links and the `pose` of their cels; the drawings themselves, posed ones too, stay. |
| `klad/5` | `rev` and `nextId` leave `doc.json`, and new ids carry the tag of the copy that made them, so drawings diff and merge in git (2026-11-09). Older drawings open with their ids unchanged; their counters move to `.cache/copy.json`. |
+| `klad/6` | stroke files version 2: eraser, smudge and blender strokes record the marks they are attached to, and attached erasers erase only those (2026-11-09). Older drawings open unchanged, with nothing attached. |