Skip to content

The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.

Python

Find a font by any family name it lists, and warn of a family no font has

Sina Atalay1a508b0a58f1
diff --git a/docs/content/changelog.md b/docs/content/changelog.md
index e817e875..0cc3962a 100644
--- a/docs/content/changelog.md
+++ b/docs/content/changelog.md
@@ -51,6 +51,7 @@ The notable changes to ManimGX, release by release. The format follows
- Make the folder a video or a storyboard is written in when it is missing (`render -o new/out.mp4`, `inspect -o new/sheet.png` and `Scene.render`), instead of failing with "No such file or directory" ([#34](https://github.com/academa-labs/manimgx/issues/34)).
- Raise a ValueError, naming where it is, for a nested, unclosed or stray bracket in a `say` script, which was spoken and captioned ([#39](https://github.com/academa-labs/manimgx/issues/39)).
- Time and caption speech in the pieces Unicode lets a line break between, so a `say` span in Chinese, Japanese or Thai, written without spaces, is timed by its own characters or words, where the whole sentence was one word ([#40](https://github.com/academa-labs/manimgx/issues/40)). Captions are the text as it is written, at most 42 columns wide (a Chinese or Japanese character takes two); a line never starts with a closing mark such as `,` or `」`, and ends where a sentence does, a quoted one too. A speech's words are found in its text by themselves, so a trimmed speech, or a voice that cuts its words its own way, no longer fails or mistimes a span; and an empty span after the last word starts where that word ends.
+- Find a font by any family name it lists, as font menus show it, not only by the one Typst reads: `Text(font="GenSenRounded2 TW")` found nothing, as the font's family is "GenSenRounded2 TW R" to Typst ([#33](https://github.com/academa-labs/manimgx/issues/33)). A family no font has, a typo too, is warned about, where its text quietly fell back to another font.
- Draw with Direct3D 12 on Windows, as the docs said, not with a GPU's Vulkan driver, which the engine took first: Intel's crashed rendering ([#50](https://github.com/academa-labs/manimgx/issues/50)). Browsers draw WebGPU with Direct3D 12 on Windows too, and CI's Windows runners test it.
- Show an image drawn smaller than its pixels as their mean: each pixel of the video shows the mean of the picture's pixels it covers, however the image is squashed and whatever its `resampling_algorithm`, where it showed the picture at one point, so thin lines broke up and small text was unreadable ([#36](https://github.com/academa-labs/manimgx/issues/36)). An image at its size or larger is drawn as before.
- Keep resources needed by queued video frames until their transparency retries finish, fixing render failures during cache cleanup ([#16](https://github.com/academa-labs/manimgx/issues/16)).
diff --git a/docs/content/user-guide/text-and-math.md b/docs/content/user-guide/text-and-math.md
index 0de08e55..b4098263 100644
--- a/docs/content/user-guide/text-and-math.md
+++ b/docs/content/user-guide/text-and-math.md
@@ -22,7 +22,8 @@ class Words(m.Scene):
- `font_size` sets the size: 48 unless you give another.
- `font` sets the font: `"sans-serif"`, `"monospace"`, or the name of a font on your
- computer. The default is New Computer Modern, the font of LaTeX.
+ computer, any family name it lists, as font menus show them. The default is New Computer
+ Modern, the font of LaTeX. If no font has the name, ManimGX warns and uses the default.
- `t2c` colors parts of the text: `m.Text("red and blue", t2c={"red": m.RED, "blue": m.BLUE})`.
Text is a mobject like any other: you can move it, scale it, color it and animate it.
diff --git a/rust/engine/src/python.rs b/rust/engine/src/python.rs
index f3e8ac96..76f04988 100644
--- a/rust/engine/src/python.rs
+++ b/rust/engine/src/python.rs
@@ -382,7 +382,7 @@ mod typesetting {
/// A typeset document: its rows (float64), its shapes' cubic points, its labelled groups, and
/// whether it needed the system's fonts.
- type Layout = (Py<PyBytes>, Vec<Py<PyBytes>>, Vec<(String, Vec<usize>)>, bool);
+ type Layout = (Py<PyBytes>, Vec<Py<PyBytes>>, Vec<(String, Vec<usize>)>, bool, Vec<String>);
/// Typeset `source` with the fonts in `font_paths` and Typst's own (a system font only by its
/// family's name), and the packages under `packages` besides mitex's (the engine's own): its
@@ -391,10 +391,10 @@ mod typesetting {
#[pyfunction]
#[pyo3(signature = (source, font_paths, packages=None, *, revision=0))]
pub(super) fn typeset(py: Python<'_>, source: String, font_paths: Vec<String>, packages: Option<String>, revision: u64) -> PyResult<Layout> {
- let (rows, shapes, labels, system) = py.detach(|| core::typeset(source, &font_paths, packages.as_deref(), revision)).map_err(TypstError::new_err)?;
+ let (rows, shapes, labels, system, missing) = py.detach(|| core::typeset(source, &font_paths, packages.as_deref(), revision)).map_err(TypstError::new_err)?;
let rows = PyBytes::new(py, bytemuck::cast_slice(&rows)).unbind();
let shapes = shapes.iter().map(|s| PyBytes::new(py, bytemuck::cast_slice(s)).unbind()).collect();
- Ok((rows, shapes, labels, system))
+ Ok((rows, shapes, labels, system, missing))
}
/// The system's fonts' fingerprint (every file under their directories: path, size, time), once
diff --git a/rust/engine/src/typeset.rs b/rust/engine/src/typeset.rs
index e3b65834..cb082782 100644
--- a/rust/engine/src/typeset.rs
+++ b/rust/engine/src/typeset.rs
@@ -7,7 +7,7 @@
//! with y up (Typst's page is y down; the flip is folded in here). Shapes come in page points,
//! y up. Python scales points to scene units.
-use std::collections::HashMap;
+use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, OnceLock};
@@ -75,11 +75,11 @@ fn setup(font_paths: &[String], packages: Option<&str>, named: &[String], revisi
}
let mut fonts = FontStore::new();
let dirs: Vec<PathBuf> = font_paths.iter().map(PathBuf::from).collect();
- fonts.extend(cached_scan(&dirs, || dirs.iter().flat_map(|dir| scan(dir)).collect()));
+ fonts.extend(cached_scan(&dirs, || with_family_names(dirs.iter().flat_map(|dir| scan(dir)).collect())));
fonts.extend(embedded());
if !named.is_empty() {
fonts.extend(
- cached_scan(&font_directories(), || system().collect())
+ cached_scan(&font_directories(), || with_family_names(system().collect()))
.into_iter()
.filter(|(_, info)| named.contains(&info.family.to_lowercase())),
);
@@ -116,7 +116,37 @@ impl FontSource for Mapped {
/// A scanned font as the cache keeps it: where it is, and its info's fields.
type Cached = (PathBuf, u32, String, FontVariant, FontFlags, Vec<FontAxis>, Coverage);
/// What made a cached scan, in its file's name: bump it with Typst, or when `Cached` changes.
-const SCAN: &str = "typst-0.15.1";
+const SCAN: &str = "typst-0.15.1-names";
+
+/// Faces found on disk, each also under every other family name its name table lists (its
+/// typographic family, name ID 16, and its family, ID 1, as written, in every language): a font
+/// is found by any name a font menu shows for it. A name that is a face's own family (Typst's:
+/// ID 1 without its style words), or one of Typst's own fonts', finds what it found before.
+fn with_family_names(found: Vec<(FontPath, FontInfo)>) -> Vec<(FontPath, FontInfo)> {
+ let mut own: HashSet<String> = found.iter().map(|(_, info)| info.family.to_lowercase()).collect();
+ own.extend(embedded().map(|(_, info)| info.family.to_lowercase()));
+ let mut all = Vec::with_capacity(found.len());
+ for (path, info) in found {
+ for family in family_names(&path).into_iter().filter(|name| !own.contains(&name.to_lowercase())) {
+ all.push((FontPath { path: path.path.clone(), index: path.index }, FontInfo { family, ..info.clone() }));
+ }
+ all.push((path, info));
+ }
+ all
+}
+
+/// The family names a face's name table lists (IDs 16 and 1, in every language), each once.
+fn family_names(path: &FontPath) -> Vec<String> {
+ let Ok(file) = std::fs::File::open(&path.path) else { return Vec::new() };
+ // SAFETY: a font file is not written while mapped (as fontdb and typst-kit assume)
+ let Ok(map) = (unsafe { memmap2::Mmap::map(&file) }) else { return Vec::new() };
+ let Ok(face) = ttf_parser::Face::parse(&map, path.index) else { return Vec::new() };
+ let families = [ttf_parser::name_id::FAMILY, ttf_parser::name_id::TYPOGRAPHIC_FAMILY];
+ let mut names: Vec<String> = face.names().into_iter().filter(|name| families.contains(&name.name_id)).filter_map(|name| name.to_string()).collect();
+ names.sort_by_key(|name| name.to_lowercase());
+ names.dedup_by_key(|name| name.to_lowercase());
+ names
+}
/// MANIMGX_CACHE_DIR when set, otherwise the current user's native cache or the browser
/// runtime's private filesystem. A missing native root disables disk reuse, with no shared-temp fallback.
@@ -551,12 +581,22 @@ fn message(diagnostics: &[SourceDiagnostic], doc: &Document) -> String {
.join("; ")
}
-pub type Layout = (Vec<f64>, Vec<Vec<f64>>, Vec<(String, Vec<usize>)>, bool);
+pub type Layout = (Vec<f64>, Vec<Vec<f64>>, Vec<(String, Vec<usize>)>, bool, Vec<String>);
+
+/// The font families a compilation found no font for, as its warnings name them, each once.
+fn unknown_families(warnings: &[SourceDiagnostic]) -> Vec<String> {
+ let mut families: Vec<String> =
+ warnings.iter().filter_map(|w| w.message.strip_prefix("unknown font family: ")).map(str::to_owned).collect();
+ families.sort();
+ families.dedup();
+ families
+}
/// Typeset `source` with the fonts in `font_paths` and Typst's own (a system font only by its
/// family's name), and the packages under `packages` besides mitex's (the engine's own): its
/// items (one row of `ROW` floats each, in document order), its shapes' cubic points and its
-/// labelled groups (a label and the items inside, nested ones too).
+/// labelled groups (a label and the items inside, nested ones too); whether it read a system font;
+/// and the families it names that no font has.
pub fn typeset(source: String, font_paths: &[String], packages: Option<&str>, revision: u64) -> Result<Layout, String> {
{
static COMPILES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
@@ -568,23 +608,17 @@ pub fn typeset(source: String, font_paths: &[String], packages: Option<&str>, re
let lean = setup(font_paths, packages, &[], revision);
let doc = Document { setup: &lean, main: main.clone() };
let warned = typst::compile::<PagedDocument>(&doc);
- let mut named: Vec<String> = warned
- .warnings
- .iter()
- .filter_map(|w| w.message.strip_prefix("unknown font family: "))
- .map(str::to_owned)
- .collect();
- named.sort();
- named.dedup();
+ let named = unknown_families(&warned.warnings);
let full;
let system = !named.is_empty();
- let (doc, compiled) = if system {
+ let (doc, compiled, missing) = if system {
full = setup(font_paths, packages, &named, revision);
let doc = Document { setup: &full, main };
- let compiled = typst::compile::<PagedDocument>(&doc).output;
- (doc, compiled)
+ let warned = typst::compile::<PagedDocument>(&doc);
+ let missing = unknown_families(&warned.warnings);
+ (doc, warned.output, missing)
} else {
- (doc, warned.output)
+ (doc, warned.output, named)
};
// Typst memoizes across documents; forget what the last few hundred didn't use
if COMPILES.fetch_add(1, std::sync::atomic::Ordering::Relaxed) % 256 == 255 {
@@ -601,7 +635,7 @@ pub fn typeset(source: String, font_paths: &[String], packages: Option<&str>, re
around: Vec::new(),
};
walk.frame(&page.frame, Transform::identity());
- Ok((walk.rows, walk.shapes, walk.labels, system))
+ Ok((walk.rows, walk.shapes, walk.labels, system, missing))
}
}
diff --git a/src/manimgx/_engine.pyi b/src/manimgx/_engine.pyi
index f8869129..a076fee2 100644
--- a/src/manimgx/_engine.pyi
+++ b/src/manimgx/_engine.pyi
@@ -252,11 +252,12 @@ def typeset(
packages: str | None = None,
*,
revision: int = 0,
-) -> tuple[bytes, list[bytes], list[tuple[str, list[int]]], bool]:
+) -> tuple[bytes, list[bytes], list[tuple[str, list[int]]], bool, list[str]]:
"""Typeset `source` (Typst): its items as float64 rows of 23 (kind, key, placement a b c d e f,
fill rgba, stroke rgba, stroke width, advance, node start, end, drawn start, end, node kind),
its shapes' cubic points (float64 x y z), its labelled groups (a label and the items inside
- it) and whether it needed the system's fonts. `revision` identifies the caller's font and
+ it), whether it needed the system's fonts, and the font families it names that no font
+ has. `revision` identifies the caller's font and
package dependencies; a changed revision replaces the setup remembered for those paths."""
def glyph_outlines(keys: Sequence[int]) -> list[bytes]:
diff --git a/src/manimgx/drawing/typesetting.py b/src/manimgx/drawing/typesetting.py
index ebbe2c99..49392628 100644
--- a/src/manimgx/drawing/typesetting.py
+++ b/src/manimgx/drawing/typesetting.py
@@ -6,6 +6,7 @@ import functools
import os
import pickle
import tempfile
+import warnings
from dataclasses import dataclass
from importlib.resources import files
from importlib.util import find_spec
@@ -82,7 +83,7 @@ _CACHE = (
# what made a layout, part of its key: the entry's format, and the engine's own file (a rebuilt
# engine never reads a layout an older one made)
_ENGINE = Path(_engine.__file__).stat()
-_VERSION = f"layout 4, engine {_ENGINE.st_size} {_ENGINE.st_mtime_ns}".encode()
+_VERSION = f"layout 5, engine {_ENGINE.st_size} {_ENGINE.st_mtime_ns}".encode()
_CONTENT = 1 << 52 # glyph keys by content: exact in float64, apart from the engine's
type Stored = tuple[
np.ndarray,
@@ -90,7 +91,11 @@ type Stored = tuple[
list[tuple[str, list[int]]],
int,
dict[int, tuple[bytes, bytes]],
+ list[str],
]
+_PACKAGE = str(
+ Path(__file__).parents[1]
+) # ManimGX's files: a warning names the caller's line
def typst_string(text: str) -> str:
@@ -122,7 +127,8 @@ def typeset(
The document is set in the fonts ManimGX ships (Typst's own and the Noto faces),
after those in `font_paths`; a system font is read only for a family the document
- names that none of them has. A layout is kept in the current user's cache directory
+ names that none of them has. A font is found by any family name it lists; a family
+ no font has is warned about, and its text is set in another font. A layout is kept in the current user's cache directory
(the browser's private filesystem in a page): the same document, with the same fonts
and packages, is read back, not typeset again, in any process.
@@ -147,7 +153,12 @@ def typeset(
stored = _typeset(source, fonts, packages, int.from_bytes(depends, "little"))
if path is not None:
_write(path, stored)
- rows, shapes, labels, _, glyphs = stored
+ rows, shapes, labels, _, glyphs, missing = stored
+ for family in missing:
+ warnings.warn(
+ f"no font has the family name {family!r}: its text is set in another font",
+ skip_file_prefixes=(_PACKAGE,),
+ )
records = {
key: _glyph(key, points, carets) for key, (points, carets) in glyphs.items()
}
@@ -209,7 +220,7 @@ def _typeset(
source: str, fonts: tuple[str, ...], packages: str | None, revision: int
) -> Stored:
"""Typeset with Typst; every glyph's key by content, with its outline and carets along."""
- raw, shapes, labels, system = _engine.typeset(
+ raw, shapes, labels, system, missing = _engine.typeset(
source, fonts, packages, revision=revision
)
rows = np.frombuffer(raw).reshape(-1, ROW).copy()
@@ -252,4 +263,5 @@ def _typeset(
labels,
_engine.system_fonts_fingerprint() if system else 0,
glyphs,
+ missing,
)
diff --git a/src/manimgx/mobjects/text.py b/src/manimgx/mobjects/text.py
index 6f2b534b..9df9535e 100644
--- a/src/manimgx/mobjects/text.py
+++ b/src/manimgx/mobjects/text.py
@@ -801,8 +801,9 @@ class Text(Typst):
text: The text, as written.
line_spacing: The space between lines, in ems: the baselines are
`1 + line_spacing` ems apart; -1 for 0.3.
- font: The font family, or "serif", "sans-serif" or "monospace"; "" for New
- Computer Modern.
+ font: The font family, by any family name its font lists, or "serif",
+ "sans-serif" or "monospace"; "" for New Computer Modern. A family no font
+ has is warned about, and the text is set in New Computer Modern.
slant: `NORMAL`, `ITALIC` or `OBLIQUE`.
weight: A weight by name, from `THIN` through `NORMAL` and `BOLD` to
`ULTRAHEAVY`; the font's nearest weight is used.
diff --git a/tests/conftest.py b/tests/conftest.py
index 77b9c9e8..a3ce1318 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -136,14 +136,16 @@ def two_fonts(
def typeset(
source: str, fonts: list[str], packages: str | None = None, *, revision: int = 0
- ) -> tuple[bytes, list[bytes], list[tuple[str, list[int]]], bool]:
- raw, shapes, labels, system = native(source, fonts, packages, revision=revision)
+ ) -> tuple[bytes, list[bytes], list[tuple[str, list[int]]], bool, list[str]]:
+ raw, shapes, labels, system, missing = native(
+ source, fonts, packages, revision=revision
+ )
rows = np.frombuffer(raw).reshape(-1, tc.ROW).copy()
wide, tall = next((sizes[path] for path in fonts if path in sizes), (1.0, 1.0))
places = rows[:, tc.PLACEMENT] # (sx, ky, kx, sy, tx, ty): x's, then y's, apart
places[:, ::2] *= wide
places[:, 1::2] *= tall
- return rows.tobytes(), shapes, labels, system
+ return rows.tobytes(), shapes, labels, system, missing
monkeypatch.setattr(tc, "_CACHE", tc.Path(tmp_path, "layouts"))
monkeypatch.setattr(tc._engine, "typeset", typeset)
diff --git a/tests/unit/drawing/test_typesetting.py b/tests/unit/drawing/test_typesetting.py
index 51a3b598..47bf3fae 100644
--- a/tests/unit/drawing/test_typesetting.py
+++ b/tests/unit/drawing/test_typesetting.py
@@ -14,7 +14,8 @@
- A glyph without an outline is no part, and labels lose it; a paragraph's blank lines are
empty lines.
- Text is set in the fonts ManimGX ships, the same on every machine: every script finds a face
- there (no .notdef glyph), and a system font is read only for a family a text names.
+ there (no .notdef glyph), and a system font is read only for a family a text names. A font is
+ found by any family name it lists; a family no font has is warned about.
"""
import gc
@@ -45,7 +46,7 @@ from manimgx.mobject import _PROTOTYPES
from manimgx.mobjects.text import TypstGlyph, _cut
type Document = m.Typst | m.Paragraph
-type Answer = tuple[bytes, list[bytes], list[tuple[str, list[int]]], bool]
+type Answer = tuple[bytes, list[bytes], list[tuple[str, list[int]]], bool, list[str]]
@pytest.mark.parametrize("coordinate", [None, -123, 456])
@@ -56,7 +57,7 @@ def test_optional_font_caret_coordinate_is_checked(
p for p in Path(tc.FONTS[0]).glob("*.ttf") if p.name.startswith("NotoSans[")
)
source = '#set text(font: "Noto Sans")\nA'
- rows, _, _, _ = _engine.typeset(source, [str(font.parent)])
+ rows, *_ = _engine.typeset(source, [str(font.parent)])
glyph = int(np.frombuffer(rows).reshape(-1, tc.ROW)[0, tc.KEY]) % 65536
# A complete font with one optional format-1 caret. Only its coordinate is
# truncated; the font still loads and shapes normally through the real engine.
@@ -72,7 +73,7 @@ def test_optional_font_caret_coordinate_is_checked(
struct.pack_into(">II", data, slot + 8, len(data), len(table))
data.extend(table)
(tmp_path / "font.ttf").write_bytes(data)
- rows, _, _, _ = _engine.typeset(source, [str(tmp_path)])
+ rows, *_ = _engine.typeset(source, [str(tmp_path)])
key = int(np.frombuffer(rows).reshape(-1, tc.ROW)[0, tc.KEY])
assert _engine.ligature_carets(key) == ([] if coordinate is None else [coordinate])
@@ -172,7 +173,7 @@ scans = Path(tempfile.gettempdir()) / 'manimgx-fonts' if root is None else Path(
layouts = t._CACHE
before_scans = set(scans.glob('*.bin'))
before_layouts = set(layouts.glob('*.layout'))
-rows, _, _, system = _engine.typeset('#set text(font:"Noto Sans")\nHello Ω', [sys.argv[1]])
+rows, _, _, system, _ = _engine.typeset('#set text(font:"Noto Sans")\nHello Ω', [sys.argv[1]])
table = np.frombuffer(rows).reshape(-1, 23)
keys = sorted(set(int(row[1]) for row in table if row[0] == 0))
native = hashlib.sha256(rows + b''.join(_engine.glyph_outlines(keys))).hexdigest()
@@ -227,7 +228,7 @@ def test_concurrent_cache_writers_publish_complete_owned_files(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
path = tmp_path / "entry.layout"
- stored: tc.Stored = (np.zeros((100, tc.ROW)), [], [], 0, {})
+ stored: tc.Stored = (np.zeros((100, tc.ROW)), [], [], 0, {}, [])
expected = pickle.dumps(stored, protocol=5)
first_written, second_half, published = Event(), Event(), Event()
write_bytes, replace = Path.write_bytes, os.replace
@@ -307,7 +308,7 @@ class Engine:
rows[:, tc.FILL] = [0, 0, 0, 1]
rows[:, tc.STROKE] = [-1, -1, -1, -1]
rows[:, tc.ADVANCE] = 1000
- return rows.tobytes(), [], [], False
+ return rows.tobytes(), [], [], False, []
def change(self) -> None:
"""Change what it answered: the made-up font's carets."""
@@ -507,7 +508,7 @@ def test_a_glyph_without_an_outline_is_no_part_and_labels_lose_it(
nonlocal calls
calls += 1
assert calls == 1, "the second construction must read its disk cache"
- return raw, [horizontal.tobytes()], labels, False
+ return raw, [horizontal.tobytes()], labels, False, []
def outlines(keys: Sequence[int]) -> list[bytes]:
return [b"" if key == 981 else square.tobytes() for key in keys]
@@ -586,7 +587,7 @@ def _set(text: m.Text) -> tuple[list[int], bool]:
preamble = tc.TYPST_TEMPLATE.format(
text_size=tc.TYPST_COMPILATION_FONT_SIZE, preamble=text.typst_preamble
)
- rows, _, _, system = _engine.typeset(preamble + text.typst_code, tc.FONTS)
+ rows, _, _, system, _ = _engine.typeset(preamble + text.typst_code, tc.FONTS)
table = np.frombuffer(rows).reshape(-1, tc.ROW)
keys = table[table[:, tc.KIND] == tc.GLYPH, tc.KEY].astype(np.int64)
return [int(k) % 65536 for k in keys], system
@@ -611,4 +612,14 @@ def test_every_script_is_set_in_a_font_manimgx_ships(text: str, font: str) -> No
def test_a_system_font_is_read_only_by_name() -> None:
- assert _set(m.Text("Hi", font="Open Sans"))[1]
+ # a family ManimGX doesn't ship is looked for among the system's fonts; no font has this one
+ with pytest.warns(UserWarning, match="no font has the family name 'no such font'"):
+ text = m.Text("Hi", font="No Such Font")
+ assert _set(text)[1]
+
+
+def test_a_font_is_found_by_any_family_name_it_lists() -> None:
+ # Noto Sans Hebrew lists "Noto Sans Hebrew Light" (its family, name ID 1) beside its
+ # typographic family, which Typst names it by
+ named = m.Text("שלום", font="Noto Sans Hebrew Light")
+ assert _set(named) == _set(m.Text("שלום", font="Noto Sans Hebrew"))