Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 33 additions & 8 deletions apps/vela-nav/fonts/mkfont.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@

The output is committed, so a build needs neither Python nor the font files. Noto Sans is under the SIL Open
Font License 1.1 (OFL.txt next to this script); the tables are a converted copy of it.

Coverage is 4 bits a pixel. The large sizes are stored as runs, a byte each (coverage << 4 | length - 1, a run
never crossing a row): their rows are long stretches of empty and solid, so that is a third to two thirds of the
packed size, and lossless. The small size has busy edges and stays packed, two pixels a byte.
"""
import sys
from pathlib import Path
Expand All @@ -13,16 +17,31 @@
OUT = Path(__file__).resolve().parent.parent / "src" / "fonts.rs"
ASCII = "".join(chr(c) for c in range(32, 127))

RLE = {"XL", "L"}

# (Rust name, file, px, characters)
FONTS = [
("XL", "NotoSans-Bold.ttf", 84, "0123456789. "),
# units, the clock, the limit, titles
("L", "NotoSans-SemiBold.ttf", 40, "0123456789:. abcdefghijklmnopqrstuvwxyzAVNRO"),
# units, the clock, the limit, titles, the Home and Work buttons
("L", "NotoSans-SemiBold.ttf", 40, "0123456789:. abcdefghijklmnopqrstuvwxyzAVNROHSW…"),
("S", "NotoSans-Medium.ttf", 26, ASCII + "…·"),
]


def glyphs(file, px, chars):
def runs(px4, w):
out = bytearray()
for r in range(0, len(px4), w):
row, i = px4[r:r + w], 0
while i < len(row):
j = i
while j < len(row) and row[j] == row[i] and j - i < 16:
j += 1
out.append(row[i] << 4 | (j - i - 1))
i = j
return bytes(out)


def glyphs(file, px, chars, rle):
font = ImageFont.truetype(str(SRC / file), px)
ascent, descent = font.getmetrics()
rows, data = [], bytearray()
Expand All @@ -38,9 +57,12 @@ def glyphs(file, px, chars):
x0, y0 = box[0] - px, box[1] - px * 2
w, h = box[2] - box[0], box[3] - box[1]
px4 = [v // 17 for v in q.crop(box).get_flattened_data()]
if len(px4) % 2:
px4.append(0)
data += bytes(px4[i] << 4 | px4[i + 1] for i in range(0, len(px4), 2))
if rle:
data += runs(px4, w)
else:
if len(px4) % 2:
px4.append(0)
data += bytes(px4[i] << 4 | px4[i + 1] for i in range(0, len(px4), 2))
rows.append((ch, adv, x0, y0, w, h, off))
cap = font.getbbox("H", anchor="ls")[1] # its top edge, so ink-exact
return ascent, descent, -cap, rows, data
Expand All @@ -58,14 +80,17 @@ def rust_char(c):
]
total = 0
for name, file, px, chars in FONTS:
ascent, descent, cap, rows, data = glyphs(file, px, chars)
rle = name in RLE
ascent, descent, cap, rows, data = glyphs(file, px, chars, rle)
total += len(data) + len(rows) * 12
print(name, len(data))
out.append(f"/// {file[:-4]} at {px} px: {len(rows)} glyphs, {len(data)} B of 4-bit coverage.")
kind = "runs of 4-bit coverage" if rle else "4-bit coverage"
out.append(f"/// {file[:-4]} at {px} px: {len(rows)} glyphs, {len(data)} B of {kind}.")
out.append(f"pub static {name}: Font = Font {{")
out.append(f" ascent: {ascent},")
out.append(f" descent: {descent},")
out.append(f" cap: {cap},")
out.append(f" rle: {str(rle).lower()},")
out.append(" glyphs: &[")
for ch, adv, x, y, w, h, off in rows:
out.append(f" Glyph {{ c: '{rust_char(ch)}', adv: {adv}, x: {x}, y: {y}, w: {w}, h: {h}, off: {off} }},")
Expand Down
Binary file removed apps/vela-nav/shots/arrived.png
Binary file not shown.
Binary file modified apps/vela-nav/shots/driving.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/vela-nav/shots/home.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/vela-nav/shots/map.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified apps/vela-nav/shots/turn.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
127 changes: 109 additions & 18 deletions apps/vela-nav/src/font.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pub struct Glyph {
pub y: i8,
pub w: u8,
pub h: u8,
/// Byte offset of the 4-bit coverage, two pixels a byte, rows packed.
/// Byte offset of the glyph's coverage in `Font::bits`.
pub off: u16,
}

Expand All @@ -21,6 +21,9 @@ pub struct Font {
pub descent: i32,
/// Height of a capital above the baseline.
pub cap: i32,
/// `bits` holds runs, a byte each (coverage << 4 | length - 1, within a row); else 4-bit coverage, two pixels a
/// byte, rows packed.
pub rle: bool,
pub glyphs: &'static [Glyph],
pub bits: &'static [u8],
}
Expand All @@ -39,6 +42,41 @@ impl Font {
t.chars().map(|c| self.glyph(c).map_or(0, |g| g.adv as i32)).sum()
}

/// Calls `f(row, start, len, coverage)` for each run of equal coverage in `g`, row by row, left to right,
/// whichever way the font stores it (runs that touch with the same coverage are merged).
fn runs(&self, g: &Glyph, mut f: impl FnMut(usize, usize, usize, u8)) {
let w = g.w as usize;
let mut at = g.off as usize;
for row in 0..g.h as usize {
let mut col = 0;
let mut open: Option<(usize, usize, u8)> = None;
while col < w {
let (a, n) = if self.rle {
let b = self.bits[at];
at += 1;
(b >> 4, (b & 15) as usize + 1)
} else {
let i = row * w + col;
let b = self.bits[g.off as usize + i / 2];
(if i.is_multiple_of(2) { b >> 4 } else { b & 15 }, 1)
};
let n = n.min(w - col);
open = match open {
Some((s, l, oa)) if oa == a => Some((s, l + n, a)),
Some((s, l, oa)) => {
f(row, s, l, oa);
Some((col, n, a))
}
None => Some((col, n, a)),
};
col += n;
}
if let Some((s, l, a)) = open {
f(row, s, l, a);
}
}
}

/// Draws `t` with its baseline at `y`, from `x`; returns the pen position after it. Characters the font
/// lacks are skipped.
pub fn draw(&self, s: &mut impl Surface, x: i32, y: i32, t: &str, fg: u16, bg: u16) -> i32 {
Expand All @@ -49,28 +87,65 @@ impl Font {
let mut pen = x;
for ch in t.chars() {
let Some(g) = self.glyph(ch) else { continue };
let (gx, gy, w) = (pen + g.x as i32, y + g.y as i32, g.w as usize);
let at = |i: usize| {
let b = self.bits[g.off as usize + i / 2];
if i.is_multiple_of(2) { b >> 4 } else { b & 15 }
};
for row in 0..g.h as usize {
let base = row * w;
let mut col = 0;
while col < w {
let a = at(base + col);
let start = col;
while col < w && at(base + col) == a {
col += 1;
let (gx, gy) = (pen + g.x as i32, y + g.y as i32);
self.runs(g, |row, start, len, a| {
if a != 0 {
s.rect(gx + start as i32, gy + row as i32, len as i32, 1, shade[a as usize]);
}
});
pen += g.adv as i32;
}
pen
}

/// A black outline `r` px (≤ 4) around the ink of `t`, for text drawn over the map: draw it, then the text over
/// it with a black background. Each glyph's ink is a bit mask a row, widened with shifts, so it is cheap.
pub fn halo(&self, s: &mut impl Surface, x: i32, y: i32, t: &str, r: i32) {
const ROWS: usize = 80;
let r = r.clamp(0, 4);
let mut pen = x;
for ch in t.chars() {
let Some(g) = self.glyph(ch) else { continue };
let (w, h) = (g.w as i32, g.h as i32);
let (gx, gy) = (pen + g.x as i32 - r, y + g.y as i32 - r);
pen += g.adv as i32;
if w == 0 || w + 2 * r > 64 || (h + 2 * r) as usize > ROWS {
continue;
}
let mut ink = [0u64; ROWS];
self.runs(g, |row, start, len, a| {
if a >= 4 {
let run = if len >= 64 { u64::MAX } else { (1u64 << len) - 1 };
ink[row + r as usize] |= run << (start as i32 + r);
}
});
let n = (h + 2 * r) as usize;
for oy in 0..n {
let mut out = 0u64;
for dy in -r..=r {
let sy = oy as i32 + dy;
if sy < 0 || sy >= n as i32 || ink[sy as usize] == 0 {
continue;
}
if a != 0 {
s.rect(gx + start as i32, gy + row as i32, (col - start) as i32, 1, shade[a as usize]);
let m = ink[sy as usize];
// a round pen: the reach across shrinks with the distance down
let reach = [[0, 0, 0, 0, 0], [1, 0, 0, 0, 0], [2, 2, 1, 0, 0], [3, 3, 2, 1, 0], [4, 4, 3, 3, 1]]
[r as usize][dy.unsigned_abs() as usize];
let mut d = m;
for i in 1..=reach {
d |= m << i | m >> i;
}
out |= d;
}
while out != 0 {
let start = out.trailing_zeros();
let len = (!(out >> start)).trailing_zeros().min(64 - start);
s.rect(gx + start as i32, gy + oy as i32, len as i32, 1, 0);
let mask = if len >= 64 { u64::MAX } else { ((1u64 << len) - 1) << start };
out &= !mask;
}
}
pen += g.adv as i32;
}
pen
}

/// The longest start of `t` that fits `max` px, and whether it was cut (then an ellipsis follows it).
Expand Down Expand Up @@ -175,6 +250,22 @@ mod tests {
assert!(!S.covers("ಹೊಸೂರು ರಸ್ತೆ"));
}

#[test]
fn every_glyph_decodes_to_whole_rows() {
for f in [&XL, &L, &S] {
for g in f.glyphs {
let mut cols = std::vec![0usize; g.h as usize];
f.runs(g, |row, start, len, _| {
assert_eq!(start, cols[row], "{:?} row {row}", g.c);
cols[row] += len;
});
assert!(cols.iter().all(|&c| c == g.w as usize), "{:?}", g.c);
}
}
// the big sizes are stored as runs, the small one packed
assert!(XL.rle && L.rle && !S.rle);
}

#[test]
fn text_is_antialiased_and_fits() {
let mut px = vec![0u16; (SIZE * SIZE) as usize];
Expand Down
Loading
Loading