Skip to main content

read_fonts/tables/gvar/
deltas.rs

1//! Computation of glyph point deltas from the `gvar` table.
2//!
3//! Tuples in a glyph's variation data come in two shapes. A *dense* tuple
4//! carries a delta for every point and is simply accumulated. A *sparse* tuple
5//! carries deltas for a subset, and the deltas for the remaining points have to
6//! be inferred by interpolating between the nearest referenced points on either
7//! side, in the manner of the `IUP` hinting instruction.
8//!
9//! See [inferred deltas for un-referenced point numbers](https://learn.microsoft.com/en-us/typography/opentype/spec/gvar#inferred-deltas-for-un-referenced-point-numbers).
10
11use core::ops::Range;
12
13use super::{GlyphDelta, GlyphVariationData, Gvar, GvarExtended, SelectedGvar};
14use crate::{
15    tables::{
16        glyf::{PointCoord, PointFlags, PointMarker, PHANTOM_POINT_COUNT},
17        variations::TupleVariation,
18    },
19    types::{F2Dot14, Fixed, GlyphId, Point},
20    ReadError,
21};
22
23/// Caller-provided storage for [`Gvar::simple_deltas`] and
24/// [`GlyphVariationData::simple_deltas`].
25///
26/// Both slices must be at least as long as the glyph's point count, including
27/// the phantom points.
28pub struct DeltaBuffers<'a, D: PointCoord> {
29    /// Receives the computed deltas.
30    pub deltas: &'a mut [Point<D>],
31    /// Working space used to interpolate the deltas of points that a sparse
32    /// tuple does not reference.
33    pub iup: &'a mut [Point<D>],
34}
35
36macro_rules! impl_gvar_deltas {
37    ($table:ident) => {
38        impl $table<'_> {
39            /// Computes the deltas for the points of a simple glyph at the given
40            /// location in variation space.
41            ///
42            /// Looks the glyph's variation data up and hands off to
43            /// [`GlyphVariationData::simple_deltas`], which documents the arguments.
44            ///
45            /// Returns `true` if the glyph has variation data, and `false` if it does
46            /// not — in which case the deltas are zeroed. Note that they are zeroed
47            /// whichever it returns, so they never retain values from a previous call.
48            pub fn simple_deltas<C, D>(
49                &self,
50                glyph_id: GlyphId,
51                coords: &[F2Dot14],
52                points: &[Point<C>],
53                flags: &mut [PointFlags],
54                contours: &[u16],
55                buffers: &mut DeltaBuffers<'_, D>,
56            ) -> Option<bool>
57            where
58                C: PointCoord,
59                D: PointCoord + From<C>,
60            {
61                self.simple_deltas_with_scalars(
62                    glyph_id,
63                    coords,
64                    &[],
65                    points,
66                    flags,
67                    contours,
68                    buffers,
69                )
70            }
71
72            /// Computes the deltas for the points of a simple glyph, reusing
73            /// `scalars`.
74            ///
75            /// `scalars` holds one entry per shared tuple, from
76            /// [`Gvar::compute_scalars`]. It may be empty or cover only some of them;
77            /// the rest are computed here.
78            #[allow(clippy::too_many_arguments)]
79            pub fn simple_deltas_with_scalars<C, D>(
80                &self,
81                glyph_id: GlyphId,
82                coords: &[F2Dot14],
83                scalars: &[Fixed],
84                points: &[Point<C>],
85                flags: &mut [PointFlags],
86                contours: &[u16],
87                buffers: &mut DeltaBuffers<'_, D>,
88            ) -> Option<bool>
89            where
90                C: PointCoord,
91                D: PointCoord + From<C>,
92            {
93                check_simple_buffers(points, flags, buffers).ok()?;
94                let Ok(Some(var_data)) = self.glyph_variation_data(glyph_id) else {
95                    // Missing or malformed variation data for a glyph is not an error.
96                    zero(buffers.deltas);
97                    return Some(false);
98                };
99                var_data.simple_deltas_with_scalars(
100                    coords, scalars, points, flags, contours, buffers,
101                )?;
102                Some(true)
103            }
104
105            /// Computes the deltas for the component offsets of a composite glyph at
106            /// the given location in variation space.
107            ///
108            /// Looks the glyph's variation data up and hands off to
109            /// [`GlyphVariationData::composite_deltas`].
110            ///
111            /// `deltas` must have one entry per component plus four for the phantom
112            /// points.
113            ///
114            /// Returns `true` if the glyph has variation data, and `false` if it does
115            /// not — in which case `deltas` is zeroed.
116            pub fn composite_deltas<D: PointCoord>(
117                &self,
118                glyph_id: GlyphId,
119                coords: &[F2Dot14],
120                deltas: &mut [Point<D>],
121            ) -> Option<bool> {
122                self.composite_deltas_with_scalars(glyph_id, coords, &[], deltas)
123            }
124
125            /// Computes the deltas for a composite glyph's component offsets,
126            /// reusing `scalars`.
127            ///
128            /// `scalars` holds one entry per shared tuple, from
129            /// [`Gvar::compute_scalars`]. It may be empty or cover only some of them;
130            /// the rest are computed here.
131            pub fn composite_deltas_with_scalars<D: PointCoord>(
132                &self,
133                glyph_id: GlyphId,
134                coords: &[F2Dot14],
135                scalars: &[Fixed],
136                deltas: &mut [Point<D>],
137            ) -> Option<bool> {
138                let Ok(Some(var_data)) = self.glyph_variation_data(glyph_id) else {
139                    zero(deltas);
140                    return Some(false);
141                };
142                var_data.composite_deltas_with_scalars(coords, scalars, deltas)?;
143                Some(true)
144            }
145        }
146    };
147}
148
149impl_gvar_deltas!(Gvar);
150impl_gvar_deltas!(GvarExtended);
151impl_gvar_deltas!(SelectedGvar);
152
153impl GlyphVariationData<'_> {
154    /// Computes the deltas for the points of a simple glyph at the given
155    /// location in variation space.
156    ///
157    /// Deltas for points that a sparse tuple does not reference are inferred by
158    /// interpolation, so this needs the glyph's points and contour end points
159    /// in addition to the buffers it writes.
160    ///
161    /// * `points` and `contours` describe the unvaried glyph. `points` must
162    ///   include the four phantom points.
163    /// * `flags` is used as scratch: the [`PointMarker::HAS_DELTA`] marker is
164    ///   cleared and set as tuples are processed.
165    /// * `buffers` supplies the output and interpolation storage.
166    ///
167    /// `flags` and both buffers must be at least as long as `points`, which
168    /// is what everything here is indexed by.
169    ///
170    /// The deltas are zeroed before anything else happens, so they never
171    /// retain values from a previous call.
172    ///
173    /// See [`Gvar::simple_deltas`] to look a glyph's data up first.
174    pub fn simple_deltas<C, D>(
175        &self,
176        coords: &[F2Dot14],
177        points: &[Point<C>],
178        flags: &mut [PointFlags],
179        contours: &[u16],
180        buffers: &mut DeltaBuffers<'_, D>,
181    ) -> Option<()>
182    where
183        C: PointCoord,
184        D: PointCoord + From<C>,
185    {
186        self.simple_deltas_with_scalars(coords, &[], points, flags, contours, buffers)
187    }
188
189    /// Computes the deltas for the points of a simple glyph, reusing
190    /// `scalars`.
191    ///
192    /// `scalars` holds one entry per shared tuple, from
193    /// [`Gvar::compute_scalars`]. It may be empty or cover only some of them;
194    /// the rest are computed here.
195    #[allow(clippy::too_many_arguments)]
196    pub fn simple_deltas_with_scalars<C, D>(
197        &self,
198        coords: &[F2Dot14],
199        scalars: &[Fixed],
200        points: &[Point<C>],
201        flags: &mut [PointFlags],
202        contours: &[u16],
203        buffers: &mut DeltaBuffers<'_, D>,
204    ) -> Option<()>
205    where
206        C: PointCoord,
207        D: PointCoord + From<C>,
208    {
209        check_simple_buffers(points, flags, buffers).ok()?;
210        let DeltaBuffers { deltas, iup } = buffers;
211        self.accumulate_deltas(coords, scalars, deltas, |scalar, tuple, deltas| {
212            // Prepare the working buffer by converting the points to 16.16,
213            // then drop the markers left by the previous tuple. Kept as two
214            // passes: fused, the read-modify-write on the flags blocks the
215            // conversion from vectorizing.
216            for (point, iup_point) in points.iter().zip(&mut iup[..]) {
217                *iup_point = point.map(D::from);
218            }
219            for flag in flags.iter_mut() {
220                flag.clear_marker(PointMarker::HAS_DELTA);
221            }
222            tuple.accumulate_sparse_deltas(iup, flags, scalar)?;
223            interpolate_deltas(points, flags, contours, &mut iup[..])
224                .ok_or(ReadError::OutOfBounds)?;
225            for ((delta, point), iup_point) in deltas.iter_mut().zip(points).zip(iup.iter()) {
226                *delta += *iup_point - point.map(D::from);
227            }
228            Ok(())
229        })
230        .ok()
231    }
232
233    /// Computes the deltas for the component offsets of a composite glyph at
234    /// the given location in variation space.
235    ///
236    /// Interpolation is meaningless for component offsets, so this skips the
237    /// expensive part of [`Self::simple_deltas`] and needs no scratch.
238    ///
239    /// `deltas` must have one entry per component plus four for the phantom
240    /// points, and is zeroed first.
241    ///
242    /// See [`Gvar::composite_deltas`] to look a glyph's data up first.
243    pub fn composite_deltas<D: PointCoord>(
244        &self,
245        coords: &[F2Dot14],
246        deltas: &mut [Point<D>],
247    ) -> Option<()> {
248        self.composite_deltas_with_scalars(coords, &[], deltas)
249    }
250
251    /// Computes the deltas for a composite glyph's component offsets,
252    /// reusing `scalars`.
253    ///
254    /// `scalars` holds one entry per shared tuple, from
255    /// [`Gvar::compute_scalars`]. It may be empty or cover only some of them;
256    /// the rest are computed here.
257    pub fn composite_deltas_with_scalars<D: PointCoord>(
258        &self,
259        coords: &[F2Dot14],
260        scalars: &[Fixed],
261        deltas: &mut [Point<D>],
262    ) -> Option<()> {
263        self.accumulate_deltas(coords, scalars, deltas, |scalar, tuple, deltas| {
264            for tuple_delta in tuple.deltas() {
265                let ix = tuple_delta.position as usize;
266                if let Some(delta) = deltas.get_mut(ix) {
267                    *delta += tuple_delta.apply_scalar(scalar);
268                }
269            }
270            Ok(())
271        })
272        .ok()
273    }
274
275    /// The parts shared by simple and composite glyph processing.
276    ///
277    /// Zeroes `deltas`, then accumulates every tuple that is active at
278    /// `coords`. Dense tuples are handled here; sparse tuples are passed to
279    /// `apply_sparse_tuple`, which differs between the two glyph kinds.
280    fn accumulate_deltas<D: PointCoord>(
281        &self,
282        coords: &[F2Dot14],
283        scalars: &[Fixed],
284        deltas: &mut [Point<D>],
285        mut apply_sparse_tuple: impl FnMut(
286            Fixed,
287            TupleVariation<GlyphDelta>,
288            &mut [Point<D>],
289        ) -> Result<(), ReadError>,
290    ) -> Result<(), ReadError> {
291        // Callers must never observe values left over from a previous glyph.
292        zero(deltas);
293        for (tuple, scalar) in self.active_tuples_at_with_scalars(coords, scalars) {
294            if tuple.has_deltas_for_all_points() {
295                // Fast path: the tuple covers every point, so the deltas can be
296                // accumulated directly with no interpolation.
297                tuple.accumulate_dense_deltas(deltas, scalar)?;
298            } else {
299                apply_sparse_tuple(scalar, tuple, deltas)?;
300            }
301        }
302        Ok(())
303    }
304}
305
306/// The buffer requirements shared by both entry points to simple glyph
307/// processing.
308///
309/// Everything hinges on `points`, which carries the glyph's real point count:
310/// each of the others is indexed or zipped by point, so one that is short
311/// either truncates the result silently or fails later with a less useful
312/// error.
313fn check_simple_buffers<C: PointCoord, D: PointCoord>(
314    points: &[Point<C>],
315    flags: &[PointFlags],
316    buffers: &DeltaBuffers<'_, D>,
317) -> Result<(), ReadError> {
318    let count = points.len();
319    if count < PHANTOM_POINT_COUNT
320        || flags.len() < count
321        || buffers.deltas.len() < count
322        || buffers.iup.len() < count
323    {
324        return Err(ReadError::InvalidArrayLen);
325    }
326    Ok(())
327}
328
329fn zero<D: PointCoord>(deltas: &mut [Point<D>]) {
330    for delta in deltas.iter_mut() {
331        *delta = Default::default();
332    }
333}
334
335/// Interpolates the points that the current tuple did not reference, in the
336/// manner of the `IUP` hinting instruction.
337///
338/// Points carrying an explicit delta are marked with [`PointMarker::HAS_DELTA`]
339/// in `flags`. Each contour is handled independently.
340///
341/// Modeled after the FreeType implementation:
342/// <https://github.com/freetype/freetype/blob/bbfcd79eacb4985d4b68783565f4b494aa64516b/src/truetype/ttgxvar.c#L3881>
343fn interpolate_deltas<C, D>(
344    points: &[Point<C>],
345    flags: &[PointFlags],
346    contours: &[u16],
347    out_points: &mut [Point<D>],
348) -> Option<()>
349where
350    C: PointCoord,
351    D: PointCoord + From<C>,
352{
353    let mut start = 0usize;
354    for &end in contours {
355        let end = end as usize;
356        // A contour ending before the previous one did is malformed. Skip it
357        // without advancing, so the contours that follow still line up with
358        // the points they describe.
359        if end < start {
360            continue;
361        }
362        let range = start..end + 1;
363        start = end + 1;
364        // Slicing all three to the same range once means everything below can
365        // work in contour local indices, with no further bounds checks.
366        Contour {
367            points: points.get(range.clone())?,
368            flags: flags.get(range.clone())?,
369            out_points: out_points.get_mut(range)?,
370        }
371        .interpolate_untouched();
372    }
373    Some(())
374}
375
376/// One contour's worth of points, as input coordinates and the moved
377/// coordinates being derived from them.
378///
379/// All three slices have the same length, so indices are interchangeable
380/// between them and are always in bounds.
381struct Contour<'a, C, D>
382where
383    C: PointCoord,
384    D: PointCoord + From<C>,
385{
386    points: &'a [Point<C>],
387    flags: &'a [PointFlags],
388    out_points: &'a mut [Point<D>],
389}
390
391impl<C, D> Contour<'_, C, D>
392where
393    C: PointCoord,
394    D: PointCoord + From<C>,
395{
396    /// Infers the deltas of every point in this contour that the current tuple
397    /// did not reference.
398    fn interpolate_untouched(&mut self) {
399        // Copy the reference out so iterating it does not borrow `self`.
400        let flags = self.flags;
401        let mut referenced = flags
402            .iter()
403            .enumerate()
404            .filter(|(_, flag)| flag.has_marker(PointMarker::HAS_DELTA))
405            .map(|(ix, _)| ix);
406        let Some(first) = referenced.next() else {
407            // Nothing in this contour is referenced, so the tuple does not
408            // affect it at all.
409            return;
410        };
411        // Interpolate each run of unreferenced points between two references.
412        let mut last = first;
413        for next in referenced {
414            self.interpolate(last + 1..next, last, next);
415            last = next;
416        }
417        if last == first {
418            // A single reference carries the whole contour with it.
419            self.shift(first);
420        } else {
421            // The points after the last reference and those before the first
422            // wrap around, and are bracketed by that same pair. Both ranges are
423            // empty when there is nothing to do.
424            let len = self.out_points.len();
425            self.interpolate(last + 1..len, last, first);
426            self.interpolate(0..first, last, first);
427        }
428    }
429
430    /// Shifts the whole contour by the delta of its one referenced point.
431    ///
432    /// Modeled after the FreeType implementation: <https://github.com/freetype/freetype/blob/bbfcd79eacb4985d4b68783565f4b494aa64516b/src/truetype/ttgxvar.c#L3776>
433    fn shift(&mut self, reference: usize) {
434        let delta = self.out_points[reference] - self.points[reference].map(D::from);
435        if delta.x == D::zeroed() && delta.y == D::zeroed() {
436            return;
437        }
438        // Every point but the reference itself, which already carries it.
439        let (before, rest) = self.out_points.split_at_mut(reference);
440        for out_point in before {
441            *out_point += delta;
442        }
443        for out_point in &mut rest[1..] {
444            *out_point += delta;
445        }
446    }
447
448    /// Interpolates the unreferenced points in `range` between the referenced
449    /// points at `ref1` and `ref2`.
450    ///
451    /// Modeled after the FreeType implementation: <https://github.com/freetype/freetype/blob/bbfcd79eacb4985d4b68783565f4b494aa64516b/src/truetype/ttgxvar.c#L3813>
452    ///
453    /// For details on the algorithm, see: <https://learn.microsoft.com/en-us/typography/opentype/spec/gvar#inferred-deltas-for-un-referenced-point-numbers>
454    fn interpolate(&mut self, range: Range<usize>, ref1: usize, ref2: usize) {
455        if range.is_empty() {
456            return;
457        }
458        // FreeType uses pointer tricks to handle x and y with a single piece of
459        // code. Try a macro instead.
460        macro_rules! interp_coord {
461            ($coord:ident) => {
462                // Order the references by coordinate, which can differ between
463                // the two axes.
464                let (lo, hi) = if self.points[ref1].$coord > self.points[ref2].$coord {
465                    (ref2, ref1)
466                } else {
467                    (ref1, ref2)
468                };
469                let in1 = D::from(self.points[lo].$coord);
470                let in2 = D::from(self.points[hi].$coord);
471                let out1 = self.out_points[lo].$coord;
472                let out2 = self.out_points[hi].$coord;
473                // If the references share a coordinate but moved apart, the
474                // inferred delta is zero and the coordinate is left alone.
475                if in1 != in2 || out1 == out2 {
476                    let scale = if in1 != in2 {
477                        (out2 - out1) / (in2 - in1)
478                    } else {
479                        D::zeroed()
480                    };
481                    let d1 = out1 - in1;
482                    let d2 = out2 - in2;
483                    for (point, out_point) in self.points[range.clone()]
484                        .iter()
485                        .zip(&mut self.out_points[range.clone()])
486                    {
487                        let coord = D::from(point.$coord);
488                        // Outside the references the nearer delta is applied
489                        // wholesale; between them it is interpolated.
490                        out_point.$coord = if coord <= in1 {
491                            coord + d1
492                        } else if coord >= in2 {
493                            coord + d2
494                        } else {
495                            out1 + (coord - in1) * scale
496                        };
497                    }
498                }
499            };
500        }
501        interp_coord!(x);
502        interp_coord!(y);
503    }
504}
505
506#[cfg(test)]
507mod tests {
508    use super::*;
509    use crate::{
510        tables::{
511            glyf::{Glyf, Glyph},
512            loca::Loca,
513        },
514        FontRef, TableProvider,
515    };
516    use alloc::{vec, vec::Vec};
517
518    fn make_points(tuples: &[(i32, i32)]) -> Vec<Point<i32>> {
519        tuples.iter().map(|&(x, y)| Point::new(x, y)).collect()
520    }
521
522    /// Seeds the working buffer the way [`Gvar::simple_deltas`] does: every
523    /// point converted to 16.16 with its explicit delta already applied, and
524    /// `HAS_DELTA` set for the points that carry one.
525    fn make_working_points_and_flags(
526        points: &[Point<i32>],
527        deltas: &[Point<i32>],
528    ) -> (Vec<Point<Fixed>>, Vec<PointFlags>) {
529        let working_points = points
530            .iter()
531            .zip(deltas)
532            .map(|(point, delta)| point.map(Fixed::from_i32) + delta.map(Fixed::from_i32))
533            .collect();
534        let flags = deltas
535            .iter()
536            .map(|delta| {
537                let mut flags = PointFlags::default();
538                if delta.x != 0 || delta.y != 0 {
539                    flags.set_marker(PointMarker::HAS_DELTA);
540                }
541                flags
542            })
543            .collect();
544        (working_points, flags)
545    }
546
547    /// Runs interpolation and returns the resulting x coordinates as integers.
548    fn interpolated_x(
549        points: &[Point<i32>],
550        deltas: &[Point<i32>],
551        contours: &[u16],
552    ) -> Option<Vec<i32>> {
553        let (mut working, flags) = make_working_points_and_flags(points, deltas);
554        interpolate_deltas(points, &flags, contours, &mut working)?;
555        Some(working.iter().map(|p| p.x.to_i32()).collect())
556    }
557
558    #[test]
559    fn shift() {
560        let points = make_points(&[(245, 630), (260, 700), (305, 680)]);
561        // Single delta triggers a full contour shift.
562        let deltas = make_points(&[(20, -10), (0, 0), (0, 0)]);
563        let (mut working_points, flags) = make_working_points_and_flags(&points, &deltas);
564        interpolate_deltas(&points, &flags, &[2], &mut working_points).unwrap();
565        let expected = &[
566            Point::new(265, 620).map(Fixed::from_i32),
567            Point::new(280, 690).map(Fixed::from_i32),
568            Point::new(325, 670).map(Fixed::from_i32),
569        ];
570        assert_eq!(&working_points, expected);
571    }
572
573    #[test]
574    fn interpolate() {
575        // Test taken from the spec:
576        // https://learn.microsoft.com/en-us/typography/opentype/spec/gvar#inferred-deltas-for-un-referenced-point-numbers
577        // with a minor adjustment to account for the precision of our fixed point math.
578        let points = make_points(&[(245, 630), (260, 700), (305, 680)]);
579        let deltas = make_points(&[(28, -62), (0, 0), (-42, -57)]);
580        let (mut working_points, flags) = make_working_points_and_flags(&points, &deltas);
581        interpolate_deltas(&points, &flags, &[2], &mut working_points).unwrap();
582        assert_eq!(
583            working_points[1],
584            Point::new(
585                Fixed::from_f64(260.0 + 10.4999237060547),
586                Fixed::from_f64(700.0 - 57.0)
587            )
588        );
589    }
590
591    /// Points below the first reference take its delta, points above the second
592    /// take that one, and points between them are interpolated. Coordinates are
593    /// chosen so the interpolation scale is exactly 2 and the 16.16 arithmetic
594    /// is exact.
595    #[test]
596    fn interpolate_clamps_outside_the_reference_range() {
597        //                       below    ref1    between   ref2     above
598        let points = make_points(&[(0, 0), (10, 0), (15, 0), (20, 0), (30, 0)]);
599        let deltas = make_points(&[(0, 0), (4, 0), (0, 0), (14, 0), (0, 0)]);
600        assert_eq!(
601            interpolated_x(&points, &deltas, &[4]).unwrap(),
602            // 0 + d1, 10 + 4, 14 + (15-10)*2, 20 + 14, 30 + d2
603            vec![4, 14, 24, 34, 44]
604        );
605    }
606
607    /// A contour whose points carry no deltas at all is left exactly as it was.
608    #[test]
609    fn contour_without_deltas_is_untouched() {
610        let points = make_points(&[(0, 0), (10, 0), (20, 0)]);
611        let deltas = make_points(&[(0, 0), (0, 0), (0, 0)]);
612        assert_eq!(
613            interpolated_x(&points, &deltas, &[2]).unwrap(),
614            vec![0, 10, 20]
615        );
616    }
617
618    /// Every point having an explicit delta leaves nothing to interpolate.
619    #[test]
620    fn fully_referenced_contour_is_untouched() {
621        let points = make_points(&[(0, 0), (10, 0), (20, 0)]);
622        let deltas = make_points(&[(1, 0), (2, 0), (3, 0)]);
623        assert_eq!(
624            interpolated_x(&points, &deltas, &[2]).unwrap(),
625            vec![1, 12, 23]
626        );
627    }
628
629    /// Deltas in one contour must not leak into another.
630    #[test]
631    fn contours_are_independent() {
632        let points = make_points(&[(0, 0), (10, 0), (20, 0), (100, 0), (110, 0), (120, 0)]);
633        // Only the first contour has a delta, so it shifts as a whole while the
634        // second stays put.
635        let deltas = make_points(&[(5, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0)]);
636        assert_eq!(
637            interpolated_x(&points, &deltas, &[2, 5]).unwrap(),
638            vec![5, 15, 25, 100, 110, 120]
639        );
640    }
641
642    /// The points before the first referenced point wrap around and use the
643    /// last referenced point as their other reference.
644    #[test]
645    fn points_before_first_reference_wrap_around() {
646        let points = make_points(&[(0, 0), (10, 0), (20, 0), (30, 0)]);
647        // References at 1 and 2; points 0 and 3 fall outside them and take the
648        // delta of the nearer reference.
649        let deltas = make_points(&[(0, 0), (6, 0), (6, 0), (0, 0)]);
650        assert_eq!(
651            interpolated_x(&points, &deltas, &[3]).unwrap(),
652            vec![6, 16, 26, 36]
653        );
654    }
655
656    /// When both references share a coordinate but move differently the
657    /// inferred delta is zero, so that coordinate is left alone.
658    #[test]
659    fn equal_reference_coords_with_different_deltas_infer_nothing() {
660        let points = make_points(&[(10, 0), (10, 5), (10, 10)]);
661        let deltas = make_points(&[(2, 0), (0, 0), (6, 0)]);
662        let (mut working, flags) = make_working_points_and_flags(&points, &deltas);
663        interpolate_deltas(&points, &flags, &[2], &mut working).unwrap();
664        // x: both references sit at 10 but move differently, so point 1 keeps
665        // its x. y: interpolated normally, and with no y deltas it stays at 5.
666        assert_eq!(working[1], Point::new(10, 5).map(Fixed::from_i32));
667    }
668
669    /// A contour end point that goes backwards is skipped rather than panicking
670    /// or corrupting the points around it.
671    #[test]
672    fn out_of_order_contour_end_is_skipped() {
673        let points = make_points(&[(0, 0), (10, 0), (20, 0), (30, 0)]);
674        let deltas = make_points(&[(5, 0), (0, 0), (0, 0), (0, 0)]);
675        // The second contour ends before the first one did.
676        assert_eq!(
677            interpolated_x(&points, &deltas, &[3, 1]).unwrap(),
678            vec![5, 15, 25, 35]
679        );
680    }
681
682    /// A contour end point past the end of the point array is reported rather
683    /// than read out of bounds.
684    #[test]
685    fn contour_end_past_last_point_is_rejected() {
686        let points = make_points(&[(0, 0), (10, 0)]);
687        let deltas = make_points(&[(5, 0), (0, 0)]);
688        assert!(interpolated_x(&points, &deltas, &[9]).is_none());
689    }
690
691    // ---- end to end, against a real variable font -------------------------
692
693    /// Vazirmatn has a single `wght` axis. Glyph 1 is a simple glyph with
694    /// variation data, glyph 2 is a composite with variation data, and glyph 0
695    /// is empty and has none.
696    const VAR_GID: GlyphId = GlyphId::new(1);
697    const COMPOSITE_GID: GlyphId = GlyphId::new(2);
698    const NO_VAR_GID: GlyphId = GlyphId::new(0);
699
700    /// A simple glyph loaded with its point buffer sized to include the
701    /// phantom points, as [`Gvar::simple_deltas`] requires.
702    struct TestGlyph<'a> {
703        gvar: Gvar<'a>,
704        points: Vec<Point<i32>>,
705        flags: Vec<PointFlags>,
706        contours: Vec<u16>,
707    }
708
709    impl<'a> TestGlyph<'a> {
710        fn new(font: &FontRef<'a>, gid: GlyphId) -> Self {
711            let glyf: Glyf<'a> = font.glyf().unwrap();
712            let loca: Loca<'a> = font.loca(None).unwrap();
713            let Some(Glyph::Simple(simple)) = loca.get(gid, &glyf).and_then(|g| g.into_glyph())
714            else {
715                panic!("expected a simple glyph");
716            };
717            let n = simple.num_points();
718            let total = n + PHANTOM_POINT_COUNT;
719            let mut points = vec![Point::<i32>::default(); total];
720            let mut flags = vec![PointFlags::default(); total];
721            simple
722                .read_points_fast(&mut points[..n], &mut flags[..n])
723                .unwrap();
724            let contours = simple
725                .end_pts_of_contours()
726                .iter()
727                .map(|c| c.get())
728                .collect();
729            Self {
730                gvar: font.gvar().unwrap(),
731                points,
732                flags,
733                contours,
734            }
735        }
736
737        fn deltas(&mut self, gid: GlyphId, coords: &[F2Dot14]) -> (bool, Vec<Point<Fixed>>) {
738            let total = self.points.len();
739            let mut deltas = vec![Point::<Fixed>::default(); total];
740            let mut iup = vec![Point::<Fixed>::default(); total];
741            let mut buffers = DeltaBuffers {
742                deltas: &mut deltas,
743                iup: &mut iup,
744            };
745            let varied = self
746                .gvar
747                .simple_deltas(
748                    gid,
749                    coords,
750                    &self.points,
751                    &mut self.flags,
752                    &self.contours,
753                    &mut buffers,
754                )
755                .unwrap();
756            (varied, deltas)
757        }
758    }
759
760    #[test]
761    fn simple_deltas_at_default_location_are_zero() {
762        let font = FontRef::new(font_test_data::VAZIRMATN_VAR).unwrap();
763        let mut glyph = TestGlyph::new(&font, VAR_GID);
764        // The glyph has variation data, but no tuple is active at the default
765        // location, so every delta is zero.
766        let (varied, deltas) = glyph.deltas(VAR_GID, &[F2Dot14::from_f32(0.0)]);
767        assert!(varied);
768        assert!(deltas.iter().all(|d| *d == Point::default()));
769    }
770
771    #[test]
772    fn simple_deltas_at_extreme_move_points() {
773        let font = FontRef::new(font_test_data::VAZIRMATN_VAR).unwrap();
774        let mut glyph = TestGlyph::new(&font, VAR_GID);
775        let (varied, deltas) = glyph.deltas(VAR_GID, &[F2Dot14::from_f32(1.0)]);
776        assert!(varied);
777        let outline_deltas = &deltas[..deltas.len() - PHANTOM_POINT_COUNT];
778        assert!(
779            outline_deltas.iter().any(|d| *d != Point::default()),
780            "expected at least one non-zero outline delta"
781        );
782    }
783
784    /// Deltas scale with position along the axis: half way along moves points,
785    /// and by less than the extreme does.
786    #[test]
787    fn simple_deltas_scale_along_the_axis() {
788        let font = FontRef::new(font_test_data::VAZIRMATN_VAR).unwrap();
789        let mut glyph = TestGlyph::new(&font, VAR_GID);
790        let (_, half) = glyph.deltas(VAR_GID, &[F2Dot14::from_f32(0.5)]);
791        let (_, full) = glyph.deltas(VAR_GID, &[F2Dot14::from_f32(1.0)]);
792        let magnitude = |ds: &[Point<Fixed>]| -> f64 {
793            ds.iter()
794                .map(|d| d.x.to_f64().abs() + d.y.to_f64().abs())
795                .sum()
796        };
797        let (half_sum, full_sum) = (magnitude(&half), magnitude(&full));
798        assert!(half_sum > 0.0);
799        assert!(
800            half_sum < full_sum,
801            "half {half_sum} should be less than full {full_sum}"
802        );
803    }
804
805    /// Repeated calls must not accumulate: each starts from a zeroed buffer.
806    #[test]
807    fn deltas_do_not_accumulate_across_calls() {
808        let font = FontRef::new(font_test_data::VAZIRMATN_VAR).unwrap();
809        let mut glyph = TestGlyph::new(&font, VAR_GID);
810        let (_, once) = glyph.deltas(VAR_GID, &[F2Dot14::from_f32(1.0)]);
811        let (_, twice) = glyph.deltas(VAR_GID, &[F2Dot14::from_f32(1.0)]);
812        assert_eq!(once, twice);
813    }
814
815    /// A glyph with no variation data reports `false` and leaves the buffer
816    /// zeroed rather than untouched, so a reused buffer cannot leak deltas from
817    /// a previously processed glyph.
818    #[test]
819    fn simple_deltas_without_variation_data_zeroes_buffer() {
820        let font = FontRef::new(font_test_data::VAZIRMATN_VAR).unwrap();
821        let mut glyph = TestGlyph::new(&font, VAR_GID);
822        let (varied, deltas) = glyph.deltas(NO_VAR_GID, &[F2Dot14::from_f32(1.0)]);
823        assert!(!varied);
824        assert!(deltas.iter().all(|d| *d == Point::default()));
825    }
826
827    #[test]
828    fn simple_deltas_rejects_short_iup_buffer() {
829        let font = FontRef::new(font_test_data::VAZIRMATN_VAR).unwrap();
830        let gvar = font.gvar().unwrap();
831        let points = [Point::<i32>::default(); 8];
832        let mut flags = [PointFlags::default(); 8];
833        let mut deltas = [Point::<Fixed>::default(); 8];
834        let mut iup = [Point::<Fixed>::default(); 4];
835        let mut buffers = DeltaBuffers {
836            deltas: &mut deltas,
837            iup: &mut iup,
838        };
839        assert!(gvar
840            .simple_deltas(VAR_GID, &[], &points, &mut flags, &[7], &mut buffers)
841            .is_none());
842    }
843
844    #[test]
845    fn simple_deltas_rejects_missing_phantom_points() {
846        let font = FontRef::new(font_test_data::VAZIRMATN_VAR).unwrap();
847        let gvar = font.gvar().unwrap();
848        // Fewer points than there are phantom points.
849        let points = [Point::<i32>::default(); 3];
850        let mut flags = [PointFlags::default(); 3];
851        let mut deltas = [Point::<Fixed>::default(); 3];
852        let mut iup = [Point::<Fixed>::default(); 3];
853        let mut buffers = DeltaBuffers {
854            deltas: &mut deltas,
855            iup: &mut iup,
856        };
857        assert!(gvar
858            .simple_deltas(VAR_GID, &[], &points, &mut flags, &[2], &mut buffers)
859            .is_none());
860    }
861
862    #[test]
863    fn composite_deltas_without_variation_data_zeroes_buffer() {
864        let font = FontRef::new(font_test_data::VAZIRMATN_VAR).unwrap();
865        let gvar = font.gvar().unwrap();
866        let coords = [F2Dot14::from_f32(0.5)];
867        let mut deltas = [Point::new(Fixed::from_i32(7), Fixed::from_i32(9)); 8];
868        let varied = gvar
869            .composite_deltas(NO_VAR_GID, &coords, &mut deltas)
870            .unwrap();
871        assert!(!varied);
872        assert!(deltas.iter().all(|d| *d == Point::default()));
873    }
874
875    #[test]
876    fn composite_deltas_with_variation_data_reports_true() {
877        let font = FontRef::new(font_test_data::VAZIRMATN_VAR).unwrap();
878        let gvar = font.gvar().unwrap();
879        let coords = [F2Dot14::from_f32(1.0)];
880        let mut deltas = [Point::<Fixed>::default(); 8];
881        let varied = gvar
882            .composite_deltas(COMPOSITE_GID, &coords, &mut deltas)
883            .unwrap();
884        assert!(varied);
885    }
886
887    /// Deltas whose position falls past the end of the buffer are ignored
888    /// rather than treated as an error, since a composite may legitimately have
889    /// fewer components than the variation data describes.
890    #[test]
891    fn composite_deltas_tolerates_short_buffer() {
892        let font = FontRef::new(font_test_data::VAZIRMATN_VAR).unwrap();
893        let gvar = font.gvar().unwrap();
894        let coords = [F2Dot14::from_f32(1.0)];
895        let mut deltas = [Point::<Fixed>::default(); 1];
896        assert!(gvar
897            .composite_deltas(COMPOSITE_GID, &coords, &mut deltas)
898            .is_some());
899    }
900
901    /// Going through `Gvar` is the same as looking the data up and calling
902    /// `GlyphVariationData` directly.
903    #[test]
904    fn both_layers_agree() {
905        let font = FontRef::new(font_test_data::VAZIRMATN_VAR).unwrap();
906        let gvar = font.gvar().unwrap();
907        let glyf = font.glyf().unwrap();
908        let loca = font.loca(None).unwrap();
909        let coords = [F2Dot14::from_f32(0.5)];
910        for gid in 0..font.maxp().unwrap().num_glyphs() {
911            let glyph_id = GlyphId::from(gid);
912            let Some(Glyph::Simple(simple)) =
913                loca.get(glyph_id, &glyf).and_then(|g| g.into_glyph())
914            else {
915                continue;
916            };
917            let count = simple.num_points() + PHANTOM_POINT_COUNT;
918            let points = vec![Point::<i32>::default(); count];
919            let contours: Vec<u16> = simple
920                .end_pts_of_contours()
921                .iter()
922                .map(|e| e.get())
923                .collect();
924
925            let mut through_gvar = vec![Point::<Fixed>::default(); count];
926            let mut iup = vec![Point::<Fixed>::default(); count];
927            let mut flags = vec![PointFlags::default(); count];
928            let had_data = gvar
929                .simple_deltas(
930                    glyph_id,
931                    &coords,
932                    &points,
933                    &mut flags,
934                    &contours,
935                    &mut DeltaBuffers {
936                        deltas: &mut through_gvar,
937                        iup: &mut iup,
938                    },
939                )
940                .unwrap();
941
942            let var_data = gvar.glyph_variation_data(glyph_id).unwrap();
943            assert_eq!(had_data, var_data.is_some(), "gid {gid}");
944            let Some(var_data) = var_data else { continue };
945
946            let mut direct = vec![Point::<Fixed>::default(); count];
947            let mut iup = vec![Point::<Fixed>::default(); count];
948            let mut flags = vec![PointFlags::default(); count];
949            var_data
950                .simple_deltas(
951                    &coords,
952                    &points,
953                    &mut flags,
954                    &contours,
955                    &mut DeltaBuffers {
956                        deltas: &mut direct,
957                        iup: &mut iup,
958                    },
959                )
960                .unwrap();
961            assert_eq!(through_gvar, direct, "gid {gid}");
962        }
963    }
964
965    /// The `Gvar` wrapper zeroes the deltas for a glyph with no variation
966    /// data, so a reused buffer never leaks the previous glyph's values.
967    #[test]
968    fn a_glyph_without_data_still_zeroes() {
969        let font = FontRef::new(font_test_data::VAZIRMATN_VAR).unwrap();
970        let gvar = font.gvar().unwrap();
971        // Past the end of the table, so there is certainly nothing there.
972        let missing = GlyphId::new(0xFFFF);
973        let mut deltas = vec![Point::new(Fixed::from_i32(7), Fixed::from_i32(9)); 8];
974        assert!(!gvar.composite_deltas(missing, &[], &mut deltas).unwrap());
975        assert!(deltas.iter().all(|d| *d == Point::default()));
976
977        let points = vec![Point::<i32>::default(); 8];
978        let mut deltas = vec![Point::new(Fixed::from_i32(7), Fixed::from_i32(9)); 8];
979        let mut iup = vec![Point::<Fixed>::default(); 8];
980        let mut flags = vec![PointFlags::default(); 8];
981        assert!(!gvar
982            .simple_deltas(
983                missing,
984                &[],
985                &points,
986                &mut flags,
987                &[7],
988                &mut DeltaBuffers {
989                    deltas: &mut deltas,
990                    iup: &mut iup,
991                },
992            )
993            .unwrap());
994        assert!(deltas.iter().all(|d| *d == Point::default()));
995    }
996
997    /// Every buffer that is indexed by point is checked against the point
998    /// count, by both entry points, before anything is written.
999    #[test]
1000    fn short_buffers_are_rejected_by_both() {
1001        let font = FontRef::new(font_test_data::VAZIRMATN_VAR).unwrap();
1002        let gvar = font.gvar().unwrap();
1003        let glyph_id = GlyphId::new(2);
1004        let var_data = gvar.glyph_variation_data(glyph_id).unwrap().unwrap();
1005        const COUNT: usize = 8;
1006
1007        // Each case leaves one buffer one element short of `points`.
1008        for short in ["flags", "deltas", "iup", "points"] {
1009            let points = vec![Point::<i32>::default(); if short == "points" { 3 } else { COUNT }];
1010            let mut flags =
1011                vec![PointFlags::default(); if short == "flags" { COUNT - 1 } else { COUNT }];
1012            let mut deltas =
1013                vec![Point::<Fixed>::default(); if short == "deltas" { COUNT - 1 } else { COUNT }];
1014            let mut iup =
1015                vec![Point::<Fixed>::default(); if short == "iup" { COUNT - 1 } else { COUNT }];
1016            let mut buffers = DeltaBuffers {
1017                deltas: &mut deltas,
1018                iup: &mut iup,
1019            };
1020            assert!(
1021                gvar.simple_deltas(glyph_id, &[], &points, &mut flags, &[7], &mut buffers)
1022                    .is_none(),
1023                "Gvar accepted a short {short}"
1024            );
1025            assert!(
1026                var_data
1027                    .simple_deltas(&[], &points, &mut flags, &[7], &mut buffers)
1028                    .is_none(),
1029                "GlyphVariationData accepted a short {short}"
1030            );
1031        }
1032
1033        // The same sizes, none of them short, are accepted.
1034        let points = vec![Point::<i32>::default(); COUNT];
1035        let mut flags = vec![PointFlags::default(); COUNT];
1036        let mut deltas = vec![Point::<Fixed>::default(); COUNT];
1037        let mut iup = vec![Point::<Fixed>::default(); COUNT];
1038        let mut buffers = DeltaBuffers {
1039            deltas: &mut deltas,
1040            iup: &mut iup,
1041        };
1042        assert!(gvar
1043            .simple_deltas(glyph_id, &[], &points, &mut flags, &[7], &mut buffers)
1044            .is_some());
1045    }
1046}