Coverage for src/manimgx/mobjects/svg.py: 95%
260 statements
« prev ^ index » next coverage.py v7.16.1, created at 2026-10-26 05:52 +0000
« prev ^ index » next coverage.py v7.16.1, created at 2026-10-26 05:52 +0000
1# SPDX-FileCopyrightText: 2026 Academa, Inc.
2# SPDX-FileCopyrightText: 2024 the Manim Community Developers
3# SPDX-FileCopyrightText: 2018 3Blue1Brown LLC
4# SPDX-License-Identifier: MIT
6"""SVG as mobjects: a file's shapes (`SVGMobject`), and one path's curves (a brace, the logo's
7letters). Ported from Manim CE 0.21 (MIT)."""
9from __future__ import annotations
11import io
12import logging
13import os
14from collections.abc import Sequence
15from copy import copy
16from pathlib import Path
17from typing import TYPE_CHECKING, Self, Unpack
18from warnings import deprecated
19from xml.etree import ElementTree as ET
21import numpy as np
23from manimgx.caches import Memo
24from manimgx.constants import RIGHT
25from manimgx.drawing.geometry import Blend
26from manimgx.drawing.paint import BLACK, Colors, Look, Repaint, Style, _Style, key_of
27from manimgx.mobject import VGroup, VMobject, copied
28from manimgx.mobjects.shapes import Circle, Line, Polygon, Rectangle, RoundedRectangle
30if TYPE_CHECKING: # svgelements loads when an SVG is read (few scenes read one)
31 import svgelements as se
33__all__ = ["SVGMobject", "VMobjectFromSVGPath"]
34logger = logging.getLogger("manimgx")
36_DRAWINGS: Memo[tuple[object, ...], tuple[list[VMobject], dict[str, VGroup]]] = Memo(
37 1 << 8
38)
41def _point(point: se.Point | None) -> np.ndarray:
42 """A path's point, in 3D (a well-formed path has every point it names)."""
43 if point is None:
44 raise ValueError("malformed SVG path: a segment without its point")
45 return np.array([point.x, point.y, 0.0])
48class PathOptions(_Style, total=False):
49 """How an SVG path becomes curves: an [SVGMobject][manimgx.SVGMobject]'s
50 `path_string_config`, the keywords of each path it reads.
52 Beyond these, they take the [style keywords][manimgx.drawing.paint.Style].
53 """
55 long_lines: bool
56 """Accepted for Manim compatibility; ignored (default False)."""
57 should_subdivide_sharp_curves: bool
58 """Accepted for Manim compatibility; ignored (default False)."""
59 should_remove_null_curves: bool
60 """Accepted for Manim compatibility; ignored (default False)."""
63class SVGMobject(VMobject):
64 """A drawing read from an SVG file: each of its shapes a part, painted as the file
65 paints it, 2 units tall unless sized.
67 Paths, lines, rectangles (rounded too), circles, ellipses, polygons and polylines
68 become parts, in the file's order, with the file's fills, strokes and transforms;
69 groups and `<use>` are followed, and text is skipped, with a warning. What the file
70 leaves unpainted takes SVG's defaults, a black fill and no stroke, unless
71 `svg_default` says otherwise. The file's groups are kept by their ids, in
72 [id_to_vgroup_dict][manimgx.SVGMobject.id_to_vgroup_dict].
74 Args:
75 file_name: The SVG file.
76 should_center: Whether the drawing is centered on the origin.
77 height: The height to scale the drawing to, in scene units; None keeps the
78 file's size, a scene unit per SVG unit.
79 width: The width to scale the drawing to, in scene units, after `height` (so it
80 wins); None: as `height` makes it.
81 color: Accepted for Manim compatibility; no effect: the parts keep the file's
82 colors (paint over them with `fill_color` and `stroke_color`, or color what
83 the file leaves unpainted through `svg_default`).
84 opacity: Accepted for Manim compatibility; ignored.
85 fill_color: A fill color for every part; None keeps the file's.
86 fill_opacity: A fill opacity for every part, from 0 to 1; None keeps the file's.
87 stroke_color: A stroke color for every part; None keeps the file's.
88 stroke_opacity: A stroke opacity for every part, from 0 to 1; None keeps the
89 file's.
90 stroke_width: A stroke width for every part, in hundredths of a scene unit;
91 None keeps the file's.
92 svg_default: [Paint keywords][manimgx.drawing.paint.Repaint] for what the file
93 leaves unpainted; None for `{"stroke_width": 0}`: no stroke.
94 path_string_config: [SVG path
95 keywords][manimgx.mobjects.svg.PathOptions] for every path.
96 use_svg_cache: Whether parsed drawings are kept and copied for the same SVG
97 content and path settings. The file is always read for changes.
98 """
100 def __init__(
101 self,
102 file_name: str | os.PathLike[str] | None = None,
103 should_center: bool = True,
104 height: float | None = 2,
105 width: float | None = None,
106 color: Colors | None = None,
107 opacity: float | None = None,
108 fill_color: Colors | None = None,
109 fill_opacity: float | Sequence[float] | None = None,
110 stroke_color: Colors | None = None,
111 stroke_opacity: float | Sequence[float] | None = None,
112 stroke_width: float | None = None,
113 svg_default: Repaint | None = None,
114 path_string_config: PathOptions | None = None,
115 use_svg_cache: bool = True,
116 **kwargs: Unpack[Look],
117 ):
118 super().__init__(stroke_color=None, fill_color=None, **kwargs)
119 self.file_name = Path(file_name) if file_name is not None else None
120 self.should_center = should_center
121 self.svg_height = height
122 self.svg_width = width
123 self.set_color(BLACK if color is None else color)
124 self.opacity = opacity
125 self.fill_color = fill_color
126 self.fill_opacity = fill_opacity
127 self.stroke_color = stroke_color
128 self.stroke_opacity = stroke_opacity
129 self.stroke_width = 0 if stroke_width is None else stroke_width
130 self.id_to_vgroup_dict: dict[str, VGroup] = {}
131 """The drawing's groups, by their ids: each `<g>` element's id names a group of
132 the shapes inside it, and "root" all of them; an element without an id is named
133 "numbered_group_" and a number."""
134 self.svg_default: Repaint = (
135 {"stroke_width": 0} if svg_default is None else svg_default
136 )
137 self.path_string_config: PathOptions = (
138 {} if path_string_config is None else path_string_config
139 )
140 self.init_svg_mobject(use_svg_cache=use_svg_cache)
141 self.set_style(
142 fill_color=fill_color,
143 fill_opacity=fill_opacity,
144 stroke_color=stroke_color,
145 stroke_opacity=stroke_opacity,
146 stroke_width=stroke_width,
147 )
148 self.move_into_position()
150 @deprecated("Manim CE's machinery: the constructor calls it", category=None)
151 def init_svg_mobject(self, use_svg_cache: bool) -> Self:
152 """Build the drawing, reusing parsed parts when caching is enabled."""
153 self.use_svg_cache = use_svg_cache
154 self.generate_mobject()
155 return self
157 @property
158 @deprecated("Manim CE's machinery: the constructor calls it", category=None)
159 def hash_seed(self) -> tuple[object, ...]:
160 """The class and path settings that interpret the SVG content. Subclasses can
161 extend this tuple with other inputs their conversion uses."""
162 return (
163 type(self),
164 key_of(sorted(self.path_string_config.items())),
165 )
167 @deprecated("Manim CE's machinery: the constructor calls it", category=None)
168 def generate_mobject(self) -> Self:
169 """Read the file and add its shapes as parts, flipped so that y points up (SVG's
170 points down). Existing geometry turns with the newly read shapes.
171 """
172 import svgelements as se
174 element_tree = ET.parse(self.get_file_path())
175 buffer = io.BytesIO()
176 self.modify_xml_tree(element_tree).write(buffer)
177 buffer.seek(0)
178 if self.has_points() or self.submobjects:
179 mobjects, self.id_to_vgroup_dict = self.get_mobjects_from(
180 se.SVG.parse(buffer)
181 )
182 self.add(*mobjects)
183 return self.flip(RIGHT)
184 try:
185 key = (buffer.getvalue(), *self.hash_seed) if self.use_svg_cache else None
186 except TypeError:
187 key = None
188 drawing = None if key is None else _DRAWINGS.get(key)
189 if drawing is None:
190 drawing = self.get_mobjects_from(se.SVG.parse(buffer))
191 VGroup(*drawing[0]).flip(RIGHT)
192 if key is not None:
193 _DRAWINGS.keep(key, copied(drawing))
194 else:
195 drawing = copied(drawing)
196 mobjects, mobject_dict = drawing
197 self.flip(RIGHT)
198 self.add(*mobjects)
199 self.id_to_vgroup_dict = mobject_dict
200 return self
202 @deprecated("Manim CE's machinery: the constructor calls it", category=None)
203 def get_file_path(self) -> Path:
204 """Find the SVG file; a mobject made without one raises ValueError.
206 Returns:
207 The file's path.
208 """
209 if self.file_name is None:
210 raise ValueError("Must specify file for SVGMobject")
211 return self.file_name
213 @deprecated("Manim CE's machinery: the constructor calls it", category=None)
214 def modify_xml_tree(
215 self, element_tree: ET.ElementTree[ET.Element]
216 ) -> ET.ElementTree[ET.Element]:
217 """Give the file's root the defaults its attributes leave unspecified, keeping
218 its viewport, transforms, styles and document structure.
220 Args:
221 element_tree: The file, parsed.
223 Returns:
224 A new tree.
225 """
226 root = element_tree.getroot()
227 new_root = ET.Element(root.tag, self.generate_config_style_dict() | root.attrib)
228 new_root.extend(root)
229 return ET.ElementTree(new_root)
231 @deprecated("Manim CE's machinery: the constructor calls it", category=None)
232 def generate_config_style_dict(self) -> dict[str, str]:
233 """The SVG attributes `svg_default` sets: `fill`, `fill-opacity`, `stroke`,
234 `stroke-opacity` and `stroke-width`.
236 Returns:
237 The attributes it gives, as strings, by name.
238 """
239 keys_converting_dict = {
240 "fill": ("color", "fill_color"),
241 "fill-opacity": ("opacity", "fill_opacity"),
242 "stroke": ("color", "stroke_color"),
243 "stroke-opacity": ("opacity", "stroke_opacity"),
244 "stroke-width": ("stroke_width",),
245 }
246 result = {}
247 for svg_key, style_keys in keys_converting_dict.items():
248 for style_key in style_keys:
249 value = self.svg_default.get(style_key)
250 if value is not None:
251 result[svg_key] = str(value)
252 return result
254 @deprecated("Manim CE's machinery: the constructor calls it", category=None)
255 def get_mobjects_from(
256 self, svg: se.SVG
257 ) -> tuple[list[VMobject], dict[str, VGroup]]:
258 """Make a part of every shape of the drawing, in document order, and a group of
259 the parts of each of its groups, named or not.
261 Args:
262 svg: The drawing, as svgelements parses it.
264 Returns:
265 The parts, and the groups by id (an unnamed group numbered; "root" for all
266 the parts).
267 """
268 import svgelements as se
270 shapes = (
271 se.Path,
272 se.SimpleLine,
273 se.Rect,
274 se.Circle,
275 se.Ellipse,
276 se.Polygon,
277 se.Polyline,
278 se.Text,
279 )
280 result: list[VMobject] = []
281 stack: list[tuple[se.SVGElement, int]] = [(svg, 1)]
282 group_id_number = 0
283 vgroup_stack: list[str] = ["root"]
284 vgroups: dict[str, VGroup] = {"root": VGroup()}
285 while stack:
286 element, depth = stack.pop()
287 vgroup_stack = vgroup_stack[0:depth]
288 try:
289 group_name = str((element.values or {})["id"])
290 except Exception:
291 group_name = f"numbered_group_{group_id_number}"
292 group_id_number += 1
293 vgroup_stack.append(group_name)
294 vgroups[group_name] = VGroup()
295 if isinstance(element, (se.Group, se.Use)):
296 stack.extend((subelement, depth + 1) for subelement in element[::-1])
297 try:
298 if isinstance(element, shapes):
299 mob = self.get_mob_from_shape_element(element)
300 if mob is not None:
301 result.append(mob)
302 for parent_name in vgroup_stack[:-1]:
303 vgroups[parent_name].add(mob)
304 except Exception as e:
305 logger.error(f"Exception occurred in 'get_mobjects_from'. Details: {e}")
306 return (result, vgroups)
308 @deprecated("Manim CE's machinery: the constructor calls it", category=None)
309 def get_mob_from_shape_element(self, shape: se.SVGElement) -> VMobject | None:
310 """Make a part of a shape of the drawing, painted and transformed as the file
311 says.
313 Args:
314 shape: The shape, as svgelements parses it.
316 Returns:
317 The part; None for an empty shape, or an element that isn't supported (text).
318 """
319 import svgelements as se
321 if isinstance(shape, se.Path):
322 mob: VMobject | None = self.path_to_mobject(shape)
323 elif isinstance(shape, se.SimpleLine):
324 mob = self.line_to_mobject(shape)
325 elif isinstance(shape, se.Rect):
326 mob = self.rect_to_mobject(shape)
327 elif isinstance(shape, (se.Circle, se.Ellipse)):
328 mob = self.ellipse_to_mobject(shape)
329 elif isinstance(shape, se.Polygon):
330 mob = self.polygon_to_mobject(shape)
331 elif isinstance(shape, se.Polyline):
332 mob = self.polyline_to_mobject(shape)
333 elif isinstance(shape, se.Text):
334 mob = self.text_to_mobject(shape)
335 else:
336 logger.warning(f"Unsupported element type: {type(shape)}")
337 mob = None
338 if mob is None or not mob.has_points():
339 return None
340 if isinstance(shape, se.GraphicObject):
341 self.apply_style_to_mobject(mob, shape)
342 if (
343 isinstance(shape, se.Transformable)
344 and shape.apply
345 and shape.transform is not None
346 ):
347 self.handle_transform(mob, shape.transform)
348 return mob
350 @staticmethod
351 @deprecated("Manim CE's machinery: the constructor calls it", category=None)
352 def handle_transform(mob: VMobject, matrix: se.Matrix) -> VMobject:
353 """Apply an SVG transform to a part: its matrix, then its translation.
355 Args:
356 mob: The part.
357 matrix: The transform, as svgelements gives it.
359 Returns:
360 The part.
361 """
362 mat = np.array([[matrix.a, matrix.c], [matrix.b, matrix.d]])
363 vec = np.array([matrix.e, matrix.f, 0.0])
364 mob.apply_matrix(mat)
365 mob.shift(vec)
366 return mob
368 @staticmethod
369 @deprecated("Manim CE's machinery: the constructor calls it", category=None)
370 def apply_style_to_mobject(mob: VMobject, shape: se.GraphicObject) -> VMobject:
371 """Paint a part as the file paints its shape: its fill, its stroke, their
372 opacities and the stroke's width.
374 Args:
375 mob: The part.
376 shape: The shape, as svgelements parses it.
378 Returns:
379 The part.
380 """
381 stroke, fill = shape.stroke, shape.fill
382 mob.set_style(
383 stroke_width=shape.stroke_width,
384 stroke_color=None if stroke is None else stroke.hexrgb,
385 stroke_opacity=None if stroke is None else stroke.opacity,
386 fill_color=None if fill is None else fill.hexrgb,
387 fill_opacity=None if fill is None else fill.opacity,
388 )
389 return mob
391 @deprecated("Manim CE's machinery: the constructor calls it", category=None)
392 def path_to_mobject(self, path: se.Path) -> VMobjectFromSVGPath:
393 """Make a part of a path, with `path_string_config`.
395 Args:
396 path: The path, as svgelements parses it.
398 Returns:
399 A new [VMobjectFromSVGPath][manimgx.VMobjectFromSVGPath].
400 """
401 return VMobjectFromSVGPath(path, **self.path_string_config)
403 @staticmethod
404 @deprecated("Manim CE's machinery: the constructor calls it", category=None)
405 def line_to_mobject(line: se.SimpleLine) -> Line:
406 """Make a part of a line.
408 Args:
409 line: The line, as svgelements parses it.
411 Returns:
412 A new [Line][manimgx.Line].
413 """
414 x1, y1, x2, y2 = (float(v or 0) for v in (line.x1, line.y1, line.x2, line.y2))
415 return Line(start=np.array([x1, y1, 0.0]), end=np.array([x2, y2, 0.0]))
417 @staticmethod
418 @deprecated("Manim CE's machinery: the constructor calls it", category=None)
419 def rect_to_mobject(rect: se.Rect) -> Rectangle:
420 """Make a part of a rectangle, its corners rounded if the file rounds them.
422 Args:
423 rect: The rectangle, as svgelements parses it.
425 Returns:
426 A new [Rectangle][manimgx.Rectangle] or
427 [RoundedRectangle][manimgx.RoundedRectangle].
428 """
429 x, y, width, height, rx, ry = (
430 float(v or 0)
431 for v in (rect.x, rect.y, rect.width, rect.height, rect.rx, rect.ry)
432 )
433 if rx == 0 or ry == 0:
434 mob = Rectangle(width=width, height=height)
435 else:
436 mob = RoundedRectangle(
437 width=width, height=height * rx / ry, corner_radius=rx
438 )
439 mob.stretch_to_fit_height(height)
440 mob.shift(np.array([x + width / 2, y + height / 2, 0.0]))
441 return mob
443 @staticmethod
444 @deprecated("Manim CE's machinery: the constructor calls it", category=None)
445 def ellipse_to_mobject(ellipse: se.Ellipse | se.Circle) -> Circle:
446 """Make a part of a circle or an ellipse.
448 Args:
449 ellipse: The circle or ellipse, as svgelements parses it.
451 Returns:
452 A new [Circle][manimgx.Circle], stretched for an ellipse.
453 """
454 rx, ry, cx, cy = (
455 float(v or 0) for v in (ellipse.rx, ellipse.ry, ellipse.cx, ellipse.cy)
456 )
457 mob = Circle(radius=rx)
458 if rx != ry:
459 mob.stretch_to_fit_height(2 * ry)
460 mob.shift(np.array([cx, cy, 0.0]))
461 return mob
463 @staticmethod
464 @deprecated("Manim CE's machinery: the constructor calls it", category=None)
465 def polygon_to_mobject(polygon: se.Polygon) -> Polygon:
466 """Make a part of a polygon.
468 Args:
469 polygon: The polygon, as svgelements parses it.
471 Returns:
472 A new [Polygon][manimgx.Polygon].
473 """
474 return Polygon(*(np.array([x, y, 0.0]) for x, y in polygon))
476 @deprecated("Manim CE's machinery: the constructor calls it", category=None)
477 def polyline_to_mobject(self, polyline: se.Polyline) -> VMobject:
478 """Make a part of a polyline: an open path through its points.
480 Args:
481 polyline: The polyline, as svgelements parses it.
483 Returns:
484 A new VMobject.
485 """
486 return VMobject().set_points_as_corners([[x, y, 0.0] for x, y in polyline])
488 @staticmethod
489 @deprecated("Manim CE's machinery: the constructor calls it", category=None)
490 def text_to_mobject(text: se.Text) -> VMobject | None:
491 """Skip a text element: SVG text is not supported, and a warning is logged.
493 Args:
494 text: The text, as svgelements parses it.
496 Returns:
497 None.
498 """
499 logger.warning(f"Unsupported element type: {type(text)}")
500 return None
502 @deprecated("Manim CE's machinery: the constructor calls it", category=None)
503 def move_into_position(self) -> Self:
504 """Center the drawing and scale it to `height` and `width`, as the constructor
505 was asked to.
506 """
507 if self.should_center:
508 self.center()
509 if self.svg_height is not None:
510 self.set(height=self.svg_height)
511 if self.svg_width is not None:
512 self.set(width=self.svg_width)
513 return self
516@deprecated("Manim CE's machinery for SVGMobject: use SVGMobject", category=None)
517class VMobjectFromSVGPath(VMobject):
518 """A path of an SVG drawing, as a mobject: its lines, quadratic and cubic curves,
519 and arcs (approximated by quadratic curves), all made cubic curves.
521 An [SVGMobject][manimgx.SVGMobject] makes one of every path in its file. The points
522 are in the path's own coordinates, a scene unit per SVG unit, and SVG's y axis
523 points down: the path is upside down until flipped, as an SVGMobject flips its
524 drawing.
526 The supplied path is converted once. Editing it later does not affect the drawing;
527 `generate_points` restores the original converted geometry.
529 Args:
530 path_obj: The path, as svgelements parses it (a `svgelements.Path`).
531 long_lines: Accepted for Manim compatibility; ignored.
532 should_subdivide_sharp_curves: Accepted for Manim compatibility; ignored.
533 should_remove_null_curves: Accepted for Manim compatibility; ignored.
534 """
536 def __init__(
537 self,
538 path_obj: se.Path,
539 long_lines: bool = False,
540 should_subdivide_sharp_curves: bool = False,
541 should_remove_null_curves: bool = False,
542 **kwargs: Unpack[Style],
543 ) -> None:
544 import svgelements as se
546 path_obj = copy(path_obj)
547 path_obj.approximate_arcs_with_quads()
548 points: list[np.ndarray] = []
549 pen = start = np.zeros(3)
550 for segment in path_obj:
551 kind = type(segment)
552 if kind is se.Move:
553 pen = start = _point(segment.end)
554 elif kind is se.Line or (
555 kind is se.Close and not np.array_equal(pen, start)
556 ):
557 end = start if kind is se.Close else _point(segment.end)
558 points += [pen, (2 * pen + end) / 3, (pen + 2 * end) / 3, end]
559 pen = end
560 elif isinstance(segment, se.QuadraticBezier):
561 control, end = _point(segment.control), _point(segment.end)
562 points += [pen, (pen + 2 * control) / 3, (2 * control + end) / 3, end]
563 pen = end
564 elif isinstance(segment, se.CubicBezier):
565 end = _point(segment.end)
566 points += [pen, _point(segment.control1), _point(segment.control2), end]
567 pen = end
568 elif kind is not se.Close:
569 raise AssertionError(f"Not implemented: {kind}")
570 source = (
571 np.array(points, ndmin=2, dtype="float64") if points else np.zeros((0, 3))
572 )
573 self._source_geometry = Blend.of(source)
574 super().__init__(**kwargs)
576 def generate_points(self) -> Self:
577 """Restore the geometry converted from the original SVG path."""
578 self._geometry = self._source_geometry
579 return self