use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use hayro_interpret::kurbo::{BezPath, Shape as _};
use crate::page::{Glyph, HLine, Page, Picture, VLine};
use crate::smufl;
const OUTLINE_SCALE: f64 = 600.0 / 72.0;
pub(crate) fn of_outline(p: &BezPath) -> Option<Picture> {
let b = p.bounding_box();
let (w, h) = (
(b.width() * OUTLINE_SCALE).ceil() as usize,
(b.height() * OUTLINE_SCALE).ceil() as usize,
);
if w == 0 || h == 0 {
return None;
}
let mut edges: Vec<(f64, f64, f64, f64)> = Vec::new();
let (mut start, mut last) = ((0.0, 0.0), (0.0, 0.0));
let px = |pt: hayro_interpret::kurbo::Point| {
((pt.x - b.x0) * OUTLINE_SCALE, (pt.y - b.y0) * OUTLINE_SCALE)
};
hayro_interpret::kurbo::flatten(p.iter(), 0.05 / OUTLINE_SCALE, |el| {
use hayro_interpret::kurbo::PathEl::*;
match el {
MoveTo(a) => {
if last != start {
edges.push((last.0, last.1, start.0, start.1));
}
start = px(a);
last = start;
}
LineTo(a) => {
let a = px(a);
edges.push((last.0, last.1, a.0, a.1));
last = a;
}
ClosePath => {
edges.push((last.0, last.1, start.0, start.1));
last = start;
}
_ => {}
}
});
if last != start {
edges.push((last.0, last.1, start.0, start.1));
}
let mut ink = vec![false; w * h];
let mut cross: Vec<(f64, i32)> = Vec::new();
for r in 0..h {
let y = r as f64 + 0.5;
cross.clear();
for &(x0, y0, x1, y1) in &edges {
if (y0 <= y) != (y1 <= y) {
cross.push((
x0 + (y - y0) / (y1 - y0) * (x1 - x0),
if y1 > y0 { 1 } else { -1 },
));
}
}
cross.sort_by(|a, b| a.0.total_cmp(&b.0));
let mut wind = 0;
for i in 0..cross.len() {
wind += cross[i].1;
if wind != 0 && i + 1 < cross.len() {
let from = (cross[i].0 - 0.5).ceil().max(0.0) as usize;
let to = ((cross[i + 1].0 - 0.5).floor() as i64).min(w as i64 - 1);
for c in from as i64..=to {
ink[r * w + c as usize] = true;
}
}
}
}
Some(Picture {
x0: b.x0,
y0: b.y0,
x1: b.x1,
y1: b.y1,
w,
h,
ink,
})
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Shape {
pub w: f64,
pub h: f64,
pub fill: f64,
pub bits: [u64; 4],
pub at: (f64, f64, f64, f64),
}
impl Shape {
pub fn hex(&self) -> String {
self.bits.iter().map(|w| format!("{w:016x}")).collect()
}
fn apart(&self, o: &[u64; 4]) -> u32 {
(0..4).map(|i| (self.bits[i] ^ o[i]).count_ones()).sum()
}
}
pub fn shape(p: &Picture, sp: f64) -> Option<Shape> {
let inked = |r: usize, c: usize| p.ink[r * p.w + c];
let r0 = (0..p.h).find(|&r| (0..p.w).any(|c| inked(r, c)))?;
let r1 = (0..p.h).rev().find(|&r| (0..p.w).any(|c| inked(r, c)))?;
let c0 = (0..p.w).find(|&c| (0..p.h).any(|r| inked(r, c)))?;
let c1 = (0..p.w).rev().find(|&c| (0..p.h).any(|r| inked(r, c)))?;
let (sx, sy) = ((p.x1 - p.x0) / p.w as f64, (p.y1 - p.y0) / p.h as f64);
let (bw, bh) = (c1 - c0 + 1, r1 - r0 + 1);
let mut bits = [0u64; 4];
for gy in 0..16 {
let (ya, yb) = (
r0 + gy * bh / 16,
r0 + ((gy + 1) * bh / 16).max(gy * bh / 16 + 1),
);
for gx in 0..16 {
let (xa, xb) = (
c0 + gx * bw / 16,
c0 + ((gx + 1) * bw / 16).max(gx * bw / 16 + 1),
);
let (mut n, mut on) = (0, 0);
for r in ya..yb.min(r1 + 1) {
for c in xa..xb.min(c1 + 1) {
n += 1;
on += inked(r, c) as usize;
}
}
if 2 * on >= n.max(1) {
bits[gy / 4] |= 1 << (63 - (gy % 4) * 16 - gx);
}
}
}
let inked_all = p.ink.iter().filter(|b| **b).count();
Some(Shape {
w: bw as f64 * sx / sp,
h: bh as f64 * sy / sp,
fill: inked_all as f64 / (bw * bh) as f64,
bits,
at: (
p.x0 + c0 as f64 * sx,
p.y0 + r0 as f64 * sy,
p.x0 + (c1 + 1) as f64 * sx,
p.y0 + (r1 + 1) as f64 * sy,
),
})
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum Kind {
Glyph(u32),
Pair(u32, u32),
Dot,
RestBlock,
BraceTop,
BraceFoot,
Ledger,
Thick,
Accent,
Nothing,
}
struct Ref {
kind: Kind,
w: f64,
h: f64,
bits: [u64; 4],
usual: f64,
}
fn kind_of(label: &str) -> Kind {
match label {
"dot" => Kind::Dot,
"restblock" => Kind::RestBlock,
"brace-top" => Kind::BraceTop,
"brace-foot" => Kind::BraceFoot,
"ledger" => Kind::Ledger,
"thick" => Kind::Thick,
"accent" => Kind::Accent,
l => match l.split_once('+') {
Some((a, b)) => match (u32::from_str_radix(a, 16), u32::from_str_radix(b, 16)) {
(Ok(a), Ok(b)) => Kind::Pair(a, b),
_ => Kind::Nothing,
},
None => u32::from_str_radix(l, 16).map_or(Kind::Nothing, Kind::Glyph),
},
}
}
fn refs() -> &'static [Ref] {
static REFS: std::sync::OnceLock<Vec<Ref>> = std::sync::OnceLock::new();
REFS.get_or_init(|| {
let mut usual: HashMap<String, f64> = HashMap::new();
let mut out = Vec::new();
for line in include_str!("pictures.txt").lines() {
let f: Vec<&str> = line.split_whitespace().collect();
if line.starts_with('#') || f.len() != 4 || f[3].len() != 64 {
continue;
}
let (Ok(w), Ok(h)) = (f[1].parse::<f64>(), f[2].parse::<f64>()) else {
continue;
};
let mut bits = [0u64; 4];
for (i, b) in bits.iter_mut().enumerate() {
*b = u64::from_str_radix(&f[3][16 * i..16 * i + 16], 16).unwrap_or(0);
}
let u = *usual.entry(f[0].to_string()).or_insert(w);
out.push(Ref {
kind: kind_of(f[0]),
w,
h,
bits,
usual: u,
});
}
out
})
}
fn classify(s: &Shape) -> Option<(Kind, f64)> {
if s.fill > 0.9 {
if s.h < 0.4 && (0.9..1.9).contains(&s.w) {
return Some((Kind::Ledger, 1.0));
}
if s.w < 0.75 && s.h > 1.5 {
return Some((Kind::Thick, 1.0));
}
if (0.35..0.7).contains(&s.h) && (0.8..1.6).contains(&s.w) {
return Some((Kind::RestBlock, s.w / 1.16));
}
}
let near = |a: f64, b: f64, by: f64| (a / b).ln().abs() < by;
let mut best: Option<(u32, &Ref)> = None;
for r in refs() {
let fits = match r.kind {
Kind::BraceTop | Kind::BraceFoot => near(s.w, r.w, 0.3) && s.h > 5.0,
_ => near(s.w, r.w, 0.15) && near(s.h, r.h, 0.15),
};
if !fits {
continue;
}
let d = s.apart(&r.bits);
if best.is_none_or(|(b, _)| d < b) {
best = Some((d, r));
}
}
let (d, r) = best?;
(d <= 40).then_some((r.kind, s.w / r.usual))
}
fn origin(code: u32, t: f64, b: f64) -> f64 {
let h = b - t;
match code {
0xE260 => b - 0.285 * h,
0xE050 => t + 0.646 * h,
0xE062 => t + 0.29 * h,
0xE240 | 0xE242 => t,
0xE241 | 0xE243 => b,
0xE4E6 => t + 0.41 * h,
0xE4E7 => t + 0.264 * h,
0xE4C0 => b,
0xE4C1 => t,
0xE043 => b + 0.2 * h,
0xE520 | 0xE522 => b - 0.2 * h,
0xE521 => b,
_ => (t + b) / 2.0,
}
}
pub fn read(pg: &mut Page) {
if pg.pictures.is_empty() {
return;
}
let lines: Vec<[f64; 5]> = pg.staves().iter().map(|s| s.lines).collect();
if lines.is_empty() {
return;
}
let staff_of = |y: f64| {
lines
.iter()
.min_by(|a, b| (a[2] - y).abs().total_cmp(&(b[2] - y).abs()))
.copied()
};
let nearest_line = |y: f64| -> f64 {
let Some(st) = staff_of(y) else {
return y;
};
let sp = (st[4] - st[0]) / 4.0;
st[0] + ((y - st[0]) / sp).round() * sp
};
let mut known: HashMap<u64, Option<(Kind, f64)>> = HashMap::new();
let (mut tops, mut feet) = (Vec::new(), Vec::new());
let pictures = std::mem::take(&mut pg.pictures);
for p in &pictures {
let Some(s) = shape(p, 1.0) else {
continue;
};
let Some(st) = staff_of((s.at.1 + s.at.3) / 2.0) else {
continue;
};
let sp = (st[4] - st[0]) / 4.0;
let s = Shape {
w: s.w / sp,
h: s.h / sp,
..s
};
let key = {
let mut h = std::collections::hash_map::DefaultHasher::new();
(p.w, p.h, &p.ink, (sp * 100.0).round() as i64).hash(&mut h);
h.finish()
};
let Some((kind, scale)) = *known.entry(key).or_insert_with(|| classify(&s)) else {
if std::env::var_os("FMV_PICTURES").is_some() {
eprintln!(
"PICTURE unknown {:.3} {:.3} {:.2} {}",
s.w,
s.h,
s.fill,
s.hex()
);
}
continue;
};
let (l, t, r, b) = s.at;
let size = 4.0 * sp * scale;
let mid = (t + b) / 2.0;
let glyph = |code: u32, y: f64| Glyph {
code,
x0: l,
x1: r,
y,
size,
};
match kind {
Kind::Glyph(code) if smufl::clef(code).is_some() => {
let y = origin(code, t, b);
let on = nearest_line(y);
pg.glyphs
.push(glyph(code, if (on - y).abs() < 0.5 * sp { on } else { y }));
}
Kind::Glyph(code) => pg.glyphs.push(glyph(code, origin(code, t, b))),
Kind::Pair(a, z) => {
let m = (l + r) / 2.0;
pg.glyphs.push(Glyph {
x1: m,
..glyph(a, origin(a, t, b))
});
pg.glyphs.push(Glyph {
x0: m,
..glyph(z, origin(z, t, b))
});
}
Kind::Dot => pg.glyphs.push(glyph(smufl::DOT, mid)),
Kind::RestBlock => {
let whole = (t - nearest_line(t)).abs() <= (b - nearest_line(b)).abs();
pg.glyphs.push(match whole {
true => glyph(0xE4E3, t),
false => glyph(0xE4E4, b),
});
}
Kind::Accent => {
let below = staff_of(mid).is_some_and(|st| mid > st[2]);
pg.glyphs.push(match below {
true => glyph(0xE4A1, t),
false => glyph(0xE4A0, b),
});
}
Kind::Ledger => pg.hlines.push(HLine {
x0: l,
x1: r,
y: mid,
w: b - t,
}),
Kind::Thick => pg.vlines.push(VLine {
x: (l + r) / 2.0,
y0: t,
y1: b,
w: r - l,
}),
Kind::BraceTop => tops.push(s.at),
Kind::BraceFoot => feet.push((s.at, sp)),
Kind::Nothing => {}
}
}
for (f, sp) in &feet {
let top = tops
.iter()
.filter(|u| (u.0 - f.0).abs() < 0.6 * sp && (f.1 - u.3).abs() < 1.0 * sp)
.min_by(|a, b| (f.1 - a.3).abs().total_cmp(&(f.1 - b.3).abs()));
if let Some(u) = top {
pg.glyphs.push(Glyph {
code: 0xE000,
x0: u.0.min(f.0),
x1: u.2.max(f.2),
y: f.3,
size: f.3 - u.1,
});
}
}
pg.pictures = pictures;
let mut counts: HashMap<i64, usize> = HashMap::new();
for g in pg.glyphs.iter().filter(|g| smufl::head(g.code).is_some()) {
*counts.entry(g.size.round() as i64).or_default() += 1;
}
if let Some((s, _)) = counts.into_iter().max_by_key(|&(s, n)| (n, s)) {
pg.size = s as f64;
}
}
#[cfg(test)]
mod tests {
use super::*;
fn picture(x: f64, y: f64, w: usize, h: usize, ink: impl Fn(usize, usize) -> bool) -> Picture {
Picture {
x0: x,
y0: y,
x1: x + w as f64 * 0.12,
y1: y + h as f64 * 0.12,
w,
h,
ink: (0..h)
.flat_map(|r| (0..w).map(move |c| (r, c)))
.map(|(r, c)| ink(r, c))
.collect(),
}
}
#[test]
fn a_shape_is_its_inked_box_in_staff_spaces() {
let p = picture(0.0, 0.0, 20, 10, |r, c| {
(3..7).contains(&r) && (5..15).contains(&c)
});
let s = shape(&p, 2.4).unwrap();
assert!(
(s.w - 0.5).abs() < 1e-9 && (s.h - 0.2).abs() < 1e-9,
"{s:?}"
);
assert_eq!(s.fill, 1.0);
assert_eq!(s.bits, [u64::MAX; 4]);
assert!((s.at.0 - 0.6).abs() < 1e-9 && (s.at.1 - 0.36).abs() < 1e-9);
assert!(shape(&picture(0.0, 0.0, 4, 4, |_, _| false), 2.4).is_none());
}
#[test]
fn every_reference_is_known_as_itself() {
for r in refs() {
let s = Shape {
w: r.w,
h: r.h,
fill: 0.5,
bits: r.bits,
at: (0.0, 0.0, 1.0, 1.0),
};
let (k, _) = classify(&s).unwrap();
assert_eq!(k, r.kind, "{} {}", r.w, r.h);
}
}
#[test]
fn a_filled_box_is_told_by_its_size() {
let s = |w: f64, h: f64| Shape {
w,
h,
fill: 1.0,
bits: [u64::MAX; 4],
at: (0.0, 0.0, 1.0, 1.0),
};
assert_eq!(classify(&s(1.3, 0.23)).unwrap().0, Kind::Ledger);
assert_eq!(classify(&s(0.52, 4.0)).unwrap().0, Kind::Thick);
assert_eq!(classify(&s(1.16, 0.5)).unwrap().0, Kind::RestBlock);
}
#[test]
fn an_outline_is_drawn_as_its_inside() {
use hayro_interpret::kurbo::Rect;
let sq = of_outline(&Rect::new(10.0, 20.0, 13.0, 23.0).to_path(0.01)).unwrap();
assert_eq!((sq.w, sq.h), (25, 25));
assert!(sq.ink.iter().all(|&i| i));
assert_eq!((sq.x0, sq.y0, sq.x1, sq.y1), (10.0, 20.0, 13.0, 23.0));
let mut frame = BezPath::new();
for (i, &(x, y)) in [(40.0, 40.0), (46.0, 40.0), (46.0, 46.0), (40.0, 46.0)]
.iter()
.enumerate()
{
if i == 0 {
frame.move_to((x, y))
} else {
frame.line_to((x, y))
}
}
frame.close_path();
for (i, &(x, y)) in [(42.0, 42.0), (42.0, 44.0), (44.0, 44.0), (44.0, 42.0)]
.iter()
.enumerate()
{
if i == 0 {
frame.move_to((x, y))
} else {
frame.line_to((x, y))
}
}
frame.close_path();
let r = of_outline(&frame).unwrap();
let at = |x: usize, y: usize| r.ink[y * r.w + x];
assert!(!at(r.w / 2, r.h / 2), "the hole");
assert!(at(r.w / 2, 3), "the rim");
}
#[test]
fn a_glyphs_origin_is_where_smufl_sets_it() {
assert_eq!(origin(0xE240, 10.0, 22.0), 10.0);
assert_eq!(origin(0xE241, 10.0, 22.0), 22.0);
assert_eq!(origin(0xE0A4, 10.0, 14.0), 12.0);
assert!((origin(0xE050, 0.0, 7.41) - 4.79).abs() < 0.01);
}
}