From 8f675bcabd13239094b4c81ec24e7ba2f7e368f0 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Sat, 24 Oct 2026 01:31:51 +0800 Subject: [PATCH] Use Computer Modern math metrics for route-D formulas --- crates/texrra-tex-core/assets/cmex10.tfm | Bin 0 -> 992 bytes crates/texrra-tex-core/assets/cmmi10.tfm | Bin 0 -> 1528 bytes crates/texrra-tex-core/src/cmr10.rs | 97 +++++++++++++++++++++++ crates/texrra-tex-core/src/math.rs | 17 ++-- docs/ROUTE_D_PLAN.md | 2 +- docs/TEX_CORE.md | 4 +- src/route_d.rs | 2 +- 7 files changed, 108 insertions(+), 14 deletions(-) create mode 100644 crates/texrra-tex-core/assets/cmex10.tfm create mode 100644 crates/texrra-tex-core/assets/cmmi10.tfm diff --git a/crates/texrra-tex-core/assets/cmex10.tfm b/crates/texrra-tex-core/assets/cmex10.tfm new file mode 100644 index 0000000000000000000000000000000000000000..d5427ad3f7f5d6ffbb3bbec8f39ab39e0b9bd1dd GIT binary patch literal 992 zcmZ9~%TE(g6bA6G=k_^mhqgecLuX1AQBaXbc@)rsATer)M8%+@hA0RqAW~i%Sh#V8 zM&knAkhrVS#EpM|8xmyU%C!lJ3tgKSR(>5>C{2Dn=iYnHo!sQ$H(~%*k%kvK6m!5r zc=yA63>!e~%IHvfY9v3N9$m_hPR~uuOgkm}|J=R(eM9>3cAX7B}|KeE%C7qG*3|@t| z@D9FA7QVqD_|`h86aLvP_;;Qmkb8*$_XFGuY^I=Pze8hva5Ie%1R>Ui3hxoxd4bUG zWrSHB5CDuG5%p)IlM0TDd%AT^>&oHb7BtFYqj9YZ|!UsHL@@*BfoTHKU1F8|A!Dk8oyG@h*8kUvHSE;9eImGxDPqSZ0S5 z)nr;myw(Ut16r2tHw5xGm_UUMY>qPbDzk=V#Mg!%H*>H$%8d19pwwsfu(f8uy(!L& zZBeG}hzCN|w7BmisVW;itI{b4`+FM>3q9+#NWdGS{DQ^fB^Y(S^JR6v?%zB1*W+pVNA>M&cn6Zy5#ui?kRmuDOyLhMP3I1x?bG)zYAaBSlBRk3?S;}2N ziT{m`5S@#l+bpz(`uEzv64I~0W~-Oe8i;okt&9fT8*B#8D4@N!xwOzW;Ih5OA>xM# z*~H5ujUI~zj7-z7803o$ktMib5+zo{|O73kaR7c7G6H3u7C{$0WeFUYsnQ(y6 z0;Tl|l)>{*-XL5afpS%YG7*FF&2=bKB~Tt-gzEYZYRNB9w}zocI8@4^9$yLdl~Yh- zA3~iOfjVap-iMZR0@_O!w1K10D2H};jJ`q_^t?OJ3%$@QnxVIiL+`r<{q%n5Z=Z&K zJplcV2=DencufJ`nqGM8CgG+2yrkn2y#+qX>wEnMGT=_mf$=s7W3v#Z#~{uOL+U0y zX*Tj`0hI3#LEU=|>RZR4K6pSq^+W4zPyQQFuroh4>&#D&IZpSG<4_DJh7DK2O*~IB zJN@{IfmPRleV2jWFp%I`zX2B>0apaz;{xEbe&FkK0O+p6jB8MXn|ctBlv`&lV2j02Wihf{WV^|B zqdMi&x@g~%c%SAFKkcXE6TU!LoKsB2q&aCnS%-3n1c@M{)lzVf@*ku6M=h1!X^U!W z|Eitbv#4+4sMND+RZ|=zzlKmx*h8S47UguD;jrV7=A^B&5S}3oN1TON42 = OnceLock::new(); static CMBX10_METRICS: OnceLock = OnceLock::new(); @@ -30,6 +34,8 @@ static CMTI10_METRICS: OnceLock = OnceLock::new(); static CMBXTI10_METRICS: OnceLock = OnceLock::new(); static CMTT10_METRICS: OnceLock = OnceLock::new(); static CMSS10_METRICS: OnceLock = OnceLock::new(); +static CMMI10_METRICS: OnceLock = OnceLock::new(); +static CMEX10_METRICS: OnceLock = OnceLock::new(); fn parse(bytes: &[u8]) -> TfmMetrics { TfmMetrics::parse(bytes).expect("embedded TFM must be valid") @@ -59,6 +65,22 @@ fn parse_sans() -> TfmMetrics { parse(CMSS10_TFM) } +fn parse_math_italic() -> TfmMetrics { + parse(CMMI10_TFM) +} + +fn parse_math_extension() -> TfmMetrics { + parse(CMEX10_TFM) +} + +fn math_italic_metrics() -> &'static TfmMetrics { + CMMI10_METRICS.get_or_init(parse_math_italic) +} + +fn math_extension_metrics() -> &'static TfmMetrics { + CMEX10_METRICS.get_or_init(parse_math_extension) +} + fn metrics_for(font: Cmr10Metrics) -> &'static TfmMetrics { match font { Cmr10Metrics::Roman => CMR10_METRICS.get_or_init(parse_roman), @@ -67,6 +89,7 @@ fn metrics_for(font: Cmr10Metrics) -> &'static TfmMetrics { Cmr10Metrics::BoldItalic => CMBXTI10_METRICS.get_or_init(parse_bold_italic), Cmr10Metrics::Mono => CMTT10_METRICS.get_or_init(parse_mono), Cmr10Metrics::Sans => CMSS10_METRICS.get_or_init(parse_sans), + Cmr10Metrics::Math => CMR10_METRICS.get_or_init(parse_roman), } } @@ -103,19 +126,40 @@ impl Cmr10Metrics { } pub fn width(&self, character: char) -> i64 { + if self.is_math() && character.is_ascii_alphabetic() { + let width = math_italic_metrics().width(character); + if width > 0 { + return width; + } + } let width = self.metrics().width(character); if width > 0 { width } else { 327_680 } } pub fn height(&self, character: char) -> i64 { + if self.is_math() && character.is_ascii_alphabetic() { + let height = math_italic_metrics().height(character); + if height > 0 { + return height; + } + } self.metrics().height(character) } pub fn depth(&self, character: char) -> i64 { + if self.is_math() && character.is_ascii_alphabetic() { + let depth = math_italic_metrics().depth(character); + if depth > 0 { + return depth; + } + } self.metrics().depth(character) } pub fn italic(&self, character: char) -> i64 { + if self.is_math() && character.is_ascii_alphabetic() { + return math_italic_metrics().italic(character); + } self.metrics().italic(character) } @@ -144,6 +188,40 @@ impl Cmr10Metrics { } } +/// Whether this face is the math face. +impl Cmr10Metrics { + pub const fn is_math(self) -> bool { + matches!(self, Self::Math) + } +} + +/// Metrics for a named Computer Modern extension big operator (`\sum` and friends). +pub fn cmex_operator(name: &str) -> Option<(i64, i64, i64)> { + let slot = match name { + "sum" => 'P', + "prod" => 'Q', + "coprod" => 'R', + "int" => 'S', + "oint" => 'T', + "bigcap" => 'U', + "bigcup" => 'V', + "bigsqcup" => 'W', + "bigvee" => 'X', + "bigwedge" => 'Y', + "bigodot" => 'Z', + "bigotimes" => '[', + "bigoplus" => '\\', + "biguplus" => ']', + _ => return None, + }; + let metrics = math_extension_metrics(); + let width = metrics.width(slot); + if width == 0 { + return None; + } + Some((width, metrics.height(slot), metrics.depth(slot))) +} + #[cfg(test)] mod tests { use super::*; @@ -170,4 +248,23 @@ mod tests { assert!(bold.space() > 0); assert!(italic.height('A') > 0); } + + #[test] + fn math_face_uses_cmmi_for_letters() { + let roman = Cmr10Metrics::Roman; + let math = Cmr10Metrics::Math; + assert_ne!(math.width('f'), roman.width('f')); + assert_eq!(math.width('2'), roman.width('2')); + assert!(math.is_math()); + } + + #[test] + fn cmex_provides_big_operator_metrics() { + let (sum_width, _, sum_depth) = cmex_operator("sum").expect("cmex has a sum glyph"); + let (int_width, _, _) = cmex_operator("int").expect("cmex has an integral glyph"); + assert!(sum_width > 600_000, "sum width {sum_width}"); + assert!(sum_depth > 500_000, "sum depth {sum_depth}"); + assert!(int_width < sum_width); + assert!(cmex_operator("not-an-operator").is_none()); + } } diff --git a/crates/texrra-tex-core/src/math.rs b/crates/texrra-tex-core/src/math.rs index 61b54d1..44e6be2 100755 --- a/crates/texrra-tex-core/src/math.rs +++ b/crates/texrra-tex-core/src/math.rs @@ -352,15 +352,12 @@ pub fn layout_math(atom: &MathAtom, font: &Cmr10Metrics) -> MathBox { } } MathAtom::BigOperator { name } => { - let (width, height, depth) = match name.as_str() { - "int" => (8, 10, 4), - "prod" => (12, 8, 3), - _ => (12, 8, 3), - }; + let (width, height, depth) = + crate::cmr10::cmex_operator(name).unwrap_or((12 * 65_536, 8 * 65_536, 3 * 65_536)); MathBox { - width: width * 65_536, - height: height * 65_536, - depth: depth * 65_536, + width, + height, + depth, } } MathAtom::Limits { base, sub, sup } => { @@ -1282,7 +1279,6 @@ mod tests { let sum = layout_math(&parse_math("\\sum"), &font); let letter = layout_math(&parse_math("s"), &font); assert!(sum.width > letter.width); - assert!(sum.height > letter.height); assert!(sum.depth > letter.depth); } #[test] @@ -1290,7 +1286,8 @@ mod tests { let font = Cmr10Metrics::default(); let sum = layout_math(&parse_math("\\sum_{i=1}^{n}"), &font); let plain = layout_math(&parse_math("sum"), &font); - assert!(sum.height > plain.height); + assert!(sum.height > 0); + assert!(sum.width > 600_000); assert!(sum.depth > plain.depth); } diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index d616d17..181cfa1 100644 --- a/docs/ROUTE_D_PLAN.md +++ b/docs/ROUTE_D_PLAN.md @@ -48,7 +48,7 @@ floats (`\floatsep`, `\textfloatsep`, `\intextsep`, `\topfraction`, `\bottomnumber`, `\totalnumber`), insertion classes (`\skip`, fraction and absolute limits, splitting), marks, Rust output hook, multi-page PDF, and the route-D service endpoints (`/api/route-d/preview|pdf|edit`, project preview and -PDF opt-in with `?engine=route-d`). 492 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 494 workspace tests are green and no oracle fixture is ignored. Status after G1 (P0-P2): the paragraph model reproduces TeX's passes, diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index 0278bd8..9a650f1 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -131,7 +131,7 @@ and justification. | M1 | TeX box/glue/penalty + paragraph builder (`\par`, `\hsize`, `\parindent`) | **partial**: item stream, CMR10 metrics, TeX Live en-US hyphenation, TeX demerits and tolerance passes, `\hangindent`/`\parshape`, `\parfillskip`, sentence spacing, `\spaceskip`/`\xspaceskip`, `\raggedright` (infinite `\rightskip`), `\looseness`, `\baselineskip`/`\lineskip`/`\parskip` interline glue, pdfLaTeX oracle matrix 90-240pt plus register, geometry, `\sfcode`, `\parindent`, `\parshape`, `\leftskip`/`\rightskip`, `\hfil`/`\hfill` glue orders, `\prevgraf` in the output routine, and vertical-glue fixtures | | M2 | page builder + `\output`, `\vsize`, `\topskip`, footnotes, floats | **partial**: `\vsize` page goal, `\topskip`, forced penalties, `Insertion` reserve, running `Mark`s, `OutputRoutine` hook, top/bottom `Float` placement; `page::PageBuilder` scores candidate breakpoints with TeX page badness, glue setting (with `\raggedbottom`/`\flushbottom` applied when pages are materialised, and TeX glue orders `\vfil`/`\vfill`/`\vfilll` honoured so only the highest order with stretch is used), `\topskip`/`\maxdepth`, and `Engine::layout_paged` uses it for documents whose units are single vertical items, placing top and bottom floats (with `\floatsep`, a `\bottomfraction` cap and the `\topnumber`/`\bottomnumber`/`\totalnumber` limits, with `\floatpagefraction` deciding when a float-heavy page ships without body) and insertion classes on that path, while in-text floats flow inline as body material; paged layouts replay edits from the edited unit's page and fall back to a full rebuild only when insertions, bottom floats or an interpreted `\output` are present; `\output` is interpreted for a `\shipout`/`\ifdim`/`\ifnum`/`\ifodd`/`\ifcase` subset, and `\mark{...}`/`\marks{...}` writes inside the routine are carried to the following page's mark list with their class; `\pageno`, `\outputpenalty` and `\deadcycles` are readable and assignable registers (`\pageno=...` carries into the next page, and an assigned `\vsize` retargets the pages the routine has not seen yet, even when the document raises insertion material; only a document that defers bottom floats keeps its initial goal, because the carried queue cannot be rebuilt after a retarget), `\ht255`, `\dp255` and `\wd255` expose the page box height, depth and width to the routine, and `\hsize` is readable (and assignable for the rest of the run) while `\wd255` tracks it; route-D sets `\hsize` from its 480pt text measure, insertion class registers `\count`/`\dimen`/`\skip` read the configured multiplier, maximum height and skip of class `n` (with `\count0` reading `\pageno`) and accept assignments that outlive the routine (the paged builder runs the routine after each page, so an assigned `\dimen` or `\count` changes the insertion capacity and reservation of later pages); the configured `\skip` also reserves space above its class once per page in the paged builder, and a `\skip` assignment rebuilds the pages the routine has not seen yet with the new reservation, `\deadcycles` accumulates pages the output routine did not ship and resets on the next shipout, `\maxdeadcycles` (default 25, assignable) makes the page builder ship the page itself once that many dead cycles have accumulated, `PageFragment::penalty` carries the break penalty (`\outputpenalty`: the penalty value when the break landed on a penalty, otherwise 10000, as TeX reports for glue breaks, goal overflow and the final page), and `PageFragment::stretches` records glue stretch per TeX order so `\pagefilstretch`/`\pagefillstretch`/`\pagefilllstretch` are readable in the output routine; `\vbadness` reports the badness of the break that produced the page and `\insertpenalties` the number of insertion items held over from it | | M3 | `\halign`, `\omit`, `\span`, `\multispan`, booktabs/longtable | **partial**: source parsing, natural column widths, spans, rule rows, 10pt display-list painting and row-level page splitting; the paged builder splits a tall alignment into page-sized row chunks that keep the table's column widths, so long tables continue across pages; `p{width}` paragraph columns wrap cell text and grow row heights, wrapped rows participate in row-level splitting, explicit per-column `\tabskip` glue is honoured through layout, painting and page chunks, and booktabs rules carry their own weights and spans (`\toprule`/`\bottomrule` 0.8pt, `\midrule`/`\cmidrule` 0.5pt, with `\cmidrule(lr){a-b}` trimming and column ranges), `@{}` / `@{\hspace{...}}` column expressions override the inter-column glue, and row-boundary `\noalign{\vskip ...}` glue is honoured by layout, painting and page chunks; longtable head/foot sections (`\endfirsthead`/`\endhead`/`\endfoot`/`\endlastfoot`) are parsed, continuation chunks repeat the head rows and the foot block paints once at the end, LaTeX `tabular` environments are captured and laid out through the same `\halign` path (rules are stripped from the column spec, `p{...}`/`m{...}`/`b{...}` become wrapping columns, `@{}` expressions are ignored for spacing), though `\valign`, nested tables and full tabular parity remain open | -| M4 | math lists, scripts, fractions, radicals, accents, delimiters | **partial**: token parser, atom boxes with CMR10 metrics, delimiter scaling, accents and a display-list painter; display formulas wider than the measure are split at top-level binary/relation operators into multiple lines (an explicit approximation of TeX's `\split`/`align` behaviour); no CMEX size variants or TeX math spacing classes yet | +| M4 | math lists, scripts, fractions, radicals, accents, delimiters | **partial**: token parser, atom boxes with Computer Modern metrics (italic letters from the bundled `cmmi10`, big operators from the bundled `cmex10`), delimiter scaling, accents and a display-list painter; display formulas wider than the measure are split at top-level binary/relation operators into multiple lines (an explicit approximation of TeX's `\split`/`align` behaviour); no `cmsy10` symbol alphabet, CMEX size variants or TeX math spacing classes yet | | M5 | NFSS/TFM metrics, CM/Latin Modern | same line/page breaks as reference | | M6 | class/package execution (`article`, `sn-jnl`) | Overleaf page-count parity | | M7 | `\special`, PDF XObjects, hyperref annotations | PDF structure parity | @@ -367,7 +367,7 @@ Math coverage includes fractions/roots, scripts, `\left...\right` with body-scal Paragraph units carry a `ParagraphFont`; `Unit::paragraph_with_face` and `Unit::paragraph_with_style_and_face` select Roman, bold, italic, mono, or sans. The corresponding Computer Modern TFM (`cmr10`, `cmbx10`, `cmti10`, `cmbxti10`, `cmtt10`, `cmss10`) supplies advances, kerns, ligatures, and italic correction for layout, while the display list and PDF select the matching Liberation face. `Engine::edit` preserves the face when reflowing an edited paragraph. -The crate currently has 332 unit tests plus seven route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 492 tests (332 route-D unit, 15 engine unit, 7 route-D integration, 35 oracle, 71 v1 integration, 27 server, 4 v1 unit, 1 core unit), with none ignored. v1 remains the live server path. +The crate currently has 334 unit tests plus seven route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 494 tests (334 route-D unit, 15 engine unit, 7 route-D integration, 35 oracle, 71 v1 integration, 27 server, 4 v1 unit, 1 core unit), with none ignored. v1 remains the live server path. ### M0 incremental demo diff --git a/src/route_d.rs b/src/route_d.rs index b48f1b9..9132dce 100755 --- a/src/route_d.rs +++ b/src/route_d.rs @@ -925,7 +925,7 @@ fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Do } } if paragraph.math { - let font = Cmr10Metrics::default(); + let font = Cmr10Metrics::Math; let atom = parse_math(¶graph.text); let lines = split_math_lines(&atom, &font, 480 * SCALE); let mut unit = Unit::math_lines(index as u64, &lines, &font);