A community-maintained Python framework for creating mathematical animations.
Reduce memory allocations when building SVGMobject (#3182)
Kevin Lubick1e8b349e007e
diff --git a/manim/mobject/svg/svg_mobject.py b/manim/mobject/svg/svg_mobject.pyindex e92f1baa4..579bbebf2 100644--- a/manim/mobject/svg/svg_mobject.py+++ b/manim/mobject/svg/svg_mobject.py@@ -12,6 +12,7 @@ import svgelements as sefrom manim import config, loggerfrom ...constants import RIGHT+from ...utils.bezier import get_quadratic_approximation_of_cubicfrom ...utils.images import get_full_vector_image_pathfrom ...utils.iterables import hash_objfrom ..geometry.arc import Circle@@ -497,28 +498,96 @@ class VMobjectFromSVGPath(VMobject, metaclass=ConvertToOpenGL):generate_points = init_pointsdef handle_commands(self) -> None:- segment_class_to_func_map = {- se.Move: (self.start_new_path, ("end",)),- se.Close: (self.close_path, ()),- se.Line: (self.add_line_to, ("end",)),- se.QuadraticBezier: (- self.add_quadratic_bezier_curve_to,- ("control", "end"),- ),- se.CubicBezier: (- self.add_cubic_bezier_curve_to,- ("control1", "control2", "end"),- ),- }+ all_points: list[np.ndarray] = []+ last_move = None+ curve_start = None++ # These lambdas behave the same as similar functions in+ # vectorized_mobject, except they add to a list of points instead+ # of updating this Mobject's numpy array of points. This way,+ # we don't observe O(n^2) behavior for complex paths due to+ # numpy's need to re-allocate memory on every append.+ def move_pen(pt):+ nonlocal last_move, curve_start+ last_move = pt+ if curve_start is None:+ curve_start = last_move++ if self.n_points_per_curve == 4:++ def add_cubic(start, cp1, cp2, end):+ nonlocal all_points+ assert len(all_points) % 4 == 0, len(all_points)+ all_points += [start, cp1, cp2, end]+ move_pen(end)++ def add_quad(start, cp, end):+ add_cubic(start, (start + cp + cp) / 3, (cp + cp + end) / 3, end)+ move_pen(end)++ def add_line(start, end):+ add_cubic(+ start, (start + start + end) / 3, (start + end + end) / 3, end+ )+ move_pen(end)++ else:++ def add_cubic(start, cp1, cp2, end):+ nonlocal all_points+ assert len(all_points) % 3 == 0, len(all_points)+ two_quads = get_quadratic_approximation_of_cubic(+ start,+ cp1,+ cp2,+ end,+ )+ all_points += two_quads[:3].tolist()+ all_points += two_quads[3:].tolist()+ move_pen(end)++ def add_quad(start, cp, end):+ nonlocal all_points+ assert len(all_points) % 3 == 0, len(all_points)+ all_points += [start, cp, end]+ move_pen(end)++ def add_line(start, end):+ add_quad(start, (start + end) / 2, end)+ move_pen(end)+for segment in self.path_obj:segment_class = segment.__class__- func, attr_names = segment_class_to_func_map[segment_class]- points = [- _convert_point_to_3d(*segment.__getattribute__(attr_name))- for attr_name in attr_names- ]- func(*points)-- # Get rid of the side effect of trailing "Z M" commands.- if self.has_new_path_started():- self.resize_points(self.get_num_points() - 1)+ if segment_class == se.Move:+ move_pen(_convert_point_to_3d(*segment.end))+ elif segment_class == se.Line:+ add_line(last_move, _convert_point_to_3d(*segment.end))+ elif segment_class == se.QuadraticBezier:+ add_quad(+ last_move,+ _convert_point_to_3d(*segment.control),+ _convert_point_to_3d(*segment.end),+ )+ elif segment_class == se.CubicBezier:+ add_cubic(+ last_move,+ _convert_point_to_3d(*segment.control1),+ _convert_point_to_3d(*segment.control2),+ _convert_point_to_3d(*segment.end),+ )+ elif segment_class == se.Close:+ # If the SVG path naturally ends at the beginning of the curve,+ # we do *not* need to draw a closing line. To account for floating+ # point precision, we use a small value to compare the two points.+ if abs(np.linalg.norm(last_move - curve_start)) > 0.0001:+ add_line(last_move, curve_start)+ curve_start = None+ else:+ raise AssertionError(f"Not implemented: {segment_class}")++ self.points = np.array(all_points, ndmin=2, dtype="float64")+ # If we have no points, make sure the array is shaped properly+ # (0 rows tall by 3 columns wide) so future operations can+ # add or remove points correctly.+ if len(all_points) == 0:+ self.points = np.reshape(self.points, (0, 3))diff --git a/tests/module/mobject/svg/test_svg_mobject.py b/tests/module/mobject/svg/test_svg_mobject.pyindex 116feb9e3..4568b51b2 100644--- a/tests/module/mobject/svg/test_svg_mobject.py+++ b/tests/module/mobject/svg/test_svg_mobject.py@@ -56,3 +56,83 @@ def test_stroke_overrides_color():stroke_color=expected_color,)assert svg.stroke_color == Color(expected_color)+++def test_single_path_turns_into_sequence_of_points():+ svg = SVGMobject(+ get_svg_resource("cubic_and_lineto.svg"),+ )+ assert len(svg.points) == 0, svg.points+ assert len(svg.submobjects) == 1, svg.submobjects+ path = svg.submobjects[0]+ np.testing.assert_almost_equal(+ path.points,+ np.array(+ [+ [-0.166666666666666, 0.66666666666666, 0.0],+ [-0.166666666666666, 0.0, 0.0],+ [0.5, 0.66666666666666, 0.0],+ [0.5, 0.0, 0.0],+ [0.5, 0.0, 0.0],+ [-0.16666666666666666, 0.0, 0.0],+ [0.5, -0.6666666666666666, 0.0],+ [-0.166666666666666, -0.66666666666666, 0.0],+ [-0.166666666666666, -0.66666666666666, 0.0],+ [-0.27777777777777, -0.77777777777777, 0.0],+ [-0.38888888888888, -0.88888888888888, 0.0],+ [-0.5, -1.0, 0.0],+ [-0.5, -1.0, 0.0],+ [-0.5, -0.333333333333, 0.0],+ [-0.5, 0.3333333333333, 0.0],+ [-0.5, 1.0, 0.0],+ [-0.5, 1.0, 0.0],+ [-0.38888888888888, 0.8888888888888, 0.0],+ [-0.27777777777777, 0.7777777777777, 0.0],+ [-0.16666666666666, 0.6666666666666, 0.0],+ ]+ ),+ decimal=5,+ )+++def test_closed_path_does_not_have_extra_point():+ # This dash.svg is the output of a "-" as generated from LaTex.+ # It ends back where it starts, so we shouldn't see a final line.+ svg = SVGMobject(+ get_svg_resource("dash.svg"),+ )+ assert len(svg.points) == 0, svg.points+ assert len(svg.submobjects) == 1, svg.submobjects+ dash = svg.submobjects[0]+ np.testing.assert_almost_equal(+ dash.points,+ np.array(+ [+ [13.524988331417841, -1.0, 0],+ [14.374988080480586, -1.0, 0],+ [15.274984567359079, -1.0, 0],+ [15.274984567359079, 0.0, 0.0],+ [15.274984567359079, 0.0, 0.0],+ [15.274984567359079, 1.0, 0.0],+ [14.374988080480586, 1.0, 0.0],+ [13.524988331417841, 1.0, 0.0],+ [13.524988331417841, 1.0, 0.0],+ [4.508331116720995, 1.0, 0],+ [-4.508326097975995, 1.0, 0.0],+ [-13.524983312672841, 1.0, 0.0],+ [-13.524983312672841, 1.0, 0.0],+ [-14.374983061735586, 1.0, 0.0],+ [-15.274984567359079, 1.0, 0.0],+ [-15.274984567359079, 0.0, 0.0],+ [-15.274984567359079, 0.0, 0.0],+ [-15.274984567359079, -1.0, 0],+ [-14.374983061735586, -1.0, 0],+ [-13.524983312672841, -1.0, 0],+ [-13.524983312672841, -1.0, 0],+ [-4.508326097975995, -1.0, 0],+ [4.508331116720995, -1.0, 0],+ [13.524988331417841, -1.0, 0],+ ]+ ),+ decimal=5,+ )diff --git a/tests/test_graphical_units/img_svg_resources/dash.svg b/tests/test_graphical_units/img_svg_resources/dash.svgnew file mode 100644index 000000000..529ab2b09--- /dev/null+++ b/tests/test_graphical_units/img_svg_resources/dash.svg@@ -0,0 +1,10 @@+<?xml version='1.0' encoding='UTF-8'?>+<!-- This file was generated by dvisvgm 2.11.1 -->+<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' width='7.748748pt' height='6.641773pt' viewBox='167.98117 -5.811546 7.748748 6.641773'>+ <defs>+ <path id='g0-0' d='M6.56538-2.291407C6.734745-2.291407 6.914072-2.291407 6.914072-2.49066S6.734745-2.689913 6.56538-2.689913H1.175592C1.006227-2.689913 .826899-2.689913 .826899-2.49066S1.006227-2.291407 1.175592-2.291407H6.56538Z'/>+ </defs>+ <g id='page1'>+ <use x='167.98117' y='0' xlink:href='#g0-0'/>+ </g>+</svg>