fmd-math 0.1.2

Clean-room TeX-mathematics layout engine: TeX-math grammar, the eight atom classes, the inter-atom spacing table, and TeX style propagation (franken_markdown's math subsystem)
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
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
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
//! Parametric drawn-path constructions — the ADR-0005 mainline for
//! delimiters past the uniform-scale ceiling, the drawn radical sign, and
//! the stretchy horizontal constructions (`\widehat`, `\widetilde`,
//! `\overbrace`/`\underbrace`, `\overrightarrow`/`\overleftarrow`).
//!
//! The bundled faces carry no cmex-style extension repertoire (CM Unicode
//! maps none of U+239B…U+23AE and has no size-variant sets — the G0-3
//! probe), so oversized constructions are **drawn**: closed quadratic
//! contours whose stroke weights are calibrated against the authored
//! glyphs, so the mechanism seam at the `1.25×` threshold is invisible at
//! a glance. The paren and surd constructions are ports of the ones the
//! G0-3 spike proved at three sizes; the rest of the family (brackets,
//! braces, bars, angles, floor/ceil, slashes) generalizes the same
//! discipline. No requested size can fail, by construction — §11.4's
//! promise made structural.
//!
//! Everything here is pure f64 add/sub/mul/div geometry — no
//! transcendental calls — so drawn output is bit-identical across
//! platforms (the determinism contract layout.rs declares).
//!
//! Coordinates: ems, y-up. Delimiter contours span `y ∈ [0, total]`;
//! horizontal stretches span `x ∈ [0, width]` with `y ∈ [0, height]`
//! (placement — axis centering, above/below the base — is the caller's).

use crate::mbox::{PathContour, PathSeg};

/// A finished construction: contours plus the advance width the caller
/// should give its box.
pub(crate) struct Drawn {
    /// Advance width, ems.
    pub(crate) width: f64,
    /// Closed contours, box-local.
    pub(crate) contours: Vec<PathContour>,
}

/// A horizontal stretchy construction: contours plus its height band.
pub(crate) struct DrawnBand {
    /// Total height of the band, ems.
    pub(crate) height: f64,
    /// Closed contours, box-local (`x ∈ [0, width]`, `y ∈ [0, height]`).
    pub(crate) contours: Vec<PathContour>,
}

/// Which horizontal stretchy construction.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum Stretch {
    /// `\widehat` — a tented chevron.
    Hat,
    /// `\widetilde` — an S-wave band.
    Tilde,
    /// `\overbrace` — a downward-hooked horizontal brace (lobe up).
    OverBrace,
    /// `\underbrace` — the mirror (lobe down).
    UnderBrace,
    /// `\overrightarrow` — shaft + right arrowhead.
    RightArrow,
    /// `\xmapsto`'s band — the right arrow with the origin bar.
    MapstoArrow,
    /// `\overleftarrow` — shaft + left arrowhead.
    LeftArrow,
}

/// Line-segment helper.
#[inline(always)]
fn line(to: (f64, f64)) -> PathSeg {
    PathSeg::Line { to }
}

/// Quadratic-segment helper.
#[inline(always)]
fn quad(ctrl: (f64, f64), to: (f64, f64)) -> PathSeg {
    PathSeg::Quad { ctrl, to }
}

/// One closed contour from a start point and segments.
#[inline(always)]
fn contour(start: (f64, f64), segments: Vec<PathSeg>) -> PathContour {
    PathContour { start, segments }
}

/// A closed axis-aligned rectangle contour.
fn rect(x0: f64, y0: f64, x1: f64, y1: f64) -> PathContour {
    contour(
        (x0, y0),
        vec![
            line((x1, y0)),
            line((x1, y1)),
            line((x0, y1)),
            line((x0, y0)),
        ],
    )
}

/// Mirror a contour horizontally about `x = w/2`.
fn mirror_x(c: &PathContour, w: f64) -> PathContour {
    let mx = |p: (f64, f64)| (w - p.0, p.1);
    PathContour {
        start: mx(c.start),
        segments: c
            .segments
            .iter()
            .map(|s| match s {
                PathSeg::Line { to } => PathSeg::Line { to: mx(*to) },
                PathSeg::Quad { ctrl, to } => PathSeg::Quad {
                    ctrl: mx(*ctrl),
                    to: mx(*to),
                },
            })
            .collect(),
    }
}

/// Mirror a contour vertically about `y = h/2`.
fn mirror_y(c: &PathContour, h: f64) -> PathContour {
    let my = |p: (f64, f64)| (p.0, h - p.1);
    PathContour {
        start: my(c.start),
        segments: c
            .segments
            .iter()
            .map(|s| match s {
                PathSeg::Line { to } => PathSeg::Line { to: my(*to) },
                PathSeg::Quad { ctrl, to } => PathSeg::Quad {
                    ctrl: my(*ctrl),
                    to: my(*to),
                },
            })
            .collect(),
    }
}

/// The drawn construction for a delimiter character covering `total` ems
/// vertically, at style size `em` (stroke weights scale with `em`; the
/// gentle size-growth terms scale with `total`, matching how authored
/// optical sizes thicken). `None` for characters without a construction —
/// the caller keeps uniform scaling for those (nothing regresses).
pub(crate) fn delimiter(ch: char, total: f64, em: f64) -> Option<Drawn> {
    match ch {
        '(' | ')' => Some(paren(ch == ')', total, em)),
        '[' | ']' => Some(bracket(ch == ']', total, em, true, true)),
        '⌈' | '⌉' => Some(bracket(ch == '⌉', total, em, true, false)),
        '⌊' | '⌋' => Some(bracket(ch == '⌋', total, em, false, true)),
        '{' | '}' => Some(brace(ch == '}', total, em)),
        '|' => Some(vert(total, em, false)),
        '‖' => Some(vert(total, em, true)),
        '⟨' | '⟩' | '〈' | '〉' => Some(angle(matches!(ch, '⟩' | '〉'), total, em)),
        '/' | '\\' => Some(slash(ch == '\\', total, em)),
        '√' => Some(surd(total, em)),
        _ => None,
    }
}

/// The spike-proven paren: one closed quadratic contour, stroke calibrated
/// to CM's authored paren (tip `0.035 em`, waist `0.062 em` growing gently
/// with size).
fn paren(closing: bool, h: f64, em: f64) -> Drawn {
    let w = 0.30 * em + 0.06 * h;
    let t_top = 0.035 * em;
    let t_mid = 0.062 * em + 0.01 * h;
    let bulge = 0.16 * w;
    let (x_out, x_in) = (0.0, t_mid);
    let start = (w, h);
    let c = contour(
        start,
        vec![
            quad((x_out - bulge, h / 2.0), (w, 0.0)),
            line((w - t_top, 0.0)),
            quad((x_in - bulge, h / 2.0), (w - t_top, h)),
            line(start),
        ],
    );
    let width = w + 0.04 * em;
    let c = if closing { mirror_x(&c, width) } else { c };
    Drawn {
        width,
        contours: vec![c],
    }
}

/// A square bracket (or floor/ceiling, dropping one foot): stem plus feet
/// as one rectilinear contour. Stem `0.065 em`, feet `0.24 em` with gentle
/// growth.
fn bracket(closing: bool, h: f64, em: f64, top_foot: bool, bottom_foot: bool) -> Drawn {
    let t = 0.065 * em + 0.004 * h;
    let foot = 0.24 * em + 0.01 * h;
    let w = t + foot;
    // Opening form, stem at the left: walk the outline clockwise from the
    // outer top-right corner. Feet are present or absent per the variant
    // (floor/ceiling are brackets missing one foot).
    let mut pts: Vec<(f64, f64)> = Vec::new();
    if top_foot {
        pts.push((w, h));
        pts.push((0.0, h));
    } else {
        pts.push((t, h));
        pts.push((0.0, h));
    }
    pts.push((0.0, 0.0));
    if bottom_foot {
        pts.push((w, 0.0));
        pts.push((w, t));
        pts.push((t, t));
    } else {
        pts.push((t, 0.0));
    }
    if top_foot {
        pts.push((t, h - t));
        pts.push((w, h - t));
    } else {
        pts.push((t, h));
    }
    let start = pts[0];
    let segments: Vec<PathSeg> = pts[1..]
        .iter()
        .copied()
        .map(line)
        .chain(core::iter::once(line(start)))
        .collect();
    let c = contour(start, segments);
    let width = w + 0.06 * em;
    let c = if closing { mirror_x(&c, width) } else { c };
    Drawn {
        width,
        contours: vec![c],
    }
}

/// A curly brace: hooked caps, straight stems, and the waist point, as one
/// closed contour of quads — the classic two-S construction. Stroke
/// `0.055 em` growing gently; hook and waist reach `0.16 em`-ish.
fn brace(closing: bool, h: f64, em: f64) -> Drawn {
    let t = 0.055 * em + 0.006 * h; // stroke
    let reach = 0.16 * em + 0.015 * h; // how far hooks/waist bend
    let w = t + 2.0 * reach; // full advance of the ink
    let mid = h / 2.0;
    let cap = (0.28 * em).min(h * 0.25); // vertical extent of each hook
    let waist = (0.30 * em).min(h * 0.25); // vertical extent of the waist bend
    // Opening brace `{`: stems at x = reach .. reach+t, hooks bend right
    // (toward the content), waist points left. Outer edge runs down the
    // left side; inner edge returns up the right.
    let xs = reach; // outer stem x
    let start = (w, h);
    let c = contour(
        start,
        vec![
            // top hook, outer: from the cap tip curving left-down into the stem
            quad((xs, h), (xs, h - cap)),
            // upper stem, outer
            line((xs, mid + waist)),
            // waist, outer: bend left to the point
            quad((xs, mid), (0.0, mid)),
            // waist back, outer
            quad((xs, mid), (xs, mid - waist)),
            // lower stem, outer
            line((xs, cap)),
            // bottom hook, outer
            quad((xs, 0.0), (w, 0.0)),
            // across the bottom cap tip
            line((w, t)),
            // bottom hook, inner
            quad((xs + t, t), (xs + t, cap)),
            // lower stem, inner
            line((xs + t, mid - waist)),
            // waist, inner (shallower bend than the outer edge)
            quad((xs + t, mid), (t, mid)),
            quad((xs + t, mid), (xs + t, mid + waist)),
            // upper stem, inner
            line((xs + t, h - cap)),
            // top hook, inner
            quad((xs + t, h - t), (w, h - t)),
            // close across the top cap tip
            line(start),
        ],
    );
    let width = w + 0.05 * em;
    let c = if closing { mirror_x(&c, width) } else { c };
    Drawn {
        width,
        contours: vec![c],
    }
}

/// A vertical bar (or double bar): thin rectangles, CM `\vert` weight.
fn vert(h: f64, em: f64, double: bool) -> Drawn {
    let t = 0.045 * em;
    if double {
        let gap = 0.14 * em;
        Drawn {
            width: 2.0 * t + gap + 0.06 * em,
            contours: vec![rect(0.0, 0.0, t, h), rect(t + gap, 0.0, 2.0 * t + gap, h)],
        }
    } else {
        Drawn {
            width: t + 0.06 * em,
            contours: vec![rect(0.0, 0.0, t, h)],
        }
    }
}

/// An angle bracket: two strokes meeting at the apex, drawn as one
/// hexagonal contour whose inner edge is the outer edge shifted right by a
/// fixed horizontal stroke width. (A constant *horizontal* thickness thins
/// the perceived stroke slightly as the bracket steepens — imperceptible
/// over the family's real aspect range, and it keeps the arithmetic to
/// add/sub/mul/div per the crate's determinism doctrine: no `sqrt`-based
/// normal offset.)
fn angle(closing: bool, h: f64, em: f64) -> Drawn {
    let w = 0.24 * em + 0.10 * h; // opening half-width grows with size
    let mid = h / 2.0;
    let shift = 0.085 * em + 0.006 * h; // horizontal stroke width
    let start = (w + shift, h);
    let c = contour(
        start,
        vec![
            line((shift, mid)),
            line((w + shift, 0.0)),
            line((w, 0.0)),
            line((0.0, mid)),
            line((w, h)),
            line(start),
        ],
    );
    let width = w + shift + 0.05 * em;
    let c = if closing { mirror_x(&c, width) } else { c };
    Drawn {
        width,
        contours: vec![c],
    }
}

/// A big solidus/reverse solidus: a thin parallelogram.
fn slash(reverse: bool, h: f64, em: f64) -> Drawn {
    let t = 0.06 * em + 0.004 * h; // horizontal thickness
    let run = 0.28 * em + 0.18 * h; // horizontal run over the height
    let w = run + t;
    // `/`: bottom-left to top-right.
    let c = contour(
        (0.0, 0.0),
        vec![
            line((t, 0.0)),
            line((w, h)),
            line((w - t, h)),
            line((0.0, 0.0)),
        ],
    );
    let width = w + 0.04 * em;
    let c = if reverse { mirror_x(&c, width) } else { c };
    Drawn {
        width,
        contours: vec![c],
    }
}

/// The spike-proven drawn surd: leading tick, heavy down-stroke to the
/// vertex, light up-stroke to the overbar corner, as one closed contour.
/// The top edge sits at `y = total` (the caller aligns it with the
/// overbar); stroke weights match CM's authored sign.
fn surd(total: f64, em: f64) -> Drawn {
    let w = 0.58 * em + 0.02 * total;
    let heavy = 0.058 * em + 0.004 * total;
    let light = 0.056 * em; // ≈1.4 × rule thickness at em = 1
    let vertex_x = 0.30 * em;
    let mid_y = total * 0.42;
    let start = (0.02 * em, mid_y);
    let c = contour(
        start,
        vec![
            line((0.13 * em, mid_y + 0.05 * em)),
            line((vertex_x - heavy * 0.6, 0.18 * em)),
            line((w - light, total)),
            line((w, total)),
            line((vertex_x, 0.0)),
            line((vertex_x - heavy, 0.0)),
            line((0.10 * em, mid_y - 0.02 * em)),
            line(start),
        ],
    );
    Drawn {
        width: w,
        contours: vec![c],
    }
}

/// A horizontal stretchy construction spanning `width` ems at style size
/// `em`. Every kind is total: any width draws.
pub(crate) fn stretch(kind: Stretch, width: f64, em: f64) -> DrawnBand {
    match kind {
        Stretch::Hat => hat(width, em),
        Stretch::Tilde => tilde(width, em),
        Stretch::OverBrace => hbrace(width, em, false),
        Stretch::UnderBrace => hbrace(width, em, true),
        Stretch::RightArrow => arrow(width, em, false),
        Stretch::LeftArrow => arrow(width, em, true),
        Stretch::MapstoArrow => mapsto_arrow(width, em),
    }
}

/// `\widehat`: a tented chevron with square ends, apex thickness equal to
/// the stroke.
fn hat(w: f64, em: f64) -> DrawnBand {
    let t = 0.048 * em + 0.010 * w.min(3.0 * em);
    let rise = 0.16 * em + 0.05 * w.min(3.0 * em);
    let h = rise + t;
    let c = contour(
        (0.0, 0.0),
        vec![
            line((0.0, t)),
            line((w / 2.0, h)),
            line((w, t)),
            line((w, 0.0)),
            line((w / 2.0, rise)),
            line((0.0, 0.0)),
        ],
    );
    DrawnBand {
        height: h,
        contours: vec![c],
    }
}

/// `\widetilde`: an S-wave band of two quadratic humps.
fn tilde(w: f64, em: f64) -> DrawnBand {
    let t = 0.055 * em;
    let amp = 0.10 * em + 0.02 * w.min(3.0 * em);
    let h = 2.0 * amp + t;
    // Lower edge: rises from the left end, dips mid-right, ends high; the
    // upper edge is the same wave lifted by t.
    let c = contour(
        (0.0, amp * 0.4),
        vec![
            quad((w * 0.25, amp * 2.0), (w * 0.5, amp)),
            quad((w * 0.75, 0.0), (w, amp * 1.6)),
            line((w, amp * 1.6 + t)),
            quad((w * 0.75, t), (w * 0.5, amp + t)),
            quad((w * 0.25, amp * 2.0 + t), (0.0, amp * 0.4 + t)),
            line((0.0, amp * 0.4)),
        ],
    );
    DrawnBand {
        height: h,
        contours: vec![c],
    }
}

/// `\overbrace`/`\underbrace`: a horizontal brace — end hooks, straight
/// runs, center point — as one closed contour. For `\overbrace` the lobe
/// points up (hooks reach down at the ends); `\underbrace` mirrors.
fn hbrace(w: f64, em: f64, under: bool) -> DrawnBand {
    let t = 0.050 * em; // stroke
    let reach = (0.16 * em).min(w * 0.12); // vertical bend of hooks/point
    let h = t + 2.0 * reach;
    let cap = (0.30 * em).min(w * 0.20); // horizontal extent of each hook
    let waist = (0.32 * em).min(w * 0.20); // horizontal extent of the point
    let mid = w / 2.0;
    let ys = reach; // the runs' lower edge
    // Overbrace form: hooks at the ends bend down, the center point bends
    // up. Outer (upper) edge left→right, inner (lower) edge back.
    let start = (0.0, 0.0);
    let c = contour(
        start,
        vec![
            // left hook, outer: up from the tip into the run
            quad((0.0, ys + t), (cap, ys + t)),
            // left run, outer
            line((mid - waist, ys + t)),
            // center point, outer
            quad((mid, ys + t), (mid, h)),
            quad((mid, ys + t), (mid + waist, ys + t)),
            // right run, outer
            line((w - cap, ys + t)),
            // right hook, outer: down to the tip
            quad((w, ys + t), (w, 0.0)),
            // across the right tip
            line((w - t, 0.0)),
            // right hook, inner
            quad((w - t, ys), (w - cap, ys)),
            // right run, inner
            line((mid + waist, ys)),
            // center point, inner (shallower)
            quad((mid + t, ys), (mid, h - t * 1.2)),
            quad((mid - t, ys), (mid - waist, ys)),
            // left run, inner
            line((cap, ys)),
            // left hook, inner
            quad((t, ys), (t, 0.0)),
            // close across the left tip
            line(start),
        ],
    );
    let c = if under { mirror_y(&c, h) } else { c };
    DrawnBand {
        height: h,
        contours: vec![c],
    }
}

/// `\overrightarrow`/`\overleftarrow`: shaft plus arrowhead as one contour.
fn arrow(w: f64, em: f64, left: bool) -> DrawnBand {
    let t = 0.048 * em; // shaft thickness
    let head_l = (0.32 * em).min(w * 0.5); // head length
    let head_h = 0.16 * em; // head half-height
    let h = 2.0 * head_h;
    let cy = head_h; // shaft centerline
    let c = contour(
        (0.0, cy - t / 2.0),
        vec![
            line((w - head_l, cy - t / 2.0)),
            line((w - head_l, cy - head_h)),
            line((w, cy)),
            line((w - head_l, cy + head_h)),
            line((w - head_l, cy + t / 2.0)),
            line((0.0, cy + t / 2.0)),
            line((0.0, cy - t / 2.0)),
        ],
    );
    let c = if left { mirror_x(&c, w) } else { c };
    DrawnBand {
        height: h,
        contours: vec![c],
    }
}

/// `\xmapsto`: the right arrow with `↦`'s origin bar — a vertical stroke
/// the full band height at the left end, the same stroke thickness as the
/// shaft.
fn mapsto_arrow(w: f64, em: f64) -> DrawnBand {
    let t = 0.048 * em;
    let band = arrow(w, em, false);
    let bar = contour(
        (0.0, 0.0),
        vec![
            line((t, 0.0)),
            line((t, band.height)),
            line((0.0, band.height)),
            line((0.0, 0.0)),
        ],
    );
    let mut contours = band.contours;
    contours.push(bar);
    DrawnBand {
        height: band.height,
        contours,
    }
}

// ── Drawn symbols (fm-j5t.4) ────────────────────────────────────────────

/// A drawn symbol in a unit box: contours plus the box metrics. The
/// contours are baseline-relative (`y ∈ [-depth, height]`), so the caller
/// places them with `dy = 0`.
pub(crate) struct DrawnSym {
    /// Advance width, ems.
    pub(crate) width: f64,
    /// Ink extent above the baseline, ems.
    pub(crate) height: f64,
    /// Ink extent below the baseline, positive, ems.
    pub(crate) depth: f64,
    /// Closed contours, baseline-relative.
    pub(crate) contours: Vec<PathContour>,
}

/// The drawn construction for a symbol character no bundled face maps
/// (fm-j5t.4): the wasysym astronomy/biology glyphs `\female` (♀,
/// U+2640), `\male`/`\mars` (♂, U+2642), and `\earth` (♁, U+2641).
/// The G0-3 probe found all three unmapped in every bundled face, so —
/// per the Checkmark/Exmark drawn-mark precedent — they are **drawn** in
/// the same unit box, strokes calibrated to the CM-authored weights
/// (`0.055 em`, the brace stroke). This is a miss-only fallback in the
/// caller: the moment a bundled face gains the exact codepoint, the
/// authored glyph wins and this construction stops firing. `None` for
/// anything else — those keep the precise `UnmappedChar` refusal.
pub(crate) fn symbol(ch: char, em: f64) -> Option<DrawnSym> {
    match ch {
        '\u{2640}' => Some(female(em)),
        '\u{2642}' => Some(male(em)),
        '\u{2641}' => Some(earth(em)),
        _ => None,
    }
}

/// √2/2 (cos 45°), a compile-time constant: the determinism doctrine
/// keeps the arithmetic to add/sub/mul/div over fixed constants. The std
/// constant is the same bit pattern, spelled canonically.
const COS45: f64 = std::f64::consts::FRAC_1_SQRT_2;
/// √2−1 (tan 22.5°): the quad circle control offset.
const TAN22: f64 = 0.414_213_562_373_095_1;

/// The eight quad control/endpoint pairs of a circle of radius `r` about
/// `(cx, cy)`, walked counterclockwise from the east point: each 45° arc
/// is one quadratic with its control on the bisector at radius
/// `r·sec(π/8)` — the `(r, r·tan(π/8))` construction — for a worst-case
/// radial error of about 0.03 %.
fn circle_quads(cx: f64, cy: f64, r: f64) -> Vec<PathSeg> {
    let b = COS45 * r;
    let a = TAN22 * r;
    vec![
        quad((cx + r, cy + a), (cx + b, cy + b)), // E → NE
        quad((cx + a, cy + r), (cx, cy + r)),     // NE → N
        quad((cx - a, cy + r), (cx - b, cy + b)), // N → NW
        quad((cx - r, cy + a), (cx - r, cy)),     // NW → W
        quad((cx - r, cy - a), (cx - b, cy - b)), // W → SW
        quad((cx - a, cy - r), (cx, cy - r)),     // SW → S
        quad((cx + a, cy - r), (cx + b, cy - b)), // S → SE
        quad((cx + r, cy - a), (cx + r, cy)),     // SE → E
    ]
}

/// A stroked circle (a ring) as ONE contour: the outer circle walked
/// counterclockwise, a radial step inward, the inner circle walked back
/// clockwise, and the return step closing the spur. The reversed inner
/// walk punches the hole under the nonzero rule; the two radial steps
/// are coincident zero-width spurs, invisible under any fill rule.
fn ring(cx: f64, cy: f64, r_out: f64, r_in: f64) -> PathContour {
    let start = (cx + r_out, cy);
    let mut segments = circle_quads(cx, cy, r_out);
    let inner_start = (cx + r_in, cy);
    segments.push(line(inner_start));
    // The inner circle walks the same arcs clockwise: the forward quads
    // in reverse order, each ending at its own start point (a quadratic
    // is symmetric in its endpoints, so the control point carries over).
    let fwd = circle_quads(cx, cy, r_in);
    let mut pts = vec![inner_start];
    for s in &fwd {
        match s {
            PathSeg::Quad { to, .. } | PathSeg::Line { to } => pts.push(*to),
        }
    }
    for (i, s) in fwd.iter().enumerate().rev() {
        match s {
            PathSeg::Quad { ctrl, .. } => segments.push(quad(*ctrl, pts[i])),
            PathSeg::Line { .. } => segments.push(line(pts[i])),
        }
    }
    segments.push(line(start));
    contour(start, segments)
}

/// A plus-sign (a cross) as one contour, walked counterclockwise from the
/// bottom-left of the vertical arm: `hx`/`hy` are the horizontal/vertical
/// half-lengths, `t` the stroke. One contour — two overlapping
/// rectangles would punch a hole at the crossing under even-odd fills.
fn plus(cx: f64, cy: f64, hx: f64, hy: f64, t: f64) -> PathContour {
    let h = t / 2.0;
    let pts = [
        (cx - h, cy - hy),
        (cx + h, cy - hy),
        (cx + h, cy - h),
        (cx + hx, cy - h),
        (cx + hx, cy + h),
        (cx + h, cy + h),
        (cx + h, cy + hy),
        (cx - h, cy + hy),
        (cx - h, cy + h),
        (cx - hx, cy + h),
        (cx - hx, cy - h),
        (cx - h, cy - h),
    ];
    contour(
        pts[0],
        pts[1..]
            .iter()
            .copied()
            .map(line)
            .chain(core::iter::once(line(pts[0])))
            .collect(),
    )
}

/// ♀ (`\female`, wasysym's Venus): a ring riding to cap height with a
/// cross hanging below, its foot reaching a small depth past the
/// baseline — the wasysym proportions.
fn female(em: f64) -> DrawnSym {
    let t = 0.055 * em;
    let r = 0.27 * em;
    let cx = 0.32 * em;
    let cy = 0.41 * em; // ring top at 0.68 em, the CM cap height
    let foot = -0.10 * em;
    let join = cy - r + t / 2.0; // the vertical arm overlaps into the ring
    let cross = plus(cx, (foot + join) / 2.0, 0.13 * em, (join - foot) / 2.0, t);
    DrawnSym {
        width: 0.64 * em,
        height: cy + r,
        depth: -foot,
        contours: vec![ring(cx, cy, r, r - t), cross],
    }
}

/// ♂ (`\male`/`\mars`): a ring near the baseline with a 45° arrow out of
/// the northeast — shaft plus triangular head.
fn male(em: f64) -> DrawnSym {
    let t = 0.055 * em;
    let r = 0.24 * em;
    let cx = 0.30 * em;
    let cy = 0.26 * em; // ring bottom a hair above the baseline
    let b = COS45;
    // Shaft: from just inside the ring edge out along the 45° diagonal.
    let s0 = r - t / 2.0;
    let s1 = r + 0.26 * em;
    let p0 = (cx + s0 * b, cy + s0 * b);
    let p1 = (cx + s1 * b, cy + s1 * b);
    let hw = t / 2.0;
    let shaft = contour(
        (p0.0 - hw * b, p0.1 + hw * b),
        vec![
            line((p1.0 - hw * b, p1.1 + hw * b)),
            line((p1.0 + hw * b, p1.1 - hw * b)),
            line((p0.0 + hw * b, p0.1 - hw * b)),
            line((p0.0 - hw * b, p0.1 + hw * b)),
        ],
    );
    // Head: a triangle whose tip continues the shaft line.
    let hl = 0.15 * em;
    let hb = 0.10 * em;
    let head = contour(
        (p1.0 + hl * b, p1.1 + hl * b),
        vec![
            line((p1.0 - hb * b, p1.1 + hb * b)),
            line((p1.0 + hb * b, p1.1 - hb * b)),
            line((p1.0 + hl * b, p1.1 + hl * b)),
        ],
    );
    let extent = s1 + hl;
    DrawnSym {
        width: cx + extent * b + 0.03 * em,
        height: cy + extent * b,
        depth: 0.0,
        contours: vec![ring(cx, cy, r, r - t), shaft, head],
    }
}

/// ♁ (`\earth`): a ring with the inscribed cross — the globe-and-cross
/// mark, bars joining the ring's inner edge.
fn earth(em: f64) -> DrawnSym {
    let t = 0.055 * em;
    let r = 0.29 * em;
    let cx = 0.32 * em;
    let cy = 0.34 * em; // ring spans 0.05..0.63 em
    let reach = r - t / 2.0; // the bars join the ring's radial mid
    DrawnSym {
        width: 0.64 * em,
        height: cy + r,
        depth: 0.0,
        contours: vec![ring(cx, cy, r, r - t), plus(cx, cy, reach, reach, t)],
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]

    use super::*;

    /// Every contour must be closed: the last segment returns to the start.
    fn assert_closed(d: &[PathContour]) {
        for c in d {
            let last = match c.segments.last().expect("segments") {
                PathSeg::Line { to } | PathSeg::Quad { to, .. } => *to,
            };
            assert!(
                (last.0 - c.start.0).abs() < 1e-12 && (last.1 - c.start.1).abs() < 1e-12,
                "contour not closed: start {:?}, last {last:?}",
                c.start
            );
        }
    }

    /// On-curve points must stay inside the declared band (control points
    /// may overshoot; the curve stays inside their hull).
    fn assert_y_range(d: &[PathContour], lo: f64, hi: f64) {
        for c in d {
            let check = |y: f64| {
                assert!(
                    y >= lo - 1e-9 && y <= hi + 1e-9,
                    "on-curve y {y} outside [{lo}, {hi}]"
                );
            };
            check(c.start.1);
            for s in &c.segments {
                match s {
                    PathSeg::Line { to } | PathSeg::Quad { to, .. } => check(to.1),
                }
            }
        }
    }

    #[test]
    fn every_delimiter_construction_exists_and_is_closed() {
        for ch in [
            '(', ')', '[', ']', '{', '}', '|', '‖', '⟨', '⟩', '⌈', '⌉', '⌊', '⌋', '/', '\\', '√',
        ] {
            for total in [1.0, 2.5, 7.0, 40.0] {
                let d = delimiter(ch, total, 1.0)
                    .unwrap_or_else(|| panic!("no construction for {ch:?}"));
                assert!(d.width > 0.0, "{ch:?} zero width");
                assert!(!d.contours.is_empty());
                assert_closed(&d.contours);
                assert_y_range(&d.contours, 0.0, total);
            }
        }
    }

    #[test]
    fn unknown_delimiters_have_no_construction() {
        // The caller keeps uniform scaling for these; nothing regresses.
        assert!(delimiter('↑', 3.0, 1.0).is_none());
        assert!(delimiter('x', 3.0, 1.0).is_none());
    }

    #[test]
    fn mirrored_pairs_share_extents() {
        for (open, close) in [('(', ')'), ('[', ']'), ('{', '}'), ('⟨', '⟩')] {
            let o = delimiter(open, 5.0, 1.0).unwrap();
            let c = delimiter(close, 5.0, 1.0).unwrap();
            assert!((o.width - c.width).abs() < 1e-12, "{open:?}/{close:?}");
            assert_eq!(o.contours.len(), c.contours.len());
        }
    }

    #[test]
    fn every_stretch_construction_draws_at_any_width() {
        for kind in [
            Stretch::Hat,
            Stretch::Tilde,
            Stretch::OverBrace,
            Stretch::UnderBrace,
            Stretch::RightArrow,
            Stretch::LeftArrow,
            Stretch::MapstoArrow,
        ] {
            for w in [0.2, 1.0, 4.0, 25.0] {
                let b = stretch(kind, w, 1.0);
                assert!(b.height > 0.0);
                assert_closed(&b.contours);
                assert_y_range(&b.contours, 0.0, b.height);
                // The band spans the requested width.
                let max_x = b
                    .contours
                    .iter()
                    .flat_map(|c| {
                        core::iter::once(c.start.0).chain(c.segments.iter().map(|s| match s {
                            PathSeg::Line { to } | PathSeg::Quad { to, .. } => to.0,
                        }))
                    })
                    .fold(0.0_f64, f64::max);
                assert!(
                    (max_x - w).abs() < 1e-9,
                    "{kind:?} at {w}: ink ends at {max_x}"
                );
            }
        }
    }

    #[test]
    fn constructions_are_deterministic() {
        let a = delimiter('{', 7.3, 1.0).unwrap();
        let b = delimiter('{', 7.3, 1.0).unwrap();
        assert_eq!(a.contours, b.contours);
        let x = stretch(Stretch::Tilde, 3.7, 1.0);
        let y = stretch(Stretch::Tilde, 3.7, 1.0);
        assert_eq!(x.contours, y.contours);
        for ch in ['\u{2640}', '\u{2642}', '\u{2641}'] {
            let s1 = symbol(ch, 1.0).unwrap();
            let s2 = symbol(ch, 1.0).unwrap();
            assert_eq!(s1.contours, s2.contours, "{ch:?}");
        }
    }

    #[test]
    fn every_drawn_symbol_is_closed_and_in_box() {
        for ch in ['\u{2640}', '\u{2642}', '\u{2641}'] {
            for em in [0.5, 1.0, 2.4] {
                let d = symbol(ch, em).unwrap_or_else(|| panic!("no symbol for {ch:?}"));
                assert!(d.width > 0.0, "{ch:?} zero width");
                assert!(!d.contours.is_empty());
                assert_closed(&d.contours);
                assert_y_range(&d.contours, -d.depth, d.height);
                // The ink stays inside the advance (plus the quad-control
                // slack of the circle approximation).
                for c in &d.contours {
                    let mut xs = vec![c.start.0];
                    xs.extend(c.segments.iter().map(|s| match s {
                        PathSeg::Line { to } | PathSeg::Quad { to, .. } => to.0,
                    }));
                    for x in xs {
                        assert!(x >= -1e-9 && x <= d.width + 1e-9, "{ch:?} x {x}");
                    }
                }
            }
        }
    }

    #[test]
    fn unmapped_symbol_chars_have_no_construction() {
        // Everything else keeps the precise UnmappedChar refusal.
        assert!(symbol('x', 1.0).is_none());
        assert!(symbol('\u{2643}', 1.0).is_none()); // Jupiter: not landed
        assert!(symbol('\u{00A9}', 1.0).is_none()); // copyright: a real glyph
    }
}