skrifa/outline/autohint/
hint.rs

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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
//! Apply edge hints to an outline.
//!
//! This happens in three passes:
//! 1. Align points that are directly attached to edges. These are the points
//!    which originally generated the edge and are coincident with the edge
//!    coordinate (within a threshold) for a given axis. This may include
//!    points that were originally classified as weak.
//! 2. Interpolate non-weak points that were not touched by the previous pass.
//!    This searches for the edges that enclose the point and interpolates the
//!    coordinate based on the adjustment applied to those edges.
//! 3. Interpolate remaining untouched points. These are generally the weak
//!    points: those that are very near other points or lacking a dominant
//!    inward or outward direction.
//!
//! The final result is a fully hinted outline.

use raw::tables::glyf::PointMarker;

use super::{
    axis::{Axis, Dimension},
    metrics::{fixed_div, fixed_mul, Scale},
    outline::{Outline, Point},
    style::ScriptGroup,
};
use core::cmp::Ordering;

/// Align all points of an edge to the same coordinate value.
///
/// See <https://gitlab.freedesktop.org/freetype/freetype/-/blob/57617782464411201ce7bbc93b086c1b4d7d84a5/src/autofit/afhints.c#L1324>
pub(crate) fn align_edge_points(
    outline: &mut Outline,
    axis: &Axis,
    group: ScriptGroup,
    scale: &Scale,
) -> Option<()> {
    let edges = axis.edges.as_slice();
    let segments = axis.segments.as_slice();
    let points = outline.points.as_mut_slice();
    // Snapping is configurable for CJK
    // See <https://gitlab.freedesktop.org/freetype/freetype/-/blob/57617782464411201ce7bbc93b086c1b4d7d84a5/src/autofit/afcjk.c#L2195>
    let snap = group == ScriptGroup::Default
        || ((axis.dim == Axis::HORIZONTAL && scale.flags & Scale::HORIZONTAL_SNAP != 0)
            || (axis.dim == Axis::VERTICAL && scale.flags & Scale::VERTICAL_SNAP != 0));
    for segment in segments {
        let Some(edge) = segment.edge(edges) else {
            continue;
        };
        let delta = edge.pos - edge.opos;
        let mut point_ix = segment.first();
        let last_ix = segment.last();
        loop {
            let point = points.get_mut(point_ix)?;
            if axis.dim == Axis::HORIZONTAL {
                if snap {
                    point.x = edge.pos;
                } else {
                    point.x += delta;
                }
                point.flags.set_marker(PointMarker::TOUCHED_X);
            } else {
                if snap {
                    point.y = edge.pos;
                } else {
                    point.y += delta;
                }
                point.flags.set_marker(PointMarker::TOUCHED_Y);
            }
            if point_ix == last_ix {
                break;
            }
            point_ix = point.next();
        }
    }
    Some(())
}

/// Align the strong points; equivalent to the TrueType `IP` instruction.
///
/// See <https://gitlab.freedesktop.org/freetype/freetype/-/blob/57617782464411201ce7bbc93b086c1b4d7d84a5/src/autofit/afhints.c#L1399>
pub(crate) fn align_strong_points(outline: &mut Outline, axis: &mut Axis) -> Option<()> {
    if axis.edges.is_empty() {
        return Some(());
    }
    let dim = axis.dim;
    let touch_flag = if dim == Axis::HORIZONTAL {
        PointMarker::TOUCHED_X
    } else {
        PointMarker::TOUCHED_Y
    };
    let points = outline.points.as_mut_slice();
    'points: for point in points {
        // Skip points that are already touched; do weak interpolation in the
        // next pass
        if point
            .flags
            .has_marker(touch_flag | PointMarker::WEAK_INTERPOLATION)
        {
            continue;
        }
        let (u, ou) = if dim == Axis::VERTICAL {
            (point.fy, point.oy)
        } else {
            (point.fx, point.ox)
        };
        let edges = axis.edges.as_mut_slice();
        // Is the point before the first edge?
        let edge = edges.first()?;
        let delta = edge.fpos as i32 - u;
        if delta >= 0 {
            store_point(point, dim, edge.pos - (edge.opos - ou));
            continue;
        }
        // Is the point after the last edge?
        let edge = edges.last()?;
        let delta = u - edge.fpos as i32;
        if delta >= 0 {
            store_point(point, dim, edge.pos + (ou - edge.opos));
            continue;
        }
        // Find enclosing edges; for a small number of edges, use a linear
        // search.
        // Note: this is actually critical for matching FreeType in cases where
        // we have more than one edge with the same fpos. When this happens,
        // linear and binary searches can produce different results.
        // See <https://gitlab.freedesktop.org/freetype/freetype/-/blob/57617782464411201ce7bbc93b086c1b4d7d84a5/src/autofit/afhints.c#L1489>
        let min_ix = if edges.len() <= 8 {
            if let Some((min_ix, edge)) = edges
                .iter()
                .enumerate()
                .find(|(_ix, edge)| edge.fpos as i32 >= u)
            {
                if edge.fpos as i32 == u {
                    store_point(point, dim, edge.pos);
                    continue 'points;
                }
                min_ix
            } else {
                0
            }
        } else {
            let mut min_ix = 0;
            let mut max_ix = edges.len();
            while min_ix < max_ix {
                let mid_ix = (min_ix + max_ix) >> 1;
                let edge = &edges[mid_ix];
                let fpos = edge.fpos as i32;
                match u.cmp(&fpos) {
                    Ordering::Less => max_ix = mid_ix,
                    Ordering::Greater => min_ix = mid_ix + 1,
                    Ordering::Equal => {
                        // We are on an edge
                        store_point(point, dim, edge.pos);
                        continue 'points;
                    }
                }
            }
            min_ix
        };
        // Point is not on an edge
        if let Some(before_ix) = min_ix.checked_sub(1) {
            let edge_before = edges.get(before_ix)?;
            let before_pos = edge_before.pos;
            let before_fpos = edge_before.fpos as i32;
            let scale = if edge_before.scale == 0 {
                let edge_after = edges.get(min_ix)?;
                let scale = fixed_div(
                    edge_after.pos - edge_before.pos,
                    edge_after.fpos as i32 - before_fpos,
                );
                edges[before_ix].scale = scale;
                scale
            } else {
                edge_before.scale
            };
            store_point(point, dim, before_pos + fixed_mul(u - before_fpos, scale));
        }
    }
    Some(())
}

/// Align the weak points; equivalent to the TrueType `IUP` instruction.
///
/// See <https://gitlab.freedesktop.org/freetype/freetype/-/blob/57617782464411201ce7bbc93b086c1b4d7d84a5/src/autofit/afhints.c#L1673>
pub(crate) fn align_weak_points(outline: &mut Outline, dim: Dimension) -> Option<()> {
    let touch_marker = if dim == Axis::HORIZONTAL {
        for point in &mut outline.points {
            point.u = point.x;
            point.v = point.ox;
        }
        PointMarker::TOUCHED_X
    } else {
        for point in &mut outline.points {
            point.u = point.y;
            point.v = point.oy;
        }
        PointMarker::TOUCHED_Y
    };
    for contour in &outline.contours {
        let points = outline.points.get_mut(contour.range())?;
        // Find first touched point
        let Some(first_touched_ix) = points
            .iter()
            .position(|point| point.flags.has_marker(touch_marker))
        else {
            continue;
        };
        let last_ix = points.len() - 1;
        let mut point_ix = first_touched_ix;
        let mut last_touched_ix;
        'outer: loop {
            // Skip any touched neighbors
            while point_ix < last_ix && points.get(point_ix + 1)?.flags.has_marker(touch_marker) {
                point_ix += 1;
            }
            last_touched_ix = point_ix;
            // Find the next touched point
            point_ix += 1;
            loop {
                if point_ix > last_ix {
                    break 'outer;
                }
                if points[point_ix].flags.has_marker(touch_marker) {
                    break;
                }
                point_ix += 1;
            }
            iup_interpolate(
                points,
                last_touched_ix + 1,
                point_ix - 1,
                last_touched_ix,
                point_ix,
            );
        }
        if last_touched_ix == first_touched_ix {
            // Special case: only one point was touched
            iup_shift(points, 0, last_ix, first_touched_ix);
        } else {
            // Interpolate the remainder
            if last_touched_ix < last_ix {
                iup_interpolate(
                    points,
                    last_touched_ix + 1,
                    last_ix,
                    last_touched_ix,
                    first_touched_ix,
                );
            }
            if first_touched_ix > 0 {
                iup_interpolate(
                    points,
                    0,
                    first_touched_ix - 1,
                    last_touched_ix,
                    first_touched_ix,
                );
            }
        }
    }
    // Save interpolated values
    if dim == Axis::HORIZONTAL {
        for point in &mut outline.points {
            point.x = point.u;
        }
    } else {
        for point in &mut outline.points {
            point.y = point.u;
        }
    }
    Some(())
}

#[inline(always)]
fn store_point(point: &mut Point, dim: Dimension, u: i32) {
    if dim == Axis::HORIZONTAL {
        point.x = u;
        point.flags.set_marker(PointMarker::TOUCHED_X);
    } else {
        point.y = u;
        point.flags.set_marker(PointMarker::TOUCHED_Y);
    }
}

/// Shift original coordinates of all points between `p1_ix` and `p2_ix`
/// (inclusive) to get hinted coordinates using the same difference as
/// given by the point at `ref_ix`.
///
/// The `u` and `v` members are the current and original coordinate values,
/// respectively.
///
/// See <https://gitlab.freedesktop.org/freetype/freetype/-/blob/57617782464411201ce7bbc93b086c1b4d7d84a5/src/autofit/afhints.c#L1578>
fn iup_shift(points: &mut [Point], p1_ix: usize, p2_ix: usize, ref_ix: usize) -> Option<()> {
    let ref_point = points.get(ref_ix)?;
    let delta = ref_point.u - ref_point.v;
    if delta == 0 {
        return Some(());
    }
    for point in points.get_mut(p1_ix..ref_ix)? {
        point.u = point.v + delta;
    }
    for point in points.get_mut(ref_ix + 1..=p2_ix)? {
        point.u = point.v + delta;
    }
    Some(())
}

/// Interpolate the original coordinates all of points between `p1_ix` and
/// `p2_ix` (inclusive) to get hinted coordinates, using the points at
/// `ref1_ix` and `ref2_ix` as the reference points.
///
/// The `u` and `v` members are the current and original coordinate values,
/// respectively.
///
/// See <https://gitlab.freedesktop.org/freetype/freetype/-/blob/57617782464411201ce7bbc93b086c1b4d7d84a5/src/autofit/afhints.c#L1605>
fn iup_interpolate(
    points: &mut [Point],
    p1_ix: usize,
    p2_ix: usize,
    ref1_ix: usize,
    ref2_ix: usize,
) -> Option<()> {
    if p1_ix > p2_ix {
        return Some(());
    }
    let mut ref_point1 = points.get(ref1_ix)?;
    let mut ref_point2 = points.get(ref2_ix)?;
    if ref_point1.v > ref_point2.v {
        core::mem::swap(&mut ref_point1, &mut ref_point2);
    }
    let (u1, v1) = (ref_point1.u, ref_point1.v);
    let (u2, v2) = (ref_point2.u, ref_point2.v);
    let d1 = u1 - v1;
    let d2 = u2 - v2;
    if u1 == u2 || v1 == v2 {
        for point in points.get_mut(p1_ix..=p2_ix)? {
            point.u = if point.v <= v1 {
                point.v + d1
            } else if point.v >= v2 {
                point.v + d2
            } else {
                u1
            };
        }
    } else {
        let scale = fixed_div(u2 - u1, v2 - v1);
        for point in points.get_mut(p1_ix..=p2_ix)? {
            point.u = if point.v <= v1 {
                point.v + d1
            } else if point.v >= v2 {
                point.v + d2
            } else {
                u1 + fixed_mul(point.v - v1, scale)
            };
        }
    }
    Some(())
}

#[cfg(test)]
mod tests {
    use super::{
        super::{
            latin,
            metrics::Scale,
            shape::{Shaper, ShaperMode},
            style,
        },
        *,
    };
    use crate::{attribute::Style, MetadataProvider};
    use raw::{
        types::{F2Dot14, GlyphId},
        FontRef, TableProvider,
    };

    #[test]
    fn hinted_coords_and_metrics_default() {
        let font = FontRef::new(font_test_data::NOTOSERIFHEBREW_AUTOHINT_METRICS).unwrap();
        let (outline, metrics) = hint_outline(
            &font,
            16.0,
            Default::default(),
            GlyphId::new(9),
            &style::STYLE_CLASSES[style::StyleClass::HEBR],
        );
        // Expected values were painfully extracted from FreeType with some
        // printf debugging
        #[rustfmt::skip]
        let expected_coords = [
            (133, -256),
            (133, 282),
            (133, 343),
            (146, 431),
            (158, 463),
            (158, 463),
            (57, 463),
            (30, 463),
            (0, 495),
            (0, 534),
            (0, 548),
            (2, 570),
            (11, 604),
            (17, 633),
            (50, 633),
            (50, 629),
            (50, 604),
            (77, 576),
            (101, 576),
            (163, 576),
            (180, 576),
            (192, 562),
            (192, 542),
            (192, 475),
            (190, 457),
            (187, 423),
            (187, 366),
            (187, 315),
            (187, -220),
            (178, -231),
            (159, -248),
            (146, -256),
        ];
        let coords = outline
            .points
            .iter()
            .map(|point| (point.x, point.y))
            .collect::<Vec<_>>();
        assert_eq!(coords, expected_coords);
        let expected_metrics = latin::HintedMetrics {
            x_scale: 67109,
            edge_metrics: Some(latin::EdgeMetrics {
                left_opos: 15,
                left_pos: 0,
                right_opos: 210,
                right_pos: 192,
            }),
        };
        assert_eq!(metrics, expected_metrics);
    }

    #[test]
    fn hinted_coords_and_metrics_cjk() {
        let font = FontRef::new(font_test_data::NOTOSERIFTC_AUTOHINT_METRICS).unwrap();
        let (outline, metrics) = hint_outline(
            &font,
            16.0,
            Default::default(),
            GlyphId::new(9),
            &style::STYLE_CLASSES[style::StyleClass::HANI],
        );
        // Expected values were painfully extracted from FreeType with some
        // printf debugging
        let expected_coords = [
            (279, 768),
            (568, 768),
            (618, 829),
            (618, 829),
            (634, 812),
            (657, 788),
            (685, 758),
            (695, 746),
            (692, 720),
            (667, 720),
            (288, 720),
            (704, 704),
            (786, 694),
            (785, 685),
            (777, 672),
            (767, 670),
            (767, 163),
            (767, 159),
            (750, 148),
            (728, 142),
            (716, 142),
            (704, 142),
            (402, 767),
            (473, 767),
            (473, 740),
            (450, 598),
            (338, 357),
            (236, 258),
            (220, 270),
            (274, 340),
            (345, 499),
            (390, 675),
            (344, 440),
            (398, 425),
            (464, 384),
            (496, 343),
            (501, 307),
            (486, 284),
            (458, 281),
            (441, 291),
            (434, 314),
            (398, 366),
            (354, 416),
            (334, 433),
            (832, 841),
            (934, 830),
            (932, 819),
            (914, 804),
            (896, 802),
            (896, 30),
            (896, 5),
            (885, -35),
            (848, -60),
            (809, -65),
            (807, -51),
            (794, -27),
            (781, -19),
            (767, -11),
            (715, 0),
            (673, 5),
            (673, 21),
            (673, 21),
            (707, 18),
            (756, 15),
            (799, 13),
            (807, 13),
            (821, 13),
            (832, 23),
            (832, 35),
            (407, 624),
            (594, 624),
            (594, 546),
            (396, 546),
            (569, 576),
            (558, 576),
            (599, 614),
            (677, 559),
            (671, 552),
            (654, 547),
            (636, 545),
            (622, 458),
            (572, 288),
            (488, 130),
            (357, -5),
            (259, -60),
            (246, -45),
            (327, 9),
            (440, 150),
            (516, 311),
            (558, 486),
            (128, 542),
            (158, 581),
            (226, 576),
            (223, 562),
            (207, 543),
            (193, 539),
            (193, -44),
            (193, -46),
            (175, -56),
            (152, -64),
            (141, -64),
            (128, -64),
            (195, 850),
            (300, 820),
            (295, 799),
            (259, 799),
            (234, 712),
            (163, 543),
            (80, 395),
            (33, 338),
            (19, 347),
            (54, 410),
            (120, 575),
            (176, 759),
        ];
        let coords = outline
            .points
            .iter()
            .map(|point| (point.x, point.y))
            .collect::<Vec<_>>();
        assert_eq!(coords, expected_coords);
        let expected_metrics = latin::HintedMetrics {
            x_scale: 67109,
            edge_metrics: Some(latin::EdgeMetrics {
                left_opos: 141,
                left_pos: 128,
                right_opos: 933,
                right_pos: 896,
            }),
        };
        assert_eq!(metrics, expected_metrics);
    }

    /// Empty glyphs (like spaces) have no edges and therefore no edge
    /// metrics
    #[test]
    fn missing_edge_metrics() {
        let font = FontRef::new(font_test_data::CUBIC_GLYF).unwrap();
        let (_outline, metrics) = hint_outline(
            &font,
            16.0,
            Default::default(),
            GlyphId::new(1),
            &style::STYLE_CLASSES[style::StyleClass::LATN],
        );
        let expected_metrics = latin::HintedMetrics {
            x_scale: 65536,
            edge_metrics: None,
        };
        assert_eq!(metrics, expected_metrics);
    }

    // Specific test case for <https://issues.skia.org/issues/344529168> which
    // uses the Ahem <https://web-platform-tests.org/writing-tests/ahem.html>
    // font
    #[test]
    fn skia_ahem_test_case() {
        let font = FontRef::new(font_test_data::AHEM).unwrap();
        let outline = hint_outline(
            &font,
            24.0,
            Default::default(),
            // This glyph is the typical Ahem block square; the link to the
            // font description above more detail.
            GlyphId::new(5),
            &style::STYLE_CLASSES[style::StyleClass::LATN],
        )
        .0;
        let expected_coords = [(0, 1216), (1536, 1216), (1536, -320), (0, -320)];
        // See <https://issues.skia.org/issues/344529168#comment3>
        // Note that Skia inverts y coords
        let expected_float_coords = [(0.0, 19.0), (24.0, 19.0), (24.0, -5.0), (0.0, -5.0)];
        let coords = outline
            .points
            .iter()
            .map(|point| (point.x, point.y))
            .collect::<Vec<_>>();
        let float_coords = coords
            .iter()
            .map(|(x, y)| (*x as f32 / 64.0, *y as f32 / 64.0))
            .collect::<Vec<_>>();
        assert_eq!(coords, expected_coords);
        assert_eq!(float_coords, expected_float_coords);
    }

    fn hint_outline(
        font: &FontRef,
        size: f32,
        coords: &[F2Dot14],
        gid: GlyphId,
        style: &style::StyleClass,
    ) -> (Outline, latin::HintedMetrics) {
        let shaper = Shaper::new(font, ShaperMode::Nominal);
        let glyphs = font.outline_glyphs();
        let glyph = glyphs.get(gid).unwrap();
        let mut outline = Outline::default();
        outline.fill(&glyph, coords).unwrap();
        let metrics = latin::compute_unscaled_style_metrics(&shaper, coords, style);
        let scale = Scale::new(
            size,
            font.head().unwrap().units_per_em() as i32,
            Style::Normal,
            Default::default(),
            metrics.style_class().script.group,
        );
        let hinted_metrics = latin::hint_outline(&mut outline, &metrics, &scale, None);
        (outline, hinted_metrics)
    }
}