spritebox 0.4.1

Create 2D pixel art and game assets from text: sprites, tilemaps, procedural textures, UI and pixel fonts. Export PNG, sprite atlases and TTF with a zero-dependency Rust library and CLI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
//! Line work: lone pixels, uneven steps, doubled outlines and stray alpha, in the
//! sprites drawn with rows.

use super::{Def, DrawnLayer, Found, Kind, LintCode, LintOptions, Sink, pixel_position};
use crate::{Color, Image, Sprite};

/// A sprite's rendered pixels, read with fully transparent pixels as one color and
/// beyond the edges as transparent.
pub(super) struct Canvas {
    image: Image,
    pub w: i64,
    pub h: i64,
}

impl Canvas {
    pub fn new(sprite: &Sprite) -> Canvas {
        Canvas {
            image: sprite.render(),
            w: sprite.width as i64,
            h: sprite.height as i64,
        }
    }
    pub fn at(&self, x: i64, y: i64) -> Color {
        if x < 0 || y < 0 || x >= self.w || y >= self.h {
            return Color::TRANSPARENT;
        }
        let c = self
            .image
            .pixel(x as u32, y as u32)
            .unwrap_or(Color::TRANSPARENT);
        if c.a == 0 { Color::TRANSPARENT } else { c }
    }
    pub fn visible(&self, x: i64, y: i64) -> bool {
        self.at(x, y).a > 0
    }
    /// Whether some pixel is transparent: a sprite without one, such as a tile, has
    /// no silhouette.
    pub fn has_silhouette(&self) -> bool {
        (0..self.h).any(|y| (0..self.w).any(|x| !self.visible(x, y)))
    }
    /// Whether `(x, y)` is visible and touches a transparent pixel or the edge.
    pub fn on_silhouette(&self, x: i64, y: i64) -> bool {
        self.visible(x, y)
            && [(-1, 0), (1, 0), (0, -1), (0, 1)]
                .iter()
                .any(|&(dx, dy)| !self.visible(x + dx, y + dy))
    }
    /// The outline's color: the color, as seen, of at least half the silhouette's
    /// pixels, when something inside it is of another color.
    pub fn outline_color(&self) -> Option<Color> {
        if !self.has_silhouette() {
            return None;
        }
        let mut counts: std::collections::HashMap<[u8; 4], usize> = Default::default();
        let mut total = 0;
        for y in 0..self.h {
            for x in 0..self.w {
                if self.on_silhouette(x, y) {
                    total += 1;
                    *counts.entry(self.at(x, y).to_array()).or_default() += 1;
                }
            }
        }
        let (&outline, &n) = counts
            .iter()
            .max_by_key(|&(c, n)| (*n, std::cmp::Reverse(*c)))?;
        if n * 2 < total {
            return None;
        }
        // An outline goes around something else: a sprite of one color, inside and
        // on its edge, has none.
        let color = Color::rgba(outline[0], outline[1], outline[2], outline[3]);
        let around = (0..self.h).any(|y| {
            (0..self.w)
                .any(|x| self.visible(x, y) && !self.on_silhouette(x, y) && self.at(x, y) != color)
        });
        around.then_some(color)
    }
}

/// The 8 neighbours of a pixel, as offsets.
pub(super) const AROUND: [(i64, i64); 8] = [
    (-1, -1),
    (0, -1),
    (1, -1),
    (-1, 0),
    (1, 0),
    (-1, 1),
    (0, 1),
    (1, 1),
];

/// Runs the line-work checks on a sprite drawn with rows, of at least 3×3.
pub(super) fn check(canvas: &Canvas, report: &Report, options: &LintOptions, sink: &mut Sink) {
    if canvas.w < 3 || canvas.h < 3 {
        return;
    }
    orphan_pixels(canvas, report, options, sink);
    jaggies(canvas, report, sink);
    double_outlines(canvas, report, sink);
    stray_alpha(canvas, report, sink);
}

/// What a warning about a sprite's pixels needs.
pub(super) struct Report<'r> {
    pub sprite: &'r Sprite,
    pub def: &'r Def,
    pub layers: &'r [DrawnLayer],
}

impl Report<'_> {
    /// Reports `pixels`, at the character of the first; with no pixels, at the
    /// sprite's name.
    pub fn push(
        &self,
        sink: &mut Sink,
        code: LintCode,
        pixels: Vec<(u32, u32)>,
        message: impl FnOnce() -> String,
    ) {
        let position = pixels
            .first()
            .and_then(|&(x, y)| pixel_position(self.sprite, self.layers, x, y))
            .unwrap_or(self.def.pos);
        let found = Found {
            code,
            kind: Kind::Sprite,
            name: &self.sprite.name,
            position: Some(position),
            sprite: Some(&self.sprite.name),
            pixels,
        };
        sink.push(found, message);
    }
}

/// Lightness, 0..=255, by the luma of Rec. 601.
fn luma(c: Color) -> i32 {
    (299 * c.r as i32 + 587 * c.g as i32 + 114 * c.b as i32) / 1000
}

/// `orphan_pixel`: a visible pixel whose four neighbours share one other color, close
/// to its own in lightness, with none of its color touching it diagonally. A visible
/// pixel with nothing visible around it at all is reported too.
fn orphan_pixels(canvas: &Canvas, report: &Report, options: &LintOptions, sink: &mut Sink) {
    let name = &report.sprite.name;
    for y in 0..canvas.h {
        for x in 0..canvas.w {
            let c = canvas.at(x, y);
            if c.a == 0 {
                continue;
            }
            let at = |(dx, dy): (i64, i64)| canvas.at(x + dx, y + dy);
            let sides = [(-1, 0), (1, 0), (0, -1), (0, 1)].map(at);
            let corners = [(-1, -1), (1, -1), (-1, 1), (1, 1)].map(at);
            let around = sides[0];
            if sides.iter().any(|&s| s != around) || around == c {
                continue;
            }
            let isolated = around.a == 0;
            if isolated {
                if corners.iter().any(|k| k.a > 0) {
                    continue;
                }
            } else {
                let contrast = (luma(c) - luma(around)).abs();
                if corners.contains(&c) || contrast > options.orphan_contrast as i32 {
                    continue;
                }
            }
            let (x, y) = (x as u32, y as u32);
            report.push(sink, LintCode::OrphanPixel, vec![(x, y)], || {
                if isolated {
                    format!("A lone pixel in sprite `{name}` at ({x}, {y}), touching nothing")
                } else {
                    format!(
                        "A lone pixel in sprite `{name}` at ({x}, {y}), close in lightness to \
                         the color around it, reads as noise"
                    )
                }
            });
        }
    }
}

/// A run of a profile: `len` places from `start` at one `value`.
#[derive(Clone, Copy)]
struct Run {
    start: i64,
    len: i64,
    value: i64,
}

/// `jaggy`: along each side of the silhouette, a stretch of steps one pixel apart
/// where one step is at least two longer, or two shorter, than the steps on both sides
/// of it: `1, 1, 3, 1, 1` rather than `1, 1, 1, 1` or a curve's `1, 2, 3`. The first
/// and last steps of a stretch, which corners cut short, are not judged.
fn jaggies(canvas: &Canvas, report: &Report, sink: &mut Sink) {
    let name = &report.sprite.name;
    // Pixels of the steps reported so far.
    let mut reported: std::collections::HashSet<(u32, u32)> = Default::default();
    // Each side: the first visible pixel of each column from the top or the bottom, or
    // of each row from the left or the right.
    for side in 0..4 {
        let (count, depth) = if side < 2 {
            (canvas.w, canvas.h)
        } else {
            (canvas.h, canvas.w)
        };
        let edge = |i: i64| -> Option<i64> {
            let mut steps = 0..depth;
            let mut find = |d: i64| {
                let d = if side % 2 == 0 { d } else { depth - 1 - d };
                let (x, y) = if side < 2 { (i, d) } else { (d, i) };
                canvas.visible(x, y).then_some(d)
            };
            steps.find_map(&mut find)
        };
        // Pixel `(x, y)` of a run's place `i`.
        let pixel = |i: i64, value: i64| -> (u32, u32) {
            if side < 2 {
                (i as u32, value as u32)
            } else {
                (value as u32, i as u32)
            }
        };
        let mut runs: Vec<Run> = Vec::new();
        for i in 0..count {
            let value = edge(i);
            match (value, runs.last_mut()) {
                (Some(v), Some(last)) if last.value == v && last.start + last.len == i => {
                    last.len += 1;
                }
                (Some(v), _) => runs.push(Run {
                    start: i,
                    len: 1,
                    value: v,
                }),
                (None, _) => {}
            }
        }
        // Stretches of runs that each step one pixel the same way.
        let mut first = 0;
        while first < runs.len() {
            let mut last = first;
            let mut direction = 0;
            let mut turns = false;
            while last + 1 < runs.len() {
                let (a, b) = (runs[last], runs[last + 1]);
                let step = b.value - a.value;
                let touching = a.start + a.len == b.start;
                if !touching || step.abs() != 1 {
                    break;
                }
                if direction != 0 && step != direction {
                    turns = true;
                    break;
                }
                direction = step;
                last += 1;
            }
            let stretch = &runs[first..=last];
            // Where the edge turns, the run at the turn ends one stretch and starts the
            // next.
            first = if turns { last } else { last + 1 };
            if stretch.len() < 5 {
                continue;
            }
            let inner = &stretch[1..stretch.len() - 1];
            let odd: Vec<Run> = inner
                .windows(3)
                .filter(|w| {
                    let (before, step, after) = (w[0].len, w[1].len, w[2].len);
                    (step >= before + 2 && step >= after + 2)
                        || (step + 2 <= before && step + 2 <= after)
                })
                .map(|w| w[1])
                .collect();
            let steps: Vec<String> = inner.iter().map(|r| r.len.to_string()).collect();
            for run in odd {
                let pixels: Vec<(u32, u32)> = (run.start..run.start + run.len)
                    .map(|i| pixel(i, run.value))
                    .collect();
                // A stroke one pixel thin shows a step from both sides, the same pixels or
                // some of them; one warning a step.
                if pixels.iter().any(|p| reported.contains(p)) {
                    continue;
                }
                reported.extend(pixels.iter().copied());
                let (x, y) = pixels[0];
                let steps = &steps;
                report.push(sink, LintCode::Jaggy, pixels, || {
                    format!(
                        "Uneven steps along the edge of sprite `{name}`: {} pixels long; the \
                         step of {} at ({x}, {y}) breaks the line's rhythm",
                        steps.join(", "),
                        run.len
                    )
                });
            }
        }
    }
}

/// `double_outline`: a pixel of the outline that makes an L corner with two others
/// where one diagonal step would do, so that the line is two pixels thick there. The
/// outline is the key of at least half the silhouette's pixels, where those pixels
/// connect. Corners within 2×2 squares of the outline, as in lines two pixels thick
/// across, are left alone, and so are corners with no fill near them: a stroke drawn
/// on its own outlines nothing.
fn double_outlines(canvas: &Canvas, report: &Report, sink: &mut Sink) {
    let sprite = report.sprite;
    let (w, h) = (canvas.w, canvas.h);
    let inside = |x: i64, y: i64| x >= 0 && y >= 0 && x < w && y < h;
    let index = |x: i64, y: i64| (y * w + x) as usize;
    let Some(outline) = canvas.outline_color() else {
        return;
    };
    let edge = |x: i64, y: i64| canvas.on_silhouette(x, y);
    let outlined = |x: i64, y: i64| canvas.visible(x, y) && canvas.at(x, y) == outline;
    // The outline's pixels: those of its key that connect to its pixels on the edge.
    let mut mask = vec![false; (w * h) as usize];
    let mut stack: Vec<(i64, i64)> = (0..h)
        .flat_map(|y| (0..w).map(move |x| (x, y)))
        .filter(|&(x, y)| edge(x, y) && outlined(x, y))
        .collect();
    while let Some((x, y)) = stack.pop() {
        if mask[index(x, y)] {
            continue;
        }
        mask[index(x, y)] = true;
        for (dx, dy) in AROUND {
            let (nx, ny) = (x + dx, y + dy);
            if inside(nx, ny) && !mask[index(nx, ny)] && canvas.visible(nx, ny) && outlined(nx, ny)
            {
                stack.push((nx, ny));
            }
        }
    }
    let on = |mask: &[bool], x: i64, y: i64| inside(x, y) && mask[index(x, y)];
    for y in 0..h {
        for x in 0..w {
            if !on(&mask, x, y) {
                continue;
            }
            let neighbours: Vec<(i64, i64)> = AROUND
                .iter()
                .map(|&(dx, dy)| (x + dx, y + dy))
                .filter(|&(nx, ny)| on(&mask, nx, ny))
                .collect();
            let across = [(-1, 0), (1, 0)]
                .iter()
                .filter(|&&(dx, dy)| on(&mask, x + dx, y + dy))
                .count();
            let down = [(0, -1), (0, 1)]
                .iter()
                .filter(|&&(dx, dy)| on(&mask, x + dx, y + dy))
                .count();
            // An L: one neighbour across and one up or down, and more besides.
            if neighbours.len() < 3 || across != 1 || down != 1 {
                continue;
            }
            // A line thick on purpose fills 2×2 squares.
            let square = [(-1, -1), (0, -1), (-1, 0), (0, 0)]
                .iter()
                .any(|&(sx, sy)| {
                    [(0, 0), (1, 0), (0, 1), (1, 1)]
                        .iter()
                        .all(|&(dx, dy)| on(&mask, x + sx + dx, y + sy + dy))
                });
            // The fill that the outline goes around, within two pixels.
            let fill = (-2..=2).any(|dy: i64| {
                (-2..=2).any(|dx: i64| {
                    let (nx, ny) = (x + dx, y + dy);
                    canvas.visible(nx, ny) && !outlined(nx, ny)
                })
            });
            if square || !fill || !connected(&neighbours) {
                continue;
            }
            // Taken out, so the rest of the line is judged without it.
            mask[index(x, y)] = false;
            let (x, y) = (x as u32, y as u32);
            report.push(sink, LintCode::DoubleOutline, vec![(x, y)], || {
                format!(
                    "The outline of sprite `{}` is two pixels thick at ({x}, {y}); one \
                     diagonal step would do",
                    sprite.name
                )
            });
        }
    }
}

/// Whether `pixels` are all connected to each other, through each other alone.
fn connected(pixels: &[(i64, i64)]) -> bool {
    let mut reached = vec![false; pixels.len()];
    let mut stack = vec![0];
    while let Some(i) = stack.pop() {
        if std::mem::replace(&mut reached[i], true) {
            continue;
        }
        let (x, y) = pixels[i];
        for (j, &(nx, ny)) in pixels.iter().enumerate() {
            if !reached[j] && (nx - x).abs() <= 1 && (ny - y).abs() <= 1 {
                stack.push(j);
            }
        }
    }
    reached.iter().all(|&r| r)
}

/// `stray_alpha`: a translucent pixel with no translucent pixel around it, in a
/// sprite whose translucent pixels are fewer than one in eight visible ones: a
/// leftover of anti-aliasing, which blurs when the sprite is scaled. Translucent areas,
/// such as glass or a shadow, are left alone.
fn stray_alpha(canvas: &Canvas, report: &Report, sink: &mut Sink) {
    let translucent = |x: i64, y: i64| {
        let a = canvas.at(x, y).a;
        a > 0 && a < 255
    };
    let (mut visible, mut partial) = (0usize, 0usize);
    for y in 0..canvas.h {
        for x in 0..canvas.w {
            visible += canvas.visible(x, y) as usize;
            partial += translucent(x, y) as usize;
        }
    }
    if partial == 0 || partial * 8 >= visible {
        return;
    }
    let name = &report.sprite.name;
    for y in 0..canvas.h {
        for x in 0..canvas.w {
            if !translucent(x, y) || AROUND.iter().any(|&(dx, dy)| translucent(x + dx, y + dy)) {
                continue;
            }
            let alpha = canvas.at(x, y).a;
            let (x, y) = (x as u32, y as u32);
            report.push(sink, LintCode::StrayAlpha, vec![(x, y)], || {
                format!(
                    "A lone translucent pixel in sprite `{name}` at ({x}, {y}), alpha {alpha}: \
                     a leftover of smoothing that blurs when scaled"
                )
            });
        }
    }
}