A community-maintained Python framework for creating mathematical animations.
Add SVG elliptical arc support (#1475)
Newell Jensen57a90b79be0d
diff --git a/manim/mobject/svg/svg_path.py b/manim/mobject/svg/svg_path.pyindex 289847c5f..c69edba81 100644--- a/manim/mobject/svg/svg_path.py+++ b/manim/mobject/svg/svg_path.py@@ -5,6 +5,7 @@ __all__ = ["SVGPathMobject", "string_to_numbers", "VMobjectFromSVGPathstring"]import re+from math import *from typing import Listimport numpy as np@@ -16,6 +17,172 @@ from ...constants import *from ...mobject.types.vectorized_mobject import VMobject+def correct_out_of_range_radii(rx, ry, x1p, y1p):+ """Correction of out-of-range radii.++ See: https://www.w3.org/TR/SVG11/implnote.html#ArcCorrectionOutOfRangeRadii+ """+ # Step 1: Ensure radii are non-zero (taken care of in elliptical_arc_to_cubic_bezier).+ # Step 2: Ensure radii are positive. If rx or ry have negative signs, these are dropped;+ # the absolute value is used instead.+ rx = abs(rx)+ ry = abs(ry)+ # Step 3: Ensure radii are large enough.+ Lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry)+ if Lambda > 1:+ rx = sqrt(Lambda) * rx+ ry = sqrt(Lambda) * ry++ # Step 4: Proceed with computations.+ return rx, ry+++def vector_angle(ux, uy, vx, vy):+ """Calculate the dot product angle between two vectors.++ This clamps the argument to the arc cosine due to roundoff errors+ from some SVG files.+ """+ sign = -1 if ux * vy - uy * vx < 0 else 1+ ua = sqrt(ux * ux + uy * uy)+ va = sqrt(vx * vx + vy * vy)+ dot = ux * vx + uy * vy++ # Clamp argument between [-1,1].+ return sign * acos(max(min(dot / (ua * va), 1), -1))+++def get_elliptical_arc_center_parameters(x1, y1, rx, ry, phi, fA, fS, x2, y2):+ """Conversion from endpoint to center parameterization.++ See: https://www.w3.org/TR/SVG11/implnote.html#ArcConversionEndpointToCenter+ """+ cos_phi = cos(phi)+ sin_phi = sin(phi)+ # Step 1: Compute (x1p,y1p).+ x = (x1 - x2) / 2+ y = (y1 - y2) / 2+ x1p = x * cos_phi + y * sin_phi+ y1p = -x * sin_phi + y * cos_phi++ # Correct out of range radii+ rx, ry = correct_out_of_range_radii(rx, ry, x1p, y1p)++ # Step 2: Compute (cxp,cyp).+ rx2 = rx * rx+ ry2 = ry * ry+ x1p2 = x1p * x1p+ y1p2 = y1p * y1p+ k = sqrt(max((rx2 * ry2 - rx2 * y1p2 - ry2 * x1p2) / (rx2 * y1p2 + ry2 * x1p2), 0))+ sign = -1 if fA == fS else 1+ cxp = sign * k * (rx * y1p) / ry+ cyp = sign * k * (-ry * x1p) / rx++ # Step 3: Compute (cx,cy) from (cxp,cyp).+ x = (x1 + x2) / 2+ y = (y1 + y2) / 2+ cx = cxp * cos_phi - cyp * sin_phi + x+ cy = cxp * sin_phi + cyp * cos_phi + y++ # Step 4: Compute theta1 and dtheta.+ x = (x1p - cxp) / rx+ y = (y1p - cyp) / ry+ theta1 = vector_angle(1, 0, x, y)++ x_ = (-x1p - cxp) / rx+ y_ = (-y1p - cyp) / ry+ dtheta = degrees(vector_angle(x, y, x_, y_)) % 360++ if fS == 0 and dtheta > 0:+ dtheta -= 360+ elif fS == 1 and dtheta < 0:+ dtheta += 360++ return cx, cy, theta1, radians(dtheta)+++def elliptical_arc_to_cubic_bezier(x1, y1, rx, ry, phi, fA, fS, x2, y2):+ """Generate cubic bezier points to approximate SVG elliptical arc.++ See: http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes+ """+ ## Out of range parameters+ # See: https://www.w3.org/TR/SVG11/implnote.html#ArcOutOfRangeParameters+ # If rx or ry are 0 then this arc is treated as a+ # straight line segment (a "lineto") joining the endpoints.+ if not rx or not ry:+ return [x1, y1, x2, y2, x2, y2]++ # phi is taken mod 360 degrees and set to radians for subsequent calculations.+ phi = radians(phi % 360)++ # Any nonzero value for either of the flags fA or fS is taken to mean the value 1.+ fA = 1 if fA else 0+ fS = 1 if fS else 0++ # Convert from endpoint to center parameterization.+ cx, cy, theta1, dtheta = get_elliptical_arc_center_parameters(+ x1, y1, rx, ry, phi, fA, fS, x2, y2+ )++ # For a given arc we should "chop" it up into segments if it is too big+ # to help miminze cubic bezier curve approximation errors.+ # If dtheta is a multiple of 90 degrees, set the limit to 90 degrees,+ # otherwise 360/10=36 degrees is a decent sweep limit.+ if degrees(dtheta) % 90 == 0:+ sweep_limit = 90+ else:+ sweep_limit = 36++ segments = int(ceil(abs(degrees(dtheta)) / sweep_limit))+ segment = dtheta / float(segments)+ current_angle = theta1+ start_x = x1+ start_y = y1+ cos_phi = cos(phi)+ sin_phi = sin(phi)+ alpha = sin(segment) * (sqrt(4 + 3 * pow(tan(segment / 2.0), 2)) - 1) / 3.0+ bezier_points = []++ # Calculate the cubic bezier points from elliptical arc parametric equations.+ # See: (the box on page 18) http://www.spaceroots.org/documents/ellipse/elliptical-arc.pdf+ for idx in range(segments):+ next_angle = current_angle + segment++ cos_start = cos(current_angle)+ sin_start = sin(current_angle)++ e1x = -rx * cos_phi * sin_start - ry * sin_phi * cos_start+ e1y = -rx * sin_phi * sin_start + ry * cos_phi * cos_start+ q1_x = start_x + alpha * e1x+ q1_y = start_y + alpha * e1y++ cos_end = cos(next_angle)+ sin_end = sin(next_angle)++ p2x = cx + rx * cos_phi * cos_end - ry * sin_phi * sin_end+ p2y = cy + rx * sin_phi * cos_end + ry * cos_phi * sin_end++ end_x = p2x+ end_y = p2y++ if idx == segments - 1:+ end_x = x2+ end_y = y2++ e2x = -rx * cos_phi * sin_end - ry * sin_phi * cos_end+ e2y = -rx * sin_phi * sin_end + ry * cos_phi * cos_end+ q2_x = end_x - alpha * e2x+ q2_y = end_y - alpha * e2y++ bezier_points += [[q1_x, q1_y, 0], [q2_x, q2_y, 0], [end_x, end_y, 0]]+ start_x = end_x+ start_y = end_y+ current_angle = next_angle++ return bezier_points++def string_to_numbers(num_string: str) -> List[float]:"""Parse the SVG string representing a sequence of numbers into an array of floats.@@ -171,7 +338,12 @@ class SVGPathMobject(VMobject):prev_quad_handle = new_quad_handleelif command == "A": # elliptical Arc- raise NotImplementedError()+ # points must be added in groups of 3. See `string_to_points` for+ # case that new_points can be None.+ if new_points is not None:+ for i in range(0, len(new_points), 3):+ self.add_cubic_bezier_curve_to(*new_points[i : i + 3])+ returnelif command == "Z": # closepathif config["renderer"] == "opengl":@@ -202,8 +374,28 @@ class SVGPathMobject(VMobject):# this call to "string to numbers" where problems like parsing 0.5.6 lienumbers = string_to_numbers(coord_string)+ # arcs are weirdest, handle them first.+ if command == "A":+ # We have to handle offsets here because ellipses are complicated.+ if is_relative:+ numbers[5] += start_point[0]+ numbers[6] += start_point[1]++ # If the endpoints (x1, y1) and (x2, y2) are identical, then this+ # is equivalent to omitting the elliptical arc segment entirely.+ # for more information of where this math came from visit:+ # http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes+ if start_point[0] == numbers[5] and start_point[1] == numbers[6]:+ return++ result = np.array(+ elliptical_arc_to_cubic_bezier(*start_point[:2], *numbers)+ )++ return result+# H and V expect a sequence of single coords, not coord pairs like the rest of the commands.- if command == "H":+ elif command == "H":result = np.zeros((len(numbers), self.dim))result[:, 0] = numbersif not is_relative:@@ -215,9 +407,6 @@ class SVGPathMobject(VMobject):if not is_relative:result[:, 0] = start_point[0]- elif command == "A":- raise NotImplementedError("Arcs are not implemented.")-else:num_points = len(numbers) // 2result = np.zeros((num_points, self.dim))diff --git a/manim/mobject/types/vectorized_mobject.py b/manim/mobject/types/vectorized_mobject.pyindex ae0a9d1b2..7e512949a 100644--- a/manim/mobject/types/vectorized_mobject.py+++ b/manim/mobject/types/vectorized_mobject.py@@ -247,9 +247,7 @@ class VMobject(Mobject):)if sheen_factor:self.set_sheen(- factor=sheen_factor,- direction=sheen_direction,- family=family,+ factor=sheen_factor, direction=sheen_direction, family=family)if background_image:self.color_using_background_image(background_image)@@ -312,17 +310,10 @@ class VMobject(Mobject):def fade(self, darkness=0.5, family=True):factor = 1.0 - darkness- self.set_fill(- opacity=factor * self.get_fill_opacity(),- family=False,- )- self.set_stroke(- opacity=factor * self.get_stroke_opacity(),- family=False,- )+ self.set_fill(opacity=factor * self.get_fill_opacity(), family=False)+ self.set_stroke(opacity=factor * self.get_stroke_opacity(), family=False)self.set_background_stroke(- opacity=factor * self.get_stroke_opacity(background=True),- family=False,+ opacity=factor * self.get_stroke_opacity(background=True), family=False)super().fade(darkness, family)return self@@ -371,6 +362,8 @@ class VMobject(Mobject):width = self.background_stroke_widthelse:width = self.stroke_width+ if isinstance(width, str):+ width = int(width)return max(0, width)def get_stroke_opacity(self, background=False):@@ -1070,14 +1063,7 @@ class VMobject(Mobject):if self.points.shape[0] == 1:return self.pointsreturn np.array(- list(- it.chain(- *zip(- self.get_start_anchors(),- self.get_end_anchors(),- )- )- )+ list(it.chain(*zip(self.get_start_anchors(), self.get_end_anchors()))))def get_points_defining_boundary(self):diff --git a/tests/control_data/graphical_units_data/img_and_svg/Arcs01Test.npz b/tests/control_data/graphical_units_data/img_and_svg/Arcs01Test.npznew file mode 100644index 000000000..5426da05aBinary files /dev/null and b/tests/control_data/graphical_units_data/img_and_svg/Arcs01Test.npz differdiff --git a/tests/control_data/graphical_units_data/img_and_svg/Arcs02Test.npz b/tests/control_data/graphical_units_data/img_and_svg/Arcs02Test.npznew file mode 100644index 000000000..5850444a8Binary files /dev/null and b/tests/control_data/graphical_units_data/img_and_svg/Arcs02Test.npz differdiff --git a/tests/control_data/graphical_units_data/img_and_svg/HalfEllipseTest.npz b/tests/control_data/graphical_units_data/img_and_svg/HalfEllipseTest.npznew file mode 100644index 000000000..931e62f00Binary files /dev/null and b/tests/control_data/graphical_units_data/img_and_svg/HalfEllipseTest.npz differdiff --git a/tests/test_graphical_units/img_svg_resources/arcs01.svg b/tests/test_graphical_units/img_svg_resources/arcs01.svgnew file mode 100644index 000000000..9e4b9a577--- /dev/null+++ b/tests/test_graphical_units/img_svg_resources/arcs01.svg@@ -0,0 +1,24 @@+<?xml version="1.0" standalone="no"?>+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"+ "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">+<svg width="12cm" height="5.25cm" viewBox="0 0 1200 400"+ xmlns="http://www.w3.org/2000/svg" version="1.1">+ <title>Example arcs01 - arc commands in path data</title>+ <desc>Picture of a pie chart with two pie wedges and+ a picture of a line with arc blips</desc>+ <rect x="1" y="1" width="1198" height="398"+ fill="none" stroke="blue" stroke-width="1" />++ <path d="M300,200 h-150 a150,150 0 1,0 150,-150 z"+ fill="red" stroke="blue" stroke-width="5" />+ <path d="M275,175 v-150 a150,150 0 0,0 -150,150 z"+ fill="yellow" stroke="blue" stroke-width="5" />++ <path d="M600,350 l 50,-25+ a25,25 -30 0,1 50,-25 l 50,-25+ a25,50 -30 0,1 50,-25 l 50,-25+ a25,75 -30 0,1 50,-25 l 50,-25+ a25,100 -30 0,1 50,-25 l 50,-25"+ fill="none" stroke="red" stroke-width="5" />+</svg>+diff --git a/tests/test_graphical_units/img_svg_resources/arcs02.svg b/tests/test_graphical_units/img_svg_resources/arcs02.svgnew file mode 100644index 000000000..c0bddf955--- /dev/null+++ b/tests/test_graphical_units/img_svg_resources/arcs02.svg@@ -0,0 +1,59 @@+<?xml version="1.0" standalone="no"?>+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"+ "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">+<svg width="12cm" height="5.25cm" viewBox="0 0 1200 525" version="1.1"+ xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">+ <title>Example arcs02 - arc options in paths</title>+ <desc>Pictures showing the result of setting+ large-arc-flag and sweep-flag to the four+ possible combinations of 0 and 1.</desc>+ <g font-family="Verdana" >+ <defs>+ <g id="baseEllipses" font-size="20" >+ <ellipse cx="125" cy="125" rx="100" ry="50"+ fill="none" stroke="#888888" stroke-width="2" />+ <ellipse cx="225" cy="75" rx="100" ry="50"+ fill="none" stroke="#888888" stroke-width="2" />+ <text x="35" y="70">Arc start</text>+ <text x="225" y="145">Arc end</text>+ </g>+ </defs>+ <rect x="1" y="1" width="1198" height="523"+ fill="none" stroke="blue" stroke-width="1" />++ <g font-size="30" >+ <g transform="translate(0,0)">+ <use xlink:href="#baseEllipses"/>+ </g>+ <g transform="translate(400,0)">+ <text x="50" y="210">large-arc-flag=0</text>+ <text x="50" y="250">sweep-flag=0</text>+ <use xlink:href="#baseEllipses"/>+ <path d="M 125,75 a100,50 0 0,0 100,50"+ fill="none" stroke="red" stroke-width="6" />+ </g>+ <g transform="translate(800,0)">+ <text x="50" y="210">large-arc-flag=0</text>+ <text x="50" y="250">sweep-flag=1</text>+ <use xlink:href="#baseEllipses"/>+ <path d="M 125,75 a100,50 0 0,1 100,50"+ fill="none" stroke="red" stroke-width="6" />+ </g>+ <g transform="translate(400,250)">+ <text x="50" y="210">large-arc-flag=1</text>+ <text x="50" y="250">sweep-flag=0</text>+ <use xlink:href="#baseEllipses"/>+ <path d="M 125,75 a100,50 0 1,0 100,50"+ fill="none" stroke="red" stroke-width="6" />+ </g>+ <g transform="translate(800,250)">+ <text x="50" y="210">large-arc-flag=1</text>+ <text x="50" y="250">sweep-flag=1</text>+ <use xlink:href="#baseEllipses"/>+ <path d="M 125,75 a100,50 0 1,1 100,50"+ fill="none" stroke="red" stroke-width="6" />+ </g>+ </g>+ </g>+</svg>+diff --git a/tests/test_graphical_units/img_svg_resources/half_ellipse.svg b/tests/test_graphical_units/img_svg_resources/half_ellipse.svgnew file mode 100644index 000000000..ce98f0afd--- /dev/null+++ b/tests/test_graphical_units/img_svg_resources/half_ellipse.svg@@ -0,0 +1,3 @@+<svg width="100" height="100">+ <path d="M 0 50 L 10 50 A 30 20, 0, 0 0, 90 50 L 100 50" style="stroke:black; fill:yellow" />+</svg>diff --git a/tests/test_graphical_units/test_img_and_svg.py b/tests/test_graphical_units/test_img_and_svg.pyindex 3b09372c6..c55299ee8 100644--- a/tests/test_graphical_units/test_img_and_svg.py+++ b/tests/test_graphical_units/test_img_and_svg.py@@ -100,6 +100,29 @@ class UseTagInheritanceTest(Scene):self.wait()+class HalfEllipseTest(Scene):+ def construct(self):+ half_ellipse = SVGMobject(get_test_resource("half_ellipse.svg"))+ self.add(half_ellipse)+ self.wait()+++class Arcs01Test(Scene):+ # See: https://www.w3.org/TR/SVG11/images/paths/arcs01.svg+ def construct(self):+ arcs = SVGMobject(get_test_resource("arcs01.svg"))+ self.add(arcs)+ self.wait()+++class Arcs02Test(Scene):+ # See: https://www.w3.org/TR/SVG11/images/paths/arcs02.svg+ def construct(self):+ arcs = SVGMobject(get_test_resource("arcs02.svg"))+ self.add(arcs)+ self.wait()++# Second are the visual tests - these are probably too complex to verify step-by-step, so# these are really more of a spot-check