diff --git a/crates/texrra-tex-core/src/opentype.rs b/crates/texrra-tex-core/src/opentype.rs index 93953f9..6109fce 100644 --- a/crates/texrra-tex-core/src/opentype.rs +++ b/crates/texrra-tex-core/src/opentype.rs @@ -38,6 +38,8 @@ pub(crate) struct Request { letterspace: Option, #[serde(default, skip_serializing_if = "Option::is_none")] extend: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + slant: Option, } fn read_decimal_prefix(value: &str) -> f64 { @@ -50,6 +52,14 @@ fn read_decimal_prefix(value: &str) -> f64 { value[..end].parse().unwrap_or(0.) } +fn read_device_factor(value: &str, option: &str, identity: f32) -> Result, String> { + let value = read_decimal_prefix(value) as f32; + if !value.is_finite() || i32::try_from(points_to_sp(value)).is_err() { + return Err(format!("OpenType {option} exceeds the device fixed-point range")); + } + Ok((value != identity).then(|| value.to_bits())) +} + impl Request { pub(crate) fn parse(spec: &str) -> Result, String> { let Some(bracketed) = spec.strip_prefix('[') else { @@ -95,6 +105,7 @@ impl Request { mapping: None, letterspace: None, extend: None, + slant: None, }; for feature in features .split([';', ',']) @@ -121,11 +132,9 @@ impl Request { } request.letterspace = (value != 0.).then(|| value.to_bits()); } else if let Some(value) = feature.strip_prefix("extend=") { - let value = read_decimal_prefix(value) as f32; - if !value.is_finite() || i32::try_from(points_to_sp(value)).is_err() { - return Err("OpenType extend exceeds the device fixed-point range".into()); - } - request.extend = (value != 1.).then(|| value.to_bits()); + request.extend = read_device_factor(value, "extend", 1.)?; + } else if let Some(value) = feature.strip_prefix("slant=") { + request.slant = read_device_factor(value, "slant", 0.)?; } else { feature .parse::() @@ -285,7 +294,10 @@ impl OpenTypeFont { ) }; let slant = (-f64::from(face.italic_angle()).to_radians().tan() * 65536. + 0.5) as i64; - let slant = (slant as f64 * f64::from(request.horizontal_scale()) + 0.5) as i32; + let slant = point_position_to_sp( + slant as f64 / 65536. * f64::from(request.horizontal_scale()) + + f64::from(request.slant.map_or(0., f32::from_bits)), + ) as i32; let mut params = vec![ slant, 0, @@ -350,10 +362,14 @@ impl OpenTypeFont { self.request.letter_space(self.size) as i64 } - pub(crate) fn paint_horizontal_scale(&self) -> f64 { - // XDV records the factor in 16.16 and the PDF device emits five decimals. - let fixed = points_to_sp(self.request.horizontal_scale()); - (fixed as f64 * 100_000. / 65536.).round() / 100_000. + pub(crate) fn device_transform(&self) -> [f64; 2] { + let fixed = |bits| points_to_sp(f32::from_bits(bits)) as f64 / 65536.; + [self.request.extend.map_or(1., fixed), self.request.slant.map_or(0., fixed)] + } + + pub(crate) fn paint_transform(&self) -> [f64; 2] { + // XDV records the factors in 16.16 and the PDF device emits five decimals. + self.device_transform().map(|factor| (factor * 100_000.).round() / 100_000.) } pub(crate) fn italic_correction(&self, glyph: u16) -> Result { @@ -448,9 +464,11 @@ impl OpenTypeFont { let letter_space = self.letter_space(); let mut tracking = 0; let horizontal_scale = self.request.horizontal_scale(); + let slant = self.request.slant.map_or(0., f32::from_bits); let units = face.tables().head.units_per_em; let points = |value: i64| units_to_points(value as f32, self.size, units); - let horizontal = |value| points(value) * horizontal_scale; + // HarfBuzz's vertical offsets are positive upwards. + let horizontal = |x: i64, y: i64| points(x) * horizontal_scale - points(-y) * slant; for paragraph in &bidi.paragraphs { let (levels, runs) = bidi.visual_runs(paragraph, paragraph.range.clone()); for range in runs { @@ -484,24 +502,26 @@ impl OpenTypeFont { let cluster = range.start + info.cluster as usize; let end = starts[starts.partition_point(|at| *at <= cluster)]; let next_x = x + i64::from(pos.x_advance); + let next_y = y + i64::from(pos.y_advance); if tracking != 0 && points_to_sp(points(i64::from(pos.x_advance))) == 0 { tracking -= letter_space; } - let x_position = |value| point_position_to_sp(x_origin + f64::from(horizontal(value))); + let x_position = |x, y| point_position_to_sp(x_origin + f64::from(horizontal(x, y))); + let glyph_y = y + i64::from(pos.y_offset); glyphs.push(OpenTypeGlyph { id: info.glyph_id as u16, - x: x_position(x + i64::from(pos.x_offset)) + tracking, - y: point_position_to_sp(y_origin + f64::from(points(-y - i64::from(pos.y_offset)))), - advance: x_position(next_x) - x_position(x), + x: x_position(x + i64::from(pos.x_offset), glyph_y) + tracking, + y: point_position_to_sp(y_origin + f64::from(points(-glyph_y))), + advance: x_position(next_x, next_y) - x_position(x, y), cluster: cluster..end, cluster_start: cluster != previous, }); tracking += letter_space; x = next_x; - y += i64::from(pos.y_advance); + y = next_y; previous = cluster; } - x_origin += f64::from(horizontal(x)); + x_origin += f64::from(horizontal(x, y)); y_origin += f64::from(points(-y)); } } diff --git a/crates/texrra-tex-core/src/pdf_opentype.rs b/crates/texrra-tex-core/src/pdf_opentype.rs index 19bed74..37d01a4 100644 --- a/crates/texrra-tex-core/src/pdf_opentype.rs +++ b/crates/texrra-tex-core/src/pdf_opentype.rs @@ -35,6 +35,28 @@ impl TextRun { output.push_str(">] TJ ET\n"); } } + + fn move_line( + &mut self, + output: &mut PageContent, + [x, y]: [i64; 2], + [extend, slant]: [f64; 2], + bp_per_unit: f64, + ) { + let dy = y - self.start[1]; + let dx = (((x - self.start[0]) as f64 - dy as f64 * slant) / extend) as i64; + let (tx, x_error) = rounded_coordinate(dx, bp_per_unit); + let (ty, y_error) = rounded_coordinate(dy, bp_per_unit); + output.push_str(&format!(">] TJ {tx:.3} {ty:.3} Td [<")); + self.start = [x - x_error, y - y_error]; + self.offset = 0; + } +} + +fn rounded_coordinate(value: i64, bp_per_unit: f64) -> (f64, i64) { + let exact = value as f64 * bp_per_unit; + let rounded = (exact * 1000.).round() / 1000.; + (rounded, ((exact - rounded) / bp_per_unit).round() as i64) } #[derive(Default)] @@ -287,35 +309,45 @@ impl EmbeddedFont { bp_per_unit: f64, ) { let glyph = &self.glyphs[&glyph]; - let horizontal_scale = font.paint_horizontal_scale(); - let horizontal_em = size as f64 * horizontal_scale; + let [horizontal_scale, slant] = font.paint_transform(); + let device = font.device_transform(); + let relative = device[1] != 0. && device[0] != 0.; + let horizontal_em = size as f64 * if relative { device[0] } else { horizontal_scale }; let override_text = glyph .cluster_text .as_deref() .is_some_and(|mapped| text != mapped); - if run.as_ref().is_some_and(|state| { - override_text - || state.font != font.id - || state.size != size - || (horizontal_em == 0. && x != state.start[0] + state.offset) - || (y - state.start[1]).abs() as f64 * bp_per_unit > 0.001 - || (x - state.start[0] - state.offset).abs() > size * 3 - }) { - TextRun::finish(run, output); + if let Some(state) = run.as_mut() { + let delh = (x - state.start[0] - state.offset).abs(); + let delv = (y - state.start[1]).abs(); + if override_text || state.font != font.id || state.size != size { + TextRun::finish(run, output); + } else if relative { + if delv > (0.001 / bp_per_unit).round() as i64 || delh > (3. * horizontal_em) as i64 { + // Td moves in text space. Precompensate for the shear and + // retain the rounded displacement error in device units. + state.move_line(output, [x, y], device, bp_per_unit); + } + } else if (horizontal_em == 0. && delh != 0) + || delv as f64 * bp_per_unit > 0.001 + || delh > size * 3 + { + TextRun::finish(run, output); + } } if override_text { begin_actual_text(output, text, false); } let state = run.get_or_insert_with(|| { - let coordinates = [x, y].map(|value| { - let exact = value as f64 * bp_per_unit; - let rounded = (exact * 1000.).round() / 1000.; - let error = ((exact - rounded) / bp_per_unit).round() as i64; - (rounded, value - error) - }); + let coordinates = [x, y].map(|value| rounded_coordinate(value, bp_per_unit)); + let start = if relative { + [x, y] + } else { + [x - coordinates[0].1, y - coordinates[1].1] + }; let size_bp = size as f64 * bp_per_unit; output.push_str(&format!( - "BT /U{} {size_bp:.4} Tf {horizontal_scale} 0 0 1 {:.3} {:.3} Tm [<", + "BT /U{} {size_bp:.4} Tf {horizontal_scale} 0 {slant} 1 {:.3} {:.3} Tm [<", font.id.index(), coordinates[0].0, coordinates[1].0 @@ -323,8 +355,8 @@ impl EmbeddedFont { TextRun { font: font.id, size, - start: coordinates.map(|(_, origin)| origin), - offset: x - coordinates[0].1, + start, + offset: x - start[0], } }); // Move in PDF's thousandth-em text units, tracking widths in TeX sp. diff --git a/crates/texrra-tex-core/src/render.rs b/crates/texrra-tex-core/src/render.rs index 73b411f..f955207 100755 --- a/crates/texrra-tex-core/src/render.rs +++ b/crates/texrra-tex-core/src/render.rs @@ -565,12 +565,25 @@ impl DisplayList { let x = *x as f64 / 65536.; let y = *y as f64 / 65536.; let scale = *size as f64 / (65536. * f64::from(face.units_per_em())); - let horizontal = scale * font.paint_horizontal_scale(); if !path.is_empty() { - out.push_str(&format!( - "\n", - escape(&font.name), escape(text), fill[0], fill[1], fill[2] - )); + use std::fmt::Write as _; + let [extend, slant] = font.paint_transform(); + let horizontal = scale * extend; + write!( + out, + "", + fill[0], fill[1], fill[2], + ).unwrap(); } } DisplayItem::MathGlyph { diff --git a/crates/texrra-tex-core/src/source_map.rs b/crates/texrra-tex-core/src/source_map.rs index 728c45b..b3eb992 100644 --- a/crates/texrra-tex-core/src/source_map.rs +++ b/crates/texrra-tex-core/src/source_map.rs @@ -409,9 +409,14 @@ impl SourceMap { let scale = |value: i64| value * size / font.size; let ascent = scale(font.ascent); let descent = scale(font.descent); + let [_, slant] = font.paint_transform(); + let top_offset = slant * ascent as f64; + let bottom_offset = -slant * descent as f64; + let left = top_offset.min(bottom_offset).floor() as i64; + let right = top_offset.max(bottom_offset).ceil() as i64; Some((PaintKind::OpenTypeGlyph { font: font.id.index(), glyph: *glyph }, Bounds { - x: x + advance.min(&0), y: y - ascent, - width: advance.abs(), height: ascent + descent, + x: x + advance.min(&0) + left, y: y - ascent, + width: advance.abs() + right - left, height: ascent + descent, })) } DisplayItem::Rule { diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 7c1cae8..4ea62d2 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -2175,6 +2175,34 @@ PDF,恢复实际 PFB 并反转斜切时复用 1277 步,只替换第二页。 全量编译一致。incremental-receipt.json 的 SHA-256 为 bbc0991b0316e6d76aa58649ec873525f5544ab530d93fe491fc6e16bd00a27d。 +### XeTeX OpenType 倾斜与 PDF 基线位移 + +`slant` 接入 XeTeX 字体选择、实际字形位置和字体斜率。造型阶段 +按实际纵向偏移计算水平位移,并与 `extend` 共用字体变换。PDF 和 +SVG 以同一组设备系数绘制,来源命中使用倾斜后布局区域的包络。 +PDF 同一文字运行换基线时,在文字坐标系计算相对位移,并保留 +位移舍入误差。 +[XeTeX 字形位置](https://github.com/TeX-Live/texlive-source/blob/279984fab6eaed8d17e02882f2668ab5caac0f27/texk/web2c/xetexdir/XeTeXLayoutInterface.cpp#L801-L832) +[xdvipdfmx 相对文字基线](https://github.com/TeX-Live/texlive-source/blob/279984fab6eaed8d17e02882f2668ab5caac0f27/texk/dvipdfm-x/pdfdev.c#L685-L751) + +XeTeX 原语与实际 `fontspec` 的 `FakeSlant` 对照共 4 页、36 个 +字形,原始编号、字号及位置一致,144 DPI 灰度图逐像素相同。 +字体宽度、斜率及版面文本一致。原生与参考读入的 +`fontspec-xetex.sty` 字节指纹相同。阿拉伯组合标记页的最初 +版本有 57 个差异像素,按参考改为相对定位后,17 次 PDF 基线 +位移与参考相同,差异像素为零。保留初版 PDF 和比较记录。 + +正、负、零倾斜三次跨文件编辑各复用 66 步、重放两次调用, +只更新第二页。PDF、SVG 和来源映射与独立全量一致,实际 SVG +矩阵、字形区间及点击命中已核对。12 项定向回归通过。原样 ACL +的 PDF、aux、out、bbl 与上一版逐字节一致。 +回执 `target/p3-xetex-font-slant/receipt.json` 的 SHA-256 为 +`8b49e6e98706c2247d1769fdad811bda2628d7d826a572f8041334b6563ac3da`。 + +下一入口为 `embolden`。`target/p3-xetex-font-embolden` +保存四页原语与一页真实 `fontspec` 的 `FakeBold` 参考,以及 +当前原生拒绝该字体选项的实际诊断。 + ### XeTeX OpenType 水平缩放与预览来源 `extend` 在原生造型阶段缩放水平位置和词宽,并进入词间胶、断行、 diff --git a/docs/PUBLISHER_TEMPLATE_MATRIX.md b/docs/PUBLISHER_TEMPLATE_MATRIX.md index 1b06769..690078e 100644 --- a/docs/PUBLISHER_TEMPLATE_MATRIX.md +++ b/docs/PUBLISHER_TEMPLATE_MATRIX.md @@ -758,6 +758,16 @@ XDV 链接注释接入后,沿原样 ACL 的第二轮辅助文件和 BibTeX `target/p3-xdv-annotation/receipt.json`。 [链接注释阶段记录](P2_M1_PROGRESS.md#xdv-链接注释与实际矩形) +#### XeTeX OpenType 倾斜复编 + +原样 ACL 在同一 schema71、字体与收敛的生成状态下复编,PDF、 +aux、out 和 bbl 与上一版逐字节相同。另用未修改的 `fontspec` +执行 `FakeSlant`,核对原始字形坐标和实际光栅。ACL 整页版面差异 +仍留在原验收门槛。 +回执 `target/p3-xetex-font-slant/receipt.json` 的 SHA-256 为 +`8b49e6e98706c2247d1769fdad811bda2628d7d826a572f8041334b6563ac3da`。 +[倾斜阶段记录](P2_M1_PROGRESS.md#xetex-opentype-倾斜与-pdf-基线位移) + #### XeTeX OpenType 水平缩放复编 原样 ACL 继续使用同一 schema71、真实字体与已收敛的生成文件。