oxideav-scribe 0.1.4

Pure-Rust font rasterizer + shaper + layout for the oxideav framework — TrueType outline flattening, scanline anti-aliasing, GSUB ligatures, GPOS kerning
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
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
//! Quadratic-Bezier outline flattening.
//!
//! TrueType glyph outlines are sequences of contours, where each contour
//! is a closed loop of *on-curve* and *off-curve* points. The off-curve
//! points are quadratic-Bezier control handles. Two consecutive
//! off-curve points imply an *implicit* on-curve midpoint at their
//! midpoint — the standard TrueType reconstruction rule documented in
//! the Apple TrueType Reference Manual.
//!
//! This module turns a [`oxideav_ttf::TtOutline`] into a flat polyline
//! (`Vec<Vec<(f32, f32)>>`, one inner Vec per contour) at the
//! rasterisation scale. Each Bezier segment is recursively subdivided by
//! the de Casteljau split until the chord length is below a tolerance
//! (we use 0.5 px which is a standard scanline AA threshold).
//!
//! The de Casteljau subdivision for a quadratic Bezier
//! `B(t) = (1-t)^2 P0 + 2(1-t)t P1 + t^2 P2` at `t = 0.5` yields:
//!
//! ```text
//! M01 = (P0 + P1) / 2
//! M12 = (P1 + P2) / 2
//! M = (M01 + M12) / 2
//! left  = (P0, M01, M)
//! right = (M, M12, P2)
//! ```
//!
//! The two halves can be concatenated to reconstruct the full curve;
//! this is the textbook "split + recurse" algorithm.
//!
//! Coordinate convention: TrueType is Y-up with the origin on the
//! baseline; the rasterizer wants Y-down with the origin at the
//! top-left of the glyph bounding box. Conversion is done at flatten
//! time so downstream code never has to think about it.

use oxideav_ttf::TtOutline;

/// Maximum chord length (in raster pixels) we tolerate before splitting
/// a Bezier segment further.
const FLATTEN_TOLERANCE_PX: f32 = 0.5;

/// Hard cap on subdivision depth — guards against pathological control
/// points that would otherwise loop forever in floating-point. A real
/// glyph at sane sizes converges in 4..6 levels; 16 levels gives 65536
/// intermediate samples which is way past anything sensible.
const MAX_SUBDIV_DEPTH: u8 = 16;

/// A flattened glyph outline ready for the scanline rasterizer.
///
/// Coordinates are in raster pixels with the origin at the **top-left**
/// of `bounds`. The `bounds` field is the bounding box used for that
/// translation (in raster pixels, also Y-down).
#[derive(Debug, Clone, Default)]
pub struct FlatOutline {
    pub contours: Vec<Vec<(f32, f32)>>,
    pub bounds: FlatBounds,
}

/// Bounding box of a flattened outline, in raster pixels (Y-down).
#[derive(Debug, Clone, Copy, Default)]
pub struct FlatBounds {
    pub x_min: f32,
    pub y_min: f32,
    pub x_max: f32,
    pub y_max: f32,
}

impl FlatBounds {
    pub fn width(&self) -> f32 {
        (self.x_max - self.x_min).max(0.0)
    }
    pub fn height(&self) -> f32 {
        (self.y_max - self.y_min).max(0.0)
    }
    /// Pixel width rounded up.
    pub fn width_px(&self) -> u32 {
        self.width().ceil() as u32
    }
    /// Pixel height rounded up.
    pub fn height_px(&self) -> u32 {
        self.height().ceil() as u32
    }
}

/// Flatten a TrueType outline at `scale` (raster-pixel-per-font-unit),
/// translating to a Y-down coordinate system with the origin at the
/// top-left of the glyph bounding box.
///
/// Returns `None` for empty outlines (e.g. the space glyph).
pub fn flatten(outline: &TtOutline, scale: f32) -> Option<FlatOutline> {
    flatten_with_shear(outline, scale, 0.0)
}

/// Flatten with an optional horizontal shear. `shear_x_per_y` is the
/// `tan(angle)` value to apply in TT (Y-up) coordinates: each input
/// point at `(x, y)` becomes `(x + shear * y, y)` *before* the
/// raster-down conversion. Used by the rasterizer when synthesising
/// italic for an upright face — see [`crate::style`].
///
/// `shear_x_per_y == 0.0` is identical to [`flatten`].
///
/// The bounding box is recomputed from the actual mapped points (the
/// font's cached bbox is invalid once shear is applied).
pub fn flatten_with_shear(
    outline: &TtOutline,
    scale: f32,
    shear_x_per_y: f32,
) -> Option<FlatOutline> {
    flatten_with_shear_offset(outline, scale, shear_x_per_y, 0.0)
}

/// Flatten with shear AND a horizontal sub-pixel offset (raster-pixel
/// units, applied AFTER scale + Y-flip). The offset shifts every
/// flattened point right by `x_subpixel`, growing the right edge of
/// the bbox by the same amount and leaving the left edge fixed at
/// `floor(x_min)`. The composer queries [`subpixel_offset`] for the
/// fractional X it baked in and uses `floor(pen_x)` as the blit
/// origin so the bitmap lands at the correct fractional position.
///
/// `x_subpixel == 0.0` is bit-identical to [`flatten_with_shear`].
///
/// [`subpixel_offset`]: crate::cache::subpixel_offset
pub fn flatten_with_shear_offset(
    outline: &TtOutline,
    scale: f32,
    shear_x_per_y: f32,
    x_subpixel: f32,
) -> Option<FlatOutline> {
    if outline.contours.is_empty() {
        return None;
    }

    // Without shear: derive bbox from the font's cached bbox. The
    // bitmap LEFT edge is pixel-aligned at `floor(raw.x_min * scale)`
    // and the bitmap WIDTH is `(raw.x_max - raw.x_min).ceil() + 1` so
    // every fractional sub_x slot ends up with the same dimensions
    // (round-3 invariant) and the analytical rightmost
    // partial-coverage column always lands inside the bitmap. The +1 px
    // slack is required by the trapezoidal coverage path at sub_x > 0
    // (and harmless at sub_x = 0 — the rightmost pixel just stays 0).
    let bounds = if shear_x_per_y == 0.0 {
        let raw = outline.bounds?;
        let raw_xmin = raw.x_min as f32 * scale;
        let raw_xmax = raw.x_max as f32 * scale;
        let xmin_aligned = raw_xmin.floor();
        let xmax_aligned = (raw_xmax - xmin_aligned).ceil() + xmin_aligned + 1.0;
        FlatBounds {
            x_min: xmin_aligned,
            y_min: -(raw.y_max as f32) * scale,
            x_max: xmax_aligned,
            y_max: -(raw.y_min as f32) * scale,
        }
    } else {
        // Sheared: compute bbox from the sheared points themselves
        // (the cached font bbox is invalid once shear is applied). The
        // bitmap LEFT edge is pixel-aligned and we leave a 1-px right-
        // hand slack column for the trapezoidal coverage's rightmost
        // partial fill — same rule as the unsheared branch.
        // Importantly, compute the bbox *without* the x_subpixel shift
        // so all sub-pixel slots produce the same dims.
        let mut x_min = f32::INFINITY;
        let mut y_min = f32::INFINITY;
        let mut x_max = f32::NEG_INFINITY;
        let mut y_max = f32::NEG_INFINITY;
        for c in &outline.contours {
            for p in &c.points {
                let (sx, sy) = shear_point(p.x as f32, p.y as f32, shear_x_per_y);
                let rx = sx * scale;
                let ry = -sy * scale;
                x_min = x_min.min(rx);
                y_min = y_min.min(ry);
                x_max = x_max.max(rx);
                y_max = y_max.max(ry);
            }
        }
        if !x_min.is_finite() {
            return None;
        }
        let xmin_aligned = x_min.floor();
        let xmax_aligned = (x_max - xmin_aligned).ceil() + xmin_aligned + 1.0;
        FlatBounds {
            x_min: xmin_aligned,
            y_min,
            x_max: xmax_aligned,
            y_max,
        }
    };

    let mut contours = Vec::with_capacity(outline.contours.len());
    for c in &outline.contours {
        let pts = flatten_contour(&c.points, scale, &bounds, shear_x_per_y, x_subpixel);
        if pts.len() >= 2 {
            contours.push(pts);
        }
    }

    if contours.is_empty() {
        return None;
    }
    Some(FlatOutline { contours, bounds })
}

/// Apply horizontal shear in TT (Y-up) coordinates. Italic-positive y
/// (above the baseline) shifts to the right when `shear_x_per_y > 0`.
#[inline]
fn shear_point(x: f32, y: f32, shear_x_per_y: f32) -> (f32, f32) {
    (x + shear_x_per_y * y, y)
}

/// Apply scale + Y-flip + bounds-relative translation to a single TT
/// point so the result is in raster pixels with origin at top-left of
/// the glyph bbox. Honour an optional horizontal shear (applied in TT
/// Y-up coordinates BEFORE the Y-flip) so synthesised italic produces
/// the visually-expected forward slant. `x_subpixel` is added in
/// raster-X after scaling so sub-pixel positioning shifts the glyph
/// inside its bitmap.
#[inline]
fn map_point(
    x: i16,
    y: i16,
    scale: f32,
    bounds: &FlatBounds,
    shear_x_per_y: f32,
    x_subpixel: f32,
) -> (f32, f32) {
    let (sx, sy) = shear_point(x as f32, y as f32, shear_x_per_y);
    let rx = sx * scale + x_subpixel - bounds.x_min;
    let ry = -sy * scale - bounds.y_min;
    (rx, ry)
}

/// Flatten a single contour (closed loop, mix of on/off-curve points).
///
/// Implements the standard TrueType implicit-on-curve rule: when two
/// off-curve points are adjacent, the implied on-curve midpoint
/// becomes the segment endpoint, then a fresh quadratic continues from
/// it.
/// One ordered point in the rotated contour: (x, y, on-curve flag).
type OrderedPoint = (f32, f32, bool);

fn flatten_contour(
    pts: &[oxideav_ttf::Point],
    scale: f32,
    bounds: &FlatBounds,
    shear_x_per_y: f32,
    x_subpixel: f32,
) -> Vec<(f32, f32)> {
    if pts.is_empty() {
        return Vec::new();
    }
    let n = pts.len();

    // Find a starting on-curve point. If every point is off-curve (rare
    // but legal — Apple's "phantom on-curve" case), synthesise one at
    // the midpoint of pts[0]..pts[1] and rotate.
    let start_idx = pts.iter().position(|p| p.on_curve);
    let (start_xy, ordered): ((f32, f32), Vec<OrderedPoint>) = if let Some(s) = start_idx {
        let mut ord: Vec<OrderedPoint> = Vec::with_capacity(n);
        for i in 0..n {
            let p = pts[(s + i) % n];
            let (x, y) = map_point(p.x, p.y, scale, bounds, shear_x_per_y, x_subpixel);
            ord.push((x, y, p.on_curve));
        }
        let s_xy = (ord[0].0, ord[0].1);
        (s_xy, ord)
    } else {
        // All-off-curve: the start is the midpoint of pts[0]..pts[1].
        let p0 = pts[0];
        let p1 = pts[1 % n];
        let (x0, y0) = map_point(p0.x, p0.y, scale, bounds, shear_x_per_y, x_subpixel);
        let (x1, y1) = map_point(p1.x, p1.y, scale, bounds, shear_x_per_y, x_subpixel);
        let mid = ((x0 + x1) * 0.5, (y0 + y1) * 0.5);
        let mut ord: Vec<OrderedPoint> = Vec::with_capacity(n + 1);
        // Insert the synthetic on-curve start, then walk the original
        // ring in order.
        ord.push((mid.0, mid.1, true));
        for p in pts.iter().take(n) {
            let (x, y) = map_point(p.x, p.y, scale, bounds, shear_x_per_y, x_subpixel);
            ord.push((x, y, p.on_curve));
        }
        (mid, ord)
    };

    let mut prev_was_off = false;
    let mut prev_off_xy: Option<(f32, f32)> = None;
    let mut out: Vec<(f32, f32)> = Vec::with_capacity(ordered.len() * 2);
    out.push(start_xy);

    // Iterate the ordered points (skipping index 0, which is the start
    // we already pushed).
    for &(x, y, on) in ordered.iter().skip(1) {
        if on {
            if prev_was_off {
                // Quadratic from out.last() — well, no: from the segment
                // start point — through prev_off_xy to (x, y).
                let p0 = *out.last().expect("started with start_xy");
                let p1 = prev_off_xy.expect("prev_was_off");
                subdivide_quad(&mut out, p0, p1, (x, y), 0);
                prev_was_off = false;
                prev_off_xy = None;
            } else {
                out.push((x, y));
            }
        } else if prev_was_off {
            // Two off-curve points in a row → implicit on-curve at
            // their midpoint terminates the previous quadratic, and a
            // new one starts.
            let prev_off = prev_off_xy.expect("prev_was_off");
            let mid = ((prev_off.0 + x) * 0.5, (prev_off.1 + y) * 0.5);
            let p0 = *out.last().expect("at least start");
            subdivide_quad(&mut out, p0, prev_off, mid, 0);
            prev_off_xy = Some((x, y));
            // prev_was_off stays true.
        } else {
            prev_was_off = true;
            prev_off_xy = Some((x, y));
        }
    }

    // Close the contour: handle a trailing off-curve point by curving
    // back to the start.
    if prev_was_off {
        let p1 = prev_off_xy.expect("prev_was_off");
        let p0 = *out.last().expect("non-empty");
        subdivide_quad(&mut out, p0, p1, start_xy, 0);
    } else {
        // Ensure the contour explicitly closes — the rasterizer doesn't
        // assume implicit closure.
        if let (Some(&last), first) = (out.last(), start_xy) {
            if (last.0 - first.0).abs() > 1e-3 || (last.1 - first.1).abs() > 1e-3 {
                out.push(start_xy);
            }
        }
    }

    out
}

/// Recursively subdivide a quadratic Bezier (`p0`, `p1`, `p2`) until
/// the chord between `p0` and `p2` is below `FLATTEN_TOLERANCE_PX` *and*
/// the off-curve handle `p1` lies within that tolerance of the chord.
/// Pushes one or more *output* points (excluding `p0`, including `p2`).
fn subdivide_quad(
    out: &mut Vec<(f32, f32)>,
    p0: (f32, f32),
    p1: (f32, f32),
    p2: (f32, f32),
    depth: u8,
) {
    let dx = p2.0 - p0.0;
    let dy = p2.1 - p0.1;
    let chord_sq = dx * dx + dy * dy;
    // Distance from p1 to the chord — perpendicular component of
    // (p1 - p0) projected against the chord normal. We bound this
    // because a tiny chord with a wild control handle still produces a
    // visible bulge.
    let d_pdx = p1.0 - p0.0;
    let d_pdy = p1.1 - p0.1;
    let cross = d_pdx * dy - d_pdy * dx;
    let chord_len = chord_sq.sqrt();
    let perp = if chord_len > 1e-6 {
        (cross / chord_len).abs()
    } else {
        // Degenerate chord: fall back to the direct distance from p0
        // to p1 (which equals "how far the curve might bulge").
        (d_pdx * d_pdx + d_pdy * d_pdy).sqrt()
    };

    if depth >= MAX_SUBDIV_DEPTH
        || (chord_sq <= FLATTEN_TOLERANCE_PX * FLATTEN_TOLERANCE_PX && perp <= FLATTEN_TOLERANCE_PX)
    {
        out.push(p2);
        return;
    }

    // de Casteljau split at t = 0.5.
    let m01 = ((p0.0 + p1.0) * 0.5, (p0.1 + p1.1) * 0.5);
    let m12 = ((p1.0 + p2.0) * 0.5, (p1.1 + p2.1) * 0.5);
    let m = ((m01.0 + m12.0) * 0.5, (m01.1 + m12.1) * 0.5);

    subdivide_quad(out, p0, m01, m, depth + 1);
    subdivide_quad(out, m, m12, p2, depth + 1);
}

// ---- CFF / cubic-Bezier flattening ----------------------------------

/// Flatten a CFF (cubic-Bezier) outline at `scale` (raster pixels per
/// font unit). Coordinate convention matches [`flatten`]: Y-down,
/// origin at the top-left of the glyph bounding box.
///
/// Type 2 charstrings (Adobe TN5177) emit explicit cubic Beziers and
/// `ClosePath` markers, so this implementation is simpler than the
/// quadratic path — there's no on-curve / off-curve dance.
///
/// Returns `None` for empty outlines.
pub fn flatten_cubic(outline: &oxideav_otf::CubicOutline, scale: f32) -> Option<FlatOutline> {
    flatten_cubic_with_shear(outline, scale, 0.0)
}

/// Sheared variant of [`flatten_cubic`]. The Y-flipped Y-down output
/// is post-multiplied by a horizontal shear `[1, shear; 0, 1]` —
/// matches the synthetic-italic transform in `style.rs`.
pub fn flatten_cubic_with_shear(
    outline: &oxideav_otf::CubicOutline,
    scale: f32,
    shear: f32,
) -> Option<FlatOutline> {
    if outline.contours.is_empty() {
        return None;
    }
    // Map the source bbox (Y-up, font units) to raster (Y-down, px).
    // Sheared output's bbox needs to account for points shifted by
    // shear * y; we recompute by walking emitted points below.
    let raw = outline.bounds;
    if raw.x_max <= raw.x_min || raw.y_max <= raw.y_min {
        return None;
    }

    let mut contours: Vec<Vec<(f32, f32)>> = Vec::with_capacity(outline.contours.len());
    let mut x_min = f32::INFINITY;
    let mut y_min = f32::INFINITY;
    let mut x_max = f32::NEG_INFINITY;
    let mut y_max = f32::NEG_INFINITY;

    for contour in &outline.contours {
        let mut pen = (0.0f32, 0.0f32);
        let mut start = (0.0f32, 0.0f32);
        let mut pts: Vec<(f32, f32)> = Vec::new();
        for seg in &contour.segments {
            match *seg {
                oxideav_otf::CubicSegment::MoveTo(p) => {
                    let xy = scribe_map(p.x, p.y, scale, shear);
                    pen = xy;
                    start = xy;
                    pts.push(xy);
                }
                oxideav_otf::CubicSegment::LineTo(p) => {
                    let xy = scribe_map(p.x, p.y, scale, shear);
                    pts.push(xy);
                    pen = xy;
                }
                oxideav_otf::CubicSegment::CurveTo { c1, c2, end } => {
                    let p0 = pen;
                    let p1 = scribe_map(c1.x, c1.y, scale, shear);
                    let p2 = scribe_map(c2.x, c2.y, scale, shear);
                    let p3 = scribe_map(end.x, end.y, scale, shear);
                    subdivide_cubic(&mut pts, p0, p1, p2, p3, 0);
                    pen = p3;
                }
                oxideav_otf::CubicSegment::ClosePath => {
                    if pts.first() != Some(&start) {
                        pts.push(start);
                    } else if let Some(&last) = pts.last() {
                        if (last.0 - start.0).abs() > 1e-3 || (last.1 - start.1).abs() > 1e-3 {
                            pts.push(start);
                        }
                    }
                    if pts.len() >= 2 {
                        for &(x, y) in &pts {
                            x_min = x_min.min(x);
                            y_min = y_min.min(y);
                            x_max = x_max.max(x);
                            y_max = y_max.max(y);
                        }
                        contours.push(std::mem::take(&mut pts));
                    } else {
                        pts.clear();
                    }
                    pen = start;
                }
            }
        }
        // Flush a trailing open subpath (a font that didn't emit a
        // ClosePath before endchar — uncommon but legal).
        if pts.len() >= 2 {
            for &(x, y) in &pts {
                x_min = x_min.min(x);
                y_min = y_min.min(y);
                x_max = x_max.max(x);
                y_max = y_max.max(y);
            }
            contours.push(pts);
        }
    }

    if contours.is_empty() || !x_min.is_finite() {
        return None;
    }

    // Translate so the bbox top-left lands at (0, 0).
    for c in &mut contours {
        for p in c.iter_mut() {
            p.0 -= x_min;
            p.1 -= y_min;
        }
    }
    let bounds = FlatBounds {
        x_min: 0.0,
        y_min: 0.0,
        x_max: x_max - x_min,
        y_max: y_max - y_min,
    };
    // Suppress an unused-variable warning if the bbox sanity check
    // above ever gets relaxed.
    let _ = raw;
    Some(FlatOutline { contours, bounds })
}

/// Apply `scale` + Y-flip + shear to a single CFF point. Note that
/// CFF point coordinates are floats already (the Type 2 interpreter
/// keeps fixed-real precision), so we don't have to round on input.
#[inline]
fn scribe_map(x: f32, y: f32, scale: f32, shear: f32) -> (f32, f32) {
    // y_raster = -y * scale (Y-up → Y-down). The shear is applied
    // post-Y-flip so it matches what the rasterizer expects.
    let rx = x * scale + shear * (-y * scale);
    let ry = -y * scale;
    (rx, ry)
}

/// Recursively subdivide a cubic Bezier (`p0`, `p1`, `p2`, `p3`)
/// using the de Casteljau split at t = 0.5. Pushes output points
/// (excluding `p0`, including `p3`).
///
/// The flatness test is the standard "max of perpendicular
/// distances from c1 / c2 to the chord (p0, p3) is below the
/// tolerance" — see e.g. Hain et al., "Fast, precise flattening of
/// cubic Bezier path and offset curves" (CAGD 2005). This is the
/// same test scribe's quadratic path uses, generalised to two
/// control points.
fn subdivide_cubic(
    out: &mut Vec<(f32, f32)>,
    p0: (f32, f32),
    p1: (f32, f32),
    p2: (f32, f32),
    p3: (f32, f32),
    depth: u8,
) {
    let dx = p3.0 - p0.0;
    let dy = p3.1 - p0.1;
    let chord_sq = dx * dx + dy * dy;
    let chord_len = chord_sq.sqrt();
    let perp = |p: (f32, f32)| -> f32 {
        let dpx = p.0 - p0.0;
        let dpy = p.1 - p0.1;
        let cross = dpx * dy - dpy * dx;
        if chord_len > 1e-6 {
            (cross / chord_len).abs()
        } else {
            (dpx * dpx + dpy * dpy).sqrt()
        }
    };
    let perp1 = perp(p1);
    let perp2 = perp(p2);
    let max_perp = perp1.max(perp2);

    if depth >= MAX_SUBDIV_DEPTH
        || (chord_sq <= FLATTEN_TOLERANCE_PX * FLATTEN_TOLERANCE_PX
            && max_perp <= FLATTEN_TOLERANCE_PX)
    {
        out.push(p3);
        return;
    }

    // de Casteljau split at t = 0.5.
    let q0 = ((p0.0 + p1.0) * 0.5, (p0.1 + p1.1) * 0.5);
    let q1 = ((p1.0 + p2.0) * 0.5, (p1.1 + p2.1) * 0.5);
    let q2 = ((p2.0 + p3.0) * 0.5, (p2.1 + p3.1) * 0.5);
    let r0 = ((q0.0 + q1.0) * 0.5, (q0.1 + q1.1) * 0.5);
    let r1 = ((q1.0 + q2.0) * 0.5, (q1.1 + q2.1) * 0.5);
    let s = ((r0.0 + r1.0) * 0.5, (r0.1 + r1.1) * 0.5);

    subdivide_cubic(out, p0, q0, r0, s, depth + 1);
    subdivide_cubic(out, s, r1, q2, p3, depth + 1);
}

#[cfg(test)]
mod tests {
    use super::*;
    use oxideav_ttf::{BBox, Contour, Point as TtPoint};

    fn outline_from(points: Vec<(i16, i16, bool)>) -> TtOutline {
        let pts: Vec<TtPoint> = points
            .into_iter()
            .map(|(x, y, on)| TtPoint { x, y, on_curve: on })
            .collect();
        let mut x_min = i16::MAX;
        let mut y_min = i16::MAX;
        let mut x_max = i16::MIN;
        let mut y_max = i16::MIN;
        for p in &pts {
            x_min = x_min.min(p.x);
            y_min = y_min.min(p.y);
            x_max = x_max.max(p.x);
            y_max = y_max.max(p.y);
        }
        TtOutline {
            contours: vec![Contour { points: pts }],
            bounds: Some(BBox {
                x_min,
                y_min,
                x_max,
                y_max,
            }),
        }
    }

    #[test]
    fn empty_outline_yields_none() {
        let o = TtOutline::default();
        assert!(flatten(&o, 0.05).is_none());
    }

    #[test]
    fn straight_triangle_round_trips() {
        // Triangle with all on-curve points.
        let o = outline_from(vec![(0, 0, true), (100, 0, true), (50, 100, true)]);
        let f = flatten(&o, 1.0).expect("non-empty outline");
        assert_eq!(f.contours.len(), 1);
        // 3 corner points + closing point = 4.
        assert_eq!(f.contours[0].len(), 4);
    }

    #[test]
    fn quadratic_curve_subdivides() {
        // A "tall" curve from (0, 0) to (100, 0) with control at
        // (50, 100) — visible bulge so subdivision must produce
        // intermediate points.
        let o = outline_from(vec![(0, 0, true), (50, 100, false), (100, 0, true)]);
        let f = flatten(&o, 1.0).expect("non-empty outline");
        // Should produce many intermediate points along the curve.
        assert!(
            f.contours[0].len() > 5,
            "expected subdivided curve, got {} points",
            f.contours[0].len()
        );
    }
}