mln-rs-engine 0.0.22

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
use std::sync::Arc;

use mln_style::bitmap::PremultipliedImage;
use mln_style::i18n;
use mln_style::image::StyleImage;
use mln_style::size::Size;
use mln_style::types::{IconTextFitType, SymbolAnchorType, TextJustifyType, TextWritingModeType, VerticalAlign};

use crate::text::atlas::{ImagePosition, ImagePositions, RectU16};
use crate::text::constants::ONE_EM;
use crate::text::font_stack::FontStack;
use crate::text::glyph::{
    Bounds, GlyphFont, GlyphID, GlyphMetrics, GlyphPosition, GlyphPositions, PositionedGlyph, PositionedLine, Shaping,
    face_type,
};
use crate::text::shaper::{GlyphAdjust, ShapedText};
use crate::text::shaping::{PositionedIcon, ShapingOptions, shape_text};
use crate::text::tagged_string::{SectionOptions, TaggedString, font_stack_hash};

fn u(s: &str) -> Vec<char> {
    s.chars().collect()
}

fn font_stack() -> FontStack {
    vec!["font-stack".to_owned()]
}

fn pbf_section(scale: f32) -> SectionOptions {
    SectionOptions::new(scale, font_stack(), GlyphFont::FontPBF, None)
}

/// Glyphs that advance 12 for every character of `string`, its vertical
/// punctuation and its shaped sections' glyphs.
fn stub_glyphs(string: &TaggedString) -> GlyphPositions {
    let metrics = GlyphMetrics { width: 10, height: 18, left: 1.0, top: -8.0, advance: 12, ..Default::default() };
    let position = GlyphPosition { metrics, ..Default::default() };
    let mut glyph_positions = GlyphPositions::new();
    for i in 0..string.len() {
        let section = string.section_of(i);
        if section.image_id.is_some() {
            continue;
        }
        let glyphs: Vec<GlyphID> = match &section.shaped {
            Some(shaped) => shaped.glyphs.clone(),
            None => std::iter::once(string.text()[i])
                .chain(i18n::verticalize_punctuation(string.text()[i]).filter(|_| section.font == GlyphFont::FontPBF))
                .map(|c| GlyphID::from_char(c).unwrap())
                .collect(),
        };
        for glyph in glyphs {
            glyph_positions.entry(section.font_stack_hash).or_default().insert(glyph, Some(position));
        }
    }
    glyph_positions
}

fn options(writing_mode: TextWritingModeType, allow_vertical_placement: bool, max_width: f32) -> ShapingOptions {
    ShapingOptions {
        max_width,
        line_height: ONE_EM,
        anchor: SymbolAnchorType::TopLeft,
        justify: TextJustifyType::Left,
        spacing: 0.0,
        offset: [0.0, 0.0],
        writing_mode,
        allow_vertical_placement,
        text_size: ONE_EM,
        text_size_at_bucket_zoom: ONE_EM,
    }
}

fn shape(string: &TaggedString, options: &ShapingOptions, image_positions: &ImagePositions) -> Shaping {
    shape_text(string, options, &stub_glyphs(string), image_positions)
}

fn shape_vertical(string: &TaggedString) -> Shaping {
    shape(string, &options(TextWritingModeType::Vertical, false, 4096.0), &ImagePositions::default())
}

fn shape_horizontal(string: &TaggedString) -> Shaping {
    shape(string, &options(TextWritingModeType::Horizontal, false, 4096.0), &ImagePositions::default())
}

/// Each glyph's orientation in a line label: `U` for upright, `-` for along
/// the line.
fn orientations(shaping: &Shaping) -> String {
    shaping.lines.iter().flat_map(|line| &line.glyphs).map(|glyph| if glyph.vertical { 'U' } else { '-' }).collect()
}

fn codes(shaping: &Shaping) -> String {
    shaping
        .lines
        .iter()
        .flat_map(|line| line.glyphs.iter().map(|glyph| char::from_u32(glyph.glyph.code.into()).unwrap()))
        .collect()
}

#[test]
fn zero_width_spaces_break_lines_that_overflow() {
    // (text, maximum width in ems, lines)
    let cases = [
        ("中中\u{200b}中中\u{200b}中中\u{200b}中中中中中中\u{200b}中中", 5.0, 3),
        ("中中\u{200b}中", 1.0, 2),
        ("中中\u{200b}", 2.0, 1),
        // At a width of 0, every zero width space breaks.
        ("中中\u{200b}中\u{200b}中", 0.0, 3),
        // No empty line before leading whitespace or after a newline.
        (" 中中", 0.0, 2),
        ("中\n 中", 0.0, 2),
        // No line starts at a zero width space.
        ("\u{200b}\u{200b}\u{200b}\u{200b}\u{200b}", 1.0, 1),
    ];
    // Only 中 has a glyph, 21 wide.
    let metrics = GlyphMetrics { width: 18, height: 18, left: 2.0, top: -8.0, advance: 21, ..Default::default() };
    let mut glyph_positions = GlyphPositions::new();
    glyph_positions
        .entry(font_stack_hash(&font_stack()))
        .or_default()
        .insert(GlyphID::from_char('中').unwrap(), Some(GlyphPosition { metrics, ..Default::default() }));
    for (text, max_width, lines) in cases {
        let string = TaggedString::new(u(text), pbf_section(1.0));
        let shaping = shape_text(
            &string,
            &ShapingOptions {
                text_size: 16.0,
                text_size_at_bucket_zoom: 16.0,
                ..options(TextWritingModeType::Horizontal, false, max_width * ONE_EM)
            },
            &glyph_positions,
            &ImagePositions::default(),
        );
        assert_eq!(shaping.lines.len(), lines, "{text:?} at {max_width} ems");
    }
}

/// Which characters of a line label stand upright on a vertical line. The
/// render suite's vertical line labels pin the cases of Han text with Latin
/// letters and ASCII digits.
#[test]
fn line_labels_stand_upright_the_characters_of_vertical_writing() {
    // (text, orientations)
    let cases = [
        // Digits of any length, and short codes of uppercase letters and
        // digits, in any script with case, stand with the Han around them.
        ("国道1234号", "UUUUUUU"),
        ("国道A号", "UUUU"),
        ("JR山手線", "UUUUU"),
        ("国道\u{041C}1号", "UUUUU"),
        ("国道১২号", "UUUUU"),
        // Lowercase letters, scripts without case, and characters with a
        // combining mark turn with the line.
        ("国道α号", "UU-U"),
        ("国道ب号", "UU-U"),
        ("国道e\u{0301}号", "UU--U"),
        ("国道1\u{0301}号", "UU--U"),
        ("国道١٢号", "UU--U"),
        ("銀座Ginza通り", "UU-----UU"),
        ("国道3.5km", "UU-----"),
    ];
    for (text, expected) in cases {
        let string = TaggedString::new(u(text), pbf_section(1.0));
        assert_eq!(orientations(&shape_vertical(&string)), expected, "{text:?}");
    }
}

#[test]
fn writing_mode_and_vertical_placement_decide_the_orientation_of_every_glyph() {
    let string = TaggedString::new(u("two 身什戰"), pbf_section(1.0));
    let horizontal =
        shape(&string, &options(TextWritingModeType::Horizontal, false, 4096.0), &ImagePositions::default());
    assert_eq!(orientations(&horizontal), "-------");
    // A point label placed vertically stands every character but whitespace.
    let placed = shape(&string, &options(TextWritingModeType::Vertical, true, 4096.0), &ImagePositions::default());
    assert_eq!(orientations(&placed), "UUU-UUU");
}

#[test]
fn a_missing_glyph_leaves_the_orientations_of_the_others() {
    let string = TaggedString::new(u("what 国21号"), pbf_section(1.0));
    let mut glyph_positions = stub_glyphs(&string);
    for glyphs in glyph_positions.values_mut() {
        glyphs.remove(&GlyphID::from_char('w').unwrap());
    }
    let shaping = shape_text(
        &string,
        &options(TextWritingModeType::Vertical, false, 4096.0),
        &glyph_positions,
        &ImagePositions::default(),
    );
    assert_eq!(codes(&shaping), "hat 国21号");
    assert_eq!(orientations(&shaping), "----UUUU");
}

#[test]
fn sections_of_another_kind_end_an_upright_run() {
    // Sections of glyph PBFs at other scales are one run: four letters turn.
    let mut scaled = TaggedString::default();
    scaled.add_text_section(&u("AB"), pbf_section(1.0));
    scaled.add_text_section(&u("CD"), pbf_section(0.5));
    assert_eq!(orientations(&shape_vertical(&scaled)), "----");

    // An image splits them into two runs of two, which stand.
    let mut with_image = TaggedString::default();
    with_image.add_text_section(&u("AB"), pbf_section(1.0));
    with_image.add_image_section("image", VerticalAlign::Bottom);
    with_image.add_text_section(&u("CD"), pbf_section(1.0));
    let image = StyleImage::new(
        "image".into(),
        PremultipliedImage::new(Size::new(12, 24)),
        1.0,
        false,
        vec![],
        vec![],
        None,
        None,
        None,
    )
    .unwrap();
    let mut image_positions = ImagePositions::default();
    image_positions.insert("image".into(), ImagePosition::new(RectU16 { x: 0, y: 0, w: 14, h: 26 }, &image));
    let shaping = shape(&with_image, &options(TextWritingModeType::Vertical, false, 4096.0), &image_positions);
    assert_eq!(orientations(&shaping), "UU-UU");
    assert_eq!(shaping.lines[0].glyphs[2].image_id.as_deref(), Some("image"));
    assert!(shaping.icons_in_text);

    // So does a section of a font face, whose glyphs turn.
    let face = face_type("shaping-test-native", "font-stack", &[(0, 0xffff)]);
    let mut with_face = TaggedString::default();
    with_face.add_text_section(&u("AB"), pbf_section(1.0));
    with_face.add_text_section(&u("C"), SectionOptions::new(1.0, font_stack(), face, None));
    with_face.add_text_section(&u("D"), pbf_section(1.0));
    assert_eq!(orientations(&shape_vertical(&with_face)), "UU-U");
}

/// A label with a section of glyphs that a font face shaped, standing in as
/// "XY", between sections drawn from glyph PBFs.
fn label_with_shaped_section(before: &str, rtl: bool, after: &str, adjusts: Vec<GlyphAdjust>) -> TaggedString {
    let shaped_type = face_type("shaping-test-shaped", "font-stack", &[(0, 0xffff)]);
    let mut text = TaggedString::default();
    if !before.is_empty() {
        text.add_text_section(&u(before), pbf_section(1.0));
    }
    let glyphs =
        vec![GlyphID::with_type(u16::from(b'X'), shaped_type), GlyphID::with_type(u16::from(b'Y'), shaped_type)];
    let shaped = Arc::new(ShapedText { glyphs, adjusts });
    text.add_shaped_section(&shaped, rtl, SectionOptions::new(1.0, font_stack(), shaped_type, None));
    if !after.is_empty() {
        text.add_text_section(&u(after), pbf_section(1.0));
    }
    text
}

#[test]
fn a_right_to_left_shaped_section_takes_its_place_in_the_line() {
    // (before, right to left, after, glyphs from left to right)
    let cases = [
        // A label that starts right to left reads from the right.
        ("", true, " Erbil", "Erbil XY"),
        ("", true, " 12", "12 XY"),
        ("Erbil ", true, "", "Erbil XY"),
        ("a ", false, " b", "a XY b"),
    ];
    for (before, rtl, after, expected) in cases {
        let shaping = shape_horizontal(&label_with_shaped_section(before, rtl, after, vec![]));
        assert_eq!(codes(&shaping), expected, "{before:?} {after:?}");
    }
}

#[test]
fn a_shaped_section_keeps_its_advances_when_it_moves() {
    let adjusts = vec![GlyphAdjust::new(0.0, 0.0, 5.0), GlyphAdjust::new(0.0, 0.0, 7.0)];
    let shaping = shape_horizontal(&label_with_shaped_section("", true, " 12", adjusts));
    let glyphs = &shaping.lines[0].glyphs;
    assert_eq!(codes(&shaping), "12 XY");
    assert_eq!(glyphs[4].x - glyphs[3].x, 5.0);
}

#[test]
fn shaped_glyphs_take_up_their_advances_on_a_line() {
    let adjusts = vec![GlyphAdjust::new(0.0, 0.0, 100.0), GlyphAdjust::new(0.0, 0.0, 100.0)];
    let text = label_with_shaped_section("", false, " ab", adjusts);
    let shaping = shape(&text, &options(TextWritingModeType::Horizontal, false, 150.0), &ImagePositions::default());
    assert_eq!(shaping.lines.len(), 2);
}

#[test]
fn fit_to_text_divides_the_text_and_padding_by_the_icon_size() {
    let image = StyleImage::new(
        "test".into(),
        PremultipliedImage::new(Size::new(20, 20)),
        1.0,
        false,
        vec![],
        vec![],
        None,
        None,
        None,
    )
    .unwrap();
    let image = ImagePosition::new(RectU16 { x: 0, y: 0, w: 22, h: 22 }, &image);
    let text = Shaping {
        lines: vec![PositionedLine {
            glyphs: vec![PositionedGlyph { glyph: GlyphID::new(32), scale: 1.0, ..Default::default() }],
            line_offset: 0.0,
        }],
        bounds: Bounds { left: -60.0, top: -10.0, right: 20.0, bottom: 30.0 },
        ..Default::default()
    };
    let fit = |fit: IconTextFitType, icon_size: f32| {
        let mut icon = PositionedIcon::new(&image, [0.0, 0.0], SymbolAnchorType::Center);
        icon.fit_to_text(&text, fit, [5.0, 10.0, 5.0, 10.0], [4.0, 6.0], 0.5, icon_size);
        icon.bounds
    };

    // The text at half size, -30..10 by -5..15, and its padding, halved,
    // then offset in the units that the icon size scales.
    assert_eq!(fit(IconTextFitType::Both, 2.0), Bounds { left: -16.0, top: 1.0, right: 14.0, bottom: 16.0 });
    // On the axis it doesn't fit, the image keeps its own size, centred on
    // the fitted text.
    assert_eq!(fit(IconTextFitType::Width, 2.0), Bounds { left: -16.0, top: -1.5, right: 14.0, bottom: 18.5 });
    assert_eq!(fit(IconTextFitType::Height, 2.0), Bounds { left: -11.0, top: 1.0, right: 9.0, bottom: 16.0 });
    // An icon of no size keeps the text's size.
    assert_eq!(fit(IconTextFitType::Both, 0.0), fit(IconTextFitType::Both, 1.0));
}