acorde-render-svg 1.2.17

Pure-Rust/WASM SVG score renderer for acorde-core scores, driven by acorde-layout
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
//! Beam geometry: turns one `acorde_layout::BeamGroup` (already-decided note grouping — this
//! module never re-infers which notes belong together) into a sloped, clearance-checked beam
//! line plus per-note stem tips, extensible to any number of secondary beam levels (16th,
//! 32nd, 64th).
//!
//! # Slope algorithm
//!
//! A beam drawn as a straight line from the first note's default stem tip to the last note's
//! default stem tip can produce absurdly long or short interior stems when the group spans a
//! wide pitch range. Instead:
//!
//! 1. Compute the "natural" (default-length) stem tip for the first and last note.
//! 2. Clamp the rise between them to [`MAX_BEAM_RISE_U`] staff-spaces — a shallow-slope cap,
//!    not a full spacing optimizer, but enough to prevent extreme angles.
//! 3. Shift the whole beam (parallel, away from the noteheads) if any *interior* note's
//!    resulting stem would be shorter than [`MIN_STEM_LEN_U`] — the "beam must clear every
//!    notehead" rule.
//!
//! # Secondary beams
//!
//! Each note's required beam level count comes from its own `Duration` (eighth = 1, 16th = 2,
//! …). Level 0 (primary) always spans the whole group. Level ≥ 1 spans only the contiguous
//! run of notes that need it; an isolated single note at a level gets a short hook stub
//! (pointing toward whichever neighbor is closer to the middle of the group) instead of a
//! run — standard partial-beam notation.

use std::collections::HashMap;

use acorde_core::Duration;

use crate::glyphs;

const MIN_STEM_LEN_U: f32 = 2.0;
const MAX_BEAM_RISE_U: f32 = 1.0;
const BEAM_THICKNESS_U: f32 = 0.5;
const BEAM_LEVEL_GAP_U: f32 = 0.9;
const HOOK_LEN_U: f32 = 0.6;

fn beam_level(duration: &Duration) -> u8 {
    match duration {
        Duration::Eighth => 1,
        Duration::Sixteenth => 2,
        Duration::ThirtySecond => 3,
        Duration::SixtyFourth => 4,
        Duration::HundredTwentyEighth => 5,
        _ => 0,
    }
}

pub(crate) struct BeamPlan {
    /// Local index within the group (0..len) -> resolved stem tip y.
    pub tips: HashMap<usize, f32>,
    pub svg: String,
}

/// Return the conservative vertical bounds of a planned beam group in staff-space units.
///
/// The bounds include the primary and secondary beam thicknesses, including isolated hooks.
/// Callers use normalized x-coordinates because only the relative slope matters here; the
/// renderer's actual pixel scale is applied by [`plan_beam_group`].
pub(crate) fn vertical_extents(
    durations: &[Duration],
    xs: &[f32],
    attach_ys: &[f32],
    stem_up: bool,
) -> (f32, f32) {
    if durations.len() < 2 || xs.len() != durations.len() || attach_ys.len() != durations.len() {
        return (0.0, 0.0);
    }
    let plan = plan_beam_group(durations, xs, attach_ys, stem_up, 1.0);
    let mut min_y = plan.tips.values().copied().fold(f32::INFINITY, f32::min);
    let mut max_y = plan
        .tips
        .values()
        .copied()
        .fold(f32::NEG_INFINITY, f32::max);
    let max_level = durations.iter().map(beam_level).max().unwrap_or(1);
    let level_extent =
        (max_level.saturating_sub(1) as f32 * BEAM_LEVEL_GAP_U) + BEAM_THICKNESS_U / 2.0;
    // Secondary beams sit inside the primary one, between it and the noteheads.
    if stem_up {
        min_y -= BEAM_THICKNESS_U / 2.0;
        max_y += level_extent;
    } else {
        min_y -= level_extent;
        max_y += BEAM_THICKNESS_U / 2.0;
    }
    (min_y, max_y)
}

/// Plan one beam group's geometry and emit its SVG.
///
/// `durations`/`xs`/`attach_ys` are parallel arrays, one entry per note in the group (already
/// sliced to just this group by the caller — this module has no notion of a "voice").
/// `attach_ys` is each note's stem-side notehead y (already resolved for chords).
pub(crate) fn plan_beam_group(
    durations: &[Duration],
    xs: &[f32],
    attach_ys: &[f32],
    stem_up: bool,
    space: f32,
) -> BeamPlan {
    let n = durations.len();
    debug_assert_eq!(xs.len(), n);
    debug_assert_eq!(attach_ys.len(), n);
    let dir = if stem_up { -1.0 } else { 1.0 };
    let mut svg = String::new();
    // Beams join the stems, which stand at the notehead's right (stem up) or left (stem down)
    // edge, not at the notehead centre; `xs` are notehead centres.
    let stem_offset = glyphs::NOTEHEAD_RX_U * space * 0.92 * -dir;
    let stem_xs: Vec<f32> = xs.iter().map(|x| x + stem_offset).collect();
    let xs = stem_xs.as_slice();
    // Cover the stem's own width at the group's outer stems.
    let half_stem = glyphs::STEM_WIDTH_U * space / 2.0;

    let natural = |i: usize| attach_ys[i] + dir * glyphs::DEFAULT_STEM_LEN_U * space;
    let raw_rise = natural(n - 1) - natural(0);
    let clamped_rise = raw_rise.clamp(-MAX_BEAM_RISE_U * space, MAX_BEAM_RISE_U * space);
    let dx = xs[n - 1] - xs[0];
    let slope = if dx.abs() > 1e-6 {
        clamped_rise / dx
    } else {
        0.0
    };
    let base_y = |x: f32| natural(0) + slope * (x - xs[0]);

    // Clearance: shift the whole beam away from noteheads if any stem would be too short. The
    // inner (secondary) beams need their own room between the primary beam and the heads.
    let levels = durations.iter().map(beam_level).max().unwrap_or(1).max(1);
    let min_stem = (MIN_STEM_LEN_U + f32::from(levels - 1) * BEAM_LEVEL_GAP_U) * space;
    let mut max_deficit = 0.0f32;
    for (&x, &attach_y) in xs.iter().zip(attach_ys) {
        let stem_len = (base_y(x) - attach_y).abs();
        let deficit = min_stem - stem_len;
        if deficit > max_deficit {
            max_deficit = deficit;
        }
    }
    let beam_y = |x: f32| base_y(x) + dir * max_deficit;

    let mut tips = HashMap::with_capacity(n);
    for (i, &x) in xs.iter().enumerate() {
        tips.insert(i, beam_y(x));
    }

    // Primary beam (level 0) always spans the full group.
    svg.push_str(&glyphs::beam_segment(
        xs[0] - half_stem,
        beam_y(xs[0] - half_stem),
        xs[n - 1] + half_stem,
        beam_y(xs[n - 1] + half_stem),
        BEAM_THICKNESS_U * space,
    ));

    // Secondary+ beams: contiguous runs (or single-note hooks) at each extra level.
    let max_level = durations.iter().map(beam_level).max().unwrap_or(1);
    for level in 1..max_level {
        let needs: Vec<bool> = durations.iter().map(|d| beam_level(d) > level).collect();
        // Secondary beams stack inward, toward the noteheads, as in engraved music.
        let level_y = |x: f32| beam_y(x) - dir * level as f32 * BEAM_LEVEL_GAP_U * space;
        let mut i = 0;
        while i < n {
            if !needs[i] {
                i += 1;
                continue;
            }
            let run_start = i;
            while i < n && needs[i] {
                i += 1;
            }
            let run_end = i - 1;
            if run_start == run_end {
                // Isolated note: hook toward the middle of the group (whichever neighbor
                // exists — the earlier one unless this is the group's first note).
                let hook_dir = if run_start > 0 { -1.0 } else { 1.0 };
                let x0 = xs[run_start];
                let x1 = x0 + hook_dir * HOOK_LEN_U * space;
                svg.push_str(&glyphs::beam_segment(
                    x0,
                    level_y(x0),
                    x1,
                    level_y(x1),
                    BEAM_THICKNESS_U * space,
                ));
            } else {
                svg.push_str(&glyphs::beam_segment(
                    xs[run_start],
                    level_y(xs[run_start]),
                    xs[run_end],
                    level_y(xs[run_end]),
                    BEAM_THICKNESS_U * space,
                ));
            }
        }
    }

    BeamPlan { tips, svg }
}

/// Plan a *kneed* beam group whose stems point both ways — typically a cross-staff group,
/// upper-staff notes stemmed down and lower-staff notes stemmed up to one beam between the
/// staves. The primary beam is horizontal, midway between the lowest point the down-stems
/// need and the highest the up-stems allow; secondary beams stack toward the noteheads of
/// the run's first note, and any stem reaching a secondary beam on its far side is extended.
pub(crate) fn plan_kneed_beam_group(
    durations: &[Duration],
    xs: &[f32],
    attach_ys: &[f32],
    stem_ups: &[bool],
    space: f32,
) -> BeamPlan {
    let n = durations.len();
    debug_assert_eq!(xs.len(), n);
    debug_assert_eq!(attach_ys.len(), n);
    debug_assert_eq!(stem_ups.len(), n);
    let stem_xs: Vec<f32> = xs
        .iter()
        .zip(stem_ups)
        .map(|(&x, &up)| x + glyphs::NOTEHEAD_RX_U * space * 0.92 * if up { 1.0 } else { -1.0 })
        .collect();
    let half_stem = glyphs::STEM_WIDTH_U * space / 2.0;
    let levels = durations.iter().map(beam_level).max().unwrap_or(1).max(1);
    let min_stem = MIN_STEM_LEN_U * space;
    let stack = f32::from(levels - 1) * BEAM_LEVEL_GAP_U * space;
    // The beam must lie below every down-stemmed head and above every up-stemmed one.
    let lowest = attach_ys
        .iter()
        .zip(stem_ups)
        .filter(|&(_, &up)| !up)
        .map(|(&y, _)| y + min_stem)
        .fold(f32::NEG_INFINITY, f32::max);
    let highest = attach_ys
        .iter()
        .zip(stem_ups)
        .filter(|&(_, &up)| up)
        .map(|(&y, _)| y - min_stem)
        .fold(f32::INFINITY, f32::min);
    let beam_y = match (lowest.is_finite(), highest.is_finite()) {
        (true, true) => (lowest + highest) / 2.0,
        (true, false) => lowest + stack,
        (false, true) => highest - stack,
        (false, false) => attach_ys.first().copied().unwrap_or(0.0),
    };
    let mut tips: HashMap<usize, f32> = (0..n).map(|i| (i, beam_y)).collect();
    let mut svg = glyphs::beam_segment(
        stem_xs[0] - half_stem,
        beam_y,
        stem_xs[n - 1] + half_stem,
        beam_y,
        BEAM_THICKNESS_U * space,
    );
    let max_level = durations.iter().map(beam_level).max().unwrap_or(1);
    for level in 1..max_level {
        let needs: Vec<bool> = durations.iter().map(|d| beam_level(d) > level).collect();
        let mut i = 0;
        while i < n {
            if !needs[i] {
                i += 1;
                continue;
            }
            let run_start = i;
            while i < n && needs[i] {
                i += 1;
            }
            let run_end = i - 1;
            // Toward the first note's head: below the beam for an up-stem, above for a down.
            let side = if stem_ups[run_start] { 1.0 } else { -1.0 };
            let y = beam_y + side * level as f32 * BEAM_LEVEL_GAP_U * space;
            for (index, &up) in stem_ups
                .iter()
                .enumerate()
                .take(run_end + 1)
                .skip(run_start)
            {
                let tip = tips.entry(index).or_insert(beam_y);
                *tip = if up { tip.min(y) } else { tip.max(y) };
            }
            let (x0, x1) = if run_start == run_end {
                let hook_dir = if run_start > 0 { -1.0 } else { 1.0 };
                let x0 = stem_xs[run_start];
                (x0, x0 + hook_dir * HOOK_LEN_U * space)
            } else {
                (stem_xs[run_start], stem_xs[run_end])
            };
            svg.push_str(&glyphs::beam_segment(
                x0,
                y,
                x1,
                y,
                BEAM_THICKNESS_U * space,
            ));
        }
    }
    BeamPlan { tips, svg }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn kneed_beam_lies_between_down_and_up_stemmed_heads() {
        let durations = vec![Duration::Eighth, Duration::Sixteenth, Duration::Sixteenth];
        let xs = vec![0.0, 20.0, 40.0];
        // Two upper-staff heads (stems down) and one lower-staff head (stem up).
        let attach_ys = vec![100.0, 90.0, 400.0];
        let plan = plan_kneed_beam_group(&durations, &xs, &attach_ys, &[false, false, true], 20.0);
        let primary = plan.tips[&0];
        assert!(primary > 100.0 + MIN_STEM_LEN_U * 20.0);
        assert!(primary < 400.0 - MIN_STEM_LEN_U * 20.0);
        // The sixteenth run's secondary beam sits above the primary (toward the first run
        // note's head), so the up-stemmed lower note is lengthened to reach it.
        assert!(plan.tips[&2] < primary);
        assert!((plan.tips[&1] - primary).abs() < 0.01);
    }

    #[test]
    fn two_note_flat_beam_gives_default_stem_length() {
        // Same pitch (attach_ys equal): rise is 0, so both stems should equal the default.
        let durations = vec![Duration::Eighth, Duration::Eighth];
        let xs = vec![0.0, 20.0];
        let attach_ys = vec![100.0, 100.0];
        let plan = plan_beam_group(&durations, &xs, &attach_ys, true, 20.0);
        assert_eq!(plan.tips.len(), 2);
        for &tip in plan.tips.values() {
            assert!((tip - (100.0 - glyphs::DEFAULT_STEM_LEN_U * 20.0)).abs() < 0.01);
        }
    }

    #[test]
    fn steep_pitch_span_clamps_beam_rise() {
        // A huge pitch difference (10 staff-spaces) must not produce a 10-space beam rise.
        let durations = vec![Duration::Eighth, Duration::Eighth];
        let xs = vec![0.0, 20.0];
        let space = 20.0;
        let attach_ys = vec![100.0, 100.0 - 10.0 * space]; // second note far higher
        let plan = plan_beam_group(&durations, &xs, &attach_ys, true, space);
        let tip0 = plan.tips[&0];
        let tip1 = plan.tips[&1];
        assert!(
            (tip0 - tip1).abs() <= MAX_BEAM_RISE_U * space + 0.01,
            "beam rise must be clamped to {MAX_BEAM_RISE_U} staff-spaces, got {}",
            (tip0 - tip1).abs()
        );
    }

    #[test]
    fn interior_note_never_gets_a_too_short_stem() {
        // Middle note sits much closer to the (flat) beam than the default stem would allow;
        // the whole beam must shift to preserve a minimum stem length for every note.
        let durations = vec![Duration::Eighth, Duration::Eighth, Duration::Eighth];
        let xs = vec![0.0, 20.0, 40.0];
        let space = 20.0;
        // Middle note very close (in the stem-up direction, i.e. numerically just below)
        // the other two notes' natural stem tips.
        let attach_ys = vec![
            100.0,
            100.0 - glyphs::DEFAULT_STEM_LEN_U * space + 5.0,
            100.0,
        ];
        let plan = plan_beam_group(&durations, &xs, &attach_ys, true, space);
        for (i, &attach_y) in attach_ys.iter().enumerate() {
            let stem_len = (plan.tips[&i] - attach_y).abs();
            assert!(
                stem_len >= MIN_STEM_LEN_U * space - 0.01,
                "note {i} stem length {stem_len} is below the {MIN_STEM_LEN_U}-space minimum"
            );
        }
    }

    #[test]
    fn sixteenth_notes_get_a_second_beam_level_spanning_the_whole_group() {
        let durations = vec![Duration::Sixteenth, Duration::Sixteenth];
        let xs = vec![0.0, 20.0];
        let attach_ys = vec![100.0, 100.0];
        let plan = plan_beam_group(&durations, &xs, &attach_ys, true, 20.0);
        // 2 beam segments expected: primary + one secondary run.
        assert_eq!(plan.svg.matches("acorde-beam").count(), 2);
    }

    #[test]
    fn isolated_sixteenth_among_eighths_gets_a_hook_not_a_full_run() {
        let durations = vec![Duration::Sixteenth, Duration::Eighth, Duration::Eighth];
        let xs = vec![0.0, 20.0, 40.0];
        let attach_ys = vec![100.0, 100.0, 100.0];
        let plan = plan_beam_group(&durations, &xs, &attach_ys, true, 20.0);
        // Primary (1) + one isolated hook segment at level 1 (1) = 2 beam polygons.
        assert_eq!(plan.svg.matches("acorde-beam").count(), 2);
    }

    #[test]
    fn stem_down_beam_sits_below_noteheads() {
        let durations = vec![Duration::Eighth, Duration::Eighth];
        let xs = vec![0.0, 20.0];
        let attach_ys = vec![100.0, 100.0];
        let plan = plan_beam_group(&durations, &xs, &attach_ys, false, 20.0);
        for &tip in plan.tips.values() {
            assert!(
                tip > 100.0,
                "stem-down beam tips must be below (larger y than) the notehead"
            );
        }
    }

    #[test]
    fn sloped_beam_bounds_include_clearance_shift_and_secondary_levels() {
        let durations = vec![
            Duration::Sixteenth,
            Duration::Sixteenth,
            Duration::Sixteenth,
        ];
        let xs = vec![0.0, 0.5, 1.0];
        let attach_ys = vec![0.0, -1.0, 0.0];
        let (min_y, max_y) = vertical_extents(&durations, &xs, &attach_ys, true);
        assert!(
            min_y < -3.0,
            "top bound must include secondary beams: {min_y}"
        );
        assert!(
            max_y < -1.5,
            "the inner (secondary) beam must clear the highest notehead: {max_y}"
        );
        let (min_down, max_down) = vertical_extents(&durations, &xs, &attach_ys, false);
        assert!(
            min_down > 1.5,
            "the inner (secondary) beam must clear the lowest notehead: {min_down}"
        );
        assert!(
            max_down > 3.0,
            "bottom bound must include secondary beams: {max_down}"
        );
    }
}