The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.
Python
Import SVG artwork as mobjects
Sina Atalay5f97ebf8c8f7
diff --git a/src/manimgx/mobjects/numbers.py b/src/manimgx/mobjects/numbers.pyindex 7bde5e26..74306358 100644--- a/src/manimgx/mobjects/numbers.py+++ b/src/manimgx/mobjects/numbers.py@@ -263,6 +263,12 @@ class DecimalNumber(VMobject):self.add_background_rectangle()def _get_num_string(self, number: float | complex) -> str:+ if isinstance(number, complex | np.complexfloating): # a+bi, not Python's a+bj+ return (+ self._get_formatter("0.real")+ + self._get_formatter("0.imag", include_sign=True)+ + "i"+ ).format(number)return self._get_formatter().format(number)def _get_formatter(@@ -270,9 +276,7 @@ class DecimalNumber(VMobject):) -> str:sign = self.include_sign if include_sign is None else include_signcommas = "," if self.group_with_commas else ""- return (- f"{{{field_name}:{'+' if sign else ''}z{commas}.{self.num_decimal_places}f}}"- )+ return f"{{{field_name}:{'+' if sign else ''}z{commas}.{self.num_decimal_places}f}}"_shown: (tuple[tuple[object, ...], tuple[tuple[Mobject, Blend, Paint], ...]] | None@@ -327,7 +331,7 @@ class DecimalNumber(VMobject):self.number = numberreturn selfold_font_size = self.font_size- move_to_point = self.get_edge_center(self.edge_to_fix)+ move_to_point = self.get_critical_point(self.edge_to_fix)key = self._set_submobjects_from_number(number)self.font_size = old_font_sizeself.move_to(move_to_point, self.edge_to_fix)diff --git a/src/manimgx/mobjects/svg.py b/src/manimgx/mobjects/svg.pynew file mode 100644index 00000000..6803c0ad--- /dev/null+++ b/src/manimgx/mobjects/svg.py@@ -0,0 +1,568 @@+# SPDX-FileCopyrightText: 2026 Academa, Inc.+# SPDX-FileCopyrightText: 2024 the Manim Community Developers+# SPDX-FileCopyrightText: 2018 3Blue1Brown LLC+# SPDX-License-Identifier: MIT++"""SVG as mobjects: a file's shapes (`SVGMobject`), and one path's curves (a brace, the logo's+letters). Ported from Manim CE 0.21 (MIT)."""++from __future__ import annotations++import io+import logging+import os+from collections.abc import Sequence+from pathlib import Path+from typing import TYPE_CHECKING, Self, Unpack+from xml.etree import ElementTree as ET++import numpy as np++from manimgx.caches import Memo+from manimgx.constants import RIGHT+from manimgx.drawing.geometry import Blend+from manimgx.drawing.paint import BLACK, Colors, Look, Repaint, Style, key_of+from manimgx.mobject import VGroup, VMobject, copied+from manimgx.mobjects.shapes import Circle, Line, Polygon, Rectangle, RoundedRectangle++if TYPE_CHECKING: # svgelements loads when an SVG is read (few scenes read one)+ import svgelements as se++__all__ = ["SVGMobject", "VMobjectFromSVGPath"]+logger = logging.getLogger("manimgx")++_DRAWINGS: Memo[tuple[object, ...], tuple[list[VMobject], dict[str, VGroup]]] = Memo(+ 1 << 8+)+++def _point(point: se.Point | None) -> np.ndarray:+ """A path's point, in 3D (a well-formed path has every point it names)."""+ if point is None:+ raise ValueError("malformed SVG path: a segment without its point")+ return np.array([point.x, point.y, 0.0])+++class PathOptions(Style, total=False):+ """How an SVG path becomes curves: an [SVGMobject][manimgx.SVGMobject]'s+ `path_string_config`, the keywords of each+ [VMobjectFromSVGPath][manimgx.VMobjectFromSVGPath] it makes.++ Beyond these, they take the [style keywords][manimgx.drawing.paint.Style].+ """++ long_lines: bool+ """Accepted for Manim compatibility; ignored (default False)."""+ should_subdivide_sharp_curves: bool+ """Accepted for Manim compatibility; ignored (default False)."""+ should_remove_null_curves: bool+ """Accepted for Manim compatibility; ignored (default False)."""+++class SVGMobject(VMobject):+ """A drawing read from an SVG file: each of its shapes a part, painted as the file+ paints it, 2 units tall unless sized.++ Paths, lines, rectangles (rounded too), circles, ellipses, polygons and polylines+ become parts, in the file's order, with the file's fills, strokes and transforms;+ groups and `<use>` are followed, and text is skipped, with a warning. What the file+ leaves unpainted takes SVG's defaults, a black fill and no stroke, unless+ `svg_default` says otherwise. The file's groups are kept by their ids, in+ [id_to_vgroup_dict][manimgx.SVGMobject.id_to_vgroup_dict].++ Args:+ file_name: The SVG file.+ should_center: Whether the drawing is centered on the origin.+ height: The height to scale the drawing to, in scene units; None keeps the+ file's size, a scene unit per SVG unit.+ width: The width to scale the drawing to, in scene units, after `height` (so it+ wins); None: as `height` makes it.+ color: Accepted for Manim compatibility; no effect: the parts keep the file's+ colors (paint over them with `fill_color` and `stroke_color`, or color what+ the file leaves unpainted through `svg_default`).+ opacity: Accepted for Manim compatibility; ignored.+ fill_color: A fill color for every part; None keeps the file's.+ fill_opacity: A fill opacity for every part, from 0 to 1; None keeps the file's.+ stroke_color: A stroke color for every part; None keeps the file's.+ stroke_opacity: A stroke opacity for every part, from 0 to 1; None keeps the+ file's.+ stroke_width: A stroke width for every part, in hundredths of a scene unit;+ None keeps the file's.+ svg_default: [Paint keywords][manimgx.drawing.paint.Repaint] for what the file+ leaves unpainted; None for `{"stroke_width": 0}`: no stroke.+ path_string_config: [SVG path+ keywords][manimgx.mobjects.svg.PathOptions] for every path.+ use_svg_cache: Whether parsed drawings are kept and copied for the same SVG+ content and path settings. The file is always read for changes.+ """++ def __init__(+ self,+ file_name: str | os.PathLike[str] | None = None,+ should_center: bool = True,+ height: float | None = 2,+ width: float | None = None,+ color: Colors | None = None,+ opacity: float | None = None,+ fill_color: Colors | None = None,+ fill_opacity: float | Sequence[float] | None = None,+ stroke_color: Colors | None = None,+ stroke_opacity: float | Sequence[float] | None = None,+ stroke_width: float | None = None,+ svg_default: Repaint | None = None,+ path_string_config: PathOptions | None = None,+ use_svg_cache: bool = True,+ **kwargs: Unpack[Look],+ ):+ super().__init__(stroke_color=None, fill_color=None, **kwargs)+ self.file_name = Path(file_name) if file_name is not None else None+ self.should_center = should_center+ self.svg_height = height+ self.svg_width = width+ self.set_color(BLACK if color is None else color)+ self.opacity = opacity+ self.fill_color = fill_color+ self.fill_opacity = fill_opacity+ self.stroke_color = stroke_color+ self.stroke_opacity = stroke_opacity+ self.stroke_width = 0 if stroke_width is None else stroke_width+ self.id_to_vgroup_dict: dict[str, VGroup] = {}+ """The drawing's groups, by their ids: each `<g>` element's id names a group of+ the shapes inside it, and "root" all of them; an element without an id is named+ "numbered_group_" and a number."""+ self.svg_default: Repaint = (+ {"stroke_width": 0} if svg_default is None else svg_default+ )+ self.path_string_config: PathOptions = (+ {} if path_string_config is None else path_string_config+ )+ self.init_svg_mobject(use_svg_cache=use_svg_cache)+ self.set_style(+ fill_color=fill_color,+ fill_opacity=fill_opacity,+ stroke_color=stroke_color,+ stroke_opacity=stroke_opacity,+ stroke_width=stroke_width,+ )+ self.move_into_position()++ def init_svg_mobject(self, use_svg_cache: bool) -> Self:+ """Build the drawing, reusing parsed parts when caching is enabled."""+ self.use_svg_cache = use_svg_cache+ self.generate_mobject()+ return self++ @property+ def hash_seed(self) -> tuple[object, ...]:+ """The class and path settings that interpret the SVG content. Subclasses can+ extend this tuple with other inputs their conversion uses."""+ return (+ type(self),+ key_of(sorted(self.path_string_config.items())),+ )++ def generate_mobject(self) -> Self:+ """Read the file and add its shapes as parts, flipped so that y points up (SVG's+ points down). Existing geometry turns with the newly read shapes.+ """+ import svgelements as se++ element_tree = ET.parse(self.get_file_path())+ buffer = io.BytesIO()+ self.modify_xml_tree(element_tree).write(buffer)+ buffer.seek(0)+ if self.has_points() or self.submobjects:+ mobjects, self.id_to_vgroup_dict = self.get_mobjects_from(+ se.SVG.parse(buffer)+ )+ self.add(*mobjects)+ return self.flip(RIGHT)+ try:+ key = (buffer.getvalue(), *self.hash_seed) if self.use_svg_cache else None+ except TypeError:+ key = None+ drawing = None if key is None else _DRAWINGS.get(key)+ if drawing is None:+ drawing = self.get_mobjects_from(se.SVG.parse(buffer))+ VGroup(*drawing[0]).flip(RIGHT)+ if key is not None:+ _DRAWINGS.keep(key, copied(drawing))+ else:+ drawing = copied(drawing)+ mobjects, mobject_dict = drawing+ self.flip(RIGHT)+ self.add(*mobjects)+ self.id_to_vgroup_dict = mobject_dict+ return self++ def get_file_path(self) -> Path:+ """Find the SVG file; a mobject made without one raises ValueError.++ Returns:+ The file's path.+ """+ if self.file_name is None:+ raise ValueError("Must specify file for SVGMobject")+ return self.file_name++ def modify_xml_tree(+ self, element_tree: ET.ElementTree[ET.Element]+ ) -> ET.ElementTree[ET.Element]:+ """Wrap the file's drawing in groups that carry `svg_default` and the style of+ the file's root, so that its shapes inherit them.++ Args:+ element_tree: The file, parsed.++ Returns:+ A new tree.+ """+ style_keys = (+ "fill",+ "fill-opacity",+ "stroke",+ "stroke-opacity",+ "stroke-width",+ "style",+ )+ root = element_tree.getroot()+ root_style = {k: v for k, v in root.attrib.items() if k in style_keys}+ new_root = ET.Element("svg", {})+ config_style = ET.SubElement(new_root, "g", self.generate_config_style_dict())+ ET.SubElement(config_style, "g", root_style).extend(root)+ return ET.ElementTree(new_root)++ def generate_config_style_dict(self) -> dict[str, str]:+ """The SVG attributes `svg_default` sets: `fill`, `fill-opacity`, `stroke`,+ `stroke-opacity` and `stroke-width`.++ Returns:+ The attributes it gives, as strings, by name.+ """+ keys_converting_dict = {+ "fill": ("color", "fill_color"),+ "fill-opacity": ("opacity", "fill_opacity"),+ "stroke": ("color", "stroke_color"),+ "stroke-opacity": ("opacity", "stroke_opacity"),+ "stroke-width": ("stroke_width",),+ }+ result = {}+ for svg_key, style_keys in keys_converting_dict.items():+ for style_key in style_keys:+ value = self.svg_default.get(style_key)+ if value is not None:+ result[svg_key] = str(value)+ return result++ def get_mobjects_from(+ self, svg: se.SVG+ ) -> tuple[list[VMobject], dict[str, VGroup]]:+ """Make a part of every shape of the drawing, in document order, and a group of+ the parts of each of its groups, named or not.++ Args:+ svg: The drawing, as svgelements parses it.++ Returns:+ The parts, and the groups by id (an unnamed group numbered; "root" for all+ the parts).+ """+ import svgelements as se++ shapes = (+ se.Path,+ se.SimpleLine,+ se.Rect,+ se.Circle,+ se.Ellipse,+ se.Polygon,+ se.Polyline,+ se.Text,+ )+ result: list[VMobject] = []+ stack: list[tuple[se.SVGElement, int]] = [(svg, 1)]+ group_id_number = 0+ vgroup_stack: list[str] = ["root"]+ vgroups: dict[str, VGroup] = {"root": VGroup()}+ while stack:+ element, depth = stack.pop()+ vgroup_stack = vgroup_stack[0:depth]+ try:+ group_name = str((element.values or {})["id"])+ except Exception:+ group_name = f"numbered_group_{group_id_number}"+ group_id_number += 1+ vgroup_stack.append(group_name)+ vgroups[group_name] = VGroup()+ if isinstance(element, (se.Group, se.Use)):+ stack.extend((subelement, depth + 1) for subelement in element[::-1])+ try:+ if isinstance(element, shapes):+ mob = self.get_mob_from_shape_element(element)+ if mob is not None:+ result.append(mob)+ for parent_name in vgroup_stack[:-1]:+ vgroups[parent_name].add(mob)+ except Exception as e:+ logger.error(f"Exception occurred in 'get_mobjects_from'. Details: {e}")+ return (result, vgroups)++ def get_mob_from_shape_element(self, shape: se.SVGElement) -> VMobject | None:+ """Make a part of a shape of the drawing, painted and transformed as the file+ says.++ Args:+ shape: The shape, as svgelements parses it.++ Returns:+ The part; None for an empty shape, or an element that isn't supported (text).+ """+ import svgelements as se++ if isinstance(shape, se.Path):+ mob: VMobject | None = self.path_to_mobject(shape)+ elif isinstance(shape, se.SimpleLine):+ mob = self.line_to_mobject(shape)+ elif isinstance(shape, se.Rect):+ mob = self.rect_to_mobject(shape)+ elif isinstance(shape, (se.Circle, se.Ellipse)):+ mob = self.ellipse_to_mobject(shape)+ elif isinstance(shape, se.Polygon):+ mob = self.polygon_to_mobject(shape)+ elif isinstance(shape, se.Polyline):+ mob = self.polyline_to_mobject(shape)+ elif isinstance(shape, se.Text):+ mob = self.text_to_mobject(shape)+ else:+ logger.warning(f"Unsupported element type: {type(shape)}")+ mob = None+ if mob is None or not mob.has_points():+ return None+ if isinstance(shape, se.GraphicObject):+ self.apply_style_to_mobject(mob, shape)+ if (+ isinstance(shape, se.Transformable)+ and shape.apply+ and shape.transform is not None+ ):+ self.handle_transform(mob, shape.transform)+ return mob++ @staticmethod+ def handle_transform(mob: VMobject, matrix: se.Matrix) -> VMobject:+ """Apply an SVG transform to a part: its matrix, then its translation.++ Args:+ mob: The part.+ matrix: The transform, as svgelements gives it.++ Returns:+ The part.+ """+ mat = np.array([[matrix.a, matrix.c], [matrix.b, matrix.d]])+ vec = np.array([matrix.e, matrix.f, 0.0])+ mob.apply_matrix(mat)+ mob.shift(vec)+ return mob++ @staticmethod+ def apply_style_to_mobject(mob: VMobject, shape: se.GraphicObject) -> VMobject:+ """Paint a part as the file paints its shape: its fill, its stroke, their+ opacities and the stroke's width.++ Args:+ mob: The part.+ shape: The shape, as svgelements parses it.++ Returns:+ The part.+ """+ stroke, fill = shape.stroke, shape.fill+ mob.set_style(+ stroke_width=shape.stroke_width,+ stroke_color=None if stroke is None else stroke.hexrgb,+ stroke_opacity=None if stroke is None else stroke.opacity,+ fill_color=None if fill is None else fill.hexrgb,+ fill_opacity=None if fill is None else fill.opacity,+ )+ return mob++ def path_to_mobject(self, path: se.Path) -> VMobjectFromSVGPath:+ """Make a part of a path, with `path_string_config`.++ Args:+ path: The path, as svgelements parses it.++ Returns:+ A new [VMobjectFromSVGPath][manimgx.VMobjectFromSVGPath].+ """+ return VMobjectFromSVGPath(path, **self.path_string_config)++ @staticmethod+ def line_to_mobject(line: se.SimpleLine) -> Line:+ """Make a part of a line.++ Args:+ line: The line, as svgelements parses it.++ Returns:+ A new [Line][manimgx.Line].+ """+ x1, y1, x2, y2 = (float(v or 0) for v in (line.x1, line.y1, line.x2, line.y2))+ return Line(start=np.array([x1, y1, 0.0]), end=np.array([x2, y2, 0.0]))++ @staticmethod+ def rect_to_mobject(rect: se.Rect) -> Rectangle:+ """Make a part of a rectangle, its corners rounded if the file rounds them.++ Args:+ rect: The rectangle, as svgelements parses it.++ Returns:+ A new [Rectangle][manimgx.Rectangle] or+ [RoundedRectangle][manimgx.RoundedRectangle].+ """+ x, y, width, height, rx, ry = (+ float(v or 0)+ for v in (rect.x, rect.y, rect.width, rect.height, rect.rx, rect.ry)+ )+ if rx == 0 or ry == 0:+ mob = Rectangle(width=width, height=height)+ else:+ mob = RoundedRectangle(+ width=width, height=height * rx / ry, corner_radius=rx+ )+ mob.stretch_to_fit_height(height)+ mob.shift(np.array([x + width / 2, y + height / 2, 0.0]))+ return mob++ @staticmethod+ def ellipse_to_mobject(ellipse: se.Ellipse | se.Circle) -> Circle:+ """Make a part of a circle or an ellipse.++ Args:+ ellipse: The circle or ellipse, as svgelements parses it.++ Returns:+ A new [Circle][manimgx.Circle], stretched for an ellipse.+ """+ rx, ry, cx, cy = (+ float(v or 0) for v in (ellipse.rx, ellipse.ry, ellipse.cx, ellipse.cy)+ )+ mob = Circle(radius=rx)+ if rx != ry:+ mob.stretch_to_fit_height(2 * ry)+ mob.shift(np.array([cx, cy, 0.0]))+ return mob++ @staticmethod+ def polygon_to_mobject(polygon: se.Polygon) -> Polygon:+ """Make a part of a polygon.++ Args:+ polygon: The polygon, as svgelements parses it.++ Returns:+ A new [Polygon][manimgx.Polygon].+ """+ return Polygon(*(np.array([x, y, 0.0]) for x, y in polygon))++ def polyline_to_mobject(self, polyline: se.Polyline) -> VMobject:+ """Make a part of a polyline: an open path through its points.++ Args:+ polyline: The polyline, as svgelements parses it.++ Returns:+ A new VMobject.+ """+ return VMobject().set_points_as_corners([[x, y, 0.0] for x, y in polyline])++ @staticmethod+ def text_to_mobject(text: se.Text) -> VMobject | None:+ """Skip a text element: SVG text is not supported, and a warning is logged.++ Args:+ text: The text, as svgelements parses it.++ Returns:+ None.+ """+ logger.warning(f"Unsupported element type: {type(text)}")+ return None++ def move_into_position(self) -> Self:+ """Center the drawing and scale it to `height` and `width`, as the constructor+ was asked to.+ """+ if self.should_center:+ self.center()+ if self.svg_height is not None:+ self.set(height=self.svg_height)+ if self.svg_width is not None:+ self.set(width=self.svg_width)+ return self+++class VMobjectFromSVGPath(VMobject):+ """A path of an SVG drawing, as a mobject: its lines, quadratic and cubic curves,+ and arcs (approximated by quadratic curves), all made cubic curves.++ An [SVGMobject][manimgx.SVGMobject] makes one of every path in its file. The points+ are in the path's own coordinates, a scene unit per SVG unit, and SVG's y axis+ points down: the path is upside down until flipped, as an SVGMobject flips its+ drawing.++ The supplied path is converted once. Editing it later does not affect the drawing;+ `generate_points` restores the original converted geometry.++ Args:+ path_obj: The path, as svgelements parses it (a `svgelements.Path`).+ long_lines: Accepted for Manim compatibility; ignored.+ should_subdivide_sharp_curves: Accepted for Manim compatibility; ignored.+ should_remove_null_curves: Accepted for Manim compatibility; ignored.+ """++ def __init__(+ self,+ path_obj: se.Path,+ long_lines: bool = False,+ should_subdivide_sharp_curves: bool = False,+ should_remove_null_curves: bool = False,+ **kwargs: Unpack[Style],+ ) -> None:+ import svgelements as se++ path_obj.approximate_arcs_with_quads()+ points: list[np.ndarray] = []+ pen = start = np.zeros(3)+ for segment in path_obj:+ kind = type(segment)+ if kind is se.Move:+ pen = start = _point(segment.end)+ elif kind is se.Line or (+ kind is se.Close and np.linalg.norm(pen - start) > 0.0001+ ):+ end = start if kind is se.Close else _point(segment.end)+ points += [pen, (2 * pen + end) / 3, (pen + 2 * end) / 3, end]+ pen = end+ elif isinstance(segment, se.QuadraticBezier):+ control, end = _point(segment.control), _point(segment.end)+ points += [pen, (pen + 2 * control) / 3, (2 * control + end) / 3, end]+ pen = end+ elif isinstance(segment, se.CubicBezier):+ end = _point(segment.end)+ points += [pen, _point(segment.control1), _point(segment.control2), end]+ pen = end+ elif kind is not se.Close:+ raise AssertionError(f"Not implemented: {kind}")+ source = (+ np.array(points, ndmin=2, dtype="float64") if points else np.zeros((0, 3))+ )+ self._source_geometry = Blend.of(source)+ super().__init__(**kwargs)++ def generate_points(self) -> Self:+ """Restore the geometry converted from the original SVG path."""+ self._geometry = self._source_geometry+ return selfdiff --git a/src/manimgx/mobjects/text.py b/src/manimgx/mobjects/text.pyindex 7f6cc437..1a6d7da4 100644--- a/src/manimgx/mobjects/text.py+++ b/src/manimgx/mobjects/text.py@@ -13,12 +13,14 @@ color is cut at its carets. A key is a slice "[a:b]" or each occurrence of a stroccurs nowhere picks nothing.CE's LaTeX classes, typeset by Typst: LaTeX converted by mitex, so `MathTex("a", "=", "b")[i]`-is part i. A MathTex's parts are one formula; Tex's are set one after another, each labelled.+is part i. A MathTex's strings are one formula, a Tex's one text: joined, and typeset once."""from __future__ import annotations+from warnings import deprecated+__all__ = ["BulletedList","MathTex",@@ -39,7 +41,7 @@ __all__ = [import bisectimport reimport unicodedata-from collections.abc import Iterable, Mapping, Sequence+from collections.abc import Callable, Collection, Iterable, Mapping, Sequencefrom pathlib import Pathfrom typing import Literal, Self, Unpack@@ -93,9 +95,6 @@ from manimgx.drawing.typesetting import (from manimgx.mobject import Mobject, Pivot, VGroup, VMobject, _append_path, prototypefrom manimgx.typing import Vector3DLike-_MANIMGRP_PREAMBLE = "#let manimgrp(lbl, body) = [#box(body) #label(lbl)]"--_HEX: Memo[tuple[float, ...], str] = Memo(1 << 12)@@ -161,11 +160,12 @@ class TypstGlyph(VMobject):_carets: bytes = b""node: int- """Where the source node the glyph came from starts in the Typst code, in bytes; -1- if it came from elsewhere (a package's code)."""+ """Where the source node the glyph came from starts in the Typst code, in bytes. A+ glyph a package's code drew (a radical a package's function sets) came from the+ innermost element of the code around it (its equation); -1 if none is."""drawn: tuple[int, int]"""The bytes of that node's text the glyph's cluster draws, from and to: of a string- literal, the bytes of its value."""+ literal, the bytes of its value; -1, -1 if the node is an element around it."""key: int"""The provenance key of its outline and font carets, the same in every process.Assigning a key does not change the live glyph's outline or carets."""@@ -333,8 +333,9 @@ class Typst(VMobject):ink = extent(place, True)[:, :2]places.append(place)if len(ink):- low, high = np.minimum(low, ink.min(axis=0)), np.maximum(- high, ink.max(axis=0)+ low, high = (+ np.minimum(low, ink.min(axis=0)),+ np.maximum(high, ink.max(axis=0)),)height = float(high[1] - low[1]) if high[1] >= low[1] else 0.0if scale is not None and height > 0:@@ -1100,7 +1101,8 @@ _IMPORT = (def _standalone(tex: str) -> str:- """CE's `_modify_special_strings`: make a lone LaTeX fragment typeset on its own."""+ """CE's `_modify_special_strings`: make a lone fragment of a formula typeset on its own.+ Its mends are math's (a trailing `dot` is `\\dot`'s); text is converted as written."""tex = tex.strip()if tex in ("\\over", "\\overline", "\\sqrt", "\\sqrt{") or tex.endswith(("_", "^", "dot")@@ -1125,11 +1127,12 @@ _BRACES = re.compile("{{(.*?)}}")_HOLE = 0xE000 # private-use characters: mitex passes them through as they are-def _isolate_braces(strings: list[str]) -> list[str]:- """CE's double braces: `{{…}}` sets what it holds apart as a part of its own; once they- split anything, every part is stripped."""+def _isolate_braces(strings: list[str], math: bool) -> list[str]:+ """CE's double braces: `{{…}}` sets what it holds apart as a part of its own. In math,+ where spaces mean nothing, once they split anything every part is stripped; text keeps+ its spaces, so its strings still join into the text as written."""pieces = [p for s in strings for p in _BRACES.split(s)]- if len(pieces) > len(strings):+ if math and len(pieces) > len(strings):pieces = [p.strip() for p in pieces]return [p for p in pieces if p]@@ -1150,37 +1153,61 @@ def _balanced(tex: str) -> bool:return depth == 0-def _one_formula(pieces: list[str], separator: str) -> tuple[str, str, set[int]]:- """The pieces as one formula: the Typst math code of their joined LaTeX; the same code- with each piece that stands on its own (a `hole`) boxed and labelled `p{i}`, to tell its- glyphs apart; and those pieces. The holes are converted on their own, in the joined- LaTeX's skeleton, so the formula's code is checked to be what the whole converts to:- telling the pieces apart never changes the formula."""- whole = _engine.mitex_math(separator.join(pieces))+def _one_formula(+ pieces: list[str], separator: str, convert: Callable[[str], str]+) -> tuple[str, str, dict[int, str]]:+ """The pieces as one formula, or one text: the Typst code of their joined LaTeX+ (`convert`: mitex's conversion of LaTeX math, or of LaTeX text); its skeleton, the same+ code with each piece that stands on its own (a `hole`) a private-use character; and each+ hole's code. The holes are converted on their own, in the joined LaTeX's skeleton, and the+ skeleton with their code in place is checked to be what the whole converts to: telling+ the pieces apart never changes the code."""+ whole = convert(separator.join(pieces))holes: dict[int, str] = {}for i, piece in enumerate(pieces):if not _balanced(piece) or piece.lstrip()[:1] in ("^", "_", "'", ""):continue # a fragment, or an attachment to what comes beforetry:- holes[i] = _engine.mitex_math(piece)+ holes[i] = convert(piece)except TypstError:continue- skeleton = _engine.mitex_math(- separator.join(- chr(_HOLE + i) if i in holes else p for i, p in enumerate(pieces)+ apart = ValueError(f"cannot tell these parts apart: {pieces}")+ try:+ skeleton = convert(+ separator.join(+ chr(_HOLE + i) if i in holes else p for i, p in enumerate(pieces)+ ))- )+ except TypstError as error: # a hole within what converts only whole (math in text)+ raise apart from errorfound = [ord(c) - _HOLE for c in skeleton if _HOLE <= ord(c) < _HOLE + len(pieces)]- plain = boxed = skeleton- for i, code in holes.items():- plain = plain.replace(chr(_HOLE + i), code)- boxed = boxed.replace(chr(_HOLE + i), f'#manimgrp("p{i}", ${code}$)')+ plain = _fill(skeleton, holes)if found != sorted(holes) or "".join(plain.split()) != "".join(whole.split()):- raise ValueError(f"MathTex cannot tell these parts apart: {pieces}")- return plain, boxed, set(holes)+ raise apart+ return whole, skeleton, holes+++def _fill(skeleton: str, holes: Mapping[int, str]) -> str:+ """The skeleton with each hole's code (or what stands for it) in its place."""+ for i, code in holes.items():+ skeleton = skeleton.replace(chr(_HOLE + i), code)+ return skeleton+++def _in_place(skeleton: str, holes: Mapping[int, str]) -> dict[int, str]:+ """Each hole's markup as it reads in the whole. Typst reads a line's first characters+ apart (`- `, `+ `, `= ` and `/ ` begin a list's item, an enumeration's, a heading, a+ term), so a hole that goes on with a line is read after an empty expression, which+ keeps it on the line."""+ read = {}+ for i, code in holes.items():+ before = _fill(skeleton[: skeleton.index(chr(_HOLE + i))], holes)+ read[i] = f"#none;{code}" if before.rsplit("\n", 1)[-1].strip() else code+ return read_MITEX = 'mode: "math", scope: mitex-scope'+_MARKUP = 'mode: "markup", scope: mitex-scope'def _math(latex: str) -> str:@@ -1189,10 +1216,41 @@ def _math(latex: str) -> str:def _text(latex: str) -> str:- converted = typst_string(_engine.mitex_text(latex))- return f'eval({converted}, mode: "markup", scope: mitex-scope)'+ return _markup(_engine.mitex_text(latex))+++def _markup(code: str, scope: str = "") -> str:+ """Typst markup (mitex's conversion of LaTeX text) as an expression of its content, in+ mitex's scope and, after it, the bindings `scope` lists ("name: value, ")."""+ within = f"mitex-scope + ({scope})" if scope else "mitex-scope"+ return f'eval({typst_string(code)}, mode: "markup", scope: {within})'+++def _bindings(codes: Mapping[int, str]) -> tuple[str, dict[int, int]]:+ """Typst code binding each string's content (its markup, evaluated) to its name, `p{i}`;+ and where in that code each string's markup starts, in bytes, which every glyph the+ markup draws comes from."""+ out, starts, at = [], {}, 0+ for i, code in codes.items():+ head = f"#let p{i} = eval("+ starts[at + len(head.encode())] = i+ binding = f"{head}{typst_string(code)}, {_MARKUP});"+ out.append(binding)+ at += len(binding.encode())+ return "".join(out), starts+def _same(a: Layout, b: Layout) -> bool:+ """Whether two layouts draw the same: the same items, placed and painted alike, wherever+ in the code they came from."""+ return (+ np.array_equal(a.rows[:, : NODE.start], b.rows[:, : NODE.start])+ and len(a.shapes) == len(b.shapes)+ and all(np.array_equal(p, q) for p, q in zip(a.shapes, b.shapes))+ )+++@deprecated("use MathTex", category=None)class SingleStringMathTex(Typst):r"""One LaTeX formula, typeset in the engine, whose parts are its glyphs: whiteunless styled.@@ -1266,8 +1324,8 @@ class MathTexOptions(TypstOptions, total=False):"""arg_separator: str- """What joins the strings into `tex_string`, the formula a MathTex is typeset as- (default " "; "" for a Tex, whose strings are typeset one after another)."""+ """What joins the strings into `tex_string`, the formula a MathTex is typeset as,+ or the text a Tex is (default " "; "" for a Tex)."""substrings_to_isolate: Iterable[str] | None"""Substrings to make parts of their own: each string is split around everyoccurrence of each (default None)."""@@ -1310,13 +1368,13 @@ class MathTex(Typst):[get_part_by_tex][manimgx.MathTex.get_part_by_tex] find parts by their LaTeX, and[TransformMatchingTex][manimgx.TransformMatchingTex] moves each part to the partwritten the same way in another formula. Read as text (see [Tex][manimgx.Tex]), the- strings are typeset one after another instead.+ strings are one text in the same way, spaces and all.Args:*tex_strings: The formula, in LaTeX: a string per part (a number is written asa string), and a part per `{{…}}` within one.- arg_separator: What joins the strings into `tex_string`, the formula they are- typeset as.+ arg_separator: What joins the strings into `tex_string`, the formula (or text)+ they are typeset as.substrings_to_isolate: Substrings to make parts of their own: each string issplit around every occurrence of each.tex_to_color_map: A color for each substring, which is made a part of its own@@ -1368,71 +1426,136 @@ class MathTex(Typst):) -> None:self.tex_to_color_map = dict(tex_to_color_map or {})isolate = list(substrings_to_isolate or []) + list(self.tex_to_color_map)- strings = _isolate_braces([str(s) for s in tex_strings])+ math = bool(tex_environment and "align" in tex_environment)+ strings = _isolate_braces([str(s) for s in tex_strings], math)self.tex_strings = (- [p for s in strings for p in _split(s, isolate)] if isolate else strings+ [p for s in strings for p in _split(s, isolate, math)]+ if isolate+ else strings)"""The strings, a part's each: the arguments, split at `{{…}}` and around theisolated substrings."""self.arg_separator = arg_separatorself.tex_string = arg_separator.join(self.tex_strings)- """The LaTeX of the whole formula: the strings, joined by `arg_separator`."""+ """The LaTeX of the whole formula, or text: the strings, joined by+ `arg_separator`."""self.tex_environment = tex_environment- fn = _math if tex_environment and "align" in tex_environment else _text- preamble = f"{_IMPORT}{_MANIMGRP_PREAMBLE}\n"-- def body(strings: list[str]) -> str:- if fn is _math: # a part's box would drop to text style; keep display style- parts = " ".join(- f'#manimgrp("p{i}", $display(#{_math(_standalone(s))})$)'- for i, s in enumerate(strings)- )- return f"$ {parts} $"- return self._set(- [- f'manimgrp("p{i}", {_text(_standalone(s))})'- for i, s in enumerate(strings)- ]+ preamble = f"{_IMPORT}{_MANIMGRP}\n" if math else _IMPORT+ kwargs["typst_preamble"] = preamble + kwargs.get("typst_preamble", "")++ def layout(source: str) -> Layout:+ return typeset(+ source,+ kwargs["typst_preamble"],+ font_paths=kwargs.get("font_paths"),+ package_path=kwargs.get("package_path"),)- formula = None- if (- fn is _math and len(self.tex_strings) > 1- ): # one formula, its parts told apart- formula = _one_formula(self.tex_strings, arg_separator)- source = f"$ #eval({typst_string(formula[0])}, {_MITEX}) $"- else:- try:- source = body(self.tex_strings)- if len(self.tex_strings) != 1: # a lone part's fallback is itself- typeset(source, preamble)- except (- TypstError- ): # the parts are not LaTeX on their own (e.g. a split environment)- source = body([self.tex_string])- kwargs["typst_preamble"] = preamble + kwargs.get("typst_preamble", "")- super().__init__(source, **kwargs)- if formula is None:- self._regroup_by_labels()- else:+ if not math:+ body, starts, whole = self._compose(self.tex_strings, arg_separator)+ owners: dict[int, int] = {}+ if len(self.tex_strings) > 1 and starts: # which string drew each item+ apart = ValueError(f"cannot tell these parts apart: {self.tex_strings}")+ reference = None if whole is None else layout(whole)+ try:+ drawn = layout(body)+ except TypstError as error: # the text is fine, its parting is not+ if reference is None:+ raise+ raise apart from error+ if reference is not None and not _same(drawn, reference):+ raise apart+ owners = self._owners(drawn, starts)+ super().__init__(body, **kwargs)+ self._regroup(owners, set(starts.values()))+ elif len(self.tex_strings) > 1: # one formula, its parts told apart+ _, skeleton, holes = _one_formula(+ self.tex_strings, arg_separator, _engine.mitex_math+ )+ plain = typst_string(_fill(skeleton, holes))+ super().__init__(f"$ #eval({plain}, {_MITEX}) $", **kwargs)+ boxed = _fill(+ skeleton,+ {i: f'#manimgrp("p{i}", ${code}$)' for i, code in holes.items()},+ )self._regroup_by_twin(- f"$ #eval({typst_string(formula[1])}, {_MITEX} + (manimgrp:"- " manimgrp)) $",- formula[2],- kwargs["typst_preamble"],- kwargs.get("font_paths"),- kwargs.get("package_path"),+ layout(+ f"$ #eval({typst_string(boxed)}, {_MITEX} + (manimgrp: manimgrp)) $"+ ),+ set(holes),+ )+ else: # a part's box would drop to text style; keep display style+ parts = " ".join(+ f'#manimgrp("p{i}", $display(#{_math(_standalone(s))})$)'+ for i, s in enumerate(self.tex_strings))+ super().__init__(f"$ {parts} $", **kwargs)+ self._regroup_by_labels()for tex, c in self.tex_to_color_map.items():self.set_color_by_tex(tex, c)- def _set(self, parts: list[str]) -> str:- """The text parts (Typst expressions, each a labelled group) as the document sets them:- one run of text, centered in the "center" environment."""- joined = " ".join(f"#{part}" for part in parts)- return (- f"#align(center)[{joined}]" if self.tex_environment == "center" else joined- )+ def _compose(+ self, strings: list[str], separator: str+ ) -> tuple[str, dict[int, int], str | None]:+ """The strings as one text, joined by `separator`, set as the document sets it (see+ `_set`): the document's body; where in it the code of each string that stands on its+ own (a hole, see `_one_formula`) starts, and the string's index; and the whole as one+ text, which the body must draw exactly (None if no string is told apart).++ Each hole's code is evaluated on its own and bound to a name, which the code of the+ joined text calls in the hole's place, so every glyph comes from the code of the+ string that drew it, and Typst shapes the text across them as it shapes the whole.+ """+ if len(strings) < 2: # nothing to tell apart+ return self._set(_text(separator.join(strings))), {}, None+ whole, skeleton, holes = _one_formula(strings, separator, _engine.mitex_text)+ if not holes:+ return self._set(_markup(whole)), {}, None+ bindings, starts = _bindings(_in_place(skeleton, holes))+ called = _fill(skeleton, {i: f"#p{i};" for i in holes})+ text = _markup(called, "".join(f"p{i}: p{i}, " for i in holes))+ return bindings + self._set(text), starts, self._set(_markup(whole))++ def _set(self, text: str) -> str:+ """The text (a Typst expression of its content) as the document sets it: centered+ in the "center" environment."""+ if self.tex_environment == "center":+ return f"#align(center)[#{text}]"+ return f"#{text}"++ def _owners(self, layout: Layout, starts: Mapping[int, int]) -> dict[int, int]:+ """The string each item of the layout came from, if it came from a string's code+ (where it starts in the body, `starts`): a glyph or shape the code drew, or one+ drawn within an element of it (a radical within an equation)."""+ nodes = (layout.rows[:, NODE.start].astype(np.int64) - layout.body).tolist()+ return {k: starts[node] for k, node in enumerate(nodes) if node in starts}++ def _regroup(self, owners: Mapping[int, int], holes: Collection[int]) -> None:+ """The parts: each string's own items (`owners`, the item's index to the string's),+ and every other item to the first string that is not a hole between the strings+ whose items are around it; else to the one before (the first, before any)."""+ count, leaves = len(self.tex_strings), list(self.submobjects)+ if not count:+ return+ groups: list[list[Mobject]] = [[] for _ in range(count)]+ start, before = 0, -1+ for k in range(len(leaves) + 1):+ owner = count if k == len(leaves) else owners.get(k)+ if owner is None:+ continue+ if start < k: # this run lies between the same two strings' items+ fragment = next(+ (i for i in range(before + 1, owner) if i not in holes),+ max(before, 0),+ )+ groups[fragment].extend(leaves[start:k])+ if k < len(leaves):+ groups[owner].append(leaves[k])+ start, before = k + 1, owner+ self.submobjects = [+ MathTexPart(s, *members)+ for s, members in zip(self.tex_strings, groups, strict=True)+ ]def _regroup_by_labels(self) -> None:groups: list[Mobject] = []@@ -1442,55 +1565,23 @@ class MathTex(Typst):if any(len(g) for g in groups):self.submobjects = groups- def _regroup_by_twin(- self,- twin: str,- holes: set[int],- preamble: str,- font_paths: list[str | Path] | None,- package_path: str | Path | None,- ) -> None:+ def _regroup_by_twin(self, twin: Layout, holes: set[int]) -> None:"""Parts from the formula's boxed twin, which draws what the formula draws in the sameorder: a hole's glyphs and shapes are labelled; the rest belong to the piece betweenthe holes around them (the first, if several are)."""- other = typeset(- twin, preamble, font_paths=font_paths, package_path=package_path- )- rows = other.rows- leaves = list(self.submobjects)+ rows, leaves = twin.rows, self.submobjectsif len(rows) != len(leaves) or any((row[KIND] == GLYPH) != isinstance(leaf, TypstGlyph)for row, leaf in zip(rows, leaves, strict=True)):- raise ValueError(- f"MathTex cannot tell these parts apart: {self.tex_strings}"- )- hole_of = {+ raise ValueError(f"cannot tell these parts apart: {self.tex_strings}")+ labelled = {row: int(label[1:])- for label, members in other.labels+ for label, members in twin.labelsif label.startswith("p") and label[1:].isdigit()for row in members}- count = len(self.tex_strings)- groups: list[list[Mobject]] = [[] for _ in range(count)]- start, before = 0, -1- for k in range(len(leaves) + 1):- hole = count if k == len(leaves) else hole_of.get(k)- if hole is None:- continue- if start < k: # this unlabelled run lies between the same two holes- piece = next(- (i for i in range(before + 1, hole) if i not in holes),- max(before, 0),- )- groups[piece].extend(leaves[start:k])- if k < len(leaves):- groups[hole].append(leaves[k])- start, before = k + 1, hole- self.submobjects = [- MathTexPart(s, *members)- for s, members in zip(self.tex_strings, groups, strict=True)- ]+ self._regroup(labelled, holes)def get_parts_by_tex(self, tex: str, substring: bool = True, case_sensitive: bool = True@@ -1617,7 +1708,9 @@ class MathTex(Typst):return self-def _split(s: str, isolate: list[str]) -> list[str]:+def _split(s: str, isolate: list[str], math: bool) -> list[str]:+ """The string split around each isolated substring; in math, where spaces mean+ nothing, without the parts that are only spaces."""parts = [s]for sub in sorted(isolate, key=len, reverse=True):out: list[str] = []@@ -1632,7 +1725,7 @@ def _split(s: str, isolate: list[str]) -> list[str]:if k < len(pieces) - 1:out.append(sub)parts = out- return [p for p in parts if p.strip()]+ return [p for p in parts if (p.strip() if math else p)]class Tex(MathTex):@@ -1642,13 +1735,15 @@ class Tex(MathTex):It is a [MathTex][manimgx.MathTex] that reads its strings as LaTeX text: bold(`\textbf`), italics (`\emph`, `\textit`), line breaks (`\\`) and inline mathconvert. The text is set in New Computer Modern, as LaTeX sets it, the math in New- Computer Modern Math; white unless styled. The strings are typeset one after- another, each on its own, a space apart; if one doesn't typeset on its own, the- text is typeset whole, and its glyphs are the first part's.+ Computer Modern Math; white unless styled. The strings are one text, joined by+ `arg_separator` (nothing, by default) and typeset whole, as a MathTex's are one+ formula: `Tex("Fade", "In")` reads "FadeIn", and parting a text moves none of its+ glyphs. Its parts are told apart as a formula's are; a ligature two strings share is+ the first's.Args:*tex_strings: The text, in LaTeX: a string per part.- **kwargs: [MathTex keywords][manimgx.mobjects.text.MathTexOptions]:+ **kwargs: [MathTex keywords][manimgx.MathTex]:the strings are joined by "" and read in a "center" environment unless`arg_separator` and `tex_environment` say otherwise.@@ -1729,13 +1824,25 @@ class BulletedList(Tex):)kwargs.setdefault("tex_environment", None)super().__init__(*items, **kwargs)- # the bullets, one glyph each, in their items' order- bullets = self.labels.get(_BULLET, VGroup())- for part, bullet in zip(self.submobjects, bullets.submobjects, strict=True):- part.add_to_back(bullet)- def _set(self, parts: list[str]) -> str:- return f"#list({', '.join(parts)})"+ def _compose(+ self, strings: list[str], separator: str+ ) -> tuple[str, dict[int, int], str | None]:+ """The items as a Typst list, each item's code bound to its name, as a Tex binds a+ string's (see `MathTex._compose`): every glyph comes from its item's code."""+ codes = {i: _engine.mitex_text(s) for i, s in enumerate(strings)}+ bindings, starts = _bindings(codes)+ items = ", ".join(f"p{i}" for i in codes)+ return f"{bindings}#list({items})", starts, None++ def _owners(self, layout: Layout, starts: Mapping[int, int]) -> dict[int, int]:+ """Each item's glyphs, and its bullet: one glyph, in its own labelled box, the+ items' bullets in their order."""+ owners = super()._owners(layout, starts)+ bullets = (rows for label, rows in layout.labels if label == _BULLET)+ for item, rows in enumerate(bullets):+ owners |= dict.fromkeys(rows, item)+ return ownersdef fade_all_but(self, index: int, opacity: float = 0.5) -> Self:"""Fade every item but one: the others' fill to `opacity`, the one's to 1.diff --git a/tests/unit/mobjects/test_svg.py b/tests/unit/mobjects/test_svg.pynew file mode 100644index 00000000..98ba5640--- /dev/null+++ b/tests/unit/mobjects/test_svg.py@@ -0,0 +1,192 @@+"""An SVG drawing remembered is the drawing made afresh.++Whatever was made before it — the same file in other sizes and looks, the file before an edit+that kept its size and time, a class of the same name, a conversion whose input in its hash+seed or whose XML hook's content has changed since, options changed in place since, settings+equal to the last ones up to their repr — the drawing the cache gives is the one converting+the file anew gives: the same parts, points and paint, and the same named groups of them.+"""++import os+from collections.abc import Callable+from pathlib import Path+from typing import ClassVar+from xml.etree import ElementTree as ET++import numpy as np+import pytest+import svgelements as se++import manimgx as m+from manimgx.drawing.paint import Look, Repaint+from manimgx.mobjects.svg import PathOptions++# a row: what is made first (and so remembered), and then the drawing, cached or not+type Row = Callable[[Path], Callable[[bool], m.SVGMobject]]+++def drawing(tmp_path: Path) -> Path:+ path = tmp_path / "drawing.svg"+ path.write_text(+ '<svg xmlns="http://www.w3.org/2000/svg">'+ '<g id="outer"><g id="inner" transform="rotate(15)">'+ '<rect x="2" y="1" width="6" height="3" rx="1" fill="#58c4dd"/>'+ '<circle cx="12" cy="5" r="3" stroke="#ffffff" stroke-width="2"/>'+ '<path d="M1 1 Q3 3 4 1 L4 0 Z" fill="#83c167"/>'+ "</g></g></svg>",+ encoding="utf-8",+ )+ return path+++def _sized(height: float | None, width: float | None, centered: bool) -> Row:+ def row(path: Path) -> Callable[[bool], m.SVGMobject]:+ m.SVGMobject(path, sheen_factor=0.2, sheen_direction=m.LEFT)+ look: Look = {+ "sheen_factor": 0.8,+ "sheen_direction": m.UP,+ "background_stroke_color": m.RED,+ "background_stroke_width": 3,+ }+ return lambda cache: m.SVGMobject(+ path,+ height=height,+ width=width,+ should_center=centered,+ use_svg_cache=cache,+ **look,+ )++ return row+++def _edited(path: Path) -> Callable[[bool], m.SVGMobject]:+ before = m.SVGMobject(path, height=None)+ stat = path.stat()+ path.write_text(+ path.read_text(encoding="utf-8").replace('width="6"', 'width="9"'),+ encoding="utf-8",+ )+ os.utime(path, ns=(stat.st_atime_ns, stat.st_mtime_ns)) # (the same size and time)+ assert (+ m.SVGMobject(path, height=None, use_svg_cache=False)[0].width != before[0].width+ )+ return lambda cache: m.SVGMobject(path, height=None, use_svg_cache=cache)+++def _same_name(path: Path) -> Callable[[bool], m.SVGMobject]:+ def scaled(factor: float) -> type[m.SVGMobject]:+ class Drawing(m.SVGMobject):+ @staticmethod+ def rect_to_mobject(rect: se.Rect) -> m.Rectangle:+ return m.SVGMobject.rect_to_mobject(rect).scale(factor)++ return Drawing++ scaled(1)(path, height=None)+ large = scaled(2)+ return lambda cache: large(path, height=None, use_svg_cache=cache)+++def _reseeded(path: Path) -> Callable[[bool], m.SVGMobject]:+ class Scaled(m.SVGMobject): # (a conversion's input, in its hash seed)+ factor: ClassVar[float] = 1.0++ @property+ def hash_seed(self) -> tuple[object, ...]:+ return (*super().hash_seed, self.factor)++ @staticmethod+ def rect_to_mobject(rect: se.Rect) -> m.Rectangle:+ return m.SVGMobject.rect_to_mobject(rect).scale(Scaled.factor)++ Scaled(path, height=None)+ Scaled.factor = 2.0+ return lambda cache: Scaled(path, height=None, use_svg_cache=cache)+++def _rewritten(path: Path) -> Callable[[bool], m.SVGMobject]:+ class Inked(m.SVGMobject):+ def __init__(self, path: Path, ink: str, use_svg_cache: bool = True) -> None:+ self.ink = ink+ super().__init__(path, use_svg_cache=use_svg_cache)++ def modify_xml_tree(+ self, element_tree: ET.ElementTree[ET.Element]+ ) -> ET.ElementTree[ET.Element]:+ for element in element_tree.iter():+ element.set("fill", self.ink)+ return super().modify_xml_tree(element_tree)++ Inked(path, "#ff0000")+ return lambda cache: Inked(path, "#0000ff", use_svg_cache=cache)+++def _changed_in_place(path: Path) -> Callable[[bool], m.SVGMobject]:+ defaults: Repaint = {"stroke_width": 2, "stroke_color": m.RED}+ options: PathOptions = {+ "sheen_factor": 0.2,+ "sheen_direction": np.array([1.0, 2.0, 3.0]),+ }+ m.SVGMobject(path, svg_default=defaults, path_string_config=options)+ defaults["stroke_color"] = m.BLUE+ options["sheen_direction"] = np.array([-1.0, 3.0, 2.0])+ return lambda cache: m.SVGMobject(+ path, svg_default=defaults, path_string_config=options, use_svg_cache=cache+ )+++def _precise(path: Path) -> Callable[[bool], m.SVGMobject]:+ first = np.array([1.0, 1.0, 0.0])+ second = np.array([1.0 + 2**-40, 1.0, 0.0])+ assert repr(first) == repr(second)+ m.SVGMobject(path, path_string_config={"sheen_direction": first})+ options: PathOptions = {"sheen_direction": second}+ return lambda cache: m.SVGMobject(+ path, path_string_config=options, use_svg_cache=cache+ )+++ROWS: dict[str, Row] = {+ **{+ f"sized {height}×{width}{', centered' if centered else ''}": _sized(+ height, width, centered+ )+ for height, width in ((None, None), (2, None), (None, 4), (3, 2))+ for centered in (False, True)+ },+ "edited, its size and time kept": _edited,+ "a class of the same name": _same_name,+ "a conversion's input in its hash seed changed": _reseeded,+ "a hook's content changed": _rewritten,+ "options changed in place": _changed_in_place,+ "settings equal up to their repr": _precise,+}+++def _assert_same(actual: m.SVGMobject, expected: m.SVGMobject) -> None:+ assert len(actual) == len(expected)+ for ours, theirs in zip(actual.get_family(), expected.get_family(), strict=True):+ np.testing.assert_array_equal(ours.points, theirs.points)+ for name in ("fill", "stroke", "background", "sheen_direction"):+ np.testing.assert_array_equal(+ getattr(ours.paint, name), getattr(theirs.paint, name)+ )+ for name in ("stroke_width", "background_width", "sheen_factor"):+ assert getattr(ours.paint, name) == getattr(theirs.paint, name)+ assert actual.id_to_vgroup_dict.keys() == expected.id_to_vgroup_dict.keys()+ for name, group in actual.id_to_vgroup_dict.items():+ assert [actual.submobjects.index(part) for part in group] == [+ expected.submobjects.index(part)+ for part in expected.id_to_vgroup_dict[name]+ ]++[email protected]("row", sorted(ROWS))+def test_a_remembered_drawing_is_the_drawing_made_afresh(+ drawing: Path, row: str+) -> None:+ make = ROWS[row](drawing)+ _assert_same(make(True), make(False))