text
stringlengths
2.1k
15.6k
line2 : The second line. radius : The radius of the :class:`Arc`. quadrant A sequence of two :class:`int` numbers determining which of the 4 quadrants should be used. The first value indicates whether to anchor the arc on the first line closer to the end point (1) or start point (-1), and the second value functions similarly for the end (1) or start (-1) of the second line. Possibilities: (1,1), (-1,1), (1,-1), (-1,-1). other_angle : Toggles between the two possible angles defined by two points and an arc center. If set to False (default), the arc will always go counterclockwise from the point on line1 until the point on line2 is reached. If set to True, the angle will go clockwise from line1 to line2. dot Allows for a :class:`Dot` in the arc. Mainly used as an convention to indicate a right angle. The dot can be customized in the next three parameters. dot_radius The radius of the :class:`Dot`. If not specified otherwise, this radius will be 1/10 of the arc radius. dot_distance Relative distance from the center to the arc: 0 puts the dot in the center and 1 on the arc itself. dot_color The color of the :class:`Dot`. elbow Produces an elbow-type mobject indicating a right angle, see :class:`RightAngle` for more information and a shorthand. **kwargs Further keyword arguments that are passed to the constructor of :class:`Arc` or :class:`Elbow`. Examples -------- The first example shows some right angles with a dot in the middle while the second example shows all 8 possible angles defined by two lines. .. manim:: RightArcAngleExample :save_last_frame: class RightArcAngleExample(Scene): def construct(self): line1 = Line( LEFT, RIGHT ) line2 = Line( DOWN, UP ) rightarcangles = [ Angle(line1, line2, dot=True), Angle(line1, line2, radius=0.4, quadrant=(1,-1), dot=True, other_angle=True), Angle(line1, line2, radius=0.5, quadrant=(-1,1), stroke_width=8, dot=True, dot_color=YELLOW, dot_radius=0.04, other_angle=True), Angle(line1, line2, radius=0.7, quadrant=(-1,-1), color=RED, dot=True, dot_color=GREEN, dot_radius=0.08), ] plots = VGroup() for angle in rightarcangles: plot=VGroup(line1.copy(),line2.copy(), angle) plots.add(plot) plots.arrange(buff=1.5) self.add(plots) .. manim:: AngleExample :save_last_frame: class AngleExample(Scene): def construct(self): line1 = Line( LEFT + (1/3) * UP, RIGHT + (1/3) * DOWN ) line2 = Line( DOWN + (1/3) * RIGHT, UP + (1/3) * LEFT ) angles = [ Angle(line1, line2), Angle(line1, line2, radius=0.4, quadrant=(1,-1), other_angle=True), Angle(line1, line2, radius=0.5, quadrant=(-1,1), stroke_width=8, other_angle=True), Angle(line1, line2, radius=0.7, quadrant=(-1,-1), color=RED), Angle(line1, line2, other_angle=True), Angle(line1, line2, radius=0.4, quadrant=(1,-1)), Angle(line1, line2, radius=0.5, quadrant=(-1,1), stroke_width=8), Angle(line1, line2, radius=0.7, quadrant=(-1,-1), color=RED, other_angle=True), ] plots = VGroup() for angle in angles: plot=VGroup(line1.copy(),line2.copy(), angle) plots.add(VGroup(plot,SurroundingRectangle(plot, buff=0.3))) plots.arrange_in_grid(rows=2,buff=1) self.add(plots) .. manim:: FilledAngle :save_last_frame: class FilledAngle(Scene): def construct(self): l1 = Line(ORIGIN, 2 * UP + RIGHT).set_color(GREEN) l2 = ( Line(ORIGIN, 2 * UP + RIGHT) .set_color(GREEN) .rotate(-20 * DEGREES, about_point=ORIGIN) ) norm = l1.get_length() a1 = Angle(l1, l2, other_angle=True, radius=norm - 0.5).set_color(GREEN) a2 = Angle(l1, l2, other_angle=True, radius=norm).set_color(GREEN) q1 = a1.points # save all coordinates of points of angle a1 q2 = a2.reverse_direction().points # save all coordinates of points of angle a1 (in reversed direction) pnts = np.concatenate([q1, q2, q1[0].reshape(1, 3)]) # adds points and ensures that path starts and
- 0.5).set_color(GREEN) a2 = Angle(l1, l2, other_angle=True, radius=norm).set_color(GREEN) q1 = a1.points # save all coordinates of points of angle a1 q2 = a2.reverse_direction().points # save all coordinates of points of angle a1 (in reversed direction) pnts = np.concatenate([q1, q2, q1[0].reshape(1, 3)]) # adds points and ensures that path starts and ends at same point mfill = VMobject().set_color(ORANGE) mfill.set_points_as_corners(pnts).set_fill(GREEN, opacity=1) self.add(l1, l2) self.add(mfill) """ def __init__( self, line1: Line, line2: Line, radius: float | None = None, quadrant: AngleQuadrant = (1, 1), other_angle: bool = False, dot: bool = False, dot_radius: float | None = None, dot_distance: float = 0.55, dot_color: ParsableManimColor = WHITE, elbow: bool = False, **kwargs: Any, ) -> None: super().__init__(**kwargs) self.lines = (line1, line2) self.quadrant = quadrant self.dot_distance = dot_distance self.elbow = elbow inter = line_intersection( [line1.get_start(), line1.get_end()], [line2.get_start(), line2.get_end()], ) if radius is None: if quadrant[0] == 1: dist_1 = np.linalg.norm(line1.get_end() - inter) else: dist_1 = np.linalg.norm(line1.get_start() - inter) if quadrant[1] == 1: dist_2 = np.linalg.norm(line2.get_end() - inter) else: dist_2 = np.linalg.norm(line2.get_start() - inter) if np.minimum(dist_1, dist_2) < 0.6: radius = (2 / 3) * np.minimum(dist_1, dist_2) else: radius = 0.4 else: self.radius = radius anchor_angle_1 = inter + quadrant[0] * radius * line1.get_unit_vector() anchor_angle_2 = inter + quadrant[1] * radius * line2.get_unit_vector() if elbow: anchor_middle = ( inter + quadrant[0] * radius * line1.get_unit_vector() + quadrant[1] * radius * line2.get_unit_vector() ) angle_mobject: VMobject = Elbow(**kwargs) angle_mobject.set_points_as_corners( np.array([anchor_angle_1, anchor_middle, anchor_angle_2]), ) else: angle_1 = angle_of_vector(anchor_angle_1 - inter) angle_2 = angle_of_vector(anchor_angle_2 - inter) if not other_angle: start_angle = angle_1 if angle_2 > angle_1: angle_fin = angle_2 - angle_1 else: angle_fin = 2 * np.pi - (angle_1 - angle_2) else: start_angle = angle_1 if angle_2 < angle_1: angle_fin = -angle_1 + angle_2 else: angle_fin = -2 * np.pi + (angle_2 - angle_1) self.angle_value = angle_fin angle_mobject = Arc( radius=radius, angle=self.angle_value, start_angle=start_angle, arc_center=inter, **kwargs, ) if dot: if dot_radius is None: dot_radius = radius / 10 else: self.dot_radius = dot_radius right_dot = Dot(ORIGIN, radius=dot_radius, color=dot_color) dot_anchor = ( inter + (angle_mobject.get_center() - inter) / np.linalg.norm(angle_mobject.get_center() - inter) * radius * dot_distance ) right_dot.move_to(dot_anchor) self.add(right_dot) self.set_points(angle_mobject.points) def get_lines(self) -> VGroup: """Get the lines forming an angle of the :class:`Angle` class. Returns ------- :class:`~.VGroup` A :class:`~.VGroup` containing the lines that form the angle of the :class:`Angle` class. Examples -------- :: >>> line_1, line_2 = Line(ORIGIN, RIGHT), Line(ORIGIN, UR) >>> angle = Angle(line_1, line_2) >>> angle.get_lines() VGroup(Line, Line) """ return VGroup(*self.lines) def get_value(self, degrees: bool = False) -> float: r"""Get the value of an angle of the :class:`Angle` class. Parameters ---------- degrees A boolean to decide the unit (deg/rad) in which the value of the angle is returned. Returns ------- :class:`float` The value in degrees/radians of an angle of the :class:`Angle` class. Examples -------- .. manim:: GetValueExample :save_last_frame: class GetValueExample(Scene): def construct(self): line1 = Line(LEFT+(1/3)*UP, RIGHT+(1/3)*DOWN) line2 = Line(DOWN+(1/3)*RIGHT, UP+(1/3)*LEFT) angle = Angle(line1, line2, radius=0.4) value = DecimalNumber(angle.get_value(degrees=True), unit=r"^{\circ}") value.next_to(angle, UR) self.add(line1, line2, angle, value) """ return self.angle_value / DEGREES if degrees else self.angle_value @staticmethod def from_three_points( A: Point3DLike, B: Point3DLike, C:
Examples -------- .. manim:: GetValueExample :save_last_frame: class GetValueExample(Scene): def construct(self): line1 = Line(LEFT+(1/3)*UP, RIGHT+(1/3)*DOWN) line2 = Line(DOWN+(1/3)*RIGHT, UP+(1/3)*LEFT) angle = Angle(line1, line2, radius=0.4) value = DecimalNumber(angle.get_value(degrees=True), unit=r"^{\circ}") value.next_to(angle, UR) self.add(line1, line2, angle, value) """ return self.angle_value / DEGREES if degrees else self.angle_value @staticmethod def from_three_points( A: Point3DLike, B: Point3DLike, C: Point3DLike, **kwargs: Any ) -> Angle: r"""The angle between the lines AB and BC. This constructs the angle :math:`\\angle ABC`. Parameters ---------- A The endpoint of the first angle leg B The vertex of the angle C The endpoint of the second angle leg **kwargs Further keyword arguments are passed to :class:`.Angle` Returns ------- The Angle calculated from the three points Angle(line1, line2, radius=0.5, quadrant=(-1,1), stroke_width=8), Angle(line1, line2, radius=0.7, quadrant=(-1,-1), color=RED, other_angle=True), Examples -------- .. manim:: AngleFromThreePointsExample :save_last_frame: class AngleFromThreePointsExample(Scene): def construct(self): sample_angle = Angle.from_three_points(UP, ORIGIN, LEFT) red_angle = Angle.from_three_points(LEFT + UP, ORIGIN, RIGHT, radius=.8, quadrant=(-1,-1), color=RED, stroke_width=8, other_angle=True) self.add(red_angle, sample_angle) """ return Angle(Line(B, A), Line(B, C), **kwargs) class RightAngle(Angle): """An elbow-type mobject representing a right angle between two lines. Parameters ---------- line1 The first line. line2 The second line. length The length of the arms. **kwargs Further keyword arguments that are passed to the constructor of :class:`Angle`. Examples -------- .. manim:: RightAngleExample :save_last_frame: class RightAngleExample(Scene): def construct(self): line1 = Line( LEFT, RIGHT ) line2 = Line( DOWN, UP ) rightangles = [ RightAngle(line1, line2), RightAngle(line1, line2, length=0.4, quadrant=(1,-1)), RightAngle(line1, line2, length=0.5, quadrant=(-1,1), stroke_width=8), RightAngle(line1, line2, length=0.7, quadrant=(-1,-1), color=RED), ] plots = VGroup() for rightangle in rightangles: plot=VGroup(line1.copy(),line2.copy(), rightangle) plots.add(plot) plots.arrange(buff=1.5) self.add(plots) """ def __init__( self, line1: Line, line2: Line, length: float | None = None, **kwargs: Any, ) -> None: super().__init__(line1, line2, radius=length, elbow=True, **kwargs) ================================================ FILE: manim/mobject/geometry/polygram.py ================================================ r"""Mobjects that are simple geometric shapes.""" from __future__ import annotations __all__ = [ "Polygram", "Polygon", "RegularPolygram", "RegularPolygon", "Star", "Triangle", "Rectangle", "Square", "RoundedRectangle", "Cutout", "ConvexHull", ] from math import ceil from typing import TYPE_CHECKING, Any, Literal import numpy as np from manim.constants import * from manim.mobject.geometry.arc import ArcBetweenPoints from manim.mobject.opengl.opengl_compatibility import ConvertToOpenGL from manim.mobject.types.vectorized_mobject import VGroup, VMobject from manim.utils.color import BLUE, WHITE, ParsableManimColor from manim.utils.iterables import adjacent_n_tuples, adjacent_pairs from manim.utils.qhull import QuickHull from manim.utils.space_ops import angle_between_vectors, normalize, regular_vertices if TYPE_CHECKING: import numpy.typing as npt from typing_extensions import Self from manim.typing import ( Point3D, Point3D_Array, Point3DLike, Point3DLike_Array, ) from manim.utils.color import ParsableManimColor class Polygram(VMobject, metaclass=ConvertToOpenGL): """A generalized :class:`Polygon`, allowing for disconnected sets of edges. Parameters ---------- vertex_groups The groups of vertices making up the :class:`Polygram`. The first vertex in each group is repeated to close the shape. Each point must be 3-dimensional: ``[x,y,z]`` color The color of the :class:`Polygram`. kwargs Forwarded to the parent constructor. Examples -------- .. manim:: PolygramExample import numpy as np class PolygramExample(Scene): def construct(self): hexagram = Polygram( [[0, 2, 0], [-np.sqrt(3), -1, 0], [np.sqrt(3), -1, 0]], [[-np.sqrt(3), 1, 0], [0, -2, 0], [np.sqrt(3), 1, 0]], ) self.add(hexagram) dot = Dot() self.play(MoveAlongPath(dot, hexagram), run_time=5, rate_func=linear) self.remove(dot) self.wait() """ def __init__( self, *vertex_groups: Point3DLike_Array, color: ParsableManimColor = BLUE, **kwargs: Any, ): super().__init__(color=color, **kwargs) for vertices in vertex_groups: # The inferred
2, 0], [-np.sqrt(3), -1, 0], [np.sqrt(3), -1, 0]], [[-np.sqrt(3), 1, 0], [0, -2, 0], [np.sqrt(3), 1, 0]], ) self.add(hexagram) dot = Dot() self.play(MoveAlongPath(dot, hexagram), run_time=5, rate_func=linear) self.remove(dot) self.wait() """ def __init__( self, *vertex_groups: Point3DLike_Array, color: ParsableManimColor = BLUE, **kwargs: Any, ): super().__init__(color=color, **kwargs) for vertices in vertex_groups: # The inferred type for *vertices is Any, but it should be # Point3D_Array first_vertex, *vertices = vertices first_vertex = np.array(first_vertex) self.start_new_path(first_vertex) self.add_points_as_corners( [*(np.array(vertex) for vertex in vertices), first_vertex], ) def get_vertices(self) -> Point3D_Array: """Gets the vertices of the :class:`Polygram`. Returns ------- :class:`numpy.ndarray` The vertices of the :class:`Polygram`. Examples -------- :: >>> sq = Square() >>> sq.get_vertices() array([[ 1., 1., 0.], [-1., 1., 0.], [-1., -1., 0.], [ 1., -1., 0.]]) """ return self.get_start_anchors() def get_vertex_groups(self) -> list[Point3D_Array]: """Gets the vertex groups of the :class:`Polygram`. Returns ------- list[Point3D_Array] The list of vertex groups of the :class:`Polygram`. Examples -------- :: >>> poly = Polygram([ORIGIN, RIGHT, UP, LEFT + UP], [LEFT, LEFT + UP, 2 * LEFT]) >>> groups = poly.get_vertex_groups() >>> len(groups) 2 >>> groups[0] array([[ 0., 0., 0.], [ 1., 0., 0.], [ 0., 1., 0.], [-1., 1., 0.]]) >>> groups[1] array([[-1., 0., 0.], [-1., 1., 0.], [-2., 0., 0.]]) """ vertex_groups = [] # TODO: If any of the original vertex groups contained the starting vertex N # times, then .get_vertex_groups() splits it into N vertex groups. group = [] for start, end in zip(self.get_start_anchors(), self.get_end_anchors()): group.append(start) if self.consider_points_equals(end, group[0]): vertex_groups.append(np.array(group)) group = [] return vertex_groups def round_corners( self, radius: float | list[float] = 0.5, evenly_distribute_anchors: bool = False, components_per_rounded_corner: int = 2, ) -> Self: """Rounds off the corners of the :class:`Polygram`. Parameters ---------- radius The curvature of the corners of the :class:`Polygram`. evenly_distribute_anchors Break long line segments into proportionally-sized segments. components_per_rounded_corner The number of points used to represent the rounded corner curve. .. seealso:: :class:`.~RoundedRectangle` .. note:: If `radius` is supplied as a single value, then the same radius will be applied to all corners. If `radius` is a list, then the individual values will be applied sequentially, with the first corner receiving `radius[0]`, the second corner receiving `radius[1]`, etc. The radius list will be repeated as necessary. The `components_per_rounded_corner` value is provided so that the fidelity of the rounded corner may be fine-tuned as needed. 2 is an appropriate value for most shapes, however a larger value may be need if the rounded corner is particularly large. 2 is the minimum number allowed, representing the start and end of the curve. 3 will result in a start, middle, and end point, meaning 2 curves will be generated. The option to `evenly_distribute_anchors` is provided so that the line segments (the part part of each line remaining after rounding off the corners) can be subdivided to a density similar to that of the average density of the rounded corners. This may be desirable in situations in which an even distribution of curves is desired for use in later transformation animations. Be aware, though, that enabling this option can result in an
corners) can be subdivided to a density similar to that of the average density of the rounded corners. This may be desirable in situations in which an even distribution of curves is desired for use in later transformation animations. Be aware, though, that enabling this option can result in an an object containing significantly more points than the original, especially when the rounded corner curves are small. Examples -------- .. manim:: PolygramRoundCorners :save_last_frame: class PolygramRoundCorners(Scene): def construct(self): star = Star(outer_radius=2) shapes = VGroup(star) shapes.add(star.copy().round_corners(radius=0.1)) shapes.add(star.copy().round_corners(radius=0.25)) shapes.arrange(RIGHT) self.add(shapes) """ if radius == 0: return self new_points: list[Point3D] = [] for vertex_group in self.get_vertex_groups(): arcs = [] # Repeat the radius list as necessary in order to provide a radius # for each vertex. if isinstance(radius, (int, float)): radius_list = [radius] * len(vertex_group) else: radius_list = radius * ceil(len(vertex_group) / len(radius)) for current_radius, (v1, v2, v3) in zip( radius_list, adjacent_n_tuples(vertex_group, 3) ): vect1 = v2 - v1 vect2 = v3 - v2 unit_vect1 = normalize(vect1) unit_vect2 = normalize(vect2) angle = angle_between_vectors(vect1, vect2) # Negative radius gives concave curves angle *= np.sign(current_radius) # Distance between vertex and start of the arc cut_off_length = current_radius * np.tan(angle / 2) # Determines counterclockwise vs. clockwise sign = np.sign(np.cross(vect1, vect2)[2]) arc = ArcBetweenPoints( v2 - unit_vect1 * cut_off_length, v2 + unit_vect2 * cut_off_length, angle=sign * angle, num_components=components_per_rounded_corner, ) arcs.append(arc) if evenly_distribute_anchors: # Determine the average length of each curve nonzero_length_arcs = [arc for arc in arcs if len(arc.points) > 4] if len(nonzero_length_arcs) > 0: total_arc_length = sum( [arc.get_arc_length() for arc in nonzero_length_arcs] ) num_curves = ( sum([len(arc.points) for arc in nonzero_length_arcs]) / 4 ) average_arc_length = total_arc_length / num_curves else: average_arc_length = 1.0 # To ensure that we loop through starting with last arcs = [arcs[-1], *arcs[:-1]] from manim.mobject.geometry.line import Line for arc1, arc2 in adjacent_pairs(arcs): new_points.extend(arc1.points) line = Line(arc1.get_end(), arc2.get_start()) # Make sure anchors are evenly distributed, if necessary if evenly_distribute_anchors: line.insert_n_curves(ceil(line.get_length() / average_arc_length)) new_points.extend(line.points) self.set_points(np.array(new_points)) return self class Polygon(Polygram): """A shape consisting of one closed loop of vertices. Parameters ---------- vertices The vertices of the :class:`Polygon`. kwargs Forwarded to the parent constructor. Examples -------- .. manim:: PolygonExample :save_last_frame: class PolygonExample(Scene): def construct(self): isosceles = Polygon([-5, 1.5, 0], [-2, 1.5, 0], [-3.5, -2, 0]) position_list = [ [4, 1, 0], # middle right [4, -2.5, 0], # bottom right [0, -2.5, 0], # bottom left [0, 3, 0], # top left [2, 1, 0], # middle [4, 3, 0], # top right ] square_and_triangles = Polygon(*position_list, color=PURPLE_B) self.add(isosceles, square_and_triangles) """ def __init__(self, *vertices: Point3DLike, **kwargs: Any) -> None: super().__init__(vertices, **kwargs) class RegularPolygram(Polygram): """A :class:`Polygram` with regularly spaced vertices. Parameters ---------- num_vertices The number of vertices. density The density of the :class:`RegularPolygram`. Can be thought of as how many vertices to hop to draw a line between them. Every ``density``-th vertex is connected. radius The radius of the circle that the vertices are placed on. start_angle The angle the vertices start at; the rotation of the :class:`RegularPolygram`. kwargs Forwarded to the parent constructor. Examples -------- ..
as how many vertices to hop to draw a line between them. Every ``density``-th vertex is connected. radius The radius of the circle that the vertices are placed on. start_angle The angle the vertices start at; the rotation of the :class:`RegularPolygram`. kwargs Forwarded to the parent constructor. Examples -------- .. manim:: RegularPolygramExample :save_last_frame: class RegularPolygramExample(Scene): def construct(self): pentagram = RegularPolygram(5, radius=2) self.add(pentagram) """ def __init__( self, num_vertices: int, *, density: int = 2, radius: float = 1, start_angle: float | None = None, **kwargs: Any, ) -> None: # Regular polygrams can be expressed by the number of their vertices # and their density. This relation can be expressed as its Schläfli # symbol: {num_vertices/density}. # # For instance, a pentagon can be expressed as {5/1} or just {5}. # A pentagram, however, can be expressed as {5/2}. # A hexagram *would* be expressed as {6/2}, except that 6 nd 2 # are not coprime, and it can be simplified to 2{3}, which corresponds # to the fact that a hexagram is actually made up of 2 triangles. # # See https://en.wikipedia.org/wiki/Polygram_(geometry)#Generalized_regular_polygons # for more information. num_gons = np.gcd(num_vertices, density) num_vertices //= num_gons density //= num_gons # Utility function for generating the individual # polygon vertices. def gen_polygon_vertices(start_angle: float | None) -> tuple[list[Any], float]: reg_vertices, start_angle = regular_vertices( num_vertices, radius=radius, start_angle=start_angle, ) vertices = [] i = 0 while True: vertices.append(reg_vertices[i]) i += density i %= num_vertices if i == 0: break return vertices, start_angle first_group, self.start_angle = gen_polygon_vertices(start_angle) vertex_groups = [first_group] for i in range(1, num_gons): start_angle = self.start_angle + (i / num_gons) * TAU / num_vertices group, _ = gen_polygon_vertices(start_angle) vertex_groups.append(group) super().__init__(*vertex_groups, **kwargs) class RegularPolygon(RegularPolygram): """An n-sided regular :class:`Polygon`. Parameters ---------- n The number of sides of the :class:`RegularPolygon`. kwargs Forwarded to the parent constructor. Examples -------- .. manim:: RegularPolygonExample :save_last_frame: class RegularPolygonExample(Scene): def construct(self): poly_1 = RegularPolygon(n=6) poly_2 = RegularPolygon(n=6, start_angle=30*DEGREES, color=GREEN) poly_3 = RegularPolygon(n=10, color=RED) poly_group = Group(poly_1, poly_2, poly_3).scale(1.5).arrange(buff=1) self.add(poly_group) """ def __init__(self, n: int = 6, **kwargs: Any) -> None: super().__init__(n, density=1, **kwargs) class Star(Polygon): """A regular polygram without the intersecting lines. Parameters ---------- n How many points on the :class:`Star`. outer_radius The radius of the circle that the outer vertices are placed on. inner_radius The radius of the circle that the inner vertices are placed on. If unspecified, the inner radius will be calculated such that the edges of the :class:`Star` perfectly follow the edges of its :class:`RegularPolygram` counterpart. density The density of the :class:`Star`. Only used if ``inner_radius`` is unspecified. See :class:`RegularPolygram` for more information. start_angle The angle the vertices start at; the rotation of the :class:`Star`. kwargs Forwardeds to the parent constructor. Raises ------ :exc:`ValueError` If ``inner_radius`` is unspecified and ``density`` is not in the range ``[1, n/2)``. Examples -------- .. manim:: StarExample class StarExample(Scene): def construct(self): pentagram = RegularPolygram(5, radius=2) star = Star(outer_radius=2, color=RED) self.add(pentagram) self.play(Create(star), run_time=3) self.play(FadeOut(star), run_time=2) .. manim:: DifferentDensitiesExample :save_last_frame: class DifferentDensitiesExample(Scene): def construct(self): density_2 = Star(7, outer_radius=2, density=2, color=RED) density_3 = Star(7, outer_radius=2, density=3, color=PURPLE) self.add(VGroup(density_2,
is not in the range ``[1, n/2)``. Examples -------- .. manim:: StarExample class StarExample(Scene): def construct(self): pentagram = RegularPolygram(5, radius=2) star = Star(outer_radius=2, color=RED) self.add(pentagram) self.play(Create(star), run_time=3) self.play(FadeOut(star), run_time=2) .. manim:: DifferentDensitiesExample :save_last_frame: class DifferentDensitiesExample(Scene): def construct(self): density_2 = Star(7, outer_radius=2, density=2, color=RED) density_3 = Star(7, outer_radius=2, density=3, color=PURPLE) self.add(VGroup(density_2, density_3).arrange(RIGHT)) """ def __init__( self, n: int = 5, *, outer_radius: float = 1, inner_radius: float | None = None, density: int = 2, start_angle: float | None = TAU / 4, **kwargs: Any, ) -> None: inner_angle = TAU / (2 * n) if inner_radius is None: # See https://math.stackexchange.com/a/2136292 for an # overview of how to calculate the inner radius of a # perfect star. if density <= 0 or density >= n / 2: raise ValueError( f"Incompatible density {density} for number of points {n}", ) outer_angle = TAU * density / n inverse_x = 1 - np.tan(inner_angle) * ( (np.cos(outer_angle) - 1) / np.sin(outer_angle) ) inner_radius = outer_radius / (np.cos(inner_angle) * inverse_x) outer_vertices, self.start_angle = regular_vertices( n, radius=outer_radius, start_angle=start_angle, ) inner_vertices, _ = regular_vertices( n, radius=inner_radius, start_angle=self.start_angle + inner_angle, ) vertices: list[npt.NDArray] = [] for pair in zip(outer_vertices, inner_vertices): vertices.extend(pair) super().__init__(*vertices, **kwargs) class Triangle(RegularPolygon): """An equilateral triangle. Parameters ---------- kwargs Additional arguments to be passed to :class:`RegularPolygon` Examples -------- .. manim:: TriangleExample :save_last_frame: class TriangleExample(Scene): def construct(self): triangle_1 = Triangle() triangle_2 = Triangle().scale(2).rotate(60*DEGREES) tri_group = Group(triangle_1, triangle_2).arrange(buff=1) self.add(tri_group) """ def __init__(self, **kwargs: Any) -> None: super().__init__(n=3, **kwargs) class Rectangle(Polygon): """A quadrilateral with two sets of parallel sides. Parameters ---------- color The color of the rectangle. height The vertical height of the rectangle. width The horizontal width of the rectangle. grid_xstep Space between vertical grid lines. grid_ystep Space between horizontal grid lines. mark_paths_closed No purpose. close_new_points No purpose. kwargs Additional arguments to be passed to :class:`Polygon` Examples ---------- .. manim:: RectangleExample :save_last_frame: class RectangleExample(Scene): def construct(self): rect1 = Rectangle(width=4.0, height=2.0, grid_xstep=1.0, grid_ystep=0.5) rect2 = Rectangle(width=1.0, height=4.0) rect3 = Rectangle(width=2.0, height=2.0, grid_xstep=1.0, grid_ystep=1.0) rect3.grid_lines.set_stroke(width=1) rects = Group(rect1, rect2, rect3).arrange(buff=1) self.add(rects) """ def __init__( self, color: ParsableManimColor = WHITE, height: float = 2.0, width: float = 4.0, grid_xstep: float | None = None, grid_ystep: float | None = None, mark_paths_closed: bool = True, close_new_points: bool = True, **kwargs: Any, ): super().__init__(UR, UL, DL, DR, color=color, **kwargs) self.stretch_to_fit_width(width) self.stretch_to_fit_height(height) v = self.get_vertices() self.grid_lines = VGroup() if grid_xstep or grid_ystep: from manim.mobject.geometry.line import Line v = self.get_vertices() if grid_xstep: grid_xstep = abs(grid_xstep) count = int(width / grid_xstep) grid = VGroup( *( Line( v[1] + i * grid_xstep * RIGHT, v[1] + i * grid_xstep * RIGHT + height * DOWN, color=color, ) for i in range(1, count) ) ) self.grid_lines.add(grid) if grid_ystep: grid_ystep = abs(grid_ystep) count = int(height / grid_ystep) grid = VGroup( *( Line( v[1] + i * grid_ystep * DOWN, v[1] + i * grid_ystep * DOWN + width * RIGHT, color=color, ) for i in range(1, count) ) ) self.grid_lines.add(grid) if self.grid_lines: self.add(self.grid_lines) class Square(Rectangle): """A rectangle with equal side lengths. Parameters ---------- side_length The length of the sides
VGroup( *( Line( v[1] + i * grid_ystep * DOWN, v[1] + i * grid_ystep * DOWN + width * RIGHT, color=color, ) for i in range(1, count) ) ) self.grid_lines.add(grid) if self.grid_lines: self.add(self.grid_lines) class Square(Rectangle): """A rectangle with equal side lengths. Parameters ---------- side_length The length of the sides of the square. kwargs Additional arguments to be passed to :class:`Rectangle`. Examples -------- .. manim:: SquareExample :save_last_frame: class SquareExample(Scene): def construct(self): square_1 = Square(side_length=2.0).shift(DOWN) square_2 = Square(side_length=1.0).next_to(square_1, direction=UP) square_3 = Square(side_length=0.5).next_to(square_2, direction=UP) self.add(square_1, square_2, square_3) """ def __init__(self, side_length: float = 2.0, **kwargs: Any) -> None: super().__init__(height=side_length, width=side_length, **kwargs) @property def side_length(self) -> float: return float(np.linalg.norm(self.get_vertices()[0] - self.get_vertices()[1])) @side_length.setter def side_length(self, value: float) -> None: self.scale(value / self.side_length) class RoundedRectangle(Rectangle): """A rectangle with rounded corners. Parameters ---------- corner_radius The curvature of the corners of the rectangle. kwargs Additional arguments to be passed to :class:`Rectangle` Examples -------- .. manim:: RoundedRectangleExample :save_last_frame: class RoundedRectangleExample(Scene): def construct(self): rect_1 = RoundedRectangle(corner_radius=0.5) rect_2 = RoundedRectangle(corner_radius=1.5, height=4.0, width=4.0) rect_group = Group(rect_1, rect_2).arrange(buff=1) self.add(rect_group) """ def __init__(self, corner_radius: float | list[float] = 0.5, **kwargs: Any): super().__init__(**kwargs) self.corner_radius = corner_radius self.round_corners(self.corner_radius) class Cutout(VMobject, metaclass=ConvertToOpenGL): """A shape with smaller cutouts. Parameters ---------- main_shape The primary shape from which cutouts are made. mobjects The smaller shapes which are to be cut out of the ``main_shape``. kwargs Further keyword arguments that are passed to the constructor of :class:`~.VMobject`. .. warning:: Technically, this class behaves similar to a symmetric difference: if parts of the ``mobjects`` are not located within the ``main_shape``, these parts will be added to the resulting :class:`~.VMobject`. Examples -------- .. manim:: CutoutExample class CutoutExample(Scene): def construct(self): s1 = Square().scale(2.5) s2 = Triangle().shift(DOWN + RIGHT).scale(0.5) s3 = Square().shift(UP + RIGHT).scale(0.5) s4 = RegularPolygon(5).shift(DOWN + LEFT).scale(0.5) s5 = RegularPolygon(6).shift(UP + LEFT).scale(0.5) c = Cutout(s1, s2, s3, s4, s5, fill_opacity=1, color=BLUE, stroke_color=RED) self.play(Write(c), run_time=4) self.wait() """ def __init__( self, main_shape: VMobject, *mobjects: VMobject, **kwargs: Any ) -> None: super().__init__(**kwargs) self.append_points(main_shape.points) sub_direction: Literal["CCW", "CW"] = ( "CCW" if main_shape.get_direction() == "CW" else "CW" ) for mobject in mobjects: self.append_points(mobject.force_direction(sub_direction).points) class ConvexHull(Polygram): """Constructs a convex hull for a set of points in no particular order. Parameters ---------- points The points to consider. tolerance The tolerance used by quickhull. kwargs Forwarded to the parent constructor. Examples -------- .. manim:: ConvexHullExample :save_last_frame: :quality: high class ConvexHullExample(Scene): def construct(self): points = [ [-2.35, -2.25, 0], [1.65, -2.25, 0], [2.65, -0.25, 0], [1.65, 1.75, 0], [-0.35, 2.75, 0], [-2.35, 0.75, 0], [-0.35, -1.25, 0], [0.65, -0.25, 0], [-1.35, 0.25, 0], [0.15, 0.75, 0] ] hull = ConvexHull(*points, color=BLUE) dots = VGroup(*[Dot(point) for point in points]) self.add(hull) self.add(dots) """ def __init__( self, *points: Point3DLike, tolerance: float = 1e-5, **kwargs: Any ) -> None: # Build Convex Hull array = np.array(points)[:, :2] hull = QuickHull(tolerance) hull.build(array) # Extract Vertices facets = set(hull.facets) - hull.removed facet = facets.pop() subfacets = list(facet.subfacets) while len(subfacets) <= len(facets): sf = subfacets[-1] (facet,) = hull.neighbors[sf] - {facet} (sf,) = facet.subfacets - {sf} subfacets.append(sf) # Setup Vertices as Point3D coordinates = np.vstack([sf.coordinates for sf in subfacets])
np.array(points)[:, :2] hull = QuickHull(tolerance) hull.build(array) # Extract Vertices facets = set(hull.facets) - hull.removed facet = facets.pop() subfacets = list(facet.subfacets) while len(subfacets) <= len(facets): sf = subfacets[-1] (facet,) = hull.neighbors[sf] - {facet} (sf,) = facet.subfacets - {sf} subfacets.append(sf) # Setup Vertices as Point3D coordinates = np.vstack([sf.coordinates for sf in subfacets]) vertices = np.hstack((coordinates, np.zeros((len(coordinates), 1)))) # Call Polygram super().__init__(vertices, **kwargs) ================================================ FILE: manim/mobject/geometry/shape_matchers.py ================================================ """Mobjects used to mark and annotate other mobjects.""" from __future__ import annotations __all__ = ["SurroundingRectangle", "BackgroundRectangle", "Cross", "Underline"] from typing import Any from typing_extensions import Self from manim import logger from manim._config import config from manim.constants import ( DOWN, LEFT, RIGHT, SMALL_BUFF, UP, ) from manim.mobject.geometry.line import Line from manim.mobject.geometry.polygram import RoundedRectangle from manim.mobject.mobject import Mobject from manim.mobject.opengl.opengl_mobject import OpenGLMobject from manim.mobject.types.vectorized_mobject import VGroup from manim.utils.color import BLACK, RED, YELLOW, ManimColor, ParsableManimColor class SurroundingRectangle(RoundedRectangle): r"""A rectangle surrounding a :class:`~.Mobject` Examples -------- .. manim:: SurroundingRectExample :save_last_frame: class SurroundingRectExample(Scene): def construct(self): title = Title("A Quote from Newton") quote = Text( "If I have seen further than others, \n" "it is by standing upon the shoulders of giants.", color=BLUE, ).scale(0.75) box = SurroundingRectangle(quote, color=YELLOW, buff=MED_LARGE_BUFF) t2 = Tex(r"Hello World").scale(1.5) box2 = SurroundingRectangle(t2, corner_radius=0.2) mobjects = VGroup(VGroup(box, quote), VGroup(t2, box2)).arrange(DOWN) self.add(title, mobjects) """ def __init__( self, *mobjects: Mobject, color: ParsableManimColor = YELLOW, buff: float | tuple[float, float] = SMALL_BUFF, corner_radius: float = 0.0, **kwargs: Any, ) -> None: from manim.mobject.mobject import Group if not all(isinstance(mob, (Mobject, OpenGLMobject)) for mob in mobjects): raise TypeError( "Expected all inputs for parameter mobjects to be a Mobjects" ) if isinstance(buff, tuple): buff_x = buff[0] buff_y = buff[1] else: buff_x = buff_y = buff group = Group(*mobjects) super().__init__( color=color, width=group.width + 2 * buff_x, height=group.height + 2 * buff_y, corner_radius=corner_radius, **kwargs, ) self.buff = buff self.move_to(group) class BackgroundRectangle(SurroundingRectangle): """A background rectangle. Its default color is the background color of the scene. Examples -------- .. manim:: ExampleBackgroundRectangle :save_last_frame: class ExampleBackgroundRectangle(Scene): def construct(self): circle = Circle().shift(LEFT) circle.set_stroke(color=GREEN, width=20) triangle = Triangle().shift(2 * RIGHT) triangle.set_fill(PINK, opacity=0.5) backgroundRectangle1 = BackgroundRectangle(circle, color=WHITE, fill_opacity=0.15) backgroundRectangle2 = BackgroundRectangle(triangle, color=WHITE, fill_opacity=0.15) self.add(backgroundRectangle1) self.add(backgroundRectangle2) self.add(circle) self.add(triangle) self.play(Rotate(backgroundRectangle1, PI / 4)) self.play(Rotate(backgroundRectangle2, PI / 2)) """ def __init__( self, *mobjects: Mobject, color: ParsableManimColor | None = None, stroke_width: float = 0, stroke_opacity: float = 0, fill_opacity: float = 0.75, buff: float | tuple[float, float] = 0, **kwargs: Any, ) -> None: if color is None: color = config.background_color super().__init__( *mobjects, color=color, stroke_width=stroke_width, stroke_opacity=stroke_opacity, fill_opacity=fill_opacity, buff=buff, **kwargs, ) self.original_fill_opacity: float = self.fill_opacity def pointwise_become_partial(self, mobject: Mobject, a: Any, b: float) -> Self: self.set_fill(opacity=b * self.original_fill_opacity) return self def set_style(self, fill_opacity: float, **kwargs: Any) -> Self: # type: ignore[override] # Unchangeable style, except for fill_opacity # All other style arguments are ignored super().set_style( stroke_color=BLACK, stroke_width=0, fill_color=BLACK, fill_opacity=fill_opacity, ) if len(kwargs) > 0: logger.info( "Argument %s is ignored in BackgroundRectangle.set_style.", kwargs, ) return self def get_fill_color(self) -> ManimColor: # The type of the color property is set to Any using the property decorator # vectorized_mobject.py#L571 temp_color: ManimColor = self.color return temp_color class Cross(VGroup): """Creates a cross. Parameters ----------
) if len(kwargs) > 0: logger.info( "Argument %s is ignored in BackgroundRectangle.set_style.", kwargs, ) return self def get_fill_color(self) -> ManimColor: # The type of the color property is set to Any using the property decorator # vectorized_mobject.py#L571 temp_color: ManimColor = self.color return temp_color class Cross(VGroup): """Creates a cross. Parameters ---------- mobject The mobject linked to this instance. It fits the mobject when specified. Defaults to None. stroke_color Specifies the color of the cross lines. Defaults to RED. stroke_width Specifies the width of the cross lines. Defaults to 6. scale_factor Scales the cross to the provided units. Defaults to 1. Examples -------- .. manim:: ExampleCross :save_last_frame: class ExampleCross(Scene): def construct(self): cross = Cross() self.add(cross) """ def __init__( self, mobject: Mobject | None = None, stroke_color: ParsableManimColor = RED, stroke_width: float = 6.0, scale_factor: float = 1.0, **kwargs: Any, ) -> None: super().__init__( Line(UP + LEFT, DOWN + RIGHT), Line(UP + RIGHT, DOWN + LEFT), **kwargs ) if mobject is not None: self.replace(mobject, stretch=True) self.scale(scale_factor) self.set_stroke(color=stroke_color, width=stroke_width) class Underline(Line): """Creates an underline. Examples -------- .. manim:: UnderLine :save_last_frame: class UnderLine(Scene): def construct(self): man = Tex("Manim") # Full Word ul = Underline(man) # Underlining the word self.add(man, ul) """ def __init__( self, mobject: Mobject, buff: float = SMALL_BUFF, **kwargs: Any ) -> None: super().__init__(LEFT, RIGHT, buff=buff, **kwargs) self.match_width(mobject) self.next_to(mobject, DOWN, buff=self.buff) ================================================ FILE: manim/mobject/geometry/tips.py ================================================ r"""A collection of tip mobjects for use with :class:`~.TipableVMobject`.""" from __future__ import annotations __all__ = [ "ArrowTip", "ArrowCircleFilledTip", "ArrowCircleTip", "ArrowSquareTip", "ArrowSquareFilledTip", "ArrowTriangleTip", "ArrowTriangleFilledTip", "StealthTip", ] from typing import TYPE_CHECKING, Any import numpy as np from manim.constants import * from manim.mobject.geometry.arc import Circle from manim.mobject.geometry.polygram import Square, Triangle from manim.mobject.opengl.opengl_compatibility import ConvertToOpenGL from manim.mobject.types.vectorized_mobject import VMobject from manim.utils.space_ops import angle_of_vector if TYPE_CHECKING: from manim.typing import Point3D, Vector3D class ArrowTip(VMobject, metaclass=ConvertToOpenGL): r"""Base class for arrow tips. .. seealso:: :class:`ArrowTriangleTip` :class:`ArrowTriangleFilledTip` :class:`ArrowCircleTip` :class:`ArrowCircleFilledTip` :class:`ArrowSquareTip` :class:`ArrowSquareFilledTip` :class:`StealthTip` Examples -------- Cannot be used directly, only intended for inheritance:: >>> tip = ArrowTip() Traceback (most recent call last): ... NotImplementedError: Has to be implemented in inheriting subclasses. Instead, use one of the pre-defined ones, or make a custom one like this: .. manim:: CustomTipExample >>> from manim import RegularPolygon, Arrow >>> class MyCustomArrowTip(ArrowTip, RegularPolygon): ... def __init__(self, length=0.35, **kwargs): ... RegularPolygon.__init__(self, n=5, **kwargs) ... self.width = length ... self.stretch_to_fit_height(length) >>> arr = Arrow( ... np.array([-2, -2, 0]), np.array([2, 2, 0]), tip_shape=MyCustomArrowTip ... ) >>> isinstance(arr.tip, RegularPolygon) True >>> from manim import Scene, Create >>> class CustomTipExample(Scene): ... def construct(self): ... self.play(Create(arr)) Using a class inherited from :class:`ArrowTip` to get a non-filled tip is a shorthand to manually specifying the arrow tip style as follows:: >>> arrow = Arrow(np.array([0, 0, 0]), np.array([1, 1, 0]), ... tip_style={'fill_opacity': 0, 'stroke_width': 3}) The following example illustrates the usage of all of the predefined arrow tips. .. manim:: ArrowTipsShowcase :save_last_frame: class ArrowTipsShowcase(Scene): def construct(self): tip_names = [ 'Default (YELLOW)', 'ArrowTriangleTip', 'Default', 'ArrowSquareTip', 'ArrowSquareFilledTip', 'ArrowCircleTip', 'ArrowCircleFilledTip', 'StealthTip' ] big_arrows = [ Arrow(start=[-4, 3.5, 0], end=[2, 3.5, 0], color=YELLOW), Arrow(start=[-4, 2.5, 0], end=[2, 2.5, 0], tip_shape=ArrowTriangleTip), Arrow(start=[-4, 1.5, 0], end=[2, 1.5,
of all of the predefined arrow tips. .. manim:: ArrowTipsShowcase :save_last_frame: class ArrowTipsShowcase(Scene): def construct(self): tip_names = [ 'Default (YELLOW)', 'ArrowTriangleTip', 'Default', 'ArrowSquareTip', 'ArrowSquareFilledTip', 'ArrowCircleTip', 'ArrowCircleFilledTip', 'StealthTip' ] big_arrows = [ Arrow(start=[-4, 3.5, 0], end=[2, 3.5, 0], color=YELLOW), Arrow(start=[-4, 2.5, 0], end=[2, 2.5, 0], tip_shape=ArrowTriangleTip), Arrow(start=[-4, 1.5, 0], end=[2, 1.5, 0]), Arrow(start=[-4, 0.5, 0], end=[2, 0.5, 0], tip_shape=ArrowSquareTip), Arrow([-4, -0.5, 0], [2, -0.5, 0], tip_shape=ArrowSquareFilledTip), Arrow([-4, -1.5, 0], [2, -1.5, 0], tip_shape=ArrowCircleTip), Arrow([-4, -2.5, 0], [2, -2.5, 0], tip_shape=ArrowCircleFilledTip), Arrow([-4, -3.5, 0], [2, -3.5, 0], tip_shape=StealthTip) ] small_arrows = ( arrow.copy().scale(0.5, scale_tips=True).next_to(arrow, RIGHT) for arrow in big_arrows ) labels = ( Text(tip_names[i], font='monospace', font_size=20, color=BLUE).next_to(big_arrows[i], LEFT) for i in range(len(big_arrows)) ) self.add(*big_arrows, *small_arrows, *labels) """ def __init__(self, *args: Any, **kwargs: Any) -> None: raise NotImplementedError("Has to be implemented in inheriting subclasses.") @property def base(self) -> Point3D: r"""The base point of the arrow tip. This is the point connecting to the arrow line. Examples -------- :: >>> from manim import Arrow >>> arrow = Arrow(np.array([0, 0, 0]), np.array([2, 0, 0]), buff=0) >>> arrow.tip.base.round(2) + 0. # add 0. to avoid negative 0 in output array([1.65, 0. , 0. ]) """ return self.point_from_proportion(0.5) @property def tip_point(self) -> Point3D: r"""The tip point of the arrow tip. Examples -------- :: >>> from manim import Arrow >>> arrow = Arrow(np.array([0, 0, 0]), np.array([2, 0, 0]), buff=0) >>> arrow.tip.tip_point.round(2) + 0. array([2., 0., 0.]) """ # Type inference of extracting an element from a list, is not # supported by numpy, see this numpy issue # https://github.com/numpy/numpy/issues/16544 tip_point: Point3D = self.points[0] return tip_point @property def vector(self) -> Vector3D: r"""The vector pointing from the base point to the tip point. Examples -------- :: >>> from manim import Arrow >>> arrow = Arrow(np.array([0, 0, 0]), np.array([2, 2, 0]), buff=0) >>> arrow.tip.vector.round(2) + 0. array([0.25, 0.25, 0. ]) """ return self.tip_point - self.base @property def tip_angle(self) -> float: r"""The angle of the arrow tip. Examples -------- :: >>> from manim import Arrow >>> arrow = Arrow(np.array([0, 0, 0]), np.array([1, 1, 0]), buff=0) >>> bool(round(arrow.tip.tip_angle, 5) == round(PI/4, 5)) True """ return angle_of_vector(self.vector) @property def length(self) -> float: r"""The length of the arrow tip. Examples -------- :: >>> from manim import Arrow >>> arrow = Arrow(np.array([0, 0, 0]), np.array([1, 2, 0])) >>> round(arrow.tip.length, 3) 0.35 """ return float(np.linalg.norm(self.vector)) class StealthTip(ArrowTip): r"""'Stealth' fighter / kite arrow shape. Naming is inspired by the corresponding `TikZ arrow shape <https://tikz.dev/tikz-arrows#sec-16.3>`__. """ def __init__( self, fill_opacity: float = 1, stroke_width: float = 3, length: float = DEFAULT_ARROW_TIP_LENGTH / 2, start_angle: float = PI, **kwargs: Any, ): self.start_angle = start_angle VMobject.__init__( self, fill_opacity=fill_opacity, stroke_width=stroke_width, **kwargs ) self.set_points_as_corners( np.array( [ [2, 0, 0], # tip [-1.2, 1.6, 0], [0, 0, 0], # base [-1.2, -1.6, 0], [2, 0, 0], # close path, back to tip ] ) ) self.scale(length / self.length) @property def length(self) -> float: """The length of the arrow tip. In this case, the length is computed as the height of the triangle encompassing the stealth tip (otherwise, the tip is scaled too large). """
0, 0], # close path, back to tip ] ) ) self.scale(length / self.length) @property def length(self) -> float: """The length of the arrow tip. In this case, the length is computed as the height of the triangle encompassing the stealth tip (otherwise, the tip is scaled too large). """ return float(np.linalg.norm(self.vector) * 1.6) class ArrowTriangleTip(ArrowTip, Triangle): r"""Triangular arrow tip.""" def __init__( self, fill_opacity: float = 0, stroke_width: float = 3, length: float = DEFAULT_ARROW_TIP_LENGTH, width: float = DEFAULT_ARROW_TIP_LENGTH, start_angle: float = PI, **kwargs: Any, ) -> None: Triangle.__init__( self, fill_opacity=fill_opacity, stroke_width=stroke_width, start_angle=start_angle, **kwargs, ) self.width = width self.stretch_to_fit_width(length) self.stretch_to_fit_height(width) class ArrowTriangleFilledTip(ArrowTriangleTip): r"""Triangular arrow tip with filled tip. This is the default arrow tip shape. """ def __init__( self, fill_opacity: float = 1, stroke_width: float = 0, **kwargs: Any ) -> None: super().__init__(fill_opacity=fill_opacity, stroke_width=stroke_width, **kwargs) class ArrowCircleTip(ArrowTip, Circle): r"""Circular arrow tip.""" def __init__( self, fill_opacity: float = 0, stroke_width: float = 3, length: float = DEFAULT_ARROW_TIP_LENGTH, start_angle: float = PI, **kwargs: Any, ) -> None: self.start_angle = start_angle Circle.__init__( self, fill_opacity=fill_opacity, stroke_width=stroke_width, **kwargs ) self.width = length self.stretch_to_fit_height(length) class ArrowCircleFilledTip(ArrowCircleTip): r"""Circular arrow tip with filled tip.""" def __init__( self, fill_opacity: float = 1, stroke_width: float = 0, **kwargs: Any ) -> None: super().__init__(fill_opacity=fill_opacity, stroke_width=stroke_width, **kwargs) class ArrowSquareTip(ArrowTip, Square): r"""Square arrow tip.""" def __init__( self, fill_opacity: float = 0, stroke_width: float = 3, length: float = DEFAULT_ARROW_TIP_LENGTH, start_angle: float = PI, **kwargs: Any, ) -> None: self.start_angle = start_angle Square.__init__( self, fill_opacity=fill_opacity, stroke_width=stroke_width, side_length=length, **kwargs, ) self.width = length self.stretch_to_fit_height(length) class ArrowSquareFilledTip(ArrowSquareTip): r"""Square arrow tip with filled tip.""" def __init__( self, fill_opacity: float = 1, stroke_width: float = 0, **kwargs: Any ) -> None: super().__init__(fill_opacity=fill_opacity, stroke_width=stroke_width, **kwargs) ================================================ FILE: manim/mobject/graphing/__init__.py ================================================ """Coordinate systems and function graphing related mobjects. Modules ======= .. autosummary:: :toctree: ../reference ~coordinate_systems ~functions ~number_line ~probability ~scale """ ================================================ FILE: manim/mobject/graphing/functions.py ================================================ """Mobjects representing function graphs.""" from __future__ import annotations __all__ = ["ParametricFunction", "FunctionGraph", "ImplicitFunction"] from collections.abc import Callable, Iterable, Sequence from typing import TYPE_CHECKING import numpy as np from isosurfaces import plot_isoline from manim import config from manim.mobject.graphing.scale import LinearBase, _ScaleBase from manim.mobject.opengl.opengl_compatibility import ConvertToOpenGL from manim.mobject.types.vectorized_mobject import VMobject if TYPE_CHECKING: from typing import Any from typing_extensions import Self from manim.typing import Point3D, Point3DLike from manim.utils.color import ParsableManimColor from manim.utils.color import YELLOW class ParametricFunction(VMobject, metaclass=ConvertToOpenGL): """A parametric curve. Parameters ---------- function The function to be plotted in the form of ``(lambda t: (x(t), y(t), z(t)))`` t_range Determines the length that the function spans in the form of (t_min, t_max, step=0.01). By default ``[0, 1]`` scaling Scaling class applied to the points of the function. Default of :class:`~.LinearBase`. use_smoothing Whether to interpolate between the points of the function after they have been created. (Will have odd behaviour with a low number of points) use_vectorized Whether to pass in the generated t value array to the function as ``[t_0, t_1, ...]``. Only use this if your function supports it. Output should be a numpy array of shape ``[[x_0, x_1, ...], [y_0, y_1, ...], [z_0, z_1, ...]]`` but ``z`` can also
low number of points) use_vectorized Whether to pass in the generated t value array to the function as ``[t_0, t_1, ...]``. Only use this if your function supports it. Output should be a numpy array of shape ``[[x_0, x_1, ...], [y_0, y_1, ...], [z_0, z_1, ...]]`` but ``z`` can also be 0 if the Axes is 2D discontinuities Values of t at which the function experiences discontinuity. dt The left and right tolerance for the discontinuities. Examples -------- .. manim:: PlotParametricFunction :save_last_frame: class PlotParametricFunction(Scene): def func(self, t): return (np.sin(2 * t), np.sin(3 * t), 0) def construct(self): func = ParametricFunction(self.func, t_range = (0, TAU), fill_opacity=0).set_color(RED) self.add(func.scale(3)) .. manim:: ThreeDParametricSpring :save_last_frame: class ThreeDParametricSpring(ThreeDScene): def construct(self): curve1 = ParametricFunction( lambda u: ( 1.2 * np.cos(u), 1.2 * np.sin(u), u * 0.05 ), color=RED, t_range = (-3*TAU, 5*TAU, 0.01) ).set_shade_in_3d(True) axes = ThreeDAxes() self.add(axes, curve1) self.set_camera_orientation(phi=80 * DEGREES, theta=-60 * DEGREES) self.wait() .. attention:: If your function has discontinuities, you'll have to specify the location of the discontinuities manually. See the following example for guidance. .. manim:: DiscontinuousExample :save_last_frame: class DiscontinuousExample(Scene): def construct(self): ax1 = NumberPlane((-3, 3), (-4, 4)) ax2 = NumberPlane((-3, 3), (-4, 4)) VGroup(ax1, ax2).arrange() discontinuous_function = lambda x: (x ** 2 - 2) / (x ** 2 - 4) incorrect = ax1.plot(discontinuous_function, color=RED) correct = ax2.plot( discontinuous_function, discontinuities=[-2, 2], # discontinuous points dt=0.1, # left and right tolerance of discontinuity color=GREEN, ) self.add(ax1, ax2, incorrect, correct) """ def __init__( self, function: Callable[[float], Point3DLike], t_range: tuple[float, float] | tuple[float, float, float] = (0, 1), scaling: _ScaleBase = LinearBase(), dt: float = 1e-8, discontinuities: Iterable[float] | None = None, use_smoothing: bool = True, use_vectorized: bool = False, **kwargs: Any, ): def internal_parametric_function(t: float) -> Point3D: """Wrap ``function``'s output inside a NumPy array.""" return np.asarray(function(t)) self.function = internal_parametric_function if len(t_range) == 2: t_range = (*t_range, 0.01) self.scaling = scaling self.dt = dt self.discontinuities = discontinuities self.use_smoothing = use_smoothing self.use_vectorized = use_vectorized self.t_min, self.t_max, self.t_step = t_range super().__init__(**kwargs) def get_function(self) -> Callable[[float], Point3D]: return self.function def get_point_from_function(self, t: float) -> Point3D: return self.function(t) def generate_points(self) -> Self: if self.discontinuities is not None: discontinuities = filter( lambda t: self.t_min <= t <= self.t_max, self.discontinuities, ) discontinuities_array = np.array(list(discontinuities)) boundary_times = np.array( [ self.t_min, self.t_max, *(discontinuities_array - self.dt), *(discontinuities_array + self.dt), ], ) boundary_times.sort() else: boundary_times = [self.t_min, self.t_max] for t1, t2 in zip(boundary_times[0::2], boundary_times[1::2]): t_range = np.array( [ *self.scaling.function(np.arange(t1, t2, self.t_step)), self.scaling.function(t2), ], ) if self.use_vectorized: x, y, z = self.function(t_range) if not isinstance(z, np.ndarray): z = np.zeros_like(x) points = np.stack([x, y, z], axis=1) else: points = np.array([self.function(t) for t in t_range]) self.start_new_path(points[0]) self.add_points_as_corners(points[1:]) if self.use_smoothing: # TODO: not in line with upstream, approx_smooth does not exist self.make_smooth() return self def init_points(self) -> None: self.generate_points() class FunctionGraph(ParametricFunction): """A :class:`ParametricFunction` that spans the length of the scene by default. Examples -------- .. manim:: ExampleFunctionGraph :save_last_frame: class ExampleFunctionGraph(Scene): def construct(self): cos_func = FunctionGraph( lambda t: np.cos(t) + 0.5 * np.cos(7 * t) + (1 / 7) * np.cos(14 * t), color=RED, ) sin_func_1 = FunctionGraph( lambda t:
class FunctionGraph(ParametricFunction): """A :class:`ParametricFunction` that spans the length of the scene by default. Examples -------- .. manim:: ExampleFunctionGraph :save_last_frame: class ExampleFunctionGraph(Scene): def construct(self): cos_func = FunctionGraph( lambda t: np.cos(t) + 0.5 * np.cos(7 * t) + (1 / 7) * np.cos(14 * t), color=RED, ) sin_func_1 = FunctionGraph( lambda t: np.sin(t) + 0.5 * np.sin(7 * t) + (1 / 7) * np.sin(14 * t), color=BLUE, ) sin_func_2 = FunctionGraph( lambda t: np.sin(t) + 0.5 * np.sin(7 * t) + (1 / 7) * np.sin(14 * t), x_range=[-4, 4], color=GREEN, ).move_to([0, 1, 0]) self.add(cos_func, sin_func_1, sin_func_2) """ def __init__( self, function: Callable[[float], Any], x_range: tuple[float, float] | tuple[float, float, float] | None = None, color: ParsableManimColor = YELLOW, **kwargs: Any, ) -> None: if x_range is None: x_range = (-config["frame_x_radius"], config["frame_x_radius"]) self.x_range = x_range self.parametric_function: Callable[[float], Point3D] = lambda t: np.array( [t, function(t), 0] ) self.function = function # type: ignore[assignment] super().__init__(self.parametric_function, self.x_range, color=color, **kwargs) def get_function(self) -> Callable[[float], Any]: return self.function def get_point_from_function(self, x: float) -> Point3D: return self.parametric_function(x) class ImplicitFunction(VMobject, metaclass=ConvertToOpenGL): def __init__( self, func: Callable[[float, float], float], x_range: Sequence[float] | None = None, y_range: Sequence[float] | None = None, min_depth: int = 5, max_quads: int = 1500, use_smoothing: bool = True, **kwargs: Any, ): """An implicit function. Parameters ---------- func The implicit function in the form ``f(x, y) = 0``. x_range The x min and max of the function. y_range The y min and max of the function. min_depth The minimum depth of the function to calculate. max_quads The maximum number of quads to use. use_smoothing Whether or not to smoothen the curves. kwargs Additional parameters to pass into :class:`VMobject` .. note:: A small ``min_depth`` :math:`d` means that some small details might be ignored if they don't cross an edge of one of the :math:`4^d` uniform quads. The value of ``max_quads`` strongly corresponds to the quality of the curve, but a higher number of quads may take longer to render. Examples -------- .. manim:: ImplicitFunctionExample :save_last_frame: class ImplicitFunctionExample(Scene): def construct(self): graph = ImplicitFunction( lambda x, y: x * y ** 2 - x ** 2 * y - 2, color=YELLOW ) self.add(NumberPlane(), graph) """ self.function = func self.min_depth = min_depth self.max_quads = max_quads self.use_smoothing = use_smoothing self.x_range = x_range or [ -config.frame_width / 2, config.frame_width / 2, ] self.y_range = y_range or [ -config.frame_height / 2, config.frame_height / 2, ] super().__init__(**kwargs) def generate_points(self) -> Self: p_min, p_max = ( np.array([self.x_range[0], self.y_range[0]]), np.array([self.x_range[1], self.y_range[1]]), ) curves = plot_isoline( fn=lambda u: self.function(u[0], u[1]), pmin=p_min, pmax=p_max, min_depth=self.min_depth, max_quads=self.max_quads, ) # returns a list of lists of 2D points curves = [ np.pad(curve, [(0, 0), (0, 1)]) for curve in curves if curve != [] ] # add z coord as 0 for curve in curves: self.start_new_path(curve[0]) self.add_points_as_corners(curve[1:]) if self.use_smoothing: self.make_smooth() return self def init_points(self) -> None: self.generate_points() ================================================ FILE: manim/mobject/graphing/number_line.py ================================================ """Mobject representing a number line.""" from __future__ import annotations from manim.mobject.mobject import Mobject from manim.mobject.opengl.opengl_vectorized_mobject import OpenGLVMobject __all__ = ["NumberLine", "UnitInterval"] from collections.abc import Callable, Iterable, Sequence from typing
0 for curve in curves: self.start_new_path(curve[0]) self.add_points_as_corners(curve[1:]) if self.use_smoothing: self.make_smooth() return self def init_points(self) -> None: self.generate_points() ================================================ FILE: manim/mobject/graphing/number_line.py ================================================ """Mobject representing a number line.""" from __future__ import annotations from manim.mobject.mobject import Mobject from manim.mobject.opengl.opengl_vectorized_mobject import OpenGLVMobject __all__ = ["NumberLine", "UnitInterval"] from collections.abc import Callable, Iterable, Sequence from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Any from typing_extensions import Self from manim.mobject.geometry.tips import ArrowTip from manim.typing import Point3D, Point3DLike, Vector3D import numpy as np from manim import config from manim.constants import * from manim.mobject.geometry.line import Line from manim.mobject.graphing.scale import LinearBase, _ScaleBase from manim.mobject.text.numbers import DecimalNumber, Integer from manim.mobject.text.tex_mobject import MathTex, Tex from manim.mobject.text.text_mobject import Text from manim.mobject.types.vectorized_mobject import VGroup, VMobject from manim.utils.bezier import interpolate from manim.utils.config_ops import merge_dicts_recursively from manim.utils.space_ops import normalize class NumberLine(Line): """Creates a number line with tick marks. Parameters ---------- x_range The ``[x_min, x_max, x_step]`` values to create the line. length The length of the number line. unit_size The distance between each tick of the line. Overwritten by :attr:`length`, if specified. include_ticks Whether to include ticks on the number line. tick_size The length of each tick mark. numbers_with_elongated_ticks An iterable of specific values with elongated ticks. longer_tick_multiple Influences how many times larger elongated ticks are than regular ticks (2 = 2x). rotation The angle (in radians) at which the line is rotated. stroke_width The thickness of the line. include_tip Whether to add a tip to the end of the line. tip_width The width of the tip. tip_height The height of the tip. tip_shape The mobject class used to construct the tip, or ``None`` (the default) for the default arrow tip. Passed classes have to inherit from :class:`.ArrowTip`. include_numbers Whether to add numbers to the tick marks. The number of decimal places is determined by the step size, this default can be overridden by ``decimal_number_config``. scaling The way the ``x_range`` is value is scaled, i.e. :class:`~.LogBase` for a logarithmic numberline. Defaults to :class:`~.LinearBase`. font_size The size of the label mobjects. Defaults to 36. label_direction The specific position to which label mobjects are added on the line. label_constructor Determines the mobject class that will be used to construct the labels of the number line. line_to_number_buff The distance between the line and the label mobject. decimal_number_config Arguments that can be passed to :class:`~.numbers.DecimalNumber` to influence number mobjects. numbers_to_exclude An explicit iterable of numbers to not be added to the number line. numbers_to_include An explicit iterable of numbers to add to the number line kwargs Additional arguments to be passed to :class:`~.Line`. .. note:: Number ranges that include both negative and positive values will be generated from the 0 point, and may not include a tick at the min / max values as the tick locations are dependent on the step size. Examples -------- .. manim:: NumberLineExample :save_last_frame: class NumberLineExample(Scene): def construct(self): l0 = NumberLine( x_range=[-10, 10, 2], length=10, color=BLUE, include_numbers=True, label_direction=UP, ) l1 = NumberLine( x_range=[-10, 10, 2], unit_size=0.5, numbers_with_elongated_ticks=[-2, 4], include_numbers=True, font_size=24, ) num6 = l1.numbers[8] num6.set_color(RED) l2 = NumberLine( x_range=[-2.5, 2.5 + 0.5, 0.5], length=12, decimal_number_config={"num_decimal_places":
the step size. Examples -------- .. manim:: NumberLineExample :save_last_frame: class NumberLineExample(Scene): def construct(self): l0 = NumberLine( x_range=[-10, 10, 2], length=10, color=BLUE, include_numbers=True, label_direction=UP, ) l1 = NumberLine( x_range=[-10, 10, 2], unit_size=0.5, numbers_with_elongated_ticks=[-2, 4], include_numbers=True, font_size=24, ) num6 = l1.numbers[8] num6.set_color(RED) l2 = NumberLine( x_range=[-2.5, 2.5 + 0.5, 0.5], length=12, decimal_number_config={"num_decimal_places": 2}, include_numbers=True, ) l3 = NumberLine( x_range=[-5, 5 + 1, 1], length=6, include_tip=True, include_numbers=True, rotation=10 * DEGREES, ) line_group = VGroup(l0, l1, l2, l3).arrange(DOWN, buff=1) self.add(line_group) """ def __init__( self, x_range: Sequence[float] | None = None, # must be first length: float | None = None, unit_size: float = 1, # ticks include_ticks: bool = True, tick_size: float = 0.1, numbers_with_elongated_ticks: Iterable[float] | None = None, longer_tick_multiple: int = 2, exclude_origin_tick: bool = False, # visuals rotation: float = 0, stroke_width: float = 2.0, # tip include_tip: bool = False, tip_width: float = DEFAULT_ARROW_TIP_LENGTH, tip_height: float = DEFAULT_ARROW_TIP_LENGTH, tip_shape: type[ArrowTip] | None = None, # numbers/labels include_numbers: bool = False, font_size: float = 36, label_direction: Point3DLike = DOWN, label_constructor: type[MathTex] = MathTex, scaling: _ScaleBase = LinearBase(), line_to_number_buff: float = MED_SMALL_BUFF, decimal_number_config: dict | None = None, numbers_to_exclude: Iterable[float] | None = None, numbers_to_include: Iterable[float] | None = None, **kwargs: Any, ): # avoid mutable arguments in defaults if numbers_to_exclude is None: numbers_to_exclude = [] if numbers_with_elongated_ticks is None: numbers_with_elongated_ticks = [] if x_range is None: x_range = [ round(-config["frame_x_radius"]), round(config["frame_x_radius"]), 1, ] elif len(x_range) == 2: # adds x_step if not specified. not sure how to feel about this. a user can't know default without peeking at source code x_range = [*x_range, 1] if decimal_number_config is None: decimal_number_config = { "num_decimal_places": self._decimal_places_from_step(x_range[2]), } # turn into a NumPy array to scale by just applying the function self.x_range = np.array(x_range, dtype=float) self.x_min: float self.x_max: float self.x_step: float self.x_min, self.x_max, self.x_step = scaling.function(self.x_range) self.length = length self.unit_size = unit_size # ticks self.include_ticks = include_ticks self.tick_size = tick_size self.numbers_with_elongated_ticks = numbers_with_elongated_ticks self.longer_tick_multiple = longer_tick_multiple self.exclude_origin_tick = exclude_origin_tick # visuals self.rotation = rotation # tip self.include_tip = include_tip self.tip_width = tip_width self.tip_height = tip_height # numbers self.font_size = font_size self.include_numbers = include_numbers self.label_direction = label_direction self.label_constructor = label_constructor self.line_to_number_buff = line_to_number_buff self.decimal_number_config = decimal_number_config self.numbers_to_exclude = numbers_to_exclude self.numbers_to_include = numbers_to_include self.scaling = scaling super().__init__( self.x_range[0] * RIGHT, self.x_range[1] * RIGHT, stroke_width=stroke_width, **kwargs, ) if self.length: self.set_length(self.length) self.unit_size = self.get_unit_size() else: self.scale(self.unit_size) self.center() if self.include_tip: self.add_tip( tip_length=self.tip_height, tip_width=self.tip_width, tip_shape=tip_shape, ) self.tip.set_stroke(self.stroke_color, self.stroke_width) if self.include_ticks: self.add_ticks() self.rotate(self.rotation) if self.include_numbers or self.numbers_to_include is not None: if self.scaling.custom_labels: tick_range = self.get_tick_range() custom_labels = self.scaling.get_custom_labels( tick_range, unit_decimal_places=decimal_number_config["num_decimal_places"], ) self.add_labels( dict( zip( tick_range, custom_labels, ) ), ) else: self.add_numbers( x_values=self.numbers_to_include, excluding=self.numbers_to_exclude, font_size=self.font_size, ) def rotate_about_zero( self, angle: float, axis: Vector3D = OUT, **kwargs: Any ) -> Self: return self.rotate_about_number(0, angle, axis, **kwargs) def rotate_about_number( self, number: float, angle: float, axis: Vector3D = OUT, **kwargs: Any ) -> Self: return self.rotate(angle, axis, about_point=self.n2p(number), **kwargs) def add_ticks(self) -> None: """Adds ticks to the number line. Ticks can be accessed after creation via ``self.ticks``. """ ticks = VGroup() elongated_tick_size = self.tick_size * self.longer_tick_multiple
axis, **kwargs) def rotate_about_number( self, number: float, angle: float, axis: Vector3D = OUT, **kwargs: Any ) -> Self: return self.rotate(angle, axis, about_point=self.n2p(number), **kwargs) def add_ticks(self) -> None: """Adds ticks to the number line. Ticks can be accessed after creation via ``self.ticks``. """ ticks = VGroup() elongated_tick_size = self.tick_size * self.longer_tick_multiple elongated_tick_offsets = ( np.array(self.numbers_with_elongated_ticks) - self.x_min ) for x in self.get_tick_range(): size = self.tick_size if np.any(np.isclose(x - self.x_min, elongated_tick_offsets)): size = elongated_tick_size ticks.add(self.get_tick(x, size)) self.add(ticks) self.ticks = ticks def get_tick(self, x: float, size: float | None = None) -> Line: """Generates a tick and positions it along the number line. Parameters ---------- x The position of the tick. size The factor by which the tick is scaled. Returns ------- :class:`~.Line` A positioned tick. """ if size is None: size = self.tick_size result = Line(size * DOWN, size * UP) result.rotate(self.get_angle()) result.move_to(self.number_to_point(x)) result.match_style(self) return result def get_tick_marks(self) -> VGroup: return self.ticks def get_tick_range(self) -> np.ndarray: """Generates the range of values on which labels are plotted based on the ``x_range`` attribute of the number line. Returns ------- np.ndarray A numpy array of floats represnting values along the number line. """ x_min, x_max, x_step = self.x_range if not self.include_tip: x_max += 1e-6 # Handle cases where min and max are both positive or both negative if x_min < x_max < 0 or x_max > x_min > 0: tick_range = np.arange(x_min, x_max, x_step) else: start_point = 0 if self.exclude_origin_tick: start_point += x_step x_min_segment = np.arange(start_point, np.abs(x_min) + 1e-6, x_step) * -1 x_max_segment = np.arange(start_point, x_max, x_step) tick_range = np.unique(np.concatenate((x_min_segment, x_max_segment))) return self.scaling.function(tick_range) def number_to_point(self, number: float | np.ndarray) -> np.ndarray: """Accepts a value along the number line and returns a point with respect to the scene. Equivalent to `NumberLine @ number` Parameters ---------- number The value to be transformed into a coordinate. Or a list of values. Returns ------- np.ndarray A point with respect to the scene's coordinate system. Or a list of points. Examples -------- >>> from manim import NumberLine >>> number_line = NumberLine() >>> number_line.number_to_point(0) array([0., 0., 0.]) >>> number_line.number_to_point(1) array([1., 0., 0.]) >>> number_line @ 1 array([1., 0., 0.]) >>> number_line.number_to_point([1, 2, 3]) array([[1., 0., 0.], [2., 0., 0.], [3., 0., 0.]]) """ number = np.asarray(number) scalar = number.ndim == 0 number = self.scaling.inverse_function(number) alphas = (number - self.x_range[0]) / (self.x_range[1] - self.x_range[0]) alphas = float(alphas) if scalar else np.vstack(alphas) val = interpolate(self.get_start(), self.get_end(), alphas) return val def point_to_number(self, point: Sequence[float]) -> float: """Accepts a point with respect to the scene and returns a float along the number line. Parameters ---------- point A sequence of values consisting of ``(x_coord, y_coord, z_coord)``. Returns ------- float A float representing a value along the number line. Examples -------- >>> from manim import NumberLine >>> number_line = NumberLine() >>> number_line.point_to_number((0, 0, 0)) np.float64(0.0) >>> number_line.point_to_number((1, 0, 0)) np.float64(1.0) >>> number_line.point_to_number([[0.5, 0, 0], [1, 0, 0], [1.5, 0, 0]]) array([0.5, 1. , 1.5]) """ point = np.asarray(point) start, end = self.get_start_and_end() unit_vect = normalize(end - start) proportion: float = np.dot(point - start, unit_vect) / np.dot( end
number_line = NumberLine() >>> number_line.point_to_number((0, 0, 0)) np.float64(0.0) >>> number_line.point_to_number((1, 0, 0)) np.float64(1.0) >>> number_line.point_to_number([[0.5, 0, 0], [1, 0, 0], [1.5, 0, 0]]) array([0.5, 1. , 1.5]) """ point = np.asarray(point) start, end = self.get_start_and_end() unit_vect = normalize(end - start) proportion: float = np.dot(point - start, unit_vect) / np.dot( end - start, unit_vect ) return interpolate(self.x_min, self.x_max, proportion) def n2p(self, number: float | np.ndarray) -> Point3D: """Abbreviation for :meth:`~.NumberLine.number_to_point`.""" return self.number_to_point(number) def p2n(self, point: Point3DLike) -> float: """Abbreviation for :meth:`~.NumberLine.point_to_number`.""" return self.point_to_number(point) def get_unit_size(self) -> float: val: float = self.get_length() / (self.x_range[1] - self.x_range[0]) return val def get_unit_vector(self) -> Vector3D: return super().get_unit_vector() * self.unit_size def get_number_mobject( self, x: float, direction: Vector3D | None = None, buff: float | None = None, font_size: float | None = None, label_constructor: type[MathTex] | None = None, **number_config: dict[str, Any], ) -> VMobject: """Generates a positioned :class:`~.DecimalNumber` mobject generated according to ``label_constructor``. Parameters ---------- x The x-value at which the mobject should be positioned. direction Determines the direction at which the label is positioned next to the line. buff The distance of the label from the line. font_size The font size of the label mobject. label_constructor The :class:`~.VMobject` class that will be used to construct the label. Defaults to the ``label_constructor`` attribute of the number line if not specified. Returns ------- :class:`~.DecimalNumber` The positioned mobject. """ number_config_merged = merge_dicts_recursively( self.decimal_number_config, number_config, ) if direction is None: direction = self.label_direction if buff is None: buff = self.line_to_number_buff if font_size is None: font_size = self.font_size if label_constructor is None: label_constructor = self.label_constructor num_mob = DecimalNumber( x, font_size=font_size, mob_class=label_constructor, **number_config_merged, ) num_mob.next_to(self.number_to_point(x), direction=direction, buff=buff) if x < 0 and self.label_direction[0] == 0: # Align without the minus sign num_mob.shift(num_mob[0].width * LEFT / 2) return num_mob def get_number_mobjects(self, *numbers: float, **kwargs: Any) -> VGroup: if len(numbers) == 0: numbers = self.default_numbers_to_display() return VGroup([self.get_number_mobject(number, **kwargs) for number in numbers]) def get_labels(self) -> VGroup: return self.get_number_mobjects() def add_numbers( self, x_values: Iterable[float] | None = None, excluding: Iterable[float] | None = None, font_size: float | None = None, label_constructor: type[MathTex] | None = None, **kwargs: Any, ) -> Self: """Adds :class:`~.DecimalNumber` mobjects representing their position at each tick of the number line. The numbers can be accessed after creation via ``self.numbers``. Parameters ---------- x_values An iterable of the values used to position and create the labels. Defaults to the output produced by :meth:`~.NumberLine.get_tick_range` excluding A list of values to exclude from :attr:`x_values`. font_size The font size of the labels. Defaults to the ``font_size`` attribute of the number line. label_constructor The :class:`~.VMobject` class that will be used to construct the label. Defaults to the ``label_constructor`` attribute of the number line if not specified. """ if x_values is None: x_values = self.get_tick_range() if excluding is None: excluding = self.numbers_to_exclude if font_size is None: font_size = self.font_size if label_constructor is None: label_constructor = self.label_constructor numbers = VGroup() for x in x_values: if x in excluding: continue numbers.add( self.get_number_mobject( x, font_size=font_size, label_constructor=label_constructor, **kwargs, ) ) self.add(numbers) self.numbers = numbers return self def add_labels( self, dict_values:
excluding is None: excluding = self.numbers_to_exclude if font_size is None: font_size = self.font_size if label_constructor is None: label_constructor = self.label_constructor numbers = VGroup() for x in x_values: if x in excluding: continue numbers.add( self.get_number_mobject( x, font_size=font_size, label_constructor=label_constructor, **kwargs, ) ) self.add(numbers) self.numbers = numbers return self def add_labels( self, dict_values: dict[float, str | float | VMobject], direction: Point3DLike | None = None, buff: float | None = None, font_size: float | None = None, label_constructor: type[MathTex] | None = None, ) -> Self: """Adds specifically positioned labels to the :class:`~.NumberLine` using a ``dict``. The labels can be accessed after creation via ``self.labels``. Parameters ---------- dict_values A dictionary consisting of the position along the number line and the mobject to be added: ``{1: Tex("Monday"), 3: Tex("Tuesday")}``. :attr:`label_constructor` will be used to construct the labels if the value is not a mobject (``str`` or ``float``). direction Determines the direction at which the label is positioned next to the line. buff The distance of the label from the line. font_size The font size of the mobject to be positioned. label_constructor The :class:`~.VMobject` class that will be used to construct the label. Defaults to the ``label_constructor`` attribute of the number line if not specified. Raises ------ AttributeError If the label does not have a ``font_size`` attribute, an ``AttributeError`` is raised. """ direction = self.label_direction if direction is None else direction buff = self.line_to_number_buff if buff is None else buff font_size = self.font_size if font_size is None else font_size if label_constructor is None: label_constructor = self.label_constructor labels = VGroup() for x, label in dict_values.items(): # TODO: remove this check and ability to call # this method via CoordinateSystem.add_coordinates() # must be explicitly called if isinstance(label, str) and label_constructor is MathTex: label = Tex(label) else: label = self._create_label_tex(label, label_constructor) if hasattr(label, "font_size"): assert isinstance(label, (MathTex, Tex, Text, Integer)), label label.font_size = font_size else: raise AttributeError(f"{label} is not compatible with add_labels.") label.next_to(self.number_to_point(x), direction=direction, buff=buff) labels.add(label) self.labels = labels self.add(labels) return self def _create_label_tex( self, label_tex: str | float | VMobject, label_constructor: Callable | None = None, **kwargs: Any, ) -> VMobject: """Checks if the label is a :class:`~.VMobject`, otherwise, creates a label by passing ``label_tex`` to ``label_constructor``. Parameters ---------- label_tex The label for which a mobject should be created. If the label already is a mobject, no new mobject is created. label_constructor Optional. A class or function returning a mobject when passing ``label_tex`` as an argument. If ``None`` is passed (the default), the label constructor from the :attr:`.label_constructor` attribute is used. Returns ------- :class:`~.VMobject` The label. """ if isinstance(label_tex, (VMobject, OpenGLVMobject)): return label_tex if label_constructor is None: label_constructor = self.label_constructor if isinstance(label_tex, str): return label_constructor(label_tex, **kwargs) return label_constructor(str(label_tex), **kwargs) @staticmethod def _decimal_places_from_step(step: float) -> int: step_str = str(step) if "." not in step_str: return 0 return len(step_str.split(".")[-1]) def __matmul__(self, other: float) -> Point3D: return self.n2p(other) def __rmatmul__(self, other: Point3DLike | Mobject) -> float: if isinstance(other, Mobject): other = other.get_center() return self.p2n(other) class UnitInterval(NumberLine): def __init__( self, unit_size: float = 10, numbers_with_elongated_ticks: list[float] | None = None, decimal_number_config:
str(step) if "." not in step_str: return 0 return len(step_str.split(".")[-1]) def __matmul__(self, other: float) -> Point3D: return self.n2p(other) def __rmatmul__(self, other: Point3DLike | Mobject) -> float: if isinstance(other, Mobject): other = other.get_center() return self.p2n(other) class UnitInterval(NumberLine): def __init__( self, unit_size: float = 10, numbers_with_elongated_ticks: list[float] | None = None, decimal_number_config: dict[str, Any] | None = None, **kwargs: Any, ): numbers_with_elongated_ticks = ( [0, 1] if numbers_with_elongated_ticks is None else numbers_with_elongated_ticks ) decimal_number_config = ( { "num_decimal_places": 1, } if decimal_number_config is None else decimal_number_config ) super().__init__( x_range=(0, 1, 0.1), unit_size=unit_size, numbers_with_elongated_ticks=numbers_with_elongated_ticks, decimal_number_config=decimal_number_config, **kwargs, ) ================================================ FILE: manim/mobject/graphing/probability.py ================================================ """Mobjects representing objects from probability theory and statistics.""" from __future__ import annotations __all__ = ["SampleSpace", "BarChart"] from collections.abc import Iterable, MutableSequence, Sequence from typing import Any import numpy as np from manim import config, logger from manim.constants import * from manim.mobject.geometry.polygram import Rectangle from manim.mobject.graphing.coordinate_systems import Axes from manim.mobject.opengl.opengl_vectorized_mobject import OpenGLVMobject from manim.mobject.svg.brace import Brace from manim.mobject.text.tex_mobject import MathTex, Tex from manim.mobject.types.vectorized_mobject import VGroup, VMobject from manim.typing import Vector3D from manim.utils.color import ( BLUE_E, DARK_GREY, GREEN_E, LIGHT_GREY, MAROON_B, YELLOW, ParsableManimColor, color_gradient, ) from manim.utils.iterables import tuplify EPSILON = 0.0001 class SampleSpace(Rectangle): """A mobject representing a twodimensional rectangular sampling space. Examples -------- .. manim:: ExampleSampleSpace :save_last_frame: class ExampleSampleSpace(Scene): def construct(self): poly1 = SampleSpace(stroke_width=15, fill_opacity=1) poly2 = SampleSpace(width=5, height=3, stroke_width=5, fill_opacity=0.5) poly3 = SampleSpace(width=2, height=2, stroke_width=5, fill_opacity=0.1) poly3.divide_vertically(p_list=np.array([0.37, 0.13, 0.5]), colors=[BLACK, WHITE, GRAY], vect=RIGHT) poly_group = VGroup(poly1, poly2, poly3).arrange() self.add(poly_group) """ def __init__( self, height: float = 3, width: float = 3, fill_color: ParsableManimColor = DARK_GREY, fill_opacity: float = 1, stroke_width: float = 0.5, stroke_color: ParsableManimColor = LIGHT_GREY, default_label_scale_val: float = 1, ): super().__init__( height=height, width=width, fill_color=fill_color, fill_opacity=fill_opacity, stroke_width=stroke_width, stroke_color=stroke_color, ) self.default_label_scale_val = default_label_scale_val def add_title( self, title: str = "Sample space", buff: float = MED_SMALL_BUFF ) -> None: # TODO, should this really exist in SampleSpaceScene title_mob = Tex(title) if title_mob.width > self.width: title_mob.width = self.width title_mob.next_to(self, UP, buff=buff) self.title = title_mob self.add(title_mob) def add_label(self, label: str) -> None: self.label = label def complete_p_list(self, p_list: float | Iterable[float]) -> list[float]: p_list_tuplified: tuple[float] = tuplify(p_list) new_p_list = list(p_list_tuplified) remainder = 1.0 - sum(new_p_list) if abs(remainder) > EPSILON: new_p_list.append(remainder) return new_p_list def get_division_along_dimension( self, p_list: float | Iterable[float], dim: int, colors: Sequence[ParsableManimColor], vect: Vector3D, ) -> VGroup: p_list_complete = self.complete_p_list(p_list) colors_in_gradient = color_gradient(colors, len(p_list_complete)) last_point = self.get_edge_center(-vect) parts = VGroup() for factor, color in zip(p_list_complete, colors_in_gradient): part = SampleSpace() part.set_fill(color, 1) part.replace(self, stretch=True) part.stretch(factor, dim) part.move_to(last_point, -vect) last_point = part.get_edge_center(vect) parts.add(part) return parts def get_horizontal_division( self, p_list: float | Iterable[float], colors: Sequence[ParsableManimColor] = [GREEN_E, BLUE_E], vect: Vector3D = DOWN, ) -> VGroup: return self.get_division_along_dimension(p_list, 1, colors, vect) def get_vertical_division( self, p_list: float | Iterable[float], colors: Sequence[ParsableManimColor] = [MAROON_B, YELLOW], vect: Vector3D = RIGHT, ) -> VGroup: return self.get_division_along_dimension(p_list, 0, colors, vect) def divide_horizontally(self, *args: Any, **kwargs: Any) -> None: self.horizontal_parts = self.get_horizontal_division(*args, **kwargs) self.add(self.horizontal_parts) def divide_vertically(self, *args: Any, **kwargs: Any) -> None: self.vertical_parts = self.get_vertical_division(*args, **kwargs) self.add(self.vertical_parts) def get_subdivision_braces_and_labels( self, parts: VGroup, labels: list[str | VMobject | OpenGLVMobject], direction: Vector3D, buff: float = SMALL_BUFF, min_num_quads:
VGroup: return self.get_division_along_dimension(p_list, 0, colors, vect) def divide_horizontally(self, *args: Any, **kwargs: Any) -> None: self.horizontal_parts = self.get_horizontal_division(*args, **kwargs) self.add(self.horizontal_parts) def divide_vertically(self, *args: Any, **kwargs: Any) -> None: self.vertical_parts = self.get_vertical_division(*args, **kwargs) self.add(self.vertical_parts) def get_subdivision_braces_and_labels( self, parts: VGroup, labels: list[str | VMobject | OpenGLVMobject], direction: Vector3D, buff: float = SMALL_BUFF, min_num_quads: int = 1, ) -> VGroup: label_mobs = VGroup() braces = VGroup() for label, part in zip(labels, parts): brace = Brace(part, direction, min_num_quads=min_num_quads, buff=buff) if isinstance(label, (VMobject, OpenGLVMobject)): label_mob = label else: label_mob = MathTex(label) label_mob.scale(self.default_label_scale_val) label_mob.next_to(brace, direction, buff) braces.add(brace) assert isinstance(label_mob, VMobject) label_mobs.add(label_mob) parts.braces = braces # type: ignore[attr-defined] parts.labels = label_mobs # type: ignore[attr-defined] parts.label_kwargs = { # type: ignore[attr-defined] "labels": label_mobs.copy(), "direction": direction, "buff": buff, } return VGroup(parts.braces, parts.labels) # type: ignore[arg-type] def get_side_braces_and_labels( self, labels: list[str | VMobject | OpenGLVMobject], direction: Vector3D = LEFT, **kwargs: Any, ) -> VGroup: assert hasattr(self, "horizontal_parts") parts = self.horizontal_parts return self.get_subdivision_braces_and_labels( parts, labels, direction, **kwargs ) def get_top_braces_and_labels( self, labels: list[str | VMobject | OpenGLVMobject], **kwargs: Any ) -> VGroup: assert hasattr(self, "vertical_parts") parts = self.vertical_parts return self.get_subdivision_braces_and_labels(parts, labels, UP, **kwargs) def get_bottom_braces_and_labels( self, labels: list[str | VMobject | OpenGLVMobject], **kwargs: Any ) -> VGroup: assert hasattr(self, "vertical_parts") parts = self.vertical_parts return self.get_subdivision_braces_and_labels(parts, labels, DOWN, **kwargs) def add_braces_and_labels(self) -> None: for attr in "horizontal_parts", "vertical_parts": if not hasattr(self, attr): continue parts = getattr(self, attr) for subattr in "braces", "labels": if hasattr(parts, subattr): self.add(getattr(parts, subattr)) def __getitem__(self, index: int) -> SampleSpace: if hasattr(self, "horizontal_parts"): val: SampleSpace = self.horizontal_parts[index] return val elif hasattr(self, "vertical_parts"): val = self.vertical_parts[index] return val return self.split()[index] class BarChart(Axes): """Creates a bar chart. Inherits from :class:`~.Axes`, so it shares its methods and attributes. Each axis inherits from :class:`~.NumberLine`, so pass in ``x_axis_config``/``y_axis_config`` to control their attributes. Parameters ---------- values A sequence of values that determines the height of each bar. Accepts negative values. bar_names A sequence of names for each bar. Does not have to match the length of ``values``. y_range The y_axis range of values. If ``None``, the range will be calculated based on the min/max of ``values`` and the step will be calculated based on ``y_length``. x_length The length of the x-axis. If ``None``, it is automatically calculated based on the number of values and the width of the screen. y_length The length of the y-axis. bar_colors The color for the bars. Accepts a sequence of colors (can contain just one item). If the length of``bar_colors`` does not match that of ``values``, intermediate colors will be automatically determined. bar_width The length of a bar. Must be between 0 and 1. bar_fill_opacity The fill opacity of the bars. bar_stroke_width The stroke width of the bars. Examples -------- .. manim:: BarChartExample :save_last_frame: class BarChartExample(Scene): def construct(self): chart = BarChart( values=[-5, 40, -10, 20, -3], bar_names=["one", "two", "three", "four", "five"], y_range=[-20, 50, 10], y_length=6, x_length=10, x_axis_config={"font_size": 36}, ) c_bar_lbls = chart.get_bar_labels(font_size=48) self.add(chart, c_bar_lbls) """ def __init__( self, values: MutableSequence[float], bar_names: Sequence[str] | None = None, y_range: Sequence[float] | None = None, x_length: float | None = None, y_length: float
BarChart( values=[-5, 40, -10, 20, -3], bar_names=["one", "two", "three", "four", "five"], y_range=[-20, 50, 10], y_length=6, x_length=10, x_axis_config={"font_size": 36}, ) c_bar_lbls = chart.get_bar_labels(font_size=48) self.add(chart, c_bar_lbls) """ def __init__( self, values: MutableSequence[float], bar_names: Sequence[str] | None = None, y_range: Sequence[float] | None = None, x_length: float | None = None, y_length: float | None = None, bar_colors: Iterable[str] = [ "#003f5c", "#58508d", "#bc5090", "#ff6361", "#ffa600", ], bar_width: float = 0.6, bar_fill_opacity: float = 0.7, bar_stroke_width: float = 3, **kwargs: Any, ): if isinstance(bar_colors, str): logger.warning( "Passing a string to `bar_colors` has been deprecated since v0.15.2 and will be removed after v0.17.0, the parameter must be a list. " ) bar_colors = list(bar_colors) y_length = y_length if y_length is not None else config.frame_height - 4 self.values = values self.bar_names = bar_names self.bar_colors = bar_colors self.bar_width = bar_width self.bar_fill_opacity = bar_fill_opacity self.bar_stroke_width = bar_stroke_width x_range = [0, len(self.values), 1] if y_range is None: y_range = [ min(0, min(self.values)), max(0, max(self.values)), round(max(self.values) / y_length, 2), ] elif len(y_range) == 2: y_range = [*y_range, round(max(self.values) / y_length, 2)] if x_length is None: x_length = min(len(self.values), config.frame_width - 2) x_axis_config = {"font_size": 24, "label_constructor": Tex} self._update_default_configs( (x_axis_config,), (kwargs.pop("x_axis_config", None),) ) self.bars: VGroup = VGroup() self.x_labels: VGroup | None = None self.bar_labels: VGroup | None = None super().__init__( x_range=x_range, y_range=y_range, x_length=x_length, y_length=y_length, x_axis_config=x_axis_config, tips=kwargs.pop("tips", False), **kwargs, ) self._add_bars() if self.bar_names is not None: self._add_x_axis_labels() self.y_axis.add_numbers() def _update_colors(self) -> None: """Initialize the colors of the bars of the chart. Sets the color of ``self.bars`` via ``self.bar_colors``. Primarily used when the bars are initialized with ``self._add_bars`` or updated via ``self.change_bar_values``. """ self.bars.set_color_by_gradient(*self.bar_colors) def _add_x_axis_labels(self) -> None: """Essentially :meth`:~.NumberLine.add_labels`, but differs in that the direction of the label with respect to the x_axis changes to UP or DOWN depending on the value. UP for negative values and DOWN for positive values. """ assert isinstance(self.bar_names, list) val_range = np.arange( 0.5, len(self.bar_names), 1 ) # 0.5 shifted so that labels are centered, not on ticks labels = VGroup() for i, (value, bar_name) in enumerate(zip(val_range, self.bar_names)): # to accommodate negative bars, the label may need to be # below or above the x_axis depending on the value of the bar direction = UP if self.values[i] < 0 else DOWN bar_name_label: MathTex = self.x_axis.label_constructor(bar_name) bar_name_label.font_size = self.x_axis.font_size bar_name_label.next_to( self.x_axis.number_to_point(value), direction=direction, buff=self.x_axis.line_to_number_buff, ) labels.add(bar_name_label) self.x_axis.labels = labels self.x_axis.add(labels) def _create_bar(self, bar_number: int, value: float) -> Rectangle: """Creates a positioned bar on the chart. Parameters ---------- bar_number Determines the x-position of the bar. value The value that determines the height of the bar. Returns ------- Rectangle A positioned rectangle representing a bar on the chart. """ # bar measurements relative to the axis # distance from between the y-axis and the top of the bar bar_h = abs(self.c2p(0, value)[1] - self.c2p(0, 0)[1]) # width of the bar bar_w = self.c2p(self.bar_width, 0)[0] - self.c2p(0, 0)[0] bar = Rectangle( height=bar_h, width=bar_w, stroke_width=self.bar_stroke_width, fill_opacity=self.bar_fill_opacity, ) pos = UP if (value >= 0) else DOWN bar.next_to(self.c2p(bar_number + 0.5, 0), pos, buff=0) return bar def _add_bars(self) -> None: for i, value in
abs(self.c2p(0, value)[1] - self.c2p(0, 0)[1]) # width of the bar bar_w = self.c2p(self.bar_width, 0)[0] - self.c2p(0, 0)[0] bar = Rectangle( height=bar_h, width=bar_w, stroke_width=self.bar_stroke_width, fill_opacity=self.bar_fill_opacity, ) pos = UP if (value >= 0) else DOWN bar.next_to(self.c2p(bar_number + 0.5, 0), pos, buff=0) return bar def _add_bars(self) -> None: for i, value in enumerate(self.values): tmp_bar = self._create_bar(bar_number=i, value=value) self.bars.add(tmp_bar) self._update_colors() self.add_to_back(self.bars) def get_bar_labels( self, color: ParsableManimColor | None = None, font_size: float = 24, buff: float = MED_SMALL_BUFF, label_constructor: type[MathTex] = Tex, ) -> VGroup: """Annotates each bar with its corresponding value. Use ``self.bar_labels`` to access the labels after creation. Parameters ---------- color The color of each label. By default ``None`` and is based on the parent's bar color. font_size The font size of each label. buff The distance from each label to its bar. By default 0.4. label_constructor The Mobject class to construct the labels, by default :class:`~.Tex`. Examples -------- .. manim:: GetBarLabelsExample :save_last_frame: class GetBarLabelsExample(Scene): def construct(self): chart = BarChart(values=[10, 9, 8, 7, 6, 5, 4, 3, 2, 1], y_range=[0, 10, 1]) c_bar_lbls = chart.get_bar_labels( color=WHITE, label_constructor=MathTex, font_size=36 ) self.add(chart, c_bar_lbls) """ bar_labels = VGroup() for bar, value in zip(self.bars, self.values): bar_lbl: MathTex = label_constructor(str(value)) if color is None: bar_lbl.set_color(bar.get_fill_color()) else: bar_lbl.set_color(color) bar_lbl.font_size = font_size pos = UP if (value >= 0) else DOWN bar_lbl.next_to(bar, pos, buff=buff) bar_labels.add(bar_lbl) return bar_labels def change_bar_values( self, values: Iterable[float], update_colors: bool = True ) -> None: """Updates the height of the bars of the chart. Parameters ---------- values The values that will be used to update the height of the bars. Does not have to match the number of bars. update_colors Whether to re-initalize the colors of the bars based on ``self.bar_colors``. Examples -------- .. manim:: ChangeBarValuesExample :save_last_frame: class ChangeBarValuesExample(Scene): def construct(self): values=[-10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10] chart = BarChart( values, y_range=[-10, 10, 2], y_axis_config={"font_size": 24}, ) self.add(chart) chart.change_bar_values(list(reversed(values))) self.add(chart.get_bar_labels(font_size=24)) """ for i, (bar, value) in enumerate(zip(self.bars, values)): chart_val = self.values[i] if chart_val > 0: bar_lim = bar.get_bottom() aligned_edge = DOWN else: bar_lim = bar.get_top() aligned_edge = UP # check if the bar has height if chart_val != 0: quotient = value / chart_val if quotient < 0: aligned_edge = UP if chart_val > 0 else DOWN # if the bar is already positive, then we now want to move it # so that it is negative. So, we move the top edge of the bar # to the location of the previous bottom # if already negative, then we move the bottom edge of the bar # to the location of the previous top bar.stretch_to_fit_height(abs(quotient) * bar.height) else: # create a new bar since the current one has a height of zero (doesn't exist) temp_bar = self._create_bar(i, value) self.bars.remove(bar) self.bars.insert(i, temp_bar) bar.move_to(bar_lim, aligned_edge) if update_colors: self._update_colors() self.values[: len(list(values))] = values ================================================ FILE: manim/mobject/graphing/scale.py ================================================ from __future__ import annotations import math from collections.abc import Iterable from typing import TYPE_CHECKING, Any, overload import numpy as np __all__ = ["LogBase", "LinearBase"] from manim.mobject.text.numbers import Integer if TYPE_CHECKING: from typing import Callable
self.bars.remove(bar) self.bars.insert(i, temp_bar) bar.move_to(bar_lim, aligned_edge) if update_colors: self._update_colors() self.values[: len(list(values))] = values ================================================ FILE: manim/mobject/graphing/scale.py ================================================ from __future__ import annotations import math from collections.abc import Iterable from typing import TYPE_CHECKING, Any, overload import numpy as np __all__ = ["LogBase", "LinearBase"] from manim.mobject.text.numbers import Integer if TYPE_CHECKING: from typing import Callable from manim.mobject.types.vectorized_mobject import VMobject class _ScaleBase: """Scale baseclass for graphing/functions. Parameters ---------- custom_labels Whether to create custom labels when plotted on a :class:`~.NumberLine`. """ def __init__(self, custom_labels: bool = False): self.custom_labels = custom_labels @overload def function(self, value: float) -> float: ... @overload def function(self, value: np.ndarray) -> np.ndarray: ... def function(self, value: float) -> float: """The function that will be used to scale the values. Parameters ---------- value The number/``np.ndarray`` to be scaled. Returns ------- float The value after it has undergone the scaling. Raises ------ NotImplementedError Must be subclassed. """ raise NotImplementedError def inverse_function(self, value: float) -> float: """The inverse of ``function``. Used for plotting on a particular axis. Raises ------ NotImplementedError Must be subclassed. """ raise NotImplementedError def get_custom_labels( self, val_range: Iterable[float], **kw_args: Any, ) -> Iterable[VMobject]: """Custom instructions for generating labels along an axis. Parameters ---------- val_range The position of labels. Also used for defining the content of the labels. Returns ------- Dict A list consisting of the labels. Can be passed to :meth:`~.NumberLine.add_labels() along with ``val_range``. Raises ------ NotImplementedError Can be subclassed, optional. """ raise NotImplementedError class LinearBase(_ScaleBase): def __init__(self, scale_factor: float = 1.0): """The default scaling class. Parameters ---------- scale_factor The slope of the linear function, by default 1.0 """ super().__init__() self.scale_factor = scale_factor def function(self, value: float) -> float: """Multiplies the value by the scale factor. Parameters ---------- value Value to be multiplied by the scale factor. """ return self.scale_factor * value def inverse_function(self, value: float) -> float: """Inverse of function. Divides the value by the scale factor. Parameters ---------- value value to be divided by the scale factor. """ return value / self.scale_factor class LogBase(_ScaleBase): def __init__(self, base: float = 10, custom_labels: bool = True): """Scale for logarithmic graphs/functions. Parameters ---------- base The base of the log, by default 10. custom_labels For use with :class:`~.Axes`: Whether or not to include ``LaTeX`` axis labels, by default True. Examples -------- .. code-block:: python func = ParametricFunction(lambda x: x, scaling=LogBase(base=2)) """ super().__init__() self.base = base self.custom_labels = custom_labels def function(self, value: float) -> float: """Scales the value to fit it to a logarithmic scale.``self.function(5)==10**5``""" return_value: float = self.base**value return return_value def inverse_function(self, value: float) -> float: """Inverse of ``function``. The value must be greater than 0""" if isinstance(value, np.ndarray): condition = value.any() <= 0 func: Callable[[float, float], float] def func(value: float, base: float) -> float: return_value: float = np.log(value) / np.log(base) return return_value else: condition = value <= 0 func = math.log if condition: raise ValueError( "log(0) is undefined. Make sure the value is in the domain of the function" ) value = func(value, self.base) return value def get_custom_labels( self, val_range: Iterable[float], unit_decimal_places: int = 0, **base_config: Any, ) -> list[Integer]: """Produces custom :class:`~.Integer` labels in
value <= 0 func = math.log if condition: raise ValueError( "log(0) is undefined. Make sure the value is in the domain of the function" ) value = func(value, self.base) return value def get_custom_labels( self, val_range: Iterable[float], unit_decimal_places: int = 0, **base_config: Any, ) -> list[Integer]: """Produces custom :class:`~.Integer` labels in the form of ``10^2``. Parameters ---------- val_range The iterable of values used to create the labels. Determines the exponent. unit_decimal_places The number of decimal places to include in the exponent base_config Additional arguments to be passed to :class:`~.Integer`. """ # uses `format` syntax to control the number of decimal places. tex_labels: list[Integer] = [ Integer( self.base, unit="^{%s}" % (f"{self.inverse_function(i):.{unit_decimal_places}f}"), # noqa: UP031 **base_config, ) for i in val_range ] return tex_labels ================================================ FILE: manim/mobject/opengl/__init__.py ================================================ [Empty file] ================================================ FILE: manim/mobject/opengl/dot_cloud.py ================================================ from __future__ import annotations __all__ = ["TrueDot", "DotCloud"] from typing import Any import numpy as np from typing_extensions import Self from manim.constants import ORIGIN, RIGHT, UP from manim.mobject.opengl.opengl_point_cloud_mobject import OpenGLPMobject from manim.typing import Point3DLike from manim.utils.color import YELLOW, ParsableManimColor class DotCloud(OpenGLPMobject): def __init__( self, color: ParsableManimColor = YELLOW, stroke_width: float = 2.0, radius: float = 2.0, density: float = 10, **kwargs: Any, ): self.radius = radius self.epsilon = 1.0 / density super().__init__( stroke_width=stroke_width, density=density, color=color, **kwargs ) def init_points(self) -> None: self.points = np.array( [ r * (np.cos(theta) * RIGHT + np.sin(theta) * UP) for r in np.arange(self.epsilon, self.radius, self.epsilon) # Num is equal to int(stop - start)/ (step + 1) reformulated. for theta in np.linspace( 0, 2 * np.pi, num=int(2 * np.pi * (r + self.epsilon) / self.epsilon), ) ], dtype=np.float32, ) def make_3d(self, gloss: float = 0.5, shadow: float = 0.2) -> Self: self.set_gloss(gloss) self.set_shadow(shadow) self.apply_depth_test() return self class TrueDot(DotCloud): def __init__( self, center: Point3DLike = ORIGIN, stroke_width: float = 2.0, **kwargs: Any ): self.radius = stroke_width super().__init__(points=[center], stroke_width=stroke_width, **kwargs) ================================================ FILE: manim/mobject/opengl/opengl_compatibility.py ================================================ from __future__ import annotations from abc import ABCMeta from manim import config from manim.mobject.opengl.opengl_mobject import OpenGLMobject from manim.mobject.opengl.opengl_point_cloud_mobject import OpenGLPMobject from manim.mobject.opengl.opengl_three_dimensions import OpenGLSurface from manim.mobject.opengl.opengl_vectorized_mobject import OpenGLVMobject from ...constants import RendererType __all__ = ["ConvertToOpenGL"] class ConvertToOpenGL(ABCMeta): """Metaclass for swapping (V)Mobject with its OpenGL counterpart at runtime depending on config.renderer. This metaclass should only need to be inherited on the lowest order inheritance classes such as Mobject and VMobject. """ _converted_classes = [] def __new__(mcls, name, bases, namespace): if config.renderer == RendererType.OPENGL: # Must check class names to prevent # cyclic importing. base_names_to_opengl = { "Mobject": OpenGLMobject, "VMobject": OpenGLVMobject, "PMobject": OpenGLPMobject, "Mobject1D": OpenGLPMobject, "Mobject2D": OpenGLPMobject, "Surface": OpenGLSurface, } bases = tuple( base_names_to_opengl.get(base.__name__, base) for base in bases ) return super().__new__(mcls, name, bases, namespace) def __init__(cls, name, bases, namespace): super().__init__(name, bases, namespace) cls._converted_classes.append(cls) ================================================ FILE: manim/mobject/opengl/opengl_geometry.py ================================================ from __future__ import annotations from typing import Any, cast import numpy as np from typing_extensions import Self from manim.constants import * from manim.mobject.mobject import Mobject from manim.mobject.opengl.opengl_vectorized_mobject import ( OpenGLDashedVMobject, OpenGLMobject, OpenGLVGroup, OpenGLVMobject, ) from manim.typing import ( Point3D, Point3D_Array, Point3DLike, QuadraticSpline, Vector2DLike, Vector3D, Vector3DLike, ) from manim.utils.color import * from manim.utils.iterables import adjacent_n_tuples, adjacent_pairs from manim.utils.simple_functions
Any, cast import numpy as np from typing_extensions import Self from manim.constants import * from manim.mobject.mobject import Mobject from manim.mobject.opengl.opengl_vectorized_mobject import ( OpenGLDashedVMobject, OpenGLMobject, OpenGLVGroup, OpenGLVMobject, ) from manim.typing import ( Point3D, Point3D_Array, Point3DLike, QuadraticSpline, Vector2DLike, Vector3D, Vector3DLike, ) from manim.utils.color import * from manim.utils.iterables import adjacent_n_tuples, adjacent_pairs from manim.utils.simple_functions import clip from manim.utils.space_ops import ( angle_between_vectors, angle_of_vector, compass_directions, find_intersection, normalize, rotate_vector, rotation_matrix_transpose, ) DEFAULT_DOT_RADIUS = 0.08 DEFAULT_DASH_LENGTH = 0.05 DEFAULT_ARROW_TIP_LENGTH = 0.35 DEFAULT_ARROW_TIP_WIDTH = 0.35 __all__ = [ "OpenGLTipableVMobject", "OpenGLArc", "OpenGLArcBetweenPoints", "OpenGLCurvedArrow", "OpenGLCurvedDoubleArrow", "OpenGLCircle", "OpenGLDot", "OpenGLEllipse", "OpenGLAnnularSector", "OpenGLSector", "OpenGLAnnulus", "OpenGLLine", "OpenGLDashedLine", "OpenGLTangentLine", "OpenGLElbow", "OpenGLArrow", "OpenGLVector", "OpenGLDoubleArrow", "OpenGLCubicBezier", "OpenGLPolygon", "OpenGLRegularPolygon", "OpenGLTriangle", "OpenGLArrowTip", ] class OpenGLTipableVMobject(OpenGLVMobject): """ Meant for shared functionality between Arc and Line. Functionality can be classified broadly into these groups: * Adding, Creating, Modifying tips - add_tip calls create_tip, before pushing the new tip into the TipableVMobject's list of submobjects - stylistic and positional configuration * Checking for tips - Boolean checks for whether the TipableVMobject has a tip and a starting tip * Getters - Straightforward accessors, returning information pertaining to the TipableVMobject instance's tip(s), its length etc """ # Adding, Creating, Modifying tips def __init__( self, tip_length: float = DEFAULT_ARROW_TIP_LENGTH, normal_vector: Vector3DLike = OUT, tip_config: dict[str, Any] = {}, **kwargs: Any, ): self.tip_length = tip_length self.normal_vector = normal_vector self.tip_config = tip_config super().__init__(**kwargs) def add_tip(self, at_start: bool = False, **kwargs: Any) -> Self: """ Adds a tip to the TipableVMobject instance, recognising that the endpoints might need to be switched if it's a 'starting tip' or not. """ tip = self.create_tip(at_start, **kwargs) self.reset_endpoints_based_on_tip(tip, at_start) self.asign_tip_attr(tip, at_start) self.add(tip) return self def create_tip(self, at_start: bool = False, **kwargs: Any) -> OpenGLArrowTip: """ Stylises the tip, positions it spacially, and returns the newly instantiated tip to the caller. """ tip = self.get_unpositioned_tip(**kwargs) self.position_tip(tip, at_start) return tip def get_unpositioned_tip(self, **kwargs: Any) -> OpenGLArrowTip: """ Returns a tip that has been stylistically configured, but has not yet been given a position in space. """ config = {} config.update(self.tip_config) config.update(kwargs) return OpenGLArrowTip(**config) def position_tip( self, tip: OpenGLArrowTip, at_start: bool = False ) -> OpenGLArrowTip: # Last two control points, defining both # the end, and the tangency direction if at_start: anchor = self.get_start() handle = self.get_first_handle() else: handle = self.get_last_handle() anchor = self.get_end() tip.rotate(angle_of_vector(handle - anchor) - PI - tip.get_angle()) tip.shift(anchor - tip.get_tip_point()) return tip def reset_endpoints_based_on_tip(self, tip: OpenGLArrowTip, at_start: bool) -> Self: if self.get_length() == 0: # Zero length, put_start_and_end_on wouldn't # work return self if at_start: start = tip.get_base() end = self.get_end() else: start = self.get_start() end = tip.get_base() self.put_start_and_end_on(start, end) return self def asign_tip_attr(self, tip: OpenGLArrowTip, at_start: bool) -> Self: if at_start: self.start_tip = tip else: self.tip = tip return self # Checking for tips def has_tip(self) -> bool: return hasattr(self, "tip") and self.tip in self def has_start_tip(self) -> bool: return hasattr(self, "start_tip") and self.start_tip in self # Getters def pop_tips(self) -> OpenGLVGroup: start, end = self.get_start_and_end() result = OpenGLVGroup() if self.has_tip(): result.add(self.tip) self.remove(self.tip) if self.has_start_tip(): result.add(self.start_tip) self.remove(self.start_tip) self.put_start_and_end_on(start, end) return result def get_tips(self) -> OpenGLVGroup: """ Returns a VGroup
hasattr(self, "tip") and self.tip in self def has_start_tip(self) -> bool: return hasattr(self, "start_tip") and self.start_tip in self # Getters def pop_tips(self) -> OpenGLVGroup: start, end = self.get_start_and_end() result = OpenGLVGroup() if self.has_tip(): result.add(self.tip) self.remove(self.tip) if self.has_start_tip(): result.add(self.start_tip) self.remove(self.start_tip) self.put_start_and_end_on(start, end) return result def get_tips(self) -> OpenGLVGroup: """ Returns a VGroup (collection of VMobjects) containing the TipableVMObject instance's tips. """ result = OpenGLVGroup() if hasattr(self, "tip"): result.add(self.tip) if hasattr(self, "start_tip"): result.add(self.start_tip) return result def get_tip(self) -> OpenGLArrowTip: """Returns the TipableVMobject instance's (first) tip, otherwise throws an exception. """ tips = self.get_tips() if len(tips) == 0: raise Exception("tip not found") else: rv = cast(OpenGLArrowTip, tips[0]) return rv def get_default_tip_length(self) -> float: return self.tip_length def get_first_handle(self) -> Point3D: return self.points[1] def get_last_handle(self) -> Point3D: return self.points[-2] def get_end(self) -> Point3D: if self.has_tip(): return self.tip.get_start() else: return super().get_end() def get_start(self) -> Point3D: if self.has_start_tip(): return self.start_tip.get_start() else: return super().get_start() def get_length(self) -> float: start, end = self.get_start_and_end() rv: float = np.linalg.norm(start - end) return rv class OpenGLArc(OpenGLTipableVMobject): def __init__( self, start_angle: float = 0, angle: float = TAU / 4, radius: float = 1.0, n_components: int = 8, arc_center: Point3DLike = ORIGIN, **kwargs: Any, ): self.start_angle = start_angle self.angle = angle self.radius = radius self.n_components = n_components self.arc_center = arc_center super().__init__(**kwargs) self.orientation = -1 def init_points(self) -> None: self.set_points( OpenGLArc.create_quadratic_bezier_points( angle=self.angle, start_angle=self.start_angle, n_components=self.n_components, ), ) # To maintain proper orientation for fill shaders. self.scale(self.radius, about_point=ORIGIN) self.shift(self.arc_center) @staticmethod def create_quadratic_bezier_points( angle: float, start_angle: float = 0, n_components: int = 8 ) -> QuadraticSpline: samples = np.array( [ [np.cos(a), np.sin(a), 0] for a in np.linspace( start_angle, start_angle + angle, 2 * n_components + 1, ) ], ) theta = angle / n_components samples[1::2] /= np.cos(theta / 2) points = np.zeros((3 * n_components, 3)) points[0::3] = samples[0:-1:2] points[1::3] = samples[1::2] points[2::3] = samples[2::2] return points def get_arc_center(self) -> Point3D: """ Looks at the normals to the first two anchors, and finds their intersection points """ # First two anchors and handles a1, h, a2 = self.points[:3] # Tangent vectors t1 = h - a1 t2 = h - a2 # Normals n1 = rotate_vector(t1, TAU / 4) n2 = rotate_vector(t2, TAU / 4) return find_intersection(a1, n1, a2, n2) def get_start_angle(self) -> float: angle = angle_of_vector(self.get_start() - self.get_arc_center()) rv: float = angle % TAU return rv def get_stop_angle(self) -> float: angle = angle_of_vector(self.get_end() - self.get_arc_center()) rv: float = angle % TAU return rv def move_arc_center_to(self, point: Point3DLike) -> Self: self.shift(point - self.get_arc_center()) return self class OpenGLArcBetweenPoints(OpenGLArc): def __init__( self, start: Point3DLike, end: Point3DLike, angle: float = TAU / 4, **kwargs: Any, ): super().__init__(angle=angle, **kwargs) if angle == 0: self.set_points_as_corners([LEFT, RIGHT]) self.put_start_and_end_on(start, end) class OpenGLCurvedArrow(OpenGLArcBetweenPoints): def __init__(self, start_point: Point3DLike, end_point: Point3DLike, **kwargs: Any): super().__init__(start_point, end_point, **kwargs) self.add_tip() class OpenGLCurvedDoubleArrow(OpenGLCurvedArrow): def __init__(self, start_point: Point3DLike, end_point: Point3DLike, **kwargs: Any): super().__init__(start_point, end_point, **kwargs) self.add_tip(at_start=True) class OpenGLCircle(OpenGLArc): def __init__(self, color: ParsableManimColor = RED, **kwargs: Any): super().__init__(0, TAU, color=color, **kwargs) def surround( self, mobject: OpenGLMobject, dim_to_match: int = 0, stretch: bool = False, buff: float = MED_SMALL_BUFF, ) -> Self: # Ignores dim_to_match and
def __init__(self, start_point: Point3DLike, end_point: Point3DLike, **kwargs: Any): super().__init__(start_point, end_point, **kwargs) self.add_tip(at_start=True) class OpenGLCircle(OpenGLArc): def __init__(self, color: ParsableManimColor = RED, **kwargs: Any): super().__init__(0, TAU, color=color, **kwargs) def surround( self, mobject: OpenGLMobject, dim_to_match: int = 0, stretch: bool = False, buff: float = MED_SMALL_BUFF, ) -> Self: # Ignores dim_to_match and stretch; result will always be a circle # TODO: Perhaps create an ellipse class to handle singele-dimension stretching self.replace(mobject, dim_to_match, stretch) self.stretch((self.get_width() + 2 * buff) / self.get_width(), 0) self.stretch((self.get_height() + 2 * buff) / self.get_height(), 1) return self def point_at_angle(self, angle: float) -> Point3D: start_angle = self.get_start_angle() return self.point_from_proportion((angle - start_angle) / TAU) class OpenGLDot(OpenGLCircle): def __init__( self, point: Point3DLike = ORIGIN, radius: float = DEFAULT_DOT_RADIUS, stroke_width: float = 0, fill_opacity: float = 1.0, color: ParsableManimColor = WHITE, **kwargs: Any, ): super().__init__( arc_center=point, radius=radius, stroke_width=stroke_width, fill_opacity=fill_opacity, color=color, **kwargs, ) class OpenGLEllipse(OpenGLCircle): def __init__(self, width: float = 2, height: float = 1, **kwargs: Any): super().__init__(**kwargs) self.set_width(width, stretch=True) self.set_height(height, stretch=True) class OpenGLAnnularSector(OpenGLArc): def __init__( self, inner_radius: float = 1, outer_radius: float = 2, angle: float = TAU / 4, start_angle: float = 0, fill_opacity: float = 1, stroke_width: float = 0, color: ParsableManimColor = WHITE, **kwargs: Any, ): self.inner_radius = inner_radius self.outer_radius = outer_radius super().__init__( start_angle=start_angle, angle=angle, fill_opacity=fill_opacity, stroke_width=stroke_width, color=color, **kwargs, ) def init_points(self) -> None: inner_arc, outer_arc = ( OpenGLArc( start_angle=self.start_angle, angle=self.angle, radius=radius, arc_center=self.arc_center, ) for radius in (self.inner_radius, self.outer_radius) ) outer_arc.reverse_points() self.append_points(inner_arc.points) self.add_line_to(outer_arc.points[0]) self.append_points(outer_arc.points) self.add_line_to(inner_arc.points[0]) class OpenGLSector(OpenGLAnnularSector): def __init__(self, outer_radius: float = 1, inner_radius: float = 0, **kwargs: Any): super().__init__(inner_radius=inner_radius, outer_radius=outer_radius, **kwargs) class OpenGLAnnulus(OpenGLCircle): def __init__( self, inner_radius: float = 1, outer_radius: float = 2, fill_opacity: float = 1, stroke_width: float = 0, color: ParsableManimColor = WHITE, mark_paths_closed: bool = False, **kwargs: Any, ): self.mark_paths_closed = mark_paths_closed # is this even used? self.inner_radius = inner_radius self.outer_radius = outer_radius super().__init__( fill_opacity=fill_opacity, stroke_width=stroke_width, color=color, **kwargs ) def init_points(self) -> None: self.radius = self.outer_radius outer_circle = OpenGLCircle(radius=self.outer_radius) inner_circle = OpenGLCircle(radius=self.inner_radius) inner_circle.reverse_points() self.append_points(outer_circle.points) self.append_points(inner_circle.points) self.shift(self.arc_center) class OpenGLLine(OpenGLTipableVMobject): def __init__( self, start: Point3DLike = LEFT, end: Point3DLike = RIGHT, buff: float = 0, path_arc: float = 0, **kwargs: Any, ): self.dim = 3 self.buff = buff self.path_arc = path_arc self.set_start_and_end_attrs(start, end) super().__init__(**kwargs) def init_points(self) -> None: self.set_points_by_ends(self.start, self.end, self.buff, self.path_arc) def set_points_by_ends( self, start: Point3DLike, end: Point3DLike, buff: float = 0, path_arc: float = 0 ) -> None: if path_arc: self.set_points(OpenGLArc.create_quadratic_bezier_points(path_arc)) self.put_start_and_end_on(start, end) else: self.set_points_as_corners([start, end]) self.account_for_buff(self.buff) def set_path_arc(self, new_value: float) -> None: self.path_arc = new_value self.init_points() def account_for_buff(self, buff: float) -> Self: if buff == 0: return self # length = self.get_length() if self.path_arc == 0 else self.get_arc_length() # if length < 2 * buff: return self buff_prop = buff / length self.pointwise_become_partial(self, buff_prop, 1 - buff_prop) return self def set_start_and_end_attrs( self, start: Mobject | Point3DLike, end: Mobject | Point3DLike ) -> None: # If either start or end are Mobjects, this # gives their centers rough_start = self.pointify(start) rough_end = self.pointify(end) vect = normalize(rough_end - rough_start) # Now that we know the direction between them, # we can find the appropriate boundary
Mobject | Point3DLike, end: Mobject | Point3DLike ) -> None: # If either start or end are Mobjects, this # gives their centers rough_start = self.pointify(start) rough_end = self.pointify(end) vect = normalize(rough_end - rough_start) # Now that we know the direction between them, # we can find the appropriate boundary point from # start and end, if they're mobjects self.start = self.pointify(start, vect) + self.buff * vect self.end = self.pointify(end, -vect) - self.buff * vect def pointify( self, mob_or_point: Mobject | Point3DLike, direction: Vector3DLike = None ) -> Point3D: """ Take an argument passed into Line (or subclass) and turn it into a 3d point. """ if isinstance(mob_or_point, Mobject): mob = mob_or_point if direction is None: return mob.get_center() else: return mob.get_continuous_bounding_box_point(direction) else: point = mob_or_point result = np.zeros(self.dim) result[: len(point)] = point return result def put_start_and_end_on(self, start: Point3DLike, end: Point3DLike) -> Self: curr_start, curr_end = self.get_start_and_end() if (curr_start == curr_end).all(): self.set_points_by_ends(start, end, self.path_arc) return super().put_start_and_end_on(start, end) def get_vector(self) -> Vector3D: return self.get_end() - self.get_start() def get_unit_vector(self) -> Vector3D: return normalize(self.get_vector()) def get_angle(self) -> float: return angle_of_vector(self.get_vector()) def get_projection(self, point: Point3DLike) -> Point3D: """Return projection of a point onto the line""" unit_vect = self.get_unit_vector() start = self.get_start() return start + np.dot(point - start, unit_vect) * unit_vect def get_slope(self) -> float: rv: float = np.tan(self.get_angle()) return rv def set_angle(self, angle: float, about_point: Point3DLike | None = None) -> Self: if about_point is None: about_point = self.get_start() self.rotate( angle - self.get_angle(), about_point=about_point, ) return self def set_length(self, length: float) -> None: self.scale(length / self.get_length()) class OpenGLDashedLine(OpenGLLine): def __init__( self, *args: Any, dash_length: float = DEFAULT_DASH_LENGTH, dashed_ratio: float = 0.5, **kwargs: Any, ): self.dashed_ratio = dashed_ratio self.dash_length = dash_length super().__init__(*args, **kwargs) dashed_ratio = self.dashed_ratio num_dashes = self.calculate_num_dashes(dashed_ratio) dashes = OpenGLDashedVMobject( self, num_dashes=num_dashes, dashed_ratio=dashed_ratio, ) self.clear_points() self.add(*dashes) def calculate_num_dashes(self, dashed_ratio: float) -> int: return max( 2, int(np.ceil((self.get_length() / self.dash_length) * dashed_ratio)), ) def get_start(self) -> Point3D: if len(self.submobjects) > 0: return self.submobjects[0].get_start() else: return super().get_start() def get_end(self) -> Point3D: if len(self.submobjects) > 0: return self.submobjects[-1].get_end() else: return super().get_end() def get_first_handle(self) -> Point3D: return self.submobjects[0].points[1] def get_last_handle(self) -> Point3D: return self.submobjects[-1].points[-2] class OpenGLTangentLine(OpenGLLine): def __init__( self, vmob: OpenGLVMobject, alpha: float, length: float = 1, d_alpha: float = 1e-6, **kwargs: Any, ): self.length = length self.d_alpha = d_alpha da = self.d_alpha a1 = clip(alpha - da, 0, 1) a2 = clip(alpha + da, 0, 1) super().__init__(vmob.pfp(a1), vmob.pfp(a2), **kwargs) self.scale(self.length / self.get_length()) class OpenGLElbow(OpenGLVMobject): def __init__(self, width: float = 0.2, angle: float = 0, **kwargs: Any): self.angle = angle super().__init__(self, **kwargs) self.set_points_as_corners([UP, UP + RIGHT, RIGHT]) self.set_width(width, about_point=ORIGIN) self.rotate(self.angle, about_point=ORIGIN) class OpenGLArrow(OpenGLLine): def __init__( self, start: Point3DLike = LEFT, end: Point3DLike = RIGHT, path_arc: float = 0, fill_color: ParsableManimColor = GREY_A, fill_opacity: float = 1, stroke_width: float = 0, buff: float = MED_SMALL_BUFF, thickness: float = 0.05, tip_width_ratio: float = 5, tip_angle: float = PI / 3, max_tip_length_to_length_ratio: float = 0.5, max_width_to_length_ratio: float = 0.1, **kwargs: Any, ): self.thickness = thickness self.tip_width_ratio = tip_width_ratio self.tip_angle = tip_angle self.max_tip_length_to_length_ratio = max_tip_length_to_length_ratio self.max_width_to_length_ratio = max_width_to_length_ratio super().__init__( start=start, end=end, buff=buff, path_arc=path_arc,
0, buff: float = MED_SMALL_BUFF, thickness: float = 0.05, tip_width_ratio: float = 5, tip_angle: float = PI / 3, max_tip_length_to_length_ratio: float = 0.5, max_width_to_length_ratio: float = 0.1, **kwargs: Any, ): self.thickness = thickness self.tip_width_ratio = tip_width_ratio self.tip_angle = tip_angle self.max_tip_length_to_length_ratio = max_tip_length_to_length_ratio self.max_width_to_length_ratio = max_width_to_length_ratio super().__init__( start=start, end=end, buff=buff, path_arc=path_arc, fill_color=fill_color, fill_opacity=fill_opacity, stroke_width=stroke_width, **kwargs, ) def set_points_by_ends( self, start: Point3DLike, end: Point3DLike, buff: float = 0, path_arc: float = 0 ) -> None: # Find the right tip length and thickness vect = np.asarray(end) - np.asarray(start) length = max(np.linalg.norm(vect), 1e-8) thickness = self.thickness w_ratio = self.max_width_to_length_ratio / (thickness / length) if w_ratio < 1: thickness *= w_ratio tip_width = self.tip_width_ratio * thickness tip_length = tip_width / (2 * np.tan(self.tip_angle / 2)) t_ratio = self.max_tip_length_to_length_ratio / (tip_length / length) if t_ratio < 1: tip_length *= t_ratio tip_width *= t_ratio # Find points for the stem if path_arc == 0: points1 = (length - tip_length) * np.array([RIGHT, 0.5 * RIGHT, ORIGIN]) points1 += thickness * UP / 2 points2 = points1[::-1] + thickness * DOWN else: # Solve for radius so that the tip-to-tail length matches |end - start| a = 2 * (1 - np.cos(path_arc)) b = -2 * tip_length * np.sin(path_arc) c = tip_length**2 - length**2 R = (-b + np.sqrt(b**2 - 4 * a * c)) / (2 * a) # Find arc points points1 = OpenGLArc.create_quadratic_bezier_points(path_arc) points2 = np.array(points1[::-1]) points1 *= R + thickness / 2 points2 *= R - thickness / 2 if path_arc < 0: tip_length *= -1 rot_T = rotation_matrix_transpose(PI / 2 - path_arc, OUT) for points in points1, points2: points[:] = np.dot(points, rot_T) points += R * DOWN self.set_points(points1) # Tip self.add_line_to(tip_width * UP / 2) self.add_line_to(tip_length * LEFT) self.tip_index = len(self.points) - 1 self.add_line_to(tip_width * DOWN / 2) self.add_line_to(points2[0]) # Close it out self.append_points(points2) self.add_line_to(points1[0]) if length > 0: # Final correction super().scale(length / self.get_length()) self.rotate(angle_of_vector(vect) - self.get_angle()) self.rotate( PI / 2 - np.arccos(normalize(vect)[2]), axis=rotate_vector(self.get_unit_vector(), -PI / 2), ) self.shift(start - self.get_start()) self.refresh_triangulation() def reset_points_around_ends(self) -> Self: self.set_points_by_ends( self.get_start(), self.get_end(), path_arc=self.path_arc, ) return self def get_start(self) -> Point3D: nppc = self.n_points_per_curve points = self.points return (points[0] + points[-nppc]) / 2 def get_end(self) -> Point3D: return self.points[self.tip_index] def put_start_and_end_on(self, start: Point3DLike, end: Point3DLike) -> Self: self.set_points_by_ends(start, end, buff=0, path_arc=self.path_arc) return self def scale(self, *args: Any, **kwargs: Any) -> Self: super().scale(*args, **kwargs) self.reset_points_around_ends() return self def set_thickness(self, thickness: float) -> Self: self.thickness = thickness self.reset_points_around_ends() return self def set_path_arc(self, path_arc: float) -> None: self.path_arc = path_arc self.reset_points_around_ends() # return self class OpenGLVector(OpenGLArrow): def __init__( self, direction: Vector2DLike | Vector3DLike = RIGHT, buff: float = 0, **kwargs: Any, ): self.buff = buff if len(direction) == 2: direction = np.hstack([direction, 0]) super().__init__(ORIGIN, direction, buff=buff, **kwargs) class OpenGLDoubleArrow(OpenGLArrow): def __init__(self, *args: Any, **kwargs: Any): super().__init__(*args, **kwargs) self.add_tip(at_start=True) class OpenGLCubicBezier(OpenGLVMobject): def __init__( self, a0: Point3DLike, h0: Point3DLike, h1: Point3DLike, a1: Point3DLike, **kwargs: Any, ): super().__init__(**kwargs) self.add_cubic_bezier_curve(a0, h0, h1, a1) class OpenGLPolygon(OpenGLVMobject): def __init__(self, *vertices: Point3DLike, **kwargs: Any): self.vertices: Point3D_Array = np.array(vertices) super().__init__(**kwargs) def init_points(self) -> None: verts = self.vertices
def __init__(self, *args: Any, **kwargs: Any): super().__init__(*args, **kwargs) self.add_tip(at_start=True) class OpenGLCubicBezier(OpenGLVMobject): def __init__( self, a0: Point3DLike, h0: Point3DLike, h1: Point3DLike, a1: Point3DLike, **kwargs: Any, ): super().__init__(**kwargs) self.add_cubic_bezier_curve(a0, h0, h1, a1) class OpenGLPolygon(OpenGLVMobject): def __init__(self, *vertices: Point3DLike, **kwargs: Any): self.vertices: Point3D_Array = np.array(vertices) super().__init__(**kwargs) def init_points(self) -> None: verts = self.vertices self.set_points_as_corners([*verts, verts[0]]) def get_vertices(self) -> Point3D_Array: return self.get_start_anchors() def round_corners(self, radius: float = 0.5) -> Self: vertices = self.get_vertices() arcs = [] for v1, v2, v3 in adjacent_n_tuples(vertices, 3): vect1 = v2 - v1 vect2 = v3 - v2 unit_vect1 = normalize(vect1) unit_vect2 = normalize(vect2) angle = angle_between_vectors(vect1, vect2) # Negative radius gives concave curves angle *= np.sign(radius) # Distance between vertex and start of the arc cut_off_length = radius * np.tan(angle / 2) # Determines counterclockwise vs. clockwise sign = np.sign(np.cross(vect1, vect2)[2]) arc = OpenGLArcBetweenPoints( v2 - unit_vect1 * cut_off_length, v2 + unit_vect2 * cut_off_length, angle=sign * angle, n_components=2, ) arcs.append(arc) self.clear_points() # To ensure that we loop through starting with last arcs = [arcs[-1], *arcs[:-1]] for arc1, arc2 in adjacent_pairs(arcs): self.append_points(arc1.points) line = OpenGLLine(arc1.get_end(), arc2.get_start()) # Make sure anchors are evenly distributed len_ratio = line.get_length() / arc1.get_arc_length() line.insert_n_curves(int(arc1.get_num_curves() * len_ratio)) self.append_points(line.points) return self class OpenGLRegularPolygon(OpenGLPolygon): def __init__(self, n: int = 6, start_angle: float | None = None, **kwargs: Any): self.start_angle = start_angle if self.start_angle is None: if n % 2 == 0: self.start_angle = 0 else: self.start_angle = 90 * DEGREES start_vect = rotate_vector(RIGHT, self.start_angle) vertices = compass_directions(n, start_vect) super().__init__(*vertices, **kwargs) class OpenGLTriangle(OpenGLRegularPolygon): def __init__(self, **kwargs: Any): super().__init__(n=3, **kwargs) class OpenGLArrowTip(OpenGLTriangle): def __init__( self, fill_opacity: float = 1, fill_color: ParsableManimColor = WHITE, stroke_width: float = 0, width: float = DEFAULT_ARROW_TIP_WIDTH, length: float = DEFAULT_ARROW_TIP_LENGTH, angle: float = 0, **kwargs: Any, ): super().__init__( start_angle=0, fill_opacity=fill_opacity, fill_color=fill_color, stroke_width=stroke_width, **kwargs, ) self.set_width(width, stretch=True) self.set_height(length, stretch=True) def get_base(self) -> Point3D: return self.point_from_proportion(0.5) def get_tip_point(self) -> Point3D: return self.points[0] def get_vector(self) -> Vector3D: return self.get_tip_point() - self.get_base() def get_angle(self) -> float: return angle_of_vector(self.get_vector()) def get_length(self) -> float: rv: float = np.linalg.norm(self.get_vector()) return rv class OpenGLRectangle(OpenGLPolygon): def __init__( self, color: ParsableManimColor = WHITE, width: float = 4.0, height: float = 2.0, **kwargs: Any, ): super().__init__(UR, UL, DL, DR, color=color, **kwargs) self.set_width(width, stretch=True) self.set_height(height, stretch=True) class OpenGLSquare(OpenGLRectangle): def __init__(self, side_length: float = 2.0, **kwargs: Any): self.side_length = side_length super().__init__(height=side_length, width=side_length, **kwargs) class OpenGLRoundedRectangle(OpenGLRectangle): def __init__(self, corner_radius: float = 0.5, **kwargs: Any): self.corner_radius = corner_radius super().__init__(**kwargs) self.round_corners(self.corner_radius) ================================================ FILE: manim/mobject/opengl/opengl_image_mobject.py ================================================ from __future__ import annotations __all__ = [ "OpenGLImageMobject", ] from pathlib import Path import numpy as np from PIL import Image from PIL.Image import Resampling from manim.mobject.opengl.opengl_surface import OpenGLSurface, OpenGLTexturedSurface from manim.utils.images import get_full_raster_image_path __all__ = ["OpenGLImageMobject"] class OpenGLImageMobject(OpenGLTexturedSurface): def __init__( self, filename_or_array: str | Path | np.ndarray, width: float = None, height: float = None, image_mode: str = "RGBA", resampling_algorithm: int = Resampling.BICUBIC, opacity: float = 1, gloss: float = 0, shadow: float = 0, **kwargs, ): self.image = filename_or_array self.resampling_algorithm = resampling_algorithm if isinstance(filename_or_array, np.ndarray): self.size = self.image.shape[1::-1] elif isinstance(filename_or_array, (str, Path)): path = get_full_raster_image_path(filename_or_array) self.size = Image.open(path).size if width is None and
None, image_mode: str = "RGBA", resampling_algorithm: int = Resampling.BICUBIC, opacity: float = 1, gloss: float = 0, shadow: float = 0, **kwargs, ): self.image = filename_or_array self.resampling_algorithm = resampling_algorithm if isinstance(filename_or_array, np.ndarray): self.size = self.image.shape[1::-1] elif isinstance(filename_or_array, (str, Path)): path = get_full_raster_image_path(filename_or_array) self.size = Image.open(path).size if width is None and height is None: width = 4 * self.size[0] / self.size[1] height = 4 if height is None: height = width * self.size[1] / self.size[0] if width is None: width = height * self.size[0] / self.size[1] surface = OpenGLSurface( lambda u, v: np.array([u, v, 0]), [-width / 2, width / 2], [-height / 2, height / 2], opacity=opacity, gloss=gloss, shadow=shadow, ) super().__init__( surface, self.image, image_mode=image_mode, opacity=opacity, gloss=gloss, shadow=shadow, **kwargs, ) def get_image_from_file( self, image_file: str | Path | np.ndarray, image_mode: str, ): if isinstance(image_file, (str, Path)): return super().get_image_from_file(image_file, image_mode) else: return ( Image.fromarray(image_file.astype("uint8")) .convert(image_mode) .resize( np.array(image_file.shape[:2]) * 200, # assumption of 200 ppmu (pixels per manim unit) would suffice resample=self.resampling_algorithm, ) ) ================================================ FILE: manim/mobject/opengl/opengl_point_cloud_mobject.py ================================================ from __future__ import annotations __all__ = ["OpenGLPMobject", "OpenGLPGroup", "OpenGLPMPoint"] from typing import TYPE_CHECKING import moderngl import numpy as np from manim.constants import * from manim.mobject.opengl.opengl_mobject import OpenGLMobject from manim.utils.bezier import interpolate from manim.utils.color import ( BLACK, WHITE, YELLOW, ParsableManimColor, color_gradient, color_to_rgba, ) from manim.utils.config_ops import _Uniforms from manim.utils.iterables import resize_with_interpolation if TYPE_CHECKING: from typing_extensions import Self from manim.typing import ( FloatRGBA_Array, FloatRGBALike_Array, Point3D_Array, Point3DLike_Array, ) __all__ = ["OpenGLPMobject", "OpenGLPGroup", "OpenGLPMPoint"] class OpenGLPMobject(OpenGLMobject): shader_folder = "true_dot" # Scale for consistency with cairo units OPENGL_POINT_RADIUS_SCALE_FACTOR = 0.01 shader_dtype = [ ("point", np.float32, (3,)), ("color", np.float32, (4,)), ] point_radius = _Uniforms() def __init__( self, stroke_width: float = 2.0, color: ParsableManimColor = YELLOW, render_primitive: int = moderngl.POINTS, **kwargs, ): self.stroke_width = stroke_width super().__init__(color=color, render_primitive=render_primitive, **kwargs) self.point_radius = ( self.stroke_width * OpenGLPMobject.OPENGL_POINT_RADIUS_SCALE_FACTOR ) def reset_points(self) -> Self: self.rgbas: FloatRGBA_Array = np.zeros((1, 4)) self.points: Point3D_Array = np.zeros((0, 3)) return self def get_array_attrs(self): return ["points", "rgbas"] def add_points( self, points: Point3DLike_Array, rgbas: FloatRGBALike_Array | None = None, color: ParsableManimColor | None = None, opacity: float | None = None, ) -> Self: """Add points. Points must be a Nx3 numpy array. Rgbas must be a Nx4 numpy array if it is not None. """ if rgbas is None and color is None: color = YELLOW self.append_points(points) # rgbas array will have been resized with points if color is not None: if opacity is None: opacity = self.rgbas[-1, 3] new_rgbas = np.repeat([color_to_rgba(color, opacity)], len(points), axis=0) elif rgbas is not None: new_rgbas = rgbas elif len(rgbas) != len(points): raise ValueError("points and rgbas must have same length") self.rgbas = np.append(self.rgbas, new_rgbas, axis=0) return self def thin_out(self, factor=5): """Removes all but every nth point for n = factor""" for mob in self.family_members_with_points(): num_points = mob.get_num_points() def thin_func(num_points=num_points): return np.arange(0, num_points, factor) if len(mob.points) == len(mob.rgbas): mob.set_rgba_array_direct(mob.rgbas[thin_func()]) mob.set_points(mob.points[thin_func()]) return self def set_color_by_gradient(self, *colors): self.rgbas = np.array( list(map(color_to_rgba, color_gradient(*colors, self.get_num_points()))), ) return self def set_colors_by_radial_gradient( self, center=None, radius=1, inner_color=WHITE, outer_color=BLACK, ): start_rgba, end_rgba = list(map(color_to_rgba, [inner_color, outer_color])) if center is None: center = self.get_center() for mob in self.family_members_with_points():
thin_func(num_points=num_points): return np.arange(0, num_points, factor) if len(mob.points) == len(mob.rgbas): mob.set_rgba_array_direct(mob.rgbas[thin_func()]) mob.set_points(mob.points[thin_func()]) return self def set_color_by_gradient(self, *colors): self.rgbas = np.array( list(map(color_to_rgba, color_gradient(*colors, self.get_num_points()))), ) return self def set_colors_by_radial_gradient( self, center=None, radius=1, inner_color=WHITE, outer_color=BLACK, ): start_rgba, end_rgba = list(map(color_to_rgba, [inner_color, outer_color])) if center is None: center = self.get_center() for mob in self.family_members_with_points(): distances = np.abs(self.points - center) alphas = np.linalg.norm(distances, axis=1) / radius mob.rgbas = np.array( np.array( [interpolate(start_rgba, end_rgba, alpha) for alpha in alphas], ), ) return self def match_colors(self, pmobject): self.rgbas[:] = resize_with_interpolation(pmobject.rgbas, self.get_num_points()) return self def fade_to(self, color, alpha, family=True): rgbas = interpolate(self.rgbas, color_to_rgba(color), alpha) for mob in self.submobjects: mob.fade_to(color, alpha, family) self.set_rgba_array_direct(rgbas) return self def filter_out(self, condition): for mob in self.family_members_with_points(): to_keep = ~np.apply_along_axis(condition, 1, mob.points) for key in mob.data: mob.data[key] = mob.data[key][to_keep] return self def sort_points(self, function=lambda p: p[0]): """function is any map from R^3 to R""" for mob in self.family_members_with_points(): indices = np.argsort(np.apply_along_axis(function, 1, mob.points)) for key in mob.data: mob.data[key] = mob.data[key][indices] return self def ingest_submobjects(self): for key in self.data: self.data[key] = np.vstack([sm.data[key] for sm in self.get_family()]) return self def point_from_proportion(self, alpha): index = alpha * (self.get_num_points() - 1) return self.points[int(index)] def pointwise_become_partial(self, pmobject, a, b): lower_index = int(a * pmobject.get_num_points()) upper_index = int(b * pmobject.get_num_points()) for key in self.data: self.data[key] = pmobject.data[key][lower_index:upper_index] return self def get_shader_data(self): shader_data = np.zeros(len(self.points), dtype=self.shader_dtype) self.read_data_to_shader(shader_data, "point", "points") self.read_data_to_shader(shader_data, "color", "rgbas") return shader_data @staticmethod def get_mobject_type_class(): return OpenGLPMobject class OpenGLPGroup(OpenGLPMobject): def __init__(self, *pmobs, **kwargs): if not all(isinstance(m, OpenGLPMobject) for m in pmobs): raise Exception("All submobjects must be of type OpenglPMObject") super().__init__(**kwargs) self.add(*pmobs) def fade_to(self, color, alpha, family=True): if family: for mob in self.submobjects: mob.fade_to(color, alpha, family) class OpenGLPMPoint(OpenGLPMobject): def __init__(self, location=ORIGIN, stroke_width=4.0, **kwargs): self.location = location super().__init__(stroke_width=stroke_width, **kwargs) def init_points(self): self.points = np.array([self.location], dtype=np.float32) ================================================ FILE: manim/mobject/opengl/opengl_surface.py ================================================ from __future__ import annotations from collections.abc import Iterable from pathlib import Path import moderngl import numpy as np from PIL import Image from manim.constants import * from manim.mobject.opengl.opengl_mobject import OpenGLMobject from manim.typing import Point3D_Array, Vector3D_Array from manim.utils.bezier import integer_interpolate, interpolate from manim.utils.color import * from manim.utils.config_ops import _Data, _Uniforms from manim.utils.images import change_to_rgba_array, get_full_raster_image_path from manim.utils.iterables import listify from manim.utils.space_ops import normalize_along_axis __all__ = ["OpenGLSurface", "OpenGLTexturedSurface"] class OpenGLSurface(OpenGLMobject): r"""Creates a Surface. Parameters ---------- uv_func The function that defines the surface. u_range The range of the ``u`` variable: ``(u_min, u_max)``. v_range The range of the ``v`` variable: ``(v_min, v_max)``. resolution The number of samples taken of the surface. axes Axes on which the surface is to be drawn. Optional parameter used when coloring a surface by z-value. color Color of the surface. Defaults to grey. colorscale Colors of the surface. Optional parameter used when coloring a surface by values. Passing a list of colors and an axes will color the surface by z-value. Passing a list of tuples in the form ``(color, pivot)`` allows user-defined pivots where the color transitions. colorscale_axis Defines the axis on which the colorscale is applied (0 = x, 1 = y, 2 = z), default is z-axis (2). opacity Opacity of the surface from 0 being fully transparent to
a list of tuples in the form ``(color, pivot)`` allows user-defined pivots where the color transitions. colorscale_axis Defines the axis on which the colorscale is applied (0 = x, 1 = y, 2 = z), default is z-axis (2). opacity Opacity of the surface from 0 being fully transparent to 1 being fully opaque. Defaults to 1. """ shader_dtype = [ ("point", np.float32, (3,)), ("du_point", np.float32, (3,)), ("dv_point", np.float32, (3,)), ("color", np.float32, (4,)), ] shader_folder = "surface" def __init__( self, uv_func=None, u_range=None, v_range=None, # Resolution counts number of points sampled, which for # each coordinate is one more than the the number of # rows/columns of approximating squares resolution=None, axes=None, color=GREY, colorscale=None, colorscale_axis=2, opacity=1.0, gloss=0.3, shadow=0.4, prefered_creation_axis=1, # For du and dv steps. Much smaller and numerical error # can crop up in the shaders. epsilon=1e-5, render_primitive=moderngl.TRIANGLES, depth_test=True, shader_folder=None, **kwargs, ): self.passed_uv_func = uv_func self.u_range = u_range if u_range is not None else (0, 1) self.v_range = v_range if v_range is not None else (0, 1) # Resolution counts number of points sampled, which for # each coordinate is one more than the the number of # rows/columns of approximating squares self.resolution = resolution if resolution is not None else (101, 101) self.axes = axes self.colorscale = colorscale self.colorscale_axis = colorscale_axis self.prefered_creation_axis = prefered_creation_axis # For du and dv steps. Much smaller and numerical error # can crop up in the shaders. self.epsilon = epsilon self.triangle_indices = None super().__init__( color=color, opacity=opacity, gloss=gloss, shadow=shadow, shader_folder=shader_folder if shader_folder is not None else "surface", render_primitive=render_primitive, depth_test=depth_test, **kwargs, ) self.compute_triangle_indices() def uv_func(self, u, v): # To be implemented in subclasses if self.passed_uv_func: return self.passed_uv_func(u, v) return (u, v, 0.0) def init_points(self): dim = self.dim nu, nv = self.resolution u_range = np.linspace(*self.u_range, nu) v_range = np.linspace(*self.v_range, nv) # Get three lists: # - Points generated by pure uv values # - Those generated by values nudged by du # - Those generated by values nudged by dv point_lists = [] for du, dv in [(0, 0), (self.epsilon, 0), (0, self.epsilon)]: uv_grid = np.array([[[u + du, v + dv] for v in v_range] for u in u_range]) point_grid = np.apply_along_axis(lambda p: self.uv_func(*p), 2, uv_grid) point_lists.append(point_grid.reshape((nu * nv, dim))) # Rather than tracking normal vectors, the points list will hold on to the # infinitesimal nudged values alongside the original values. This way, one # can perform all the manipulations they'd like to the surface, and normals # are still easily recoverable. self.set_points(np.vstack(point_lists)) def compute_triangle_indices(self): # TODO, if there is an event which changes # the resolution of the surface, make sure # this is called. nu, nv = self.resolution if nu == 0 or nv == 0: self.triangle_indices = np.zeros(0, dtype=int) return index_grid = np.arange(nu * nv).reshape((nu, nv)) indices = np.zeros(6 * (nu - 1) * (nv - 1), dtype=int) indices[0::6] = index_grid[:-1, :-1].flatten() # Top left indices[1::6] = index_grid[+1:, :-1].flatten() # Bottom left indices[2::6] = index_grid[:-1, +1:].flatten() # Top right indices[3::6] = index_grid[:-1, +1:].flatten() # Top right indices[4::6] = index_grid[+1:, :-1].flatten() # Bottom left indices[5::6]
nv).reshape((nu, nv)) indices = np.zeros(6 * (nu - 1) * (nv - 1), dtype=int) indices[0::6] = index_grid[:-1, :-1].flatten() # Top left indices[1::6] = index_grid[+1:, :-1].flatten() # Bottom left indices[2::6] = index_grid[:-1, +1:].flatten() # Top right indices[3::6] = index_grid[:-1, +1:].flatten() # Top right indices[4::6] = index_grid[+1:, :-1].flatten() # Bottom left indices[5::6] = index_grid[+1:, +1:].flatten() # Bottom right self.triangle_indices = indices def get_triangle_indices(self): return self.triangle_indices def get_surface_points_and_nudged_points( self, ) -> tuple[Point3D_Array, Point3D_Array, Point3D_Array]: points = self.points k = len(points) // 3 return points[:k], points[k : 2 * k], points[2 * k :] def get_unit_normals(self) -> Vector3D_Array: s_points, du_points, dv_points = self.get_surface_points_and_nudged_points() normals = np.cross( (du_points - s_points) / self.epsilon, (dv_points - s_points) / self.epsilon, ) return normalize_along_axis(normals, 1) def pointwise_become_partial(self, smobject, a, b, axis=None): assert isinstance(smobject, OpenGLSurface) if axis is None: axis = self.prefered_creation_axis if a <= 0 and b >= 1: self.match_points(smobject) return self nu, nv = smobject.resolution self.set_points( np.vstack( [ self.get_partial_points_array( arr.copy(), a, b, (nu, nv, 3), axis=axis, ) for arr in smobject.get_surface_points_and_nudged_points() ], ), ) return self def get_partial_points_array(self, points, a, b, resolution, axis): if len(points) == 0: return points nu, nv = resolution[:2] points = points.reshape(resolution) max_index = resolution[axis] - 1 lower_index, lower_residue = integer_interpolate(0, max_index, a) upper_index, upper_residue = integer_interpolate(0, max_index, b) if axis == 0: points[:lower_index] = interpolate( points[lower_index], points[lower_index + 1], lower_residue, ) points[upper_index + 1 :] = interpolate( points[upper_index], points[upper_index + 1], upper_residue, ) else: shape = (nu, 1, resolution[2]) points[:, :lower_index] = interpolate( points[:, lower_index], points[:, lower_index + 1], lower_residue, ).reshape(shape) points[:, upper_index + 1 :] = interpolate( points[:, upper_index], points[:, upper_index + 1], upper_residue, ).reshape(shape) return points.reshape((nu * nv, *resolution[2:])) def sort_faces_back_to_front(self, vect=OUT): tri_is = self.triangle_indices indices = list(range(len(tri_is) // 3)) points = self.points def index_dot(index): return np.dot(points[tri_is[3 * index]], vect) indices.sort(key=index_dot) for k in range(3): tri_is[k::3] = tri_is[k::3][indices] return self # For shaders def get_shader_data(self): """Called by parent Mobject to calculate and return the shader data. Returns ------- shader_dtype An array containing the shader data (vertices and color of each vertex) """ s_points, du_points, dv_points = self.get_surface_points_and_nudged_points() shader_data = np.zeros(len(s_points), dtype=self.shader_dtype) if "points" not in self.locked_data_keys: shader_data["point"] = s_points shader_data["du_point"] = du_points shader_data["dv_point"] = dv_points if self.colorscale: if not hasattr(self, "color_by_val"): self.color_by_val = self._get_color_by_value(s_points) shader_data["color"] = self.color_by_val else: self.fill_in_shader_color_info(shader_data) return shader_data def fill_in_shader_color_info(self, shader_data): """Fills in the shader color data when the surface is all one color. Parameters ---------- shader_data The vertices of the surface. Returns ------- shader_dtype An array containing the shader data (vertices and color of each vertex) """ self.read_data_to_shader(shader_data, "color", "rgbas") return shader_data def _get_color_by_value(self, s_points): """Matches each vertex to a color associated to it's z-value. Parameters ---------- s_points The vertices of the surface. Returns ------- List A list of colors matching the vertex inputs. """ if type(self.colorscale[0]) in (list, tuple): new_colors, pivots = [ [i for i, j in self.colorscale], [j for i, j in self.colorscale], ] else: new_colors = self.colorscale pivot_min = self.axes.z_range[0] pivot_max = self.axes.z_range[1] pivot_frequency = (pivot_max - pivot_min) / (len(new_colors) - 1) pivots = np.arange( start=pivot_min, stop=pivot_max + pivot_frequency, step=pivot_frequency, ) return_colors =
in (list, tuple): new_colors, pivots = [ [i for i, j in self.colorscale], [j for i, j in self.colorscale], ] else: new_colors = self.colorscale pivot_min = self.axes.z_range[0] pivot_max = self.axes.z_range[1] pivot_frequency = (pivot_max - pivot_min) / (len(new_colors) - 1) pivots = np.arange( start=pivot_min, stop=pivot_max + pivot_frequency, step=pivot_frequency, ) return_colors = [] for point in s_points: axis_value = self.axes.point_to_coords(point)[self.colorscale_axis] if axis_value <= pivots[0]: return_colors.append(color_to_rgba(new_colors[0], self.opacity)) elif axis_value >= pivots[-1]: return_colors.append(color_to_rgba(new_colors[-1], self.opacity)) else: for i, pivot in enumerate(pivots): if pivot > axis_value: color_index = (axis_value - pivots[i - 1]) / ( pivots[i] - pivots[i - 1] ) color_index = max(min(color_index, 1), 0) temp_color = interpolate_color( new_colors[i - 1], new_colors[i], color_index, ) break return_colors.append(color_to_rgba(temp_color, self.opacity)) return return_colors def get_shader_vert_indices(self): return self.get_triangle_indices() class OpenGLSurfaceGroup(OpenGLSurface): def __init__(self, *parametric_surfaces, resolution=None, **kwargs): self.resolution = (0, 0) if resolution is None else resolution super().__init__(uv_func=None, **kwargs) self.add(*parametric_surfaces) def init_points(self): pass # Needed? class OpenGLTexturedSurface(OpenGLSurface): shader_dtype = [ ("point", np.float32, (3,)), ("du_point", np.float32, (3,)), ("dv_point", np.float32, (3,)), ("im_coords", np.float32, (2,)), ("opacity", np.float32, (1,)), ] shader_folder = "textured_surface" im_coords = _Data() opacity = _Data() num_textures = _Uniforms() def __init__( self, uv_surface: OpenGLSurface, image_file: str | Path, dark_image_file: str | Path = None, image_mode: str | Iterable[str] = "RGBA", shader_folder: str | Path = None, **kwargs, ): self.uniforms = {} if not isinstance(uv_surface, OpenGLSurface): raise Exception("uv_surface must be of type OpenGLSurface") if isinstance(image_file, np.ndarray): image_file = change_to_rgba_array(image_file) # Set texture information if isinstance(image_mode, (str, Path)): image_mode = [image_mode] * 2 image_mode_light, image_mode_dark = image_mode texture_paths = { "LightTexture": self.get_image_from_file( image_file, image_mode_light, ), "DarkTexture": self.get_image_from_file( dark_image_file or image_file, image_mode_dark, ), } if dark_image_file: self.num_textures = 2 self.uv_surface = uv_surface self.uv_func = uv_surface.uv_func self.u_range = uv_surface.u_range self.v_range = uv_surface.v_range self.resolution = uv_surface.resolution self.gloss = self.uv_surface.gloss super().__init__(texture_paths=texture_paths, **kwargs) def get_image_from_file( self, image_file: str | Path, image_mode: str, ): image_file = get_full_raster_image_path(image_file) return Image.open(image_file).convert(image_mode) def init_data(self): super().init_data() self.im_coords = np.zeros((0, 2)) self.opacity = np.zeros((0, 1)) def init_points(self): nu, nv = self.uv_surface.resolution self.set_points(self.uv_surface.points) self.im_coords = np.array( [ [u, v] for u in np.linspace(0, 1, nu) for v in np.linspace(1, 0, nv) # Reverse y-direction ], ) def init_colors(self): self.opacity = np.array([self.uv_surface.rgbas[:, 3]]) def set_opacity(self, opacity, recurse=True): for mob in self.get_family(recurse): mob.opacity = np.array([[o] for o in listify(opacity)]) return self def pointwise_become_partial(self, tsmobject, a, b, axis=1): super().pointwise_become_partial(tsmobject, a, b, axis) im_coords = self.im_coords im_coords[:] = tsmobject.im_coords if a <= 0 and b >= 1: return self nu, nv = tsmobject.resolution im_coords[:] = self.get_partial_points_array(im_coords, a, b, (nu, nv, 2), axis) return self def fill_in_shader_color_info(self, shader_data): self.read_data_to_shader(shader_data, "opacity", "opacity") self.read_data_to_shader(shader_data, "im_coords", "im_coords") return shader_data ================================================ FILE: manim/mobject/opengl/opengl_three_dimensions.py ================================================ from __future__ import annotations from typing import Any import numpy as np from manim.mobject.opengl.opengl_surface import OpenGLSurface from manim.mobject.opengl.opengl_vectorized_mobject import OpenGLVGroup, OpenGLVMobject __all__ = ["OpenGLSurfaceMesh"] class OpenGLSurfaceMesh(OpenGLVGroup): def __init__( self, uv_surface: OpenGLSurface, resolution: tuple[int, int] | None = None, stroke_width: float = 1, normal_nudge: float = 1e-2, depth_test: bool = True, flat_stroke: bool = False, **kwargs: Any, ): if not isinstance(uv_surface, OpenGLSurface): raise Exception("uv_surface must be of type OpenGLSurface") self.uv_surface = uv_surface self.resolution = resolution if resolution is not None else (21, 21)
tuple[int, int] | None = None, stroke_width: float = 1, normal_nudge: float = 1e-2, depth_test: bool = True, flat_stroke: bool = False, **kwargs: Any, ): if not isinstance(uv_surface, OpenGLSurface): raise Exception("uv_surface must be of type OpenGLSurface") self.uv_surface = uv_surface self.resolution = resolution if resolution is not None else (21, 21) self.normal_nudge = normal_nudge super().__init__( stroke_width=stroke_width, depth_test=depth_test, flat_stroke=flat_stroke, **kwargs, ) def init_points(self) -> None: uv_surface = self.uv_surface full_nu, full_nv = uv_surface.resolution part_nu, part_nv = self.resolution u_indices = np.linspace(0, full_nu, part_nu).astype(int) v_indices = np.linspace(0, full_nv, part_nv).astype(int) points, du_points, dv_points = uv_surface.get_surface_points_and_nudged_points() normals = uv_surface.get_unit_normals() nudged_points = points + self.normal_nudge * normals for ui in u_indices: path = OpenGLVMobject() full_ui = full_nv * ui path.set_points_smoothly(nudged_points[full_ui : full_ui + full_nv]) self.add(path) for vi in v_indices: path = OpenGLVMobject() path.set_points_smoothly(nudged_points[vi::full_nv]) self.add(path) ================================================ FILE: manim/mobject/svg/__init__.py ================================================ """Mobjects related to SVG images. Modules ======= .. autosummary:: :toctree: ../reference ~brace ~svg_mobject """ ================================================ FILE: manim/mobject/svg/brace.py ================================================ """Mobject representing curly braces.""" from __future__ import annotations __all__ = ["Brace", "BraceLabel", "ArcBrace", "BraceText", "BraceBetweenPoints"] from typing import TYPE_CHECKING, Any import numpy as np import svgelements as se from typing_extensions import Self from manim._config import config from manim.mobject.geometry.arc import Arc from manim.mobject.geometry.line import Line from manim.mobject.mobject import Mobject from manim.mobject.opengl.opengl_compatibility import ConvertToOpenGL from manim.mobject.text.tex_mobject import MathTex, SingleStringMathTex, Tex from manim.mobject.text.text_mobject import Text from ...animation.animation import Animation from ...animation.composition import AnimationGroup from ...animation.fading import FadeIn from ...animation.growing import GrowFromCenter from ...constants import * from ...mobject.types.vectorized_mobject import VMobject from ...utils.color import BLACK from ..svg.svg_mobject import VMobjectFromSVGPath if TYPE_CHECKING: from manim.typing import Point3D, Point3DLike, Vector3D, Vector3DLike from manim.utils.color.core import ParsableManimColor class Brace(VMobjectFromSVGPath): """Takes a mobject and draws a brace adjacent to it. Passing a direction vector determines the direction from which the brace is drawn. By default it is drawn from below. Parameters ---------- mobject The mobject adjacent to which the brace is placed. direction : The direction from which the brace faces the mobject. See Also -------- :class:`BraceBetweenPoints` Examples -------- .. manim:: BraceExample :save_last_frame: class BraceExample(Scene): def construct(self): s = Square() self.add(s) for i in np.linspace(0.1,1.0,4): br = Brace(s, sharpness=i) t = Text(f"sharpness= {i}").next_to(br, RIGHT) self.add(t) self.add(br) VGroup(*self.mobjects).arrange(DOWN, buff=0.2) """ def __init__( self, mobject: Mobject, direction: Vector3DLike = DOWN, buff: float = 0.2, sharpness: float = 2, stroke_width: float = 0, fill_opacity: float = 1.0, background_stroke_width: float = 0, background_stroke_color: ParsableManimColor = BLACK, **kwargs: Any, ): path_string_template = ( "m0.01216 0c-0.01152 0-0.01216 6.103e-4 -0.01216 0.01311v0.007762c0.06776 " "0.122 0.1799 0.1455 0.2307 0.1455h{0}c0.03046 3.899e-4 0.07964 0.00449 " "0.1246 0.02636 0.0537 0.02695 0.07418 0.05816 0.08648 0.07769 0.001562 " "0.002538 0.004539 0.002563 0.01098 0.002563 0.006444-2e-8 0.009421-2.47e-" "5 0.01098-0.002563 0.0123-0.01953 0.03278-0.05074 0.08648-0.07769 0.04491" "-0.02187 0.09409-0.02597 0.1246-0.02636h{0}c0.05077 0 0.1629-0.02346 " "0.2307-0.1455v-0.007762c-1.78e-6 -0.0125-6.365e-4 -0.01311-0.01216-0.0131" "1-0.006444-3.919e-8 -0.009348 2.448e-5 -0.01091 0.002563-0.0123 0.01953-" "0.03278 0.05074-0.08648 0.07769-0.04491 0.02187-0.09416 0.02597-0.1246 " "0.02636h{1}c-0.04786 0-0.1502 0.02094-0.2185 0.1256-0.06833-0.1046-0.1706" "-0.1256-0.2185-0.1256h{1}c-0.03046-3.899e-4 -0.07972-0.004491-0.1246-0.02" "636-0.0537-0.02695-0.07418-0.05816-0.08648-0.07769-0.001562-0.002538-" "0.004467-0.002563-0.01091-0.002563z" ) default_min_width = 0.90552 self.buff = buff angle = -np.arctan2(*direction[:2]) + np.pi mobject.rotate(-angle, about_point=ORIGIN) left = mobject.get_corner(DOWN + LEFT) right = mobject.get_corner(DOWN + RIGHT) target_width = right[0] - left[0] linear_section_length = max( 0, (target_width * sharpness - default_min_width) / 2, ) path = se.Path( path_string_template.format( linear_section_length, -linear_section_length,
-0.07972-0.004491-0.1246-0.02" "636-0.0537-0.02695-0.07418-0.05816-0.08648-0.07769-0.001562-0.002538-" "0.004467-0.002563-0.01091-0.002563z" ) default_min_width = 0.90552 self.buff = buff angle = -np.arctan2(*direction[:2]) + np.pi mobject.rotate(-angle, about_point=ORIGIN) left = mobject.get_corner(DOWN + LEFT) right = mobject.get_corner(DOWN + RIGHT) target_width = right[0] - left[0] linear_section_length = max( 0, (target_width * sharpness - default_min_width) / 2, ) path = se.Path( path_string_template.format( linear_section_length, -linear_section_length, ) ) super().__init__( path_obj=path, stroke_width=stroke_width, fill_opacity=fill_opacity, background_stroke_width=background_stroke_width, background_stroke_color=background_stroke_color, **kwargs, ) self.flip(RIGHT) self.stretch_to_fit_width(target_width) self.shift(left - self.get_corner(UP + LEFT) + self.buff * DOWN) for mob in mobject, self: mob.rotate(angle, about_point=ORIGIN) def put_at_tip(self, mob: Mobject, use_next_to: bool = True, **kwargs: Any) -> Self: """Puts the given mobject at the brace tip. Parameters ---------- mob The mobject to be placed at the tip. use_next_to If true, then :meth:`next_to` is used to place the mobject at the tip. kwargs Any additional keyword arguments are passed to :meth:`next_to` which is used to put the mobject next to the brace tip. """ if use_next_to: mob.next_to(self.get_tip(), np.round(self.get_direction()), **kwargs) else: mob.move_to(self.get_tip()) buff = kwargs.get("buff", DEFAULT_MOBJECT_TO_MOBJECT_BUFFER) shift_distance = mob.width / 2.0 + buff mob.shift(self.get_direction() * shift_distance) return self def get_text(self, *text: str, **kwargs: Any) -> Tex: """Places the text at the brace tip. Parameters ---------- text The text to be placed at the brace tip. kwargs Any additional keyword arguments are passed to :meth:`.put_at_tip` which is used to position the text at the brace tip. Returns ------- :class:`~.Tex` """ text_mob = Tex(*text) self.put_at_tip(text_mob, **kwargs) return text_mob def get_tex(self, *tex: str, **kwargs: Any) -> MathTex: """Places the tex at the brace tip. Parameters ---------- tex The tex to be placed at the brace tip. kwargs Any further keyword arguments are passed to :meth:`.put_at_tip` which is used to position the tex at the brace tip. Returns ------- :class:`~.MathTex` """ tex_mob = MathTex(*tex) self.put_at_tip(tex_mob, **kwargs) return tex_mob def get_tip(self) -> Point3D: """Returns the point at the brace tip.""" # Returns the position of the seventh point in the path, which is the tip. if config["renderer"] == "opengl": return self.points[34] return self.points[28] # = 7*4 def get_direction(self) -> Vector3D: """Returns the direction from the center to the brace tip.""" vect = self.get_tip() - self.get_center() return vect / np.linalg.norm(vect) class BraceLabel(VMobject, metaclass=ConvertToOpenGL): """Create a brace with a label attached. Parameters ---------- obj The mobject adjacent to which the brace is placed. text The label text. brace_direction The direction of the brace. By default ``DOWN``. label_constructor A class or function used to construct a mobject representing the label. By default :class:`~.MathTex`. font_size The font size of the label, passed to the ``label_constructor``. buff The buffer between the mobject and the brace. brace_config Arguments to be passed to :class:`.Brace`. kwargs Additional arguments to be passed to :class:`~.VMobject`. """ def __init__( self, obj: Mobject, text: str, brace_direction: Vector3DLike = DOWN, label_constructor: type[SingleStringMathTex | Text] = MathTex, font_size: float = DEFAULT_FONT_SIZE, buff: float = 0.2, brace_config: dict[str, Any] | None = None, **kwargs: Any, ): self.label_constructor = label_constructor super().__init__(**kwargs) self.brace_direction = brace_direction if brace_config is None: brace_config = {} self.brace = Brace(obj, brace_direction, buff, **brace_config) if isinstance(text, (tuple, list)): self.label: VMobject = self.label_constructor( *text, font_size=font_size, **kwargs ) else: self.label
= DEFAULT_FONT_SIZE, buff: float = 0.2, brace_config: dict[str, Any] | None = None, **kwargs: Any, ): self.label_constructor = label_constructor super().__init__(**kwargs) self.brace_direction = brace_direction if brace_config is None: brace_config = {} self.brace = Brace(obj, brace_direction, buff, **brace_config) if isinstance(text, (tuple, list)): self.label: VMobject = self.label_constructor( *text, font_size=font_size, **kwargs ) else: self.label = self.label_constructor(str(text), font_size=font_size) self.brace.put_at_tip(self.label) self.add(self.brace, self.label) def creation_anim( self, label_anim: type[Animation] = FadeIn, brace_anim: type[Animation] = GrowFromCenter, ) -> AnimationGroup: return AnimationGroup(brace_anim(self.brace), label_anim(self.label)) def shift_brace(self, obj: Mobject, **kwargs: Any) -> Self: if isinstance(obj, list): obj = self.get_group_class()(*obj) self.brace = Brace(obj, self.brace_direction, **kwargs) self.brace.put_at_tip(self.label) return self def change_label(self, *text: str, **kwargs: Any) -> Self: self.remove(self.label) self.label = self.label_constructor(*text, **kwargs) # type: ignore[arg-type] self.brace.put_at_tip(self.label) self.add(self.label) return self def change_brace_label(self, obj: Mobject, *text: str, **kwargs: Any) -> Self: self.shift_brace(obj) self.change_label(*text, **kwargs) return self class BraceText(BraceLabel): """Create a brace with a text label attached. Parameters ---------- obj The mobject adjacent to which the brace is placed. text The label text. brace_direction The direction of the brace. By default ``DOWN``. label_constructor A class or function used to construct a mobject representing the label. By default :class:`~.Text`. font_size The font size of the label, passed to the ``label_constructor``. buff The buffer between the mobject and the brace. brace_config Arguments to be passed to :class:`.Brace`. kwargs Additional arguments to be passed to :class:`~.VMobject`. Examples -------- .. manim:: BraceTextExample :save_last_frame: class BraceTextExample(Scene): def construct(self): s1 = Square().move_to(2*LEFT) self.add(s1) br1 = BraceText(s1, "Label") self.add(br1) s2 = Square().move_to(2*RIGHT) self.add(s2) br2 = BraceText(s2, "Label") br2.change_label("new") self.add(br2) self.wait(0.1) """ def __init__( self, obj: Mobject, text: str, label_constructor: type[SingleStringMathTex | Text] = Text, **kwargs: Any, ): super().__init__(obj, text, label_constructor=label_constructor, **kwargs) class BraceBetweenPoints(Brace): """Similar to Brace, but instead of taking a mobject it uses 2 points to place the brace. A fitting direction for the brace is computed, but it still can be manually overridden. If the points go from left to right, the brace is drawn from below. Swapping the points places the brace on the opposite side. Parameters ---------- point_1 : The first point. point_2 : The second point. direction : The direction from which the brace faces towards the points. Examples -------- .. manim:: BraceBPExample class BraceBPExample(Scene): def construct(self): p1 = [0,0,0] p2 = [1,2,0] brace = BraceBetweenPoints(p1,p2) self.play(Create(NumberPlane())) self.play(Create(brace)) self.wait(2) """ def __init__( self, point_1: Point3DLike, point_2: Point3DLike, direction: Vector3DLike = ORIGIN, **kwargs: Any, ): if all(direction == ORIGIN): line_vector = np.array(point_2) - np.array(point_1) direction = np.array([line_vector[1], -line_vector[0], 0]) super().__init__(Line(point_1, point_2), direction=direction, **kwargs) class ArcBrace(Brace): """Creates a :class:`~Brace` that wraps around an :class:`~.Arc`. The direction parameter allows the brace to be applied from outside or inside the arc. .. warning:: The :class:`ArcBrace` is smaller for arcs with smaller radii. .. note:: The :class:`ArcBrace` is initially a vertical :class:`Brace` defined by the length of the :class:`~.Arc`, but is scaled down to match the start and end angles. An exponential function is then applied after it is shifted based on the radius of the arc. The scaling effect is not applied for arcs with radii smaller than 1 to prevent over-scaling. Parameters
the length of the :class:`~.Arc`, but is scaled down to match the start and end angles. An exponential function is then applied after it is shifted based on the radius of the arc. The scaling effect is not applied for arcs with radii smaller than 1 to prevent over-scaling. Parameters ---------- arc The :class:`~.Arc` that wraps around the :class:`Brace` mobject. direction The direction from which the brace faces the arc. ``LEFT`` for inside the arc, and ``RIGHT`` for the outside. Example ------- .. manim:: ArcBraceExample :save_last_frame: :ref_classes: Arc class ArcBraceExample(Scene): def construct(self): arc_1 = Arc(radius=1.5,start_angle=0,angle=2*PI/3).set_color(RED) brace_1 = ArcBrace(arc_1,LEFT) group_1 = VGroup(arc_1,brace_1) arc_2 = Arc(radius=3,start_angle=0,angle=5*PI/6).set_color(YELLOW) brace_2 = ArcBrace(arc_2) group_2 = VGroup(arc_2,brace_2) arc_3 = Arc(radius=0.5,start_angle=-0,angle=PI).set_color(BLUE) brace_3 = ArcBrace(arc_3) group_3 = VGroup(arc_3,brace_3) arc_4 = Arc(radius=0.2,start_angle=0,angle=3*PI/2).set_color(GREEN) brace_4 = ArcBrace(arc_4) group_4 = VGroup(arc_4,brace_4) arc_group = VGroup(group_1, group_2, group_3, group_4).arrange_in_grid(buff=1.5) self.add(arc_group.center()) """ def __init__( self, arc: Arc | None = None, direction: Vector3DLike = RIGHT, **kwargs: Any, ): if arc is None: arc = Arc(start_angle=-1, angle=2, radius=1) arc_end_angle = arc.start_angle + arc.angle line = Line(UP * arc.start_angle, UP * arc_end_angle) scale_shift = RIGHT * np.log(arc.radius) if arc.radius >= 1: line.scale(arc.radius, about_point=ORIGIN) super().__init__(line, direction=direction, **kwargs) self.scale(1 / (arc.radius), about_point=ORIGIN) else: super().__init__(line, direction=direction, **kwargs) if arc.radius >= 0.3: self.shift(scale_shift) else: self.shift(RIGHT * np.log(0.3)) self.apply_complex_function(np.exp) self.shift(arc.get_arc_center()) ================================================ FILE: manim/mobject/svg/svg_mobject.py ================================================ """Mobjects generated from an SVG file.""" from __future__ import annotations import os from pathlib import Path from typing import Any from xml.etree import ElementTree as ET import numpy as np import svgelements as se from manim import config, logger from manim.utils.color import ManimColor, ParsableManimColor from ...constants import RIGHT from ...utils.bezier import get_quadratic_approximation_of_cubic from ...utils.images import get_full_vector_image_path from ...utils.iterables import hash_obj from ..geometry.arc import Circle from ..geometry.line import Line from ..geometry.polygram import Polygon, Rectangle, RoundedRectangle from ..opengl.opengl_compatibility import ConvertToOpenGL from ..types.vectorized_mobject import VMobject __all__ = ["SVGMobject", "VMobjectFromSVGPath"] SVG_HASH_TO_MOB_MAP: dict[int, VMobject] = {} def _convert_point_to_3d(x: float, y: float) -> np.ndarray: return np.array([x, y, 0.0]) class SVGMobject(VMobject, metaclass=ConvertToOpenGL): """A vectorized mobject created from importing an SVG file. Parameters ---------- file_name The path to the SVG file. should_center Whether or not the mobject should be centered after being imported. height The target height of the mobject, set to 2 Manim units by default. If the height and width are both set to ``None``, the mobject is imported without being scaled. width The target width of the mobject, set to ``None`` by default. If the height and the width are both set to ``None``, the mobject is imported without being scaled. color The color (both fill and stroke color) of the mobject. If ``None`` (the default), the colors set in the SVG file are used. opacity The opacity (both fill and stroke opacity) of the mobject. If ``None`` (the default), the opacity set in the SVG file is used. fill_color The fill color of the mobject. If ``None`` (the default), the fill colors set in the SVG file are used. fill_opacity The fill opacity of the mobject. If ``None`` (the default), the fill opacities set in the SVG file are used. stroke_color The stroke
the SVG file is used. fill_color The fill color of the mobject. If ``None`` (the default), the fill colors set in the SVG file are used. fill_opacity The fill opacity of the mobject. If ``None`` (the default), the fill opacities set in the SVG file are used. stroke_color The stroke color of the mobject. If ``None`` (the default), the stroke colors set in the SVG file are used. stroke_opacity The stroke opacity of the mobject. If ``None`` (the default), the stroke opacities set in the SVG file are used. stroke_width The stroke width of the mobject. If ``None`` (the default), the stroke width values set in the SVG file are used. svg_default A dictionary in which fallback values for unspecified properties of elements in the SVG file are defined. If ``None`` (the default), ``color``, ``opacity``, ``fill_color`` ``fill_opacity``, ``stroke_color``, and ``stroke_opacity`` are set to ``None``, and ``stroke_width`` is set to 0. path_string_config A dictionary with keyword arguments passed to :class:`.VMobjectFromSVGPath` used for importing path elements. If ``None`` (the default), no additional arguments are passed. use_svg_cache If True (default), the svg inputs (e.g. file_name, settings) will be used as a key and a copy of the created mobject will be saved using that key to be quickly retrieved if the same inputs need be processed later. For large SVGs which are used only once, this can be omitted to improve performance. kwargs Further arguments passed to the parent class. """ def __init__( self, file_name: str | os.PathLike | None = None, should_center: bool = True, height: float | None = 2, width: float | None = None, color: ParsableManimColor | None = None, opacity: float | None = None, fill_color: ParsableManimColor | None = None, fill_opacity: float | None = None, stroke_color: ParsableManimColor | None = None, stroke_opacity: float | None = None, stroke_width: float | None = None, svg_default: dict | None = None, path_string_config: dict | None = None, use_svg_cache: bool = True, **kwargs: Any, ): super().__init__(color=None, stroke_color=None, fill_color=None, **kwargs) # process keyword arguments 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.color = ManimColor(color) self.opacity = opacity self.fill_color = fill_color self.fill_opacity = fill_opacity # type: ignore[assignment] self.stroke_color = stroke_color self.stroke_opacity = stroke_opacity # type: ignore[assignment] self.stroke_width = stroke_width # type: ignore[assignment] if self.stroke_width is None: self.stroke_width = 0 if svg_default is None: svg_default = { "color": None, "opacity": None, "fill_color": None, "fill_opacity": None, "stroke_width": 0, "stroke_color": None, "stroke_opacity": None, } self.svg_default = svg_default if path_string_config is None: path_string_config = {} self.path_string_config = 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) -> None: """Checks whether the SVG has already been imported and generates it if not. See also -------- :meth:`.SVGMobject.generate_mobject` """ if use_svg_cache: hash_val = hash_obj(self.hash_seed) if hash_val in SVG_HASH_TO_MOB_MAP: mob = SVG_HASH_TO_MOB_MAP[hash_val].copy() self.add(*mob) return self.generate_mobject() if use_svg_cache: SVG_HASH_TO_MOB_MAP[hash_val] = self.copy() @property def hash_seed(self) -> tuple: """A unique hash representing the result of the generated mobject points. Used as keys in the ``SVG_HASH_TO_MOB_MAP``
it if not. See also -------- :meth:`.SVGMobject.generate_mobject` """ if use_svg_cache: hash_val = hash_obj(self.hash_seed) if hash_val in SVG_HASH_TO_MOB_MAP: mob = SVG_HASH_TO_MOB_MAP[hash_val].copy() self.add(*mob) return self.generate_mobject() if use_svg_cache: SVG_HASH_TO_MOB_MAP[hash_val] = self.copy() @property def hash_seed(self) -> tuple: """A unique hash representing the result of the generated mobject points. Used as keys in the ``SVG_HASH_TO_MOB_MAP`` caching dictionary. """ return ( self.__class__.__name__, self.svg_default, self.path_string_config, self.file_name, config.renderer, ) def generate_mobject(self) -> None: """Parse the SVG and translate its elements to submobjects.""" file_path = self.get_file_path() element_tree = ET.parse(file_path) new_tree = self.modify_xml_tree(element_tree) # type: ignore[arg-type] # Create a temporary svg file to dump modified svg to be parsed modified_file_path = file_path.with_name(f"{file_path.stem}_{file_path.suffix}") new_tree.write(modified_file_path) svg = se.SVG.parse(modified_file_path) modified_file_path.unlink() mobjects = self.get_mobjects_from(svg) self.add(*mobjects) self.flip(RIGHT) # Flip y def get_file_path(self) -> Path: """Search for an existing file based on the specified file name.""" if self.file_name is None: raise ValueError("Must specify file for SVGMobject") return get_full_vector_image_path(self.file_name) def modify_xml_tree(self, element_tree: ET.ElementTree) -> ET.ElementTree: """Modifies the SVG element tree to include default style information. Parameters ---------- element_tree The parsed element tree from the SVG file. """ config_style_dict = self.generate_config_style_dict() style_keys = ( "fill", "fill-opacity", "stroke", "stroke-opacity", "stroke-width", "style", ) root = element_tree.getroot() root_style_dict = {k: v for k, v in root.attrib.items() if k in style_keys} # type: ignore[union-attr] new_root = ET.Element("svg", {}) config_style_node = ET.SubElement(new_root, "g", config_style_dict) root_style_node = ET.SubElement(config_style_node, "g", root_style_dict) root_style_node.extend(root) # type: ignore[arg-type] return ET.ElementTree(new_root) def generate_config_style_dict(self) -> dict[str, str]: """Generate a dictionary holding the default style information.""" 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",), } svg_default_dict = self.svg_default result = {} for svg_key, style_keys in keys_converting_dict.items(): for style_key in style_keys: if svg_default_dict[style_key] is None: continue result[svg_key] = str(svg_default_dict[style_key]) return result def get_mobjects_from(self, svg: se.SVG) -> list[VMobject]: """Convert the elements of the SVG to a list of mobjects. Parameters ---------- svg The parsed SVG file. """ result: list[VMobject] = [] for shape in svg.elements(): # can we combine the two continue cases into one? if isinstance(shape, se.Group): # noqa: SIM114 continue elif isinstance(shape, se.Path): mob: VMobject = 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) elif isinstance(shape, se.Use) or type(shape) is se.SVGElement: continue else: logger.warning(f"Unsupported element type: {type(shape)}") continue if mob is None or not mob.has_points(): continue self.apply_style_to_mobject(mob, shape) if isinstance(shape, se.Transformable) and shape.apply: self.handle_transform(mob, shape.transform) result.append(mob) return result @staticmethod def handle_transform(mob: VMobject, matrix: se.Matrix) -> VMobject: """Apply SVG transformations to the converted mobject. Parameters ---------- mob The converted mobject. matrix The transformation matrix determined from the SVG transformation. """ 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: """Apply SVG style information to the converted mobject. Parameters ---------- mob The converted mobject. shape The parsed SVG element. """ mob.set_style( stroke_width=shape.stroke_width, stroke_color=shape.stroke.hexrgb, stroke_opacity=shape.stroke.opacity, fill_color=shape.fill.hexrgb, fill_opacity=shape.fill.opacity, ) return mob def path_to_mobject(self, path: se.Path) -> VMobjectFromSVGPath: """Convert a path element to
return mob @staticmethod def apply_style_to_mobject(mob: VMobject, shape: se.GraphicObject) -> VMobject: """Apply SVG style information to the converted mobject. Parameters ---------- mob The converted mobject. shape The parsed SVG element. """ mob.set_style( stroke_width=shape.stroke_width, stroke_color=shape.stroke.hexrgb, stroke_opacity=shape.stroke.opacity, fill_color=shape.fill.hexrgb, fill_opacity=shape.fill.opacity, ) return mob def path_to_mobject(self, path: se.Path) -> VMobjectFromSVGPath: """Convert a path element to a vectorized mobject. Parameters ---------- path The parsed SVG path. """ return VMobjectFromSVGPath(path, **self.path_string_config) @staticmethod def line_to_mobject(line: se.Line) -> Line: """Convert a line element to a vectorized mobject. Parameters ---------- line The parsed SVG line. """ return Line( start=_convert_point_to_3d(line.x1, line.y1), end=_convert_point_to_3d(line.x2, line.y2), ) @staticmethod def rect_to_mobject(rect: se.Rect) -> Rectangle: """Convert a rectangle element to a vectorized mobject. Parameters ---------- rect The parsed SVG rectangle. """ if rect.rx == 0 or rect.ry == 0: mob = Rectangle( width=rect.width, height=rect.height, ) else: mob = RoundedRectangle( width=rect.width, height=rect.height * rect.rx / rect.ry, corner_radius=rect.rx, ) mob.stretch_to_fit_height(rect.height) mob.shift( _convert_point_to_3d(rect.x + rect.width / 2, rect.y + rect.height / 2) ) return mob @staticmethod def ellipse_to_mobject(ellipse: se.Ellipse | se.Circle) -> Circle: """Convert an ellipse or circle element to a vectorized mobject. Parameters ---------- ellipse The parsed SVG ellipse or circle. """ mob = Circle(radius=ellipse.rx) if ellipse.rx != ellipse.ry: mob.stretch_to_fit_height(2 * ellipse.ry) mob.shift(_convert_point_to_3d(ellipse.cx, ellipse.cy)) return mob @staticmethod def polygon_to_mobject(polygon: se.Polygon) -> Polygon: """Convert a polygon element to a vectorized mobject. Parameters ---------- polygon The parsed SVG polygon. """ points = [_convert_point_to_3d(*point) for point in polygon] return Polygon(*points) def polyline_to_mobject(self, polyline: se.Polyline) -> VMobject: """Convert a polyline element to a vectorized mobject. Parameters ---------- polyline The parsed SVG polyline. """ points = [_convert_point_to_3d(*point) for point in polyline] vmobject_class = self.get_mobject_type_class() return vmobject_class().set_points_as_corners(points) @staticmethod def text_to_mobject(text: se.Text) -> VMobject: """Convert a text element to a vectorized mobject. .. warning:: Not yet implemented. Parameters ---------- text The parsed SVG text. """ logger.warning(f"Unsupported element type: {type(text)}") return # type: ignore[return-value] def move_into_position(self) -> None: """Scale and move the generated mobject into position.""" 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) class VMobjectFromSVGPath(VMobject, metaclass=ConvertToOpenGL): """A vectorized mobject representing an SVG path. .. note:: The ``long_lines``, ``should_subdivide_sharp_curves``, and ``should_remove_null_curves`` keyword arguments are only respected with the OpenGL renderer. Parameters ---------- path_obj A parsed SVG path object. long_lines Whether or not straight lines in the vectorized mobject are drawn in one or two segments. should_subdivide_sharp_curves Whether or not to subdivide subcurves further in case two segments meet at an angle that is sharper than a given threshold. should_remove_null_curves Whether or not to remove subcurves of length 0. kwargs Further keyword arguments are passed to the parent class. """ def __init__( self, path_obj: se.Path, long_lines: bool = False, should_subdivide_sharp_curves: bool = False, should_remove_null_curves: bool = False, **kwargs: Any, ): # Get rid of arcs path_obj.approximate_arcs_with_quads() self.path_obj = path_obj self.long_lines = long_lines self.should_subdivide_sharp_curves = should_subdivide_sharp_curves self.should_remove_null_curves = should_remove_null_curves super().__init__(**kwargs) def generate_points(self) -> None: # TODO: cache mobject in a re-importable way self.handle_commands() if config.renderer == "opengl": if self.should_subdivide_sharp_curves: # For a healthy triangulation later self.subdivide_sharp_curves() if self.should_remove_null_curves: # Get rid of any null curves self.set_points(self.get_points_without_null_curves()) def init_points(self) -> None: self.generate_points()
= long_lines self.should_subdivide_sharp_curves = should_subdivide_sharp_curves self.should_remove_null_curves = should_remove_null_curves super().__init__(**kwargs) def generate_points(self) -> None: # TODO: cache mobject in a re-importable way self.handle_commands() if config.renderer == "opengl": if self.should_subdivide_sharp_curves: # For a healthy triangulation later self.subdivide_sharp_curves() if self.should_remove_null_curves: # Get rid of any null curves self.set_points(self.get_points_without_null_curves()) def init_points(self) -> None: self.generate_points() def handle_commands(self) -> None: all_points: list[np.ndarray] = [] last_move: np.ndarray = None curve_start = None last_true_move = None def move_pen(pt: np.ndarray, *, true_move: bool = False) -> None: nonlocal last_move, curve_start, last_true_move last_move = pt if curve_start is None: curve_start = last_move if true_move: last_true_move = last_move if self.n_points_per_curve == 4: def add_cubic( start: np.ndarray, cp1: np.ndarray, cp2: np.ndarray, end: np.ndarray ) -> None: 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: np.ndarray, cp: np.ndarray, end: np.ndarray) -> None: add_cubic(start, (start + cp + cp) / 3, (cp + cp + end) / 3, end) move_pen(end) def add_line(start: np.ndarray, end: np.ndarray) -> None: add_cubic( start, (start + start + end) / 3, (start + end + end) / 3, end ) move_pen(end) else: def add_cubic( start: np.ndarray, cp1: np.ndarray, cp2: np.ndarray, end: np.ndarray ) -> None: 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: np.ndarray, cp: np.ndarray, end: np.ndarray) -> None: nonlocal all_points assert len(all_points) % 3 == 0, len(all_points) all_points += [start, cp, end] move_pen(end) def add_line(start: np.ndarray, end: np.ndarray) -> None: add_quad(start, (start + end) / 2, end) move_pen(end) for segment in self.path_obj: segment_class = segment.__class__ if segment_class == se.Move: move_pen(_convert_point_to_3d(*segment.end), true_move=True) 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 - last_true_move)) > 0.0001: add_line(last_move, last_true_move) 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)) ================================================ FILE: manim/mobject/text/__init__.py ================================================ """Mobjects used to display Text using Pango or LaTeX. Modules ======= .. autosummary:: :toctree: ../reference ~code_mobject ~numbers ~tex_mobject ~text_mobject """ ================================================ FILE: manim/mobject/text/code_mobject.py ================================================ """Mobject representing highlighted source code listings.""" from __future__ import annotations __all__ = [ "Code", ] from pathlib import Path from typing import Any, Literal from bs4 import BeautifulSoup, Tag from pygments import highlight from pygments.formatters.html import HtmlFormatter from pygments.lexers import get_lexer_by_name, guess_lexer, guess_lexer_for_filename from pygments.styles import get_all_styles from manim.constants import * from manim.mobject.geometry.arc import Dot from manim.mobject.geometry.shape_matchers import SurroundingRectangle from manim.mobject.opengl.opengl_compatibility import ConvertToOpenGL from manim.mobject.types.vectorized_mobject import VGroup, VMobject from manim.typing
typing import Any, Literal from bs4 import BeautifulSoup, Tag from pygments import highlight from pygments.formatters.html import HtmlFormatter from pygments.lexers import get_lexer_by_name, guess_lexer, guess_lexer_for_filename from pygments.styles import get_all_styles from manim.constants import * from manim.mobject.geometry.arc import Dot from manim.mobject.geometry.shape_matchers import SurroundingRectangle from manim.mobject.opengl.opengl_compatibility import ConvertToOpenGL from manim.mobject.types.vectorized_mobject import VGroup, VMobject from manim.typing import StrPath from manim.utils.color import WHITE, ManimColor class Code(VMobject, metaclass=ConvertToOpenGL): """A highlighted source code listing. Examples -------- Normal usage:: listing = Code( "helloworldcpp.cpp", tab_width=4, formatter_style="emacs", background="window", language="cpp", background_config={"stroke_color": WHITE}, paragraph_config={"font": "Noto Sans Mono"}, ) We can also render code passed as a string. As the automatic language detection can be a bit flaky, it is recommended to specify the language explicitly: .. manim:: CodeFromString :save_last_frame: class CodeFromString(Scene): def construct(self): code = '''from manim import Scene, Square class FadeInSquare(Scene): def construct(self): s = Square() self.play(FadeIn(s)) self.play(s.animate.scale(2)) self.wait()''' rendered_code = Code( code_string=code, language="python", background="window", background_config={"stroke_color": "maroon"}, ) self.add(rendered_code) Parameters ---------- code_file The path to the code file to display. code_string Alternatively, the code string to display. language The programming language of the code. If not specified, it will be guessed from the file extension or the code itself. formatter_style The style to use for the code highlighting. Defaults to ``"vim"``. A list of all available styles can be obtained by calling :meth:`.Code.get_styles_list`. tab_width The width of a tab character in spaces. Defaults to 4. add_line_numbers Whether to display line numbers. Defaults to ``True``. line_numbers_from The first line number to display. Defaults to 1. background The type of background to use. Can be either ``"rectangle"`` (the default) or ``"window"``. background_config Keyword arguments passed to the background constructor. Default settings are stored in the class attribute :attr:`.default_background_config` (which can also be modified directly). paragraph_config Keyword arguments passed to the constructor of the :class:`.Paragraph` objects holding the code, and the line numbers. Default settings are stored in the class attribute :attr:`.default_paragraph_config` (which can also be modified directly). """ _styles_list_cache: list[str] | None = None default_background_config: dict[str, Any] = { "buff": 0.3, "fill_color": ManimColor("#222"), "stroke_color": WHITE, "corner_radius": 0.2, "stroke_width": 1, "fill_opacity": 1, } default_paragraph_config: dict[str, Any] = { "font": "Monospace", "font_size": 24, "line_spacing": 0.5, "disable_ligatures": True, } code: VMobject def __init__( self, code_file: StrPath | None = None, code_string: str | None = None, language: str | None = None, formatter_style: str = "vim", tab_width: int = 4, add_line_numbers: bool = True, line_numbers_from: int = 1, background: Literal["rectangle", "window"] = "rectangle", background_config: dict[str, Any] | None = None, paragraph_config: dict[str, Any] | None = None, ): super().__init__() if code_file is not None: code_file = Path(code_file) code_string = code_file.read_text(encoding="utf-8") lexer = guess_lexer_for_filename(code_file.name, code_string) elif code_string is not None: if language is not None: lexer = get_lexer_by_name(language) else: lexer = guess_lexer(code_string) else: raise ValueError("Either a code file or a code string must be specified.") code_string = code_string.expandtabs(tabsize=tab_width) formatter = HtmlFormatter( style=formatter_style, noclasses=True, cssclasses="", ) soup = BeautifulSoup( highlight(code_string, lexer, formatter), features="html.parser" ) self._code_html = soup.find("pre") assert isinstance(self._code_html, Tag) # as we are using Paragraph to render the text, we need to find the character indices # of the
a code string must be specified.") code_string = code_string.expandtabs(tabsize=tab_width) formatter = HtmlFormatter( style=formatter_style, noclasses=True, cssclasses="", ) soup = BeautifulSoup( highlight(code_string, lexer, formatter), features="html.parser" ) self._code_html = soup.find("pre") assert isinstance(self._code_html, Tag) # as we are using Paragraph to render the text, we need to find the character indices # of the segments of changed color in the HTML code color_ranges = [] current_line_color_ranges = [] current_line_char_index = 0 for child in self._code_html.children: if child.name == "span": try: child_style = child["style"] if isinstance(child_style, str): color = child_style.removeprefix("color: ") else: color = None except KeyError: color = None current_line_color_ranges.append( ( current_line_char_index, current_line_char_index + len(child.text), color, ) ) current_line_char_index += len(child.text) else: for char in child.text: if char == "\n": color_ranges.append(current_line_color_ranges) current_line_color_ranges = [] current_line_char_index = 0 else: current_line_char_index += 1 color_ranges.append(current_line_color_ranges) code_lines = self._code_html.get_text().removesuffix("\n").split("\n") if paragraph_config is None: paragraph_config = {} base_paragraph_config = self.default_paragraph_config.copy() base_paragraph_config.update(paragraph_config) from manim.mobject.text.text_mobject import Paragraph self.code_lines = Paragraph( *code_lines, **base_paragraph_config, ) for line, color_range in zip(self.code_lines, color_ranges): for start, end, color in color_range: line[start:end].set_color(color) if add_line_numbers: base_paragraph_config.update({"alignment": "right"}) self.line_numbers = Paragraph( *[ str(i) for i in range( line_numbers_from, line_numbers_from + len(self.code_lines) ) ], **base_paragraph_config, ) self.line_numbers.next_to(self.code_lines, direction=LEFT).align_to( self.code_lines, UP ) self.add(self.line_numbers) for line in self.code_lines: line.submobjects = [c for c in line if not isinstance(c, Dot)] self.add(self.code_lines) if background_config is None: background_config = {} background_config_base = self.default_background_config.copy() background_config_base.update(background_config) if background == "rectangle": self.background = SurroundingRectangle( self, **background_config_base, ) elif background == "window": buttons = VGroup( Dot(radius=0.1, stroke_width=0, color=button_color) for button_color in ["#ff5f56", "#ffbd2e", "#27c93f"] ).arrange(RIGHT, buff=0.1) buttons.next_to(self, UP, buff=0.1).align_to(self, LEFT).shift(LEFT * 0.1) self.background = SurroundingRectangle( VGroup(self, buttons), **background_config_base, ) buttons.shift(UP * 0.1 + LEFT * 0.1) self.background.add(buttons) else: raise ValueError(f"Unknown background type: {background}") self.add_to_back(self.background) @classmethod def get_styles_list(cls) -> list[str]: """Get the list of all available formatter styles.""" if cls._styles_list_cache is None: cls._styles_list_cache = list(get_all_styles()) return cls._styles_list_cache ================================================ FILE: manim/mobject/text/numbers.py ================================================ """Mobjects representing numbers.""" from __future__ import annotations __all__ = ["DecimalNumber", "Integer", "Variable"] from typing import Any import numpy as np from typing_extensions import Self from manim import config from manim.constants import * from manim.mobject.opengl.opengl_compatibility import ConvertToOpenGL from manim.mobject.text.tex_mobject import MathTex, SingleStringMathTex, Tex from manim.mobject.text.text_mobject import Text from manim.mobject.types.vectorized_mobject import VMobject from manim.mobject.value_tracker import ValueTracker from manim.typing import Vector3DLike string_to_mob_map: dict[str, SingleStringMathTex] = {} class DecimalNumber(VMobject, metaclass=ConvertToOpenGL): r"""An mobject representing a decimal number. Parameters ---------- number The numeric value to be displayed. It can later be modified using :meth:`.set_value`. num_decimal_places The number of decimal places after the decimal separator. Values are automatically rounded. mob_class The class for rendering digits and units, by default :class:`.MathTex`. include_sign Set to ``True`` to include a sign for positive numbers and zero. group_with_commas When ``True`` thousands groups are separated by commas for readability. digit_buff_per_font_unit Additional spacing between digits. Scales with font size. show_ellipsis When a number has been truncated by rounding, indicate with an ellipsis (``...``). unit A unit string which can be placed to the right of the numerical values. unit_buff_per_font_unit An additional spacing between the numerical values and the unit. A value of ``unit_buff_per_font_unit=0.003`` gives a decent spacing. Scales with font size. include_background_rectangle
number has been truncated by rounding, indicate with an ellipsis (``...``). unit A unit string which can be placed to the right of the numerical values. unit_buff_per_font_unit An additional spacing between the numerical values and the unit. A value of ``unit_buff_per_font_unit=0.003`` gives a decent spacing. Scales with font size. include_background_rectangle Adds a background rectangle to increase contrast on busy scenes. edge_to_fix Assuring right- or left-alignment of the full object. font_size Size of the font. Examples -------- .. manim:: MovingSquareWithUpdaters class MovingSquareWithUpdaters(Scene): def construct(self): decimal = DecimalNumber( 0, show_ellipsis=True, num_decimal_places=3, include_sign=True, unit=r"\text{M-Units}", unit_buff_per_font_unit=0.003 ) square = Square().to_edge(UP) decimal.add_updater(lambda d: d.next_to(square, RIGHT)) decimal.add_updater(lambda d: d.set_value(square.get_center()[1])) self.add(square, decimal) self.play( square.animate.to_edge(DOWN), rate_func=there_and_back, run_time=5, ) self.wait() """ def __init__( self, number: float = 0, num_decimal_places: int = 2, mob_class: type[SingleStringMathTex] = MathTex, include_sign: bool = False, group_with_commas: bool = True, digit_buff_per_font_unit: float = 0.001, show_ellipsis: bool = False, unit: str | None = None, # Aligned to bottom unless it starts with "^" unit_buff_per_font_unit: float = 0, include_background_rectangle: bool = False, edge_to_fix: Vector3DLike = LEFT, font_size: float = DEFAULT_FONT_SIZE, stroke_width: float = 0, fill_opacity: float = 1.0, **kwargs: Any, ): super().__init__(**kwargs, fill_opacity=fill_opacity, stroke_width=stroke_width) self.number = number self.num_decimal_places = num_decimal_places self.include_sign = include_sign self.mob_class = mob_class self.group_with_commas = group_with_commas self.digit_buff_per_font_unit = digit_buff_per_font_unit self.show_ellipsis = show_ellipsis self.unit = unit self.unit_buff_per_font_unit = unit_buff_per_font_unit self.include_background_rectangle = include_background_rectangle self.edge_to_fix = edge_to_fix self._font_size = font_size self.fill_opacity = fill_opacity self.initial_config = kwargs.copy() self.initial_config.update( { "num_decimal_places": num_decimal_places, "include_sign": include_sign, "group_with_commas": group_with_commas, "digit_buff_per_font_unit": digit_buff_per_font_unit, "show_ellipsis": show_ellipsis, "unit": unit, "unit_buff_per_font_unit": unit_buff_per_font_unit, "include_background_rectangle": include_background_rectangle, "edge_to_fix": edge_to_fix, "font_size": font_size, "stroke_width": stroke_width, "fill_opacity": fill_opacity, }, ) self._set_submobjects_from_number(number) self.init_colors() @property def font_size(self) -> float: """The font size of the tex mobject.""" return_value: float = self.height / self.initial_height * self._font_size return return_value @font_size.setter def font_size(self, font_val: float) -> None: if font_val <= 0: raise ValueError("font_size must be greater than 0.") elif self.height > 0: # sometimes manim generates a SingleStringMathex mobject with 0 height. # can't be scaled regardless and will error without the elif. # scale to a factor of the initial height so that setting # font_size does not depend on current size. self.scale(font_val / self.font_size) def _set_submobjects_from_number(self, number: float) -> None: self.number = number self.submobjects = [] num_string = self._get_num_string(number) self.add(*(map(self._string_to_mob, num_string))) # Add non-numerical bits if self.show_ellipsis: self.add( self._string_to_mob("\\dots", SingleStringMathTex, color=self.color), ) self.arrange( buff=self.digit_buff_per_font_unit * self._font_size, aligned_edge=DOWN, ) if self.unit is not None: self.unit_sign = self._string_to_mob(self.unit, SingleStringMathTex) self.add( self.unit_sign.next_to( self, direction=RIGHT, buff=(self.unit_buff_per_font_unit + self.digit_buff_per_font_unit) * self._font_size, aligned_edge=DOWN, ) ) self.move_to(ORIGIN) # Handle alignment of parts that should be aligned # to the bottom for i, c in enumerate(num_string): if c == "-" and len(num_string) > i + 1: self[i].align_to(self[i + 1], UP) self[i].shift(self[i + 1].height * DOWN / 2) elif c == ",": self[i].shift(self[i].height * DOWN / 2) if self.unit and self.unit.startswith("^"): self.unit_sign.align_to(self, UP) # track the initial height to enable scaling via font_size self.initial_height: float = self.height if self.include_background_rectangle: self.add_background_rectangle() def _get_num_string(self, number: float | complex) -> str: if isinstance(number, complex): formatter = self._get_complex_formatter() else: formatter = self._get_formatter() num_string = formatter.format(number) rounded_num = np.round(number, self.num_decimal_places)
/ 2) if self.unit and self.unit.startswith("^"): self.unit_sign.align_to(self, UP) # track the initial height to enable scaling via font_size self.initial_height: float = self.height if self.include_background_rectangle: self.add_background_rectangle() def _get_num_string(self, number: float | complex) -> str: if isinstance(number, complex): formatter = self._get_complex_formatter() else: formatter = self._get_formatter() num_string = formatter.format(number) rounded_num = np.round(number, self.num_decimal_places) if num_string.startswith("-") and rounded_num == 0: num_string = "+" + num_string[1:] if self.include_sign else num_string[1:] return num_string def _string_to_mob( self, string: str, mob_class: type[SingleStringMathTex] | None = None, **kwargs: Any, ) -> VMobject: if mob_class is None: mob_class = self.mob_class if string not in string_to_mob_map: string_to_mob_map[string] = mob_class(string, **kwargs) mob = string_to_mob_map[string].copy() mob.font_size = self._font_size return mob def _get_formatter(self, **kwargs: Any) -> str: """ Configuration is based first off instance attributes, but overwritten by any kew word argument. Relevant key words: - include_sign - group_with_commas - num_decimal_places - field_name (e.g. 0 or 0.real) """ config = { attr: getattr(self, attr) for attr in [ "include_sign", "group_with_commas", "num_decimal_places", ] } config.update(kwargs) return "".join( [ "{", config.get("field_name", ""), ":", "+" if config["include_sign"] else "", "," if config["group_with_commas"] else "", ".", str(config["num_decimal_places"]), "f", "}", ], ) def _get_complex_formatter(self) -> str: return "".join( [ self._get_formatter(field_name="0.real"), self._get_formatter(field_name="0.imag", include_sign=True), "i", ], ) def set_value(self, number: float) -> Self: """Set the value of the :class:`~.DecimalNumber` to a new number. Parameters ---------- number The value that will overwrite the current number of the :class:`~.DecimalNumber`. """ # creates a new number mob via `set_submobjects_from_number` # then matches the properties (color, font_size, etc...) # of the previous mobject to the new one # old_family needed with cairo old_family = self.get_family() old_font_size = self.font_size move_to_point = self.get_edge_center(self.edge_to_fix) old_submobjects = self.submobjects self._set_submobjects_from_number(number) self.font_size = old_font_size self.move_to(move_to_point, self.edge_to_fix) for sm1, sm2 in zip(self.submobjects, old_submobjects): sm1.match_style(sm2) if config.renderer == RendererType.CAIRO: for mob in old_family: # Dumb hack...due to how scene handles families # of animated mobjects # for compatibility with updaters to not leave first number in place while updating, # not needed with opengl renderer mob.points[:] = 0 self.init_colors() return self def get_value(self) -> float: return self.number def increment_value(self, delta_t: float = 1) -> None: self.set_value(self.get_value() + delta_t) class Integer(DecimalNumber): """A class for displaying Integers. Examples -------- .. manim:: IntegerExample :save_last_frame: class IntegerExample(Scene): def construct(self): self.add(Integer(number=2.5).set_color(ORANGE).scale(2.5).set_x(-0.5).set_y(0.8)) self.add(Integer(number=3.14159, show_ellipsis=True).set_x(3).set_y(3.3).scale(3.14159)) self.add(Integer(number=42).set_x(2.5).set_y(-2.3).set_color_by_gradient(BLUE, TEAL).scale(1.7)) self.add(Integer(number=6.28).set_x(-1.5).set_y(-2).set_color(YELLOW).scale(1.4)) """ def __init__( self, number: float = 0, num_decimal_places: int = 0, **kwargs: Any ) -> None: super().__init__(number=number, num_decimal_places=num_decimal_places, **kwargs) def get_value(self) -> int: return int(np.round(super().get_value())) class Variable(VMobject, metaclass=ConvertToOpenGL): """A class for displaying text that shows "label = value" with the value continuously updated from a :class:`~.ValueTracker`. Parameters ---------- var The initial value you need to keep track of and display. label The label for your variable. Raw strings are convertex to :class:`~.MathTex` objects. var_type The class used for displaying the number. Defaults to :class:`DecimalNumber`. num_decimal_places The number of decimal places to display in your variable. Defaults to 2. If `var_type` is an :class:`Integer`, this parameter is ignored. kwargs Other arguments to be passed to `~.Mobject`. Attributes ---------- label : Union[:class:`str`, :class:`~.Tex`, :class:`~.MathTex`, :class:`~.Text`, :class:`~.SingleStringMathTex`] The label for your variable, for example
Defaults to :class:`DecimalNumber`. num_decimal_places The number of decimal places to display in your variable. Defaults to 2. If `var_type` is an :class:`Integer`, this parameter is ignored. kwargs Other arguments to be passed to `~.Mobject`. Attributes ---------- label : Union[:class:`str`, :class:`~.Tex`, :class:`~.MathTex`, :class:`~.Text`, :class:`~.SingleStringMathTex`] The label for your variable, for example ``x = ...``. tracker : :class:`~.ValueTracker` Useful in updating the value of your variable on-screen. value : Union[:class:`DecimalNumber`, :class:`Integer`] The tex for the value of your variable. Examples -------- Normal usage:: # DecimalNumber type var = 0.5 on_screen_var = Variable(var, Text("var"), num_decimal_places=3) # Integer type int_var = 0 on_screen_int_var = Variable(int_var, Text("int_var"), var_type=Integer) # Using math mode for the label on_screen_int_var = Variable(int_var, "{a}_{i}", var_type=Integer) .. manim:: VariablesWithValueTracker class VariablesWithValueTracker(Scene): def construct(self): var = 0.5 on_screen_var = Variable(var, Text("var"), num_decimal_places=3) # You can also change the colours for the label and value on_screen_var.label.set_color(RED) on_screen_var.value.set_color(GREEN) self.play(Write(on_screen_var)) # The above line will just display the variable with # its initial value on the screen. If you also wish to # update it, you can do so by accessing the `tracker` attribute self.wait() var_tracker = on_screen_var.tracker var = 10.5 self.play(var_tracker.animate.set_value(var)) self.wait() int_var = 0 on_screen_int_var = Variable( int_var, Text("int_var"), var_type=Integer ).next_to(on_screen_var, DOWN) on_screen_int_var.label.set_color(RED) on_screen_int_var.value.set_color(GREEN) self.play(Write(on_screen_int_var)) self.wait() var_tracker = on_screen_int_var.tracker var = 10.5 self.play(var_tracker.animate.set_value(var)) self.wait() # If you wish to have a somewhat more complicated label for your # variable with subscripts, superscripts, etc. the default class # for the label is MathTex subscript_label_var = 10 on_screen_subscript_var = Variable(subscript_label_var, "{a}_{i}").next_to( on_screen_int_var, DOWN ) self.play(Write(on_screen_subscript_var)) self.wait() .. manim:: VariableExample class VariableExample(Scene): def construct(self): start = 2.0 x_var = Variable(start, 'x', num_decimal_places=3) sqr_var = Variable(start**2, 'x^2', num_decimal_places=3) Group(x_var, sqr_var).arrange(DOWN) sqr_var.add_updater(lambda v: v.tracker.set_value(x_var.tracker.get_value()**2)) self.add(x_var, sqr_var) self.play(x_var.tracker.animate.set_value(5), run_time=2, rate_func=linear) self.wait(0.1) """ def __init__( self, var: float, label: str | Tex | MathTex | Text | SingleStringMathTex, var_type: type[DecimalNumber | Integer] = DecimalNumber, num_decimal_places: int = 2, **kwargs: Any, ): self.label = MathTex(label) if isinstance(label, str) else label equals = MathTex("=").next_to(self.label, RIGHT) self.label.add(equals) self.tracker = ValueTracker(var) if var_type == DecimalNumber: self.value = DecimalNumber( self.tracker.get_value(), num_decimal_places=num_decimal_places, ) elif var_type == Integer: self.value = Integer(self.tracker.get_value()) self.value.add_updater(lambda v: v.set_value(self.tracker.get_value())).next_to( self.label, RIGHT, ) super().__init__(**kwargs) self.add(self.label, self.value) ================================================ FILE: manim/mobject/text/tex_mobject.py ================================================ r"""Mobjects representing text rendered using LaTeX. .. important:: See the corresponding tutorial :ref:`rendering-with-latex` .. note:: Just as you can use :class:`~.Text` (from the module :mod:`~.text_mobject`) to add text to your videos, you can use :class:`~.Tex` and :class:`~.MathTex` to insert LaTeX. """ from __future__ import annotations from manim.utils.color import BLACK, ManimColor, ParsableManimColor __all__ = [ "SingleStringMathTex", "MathTex", "Tex", "BulletedList", "Title", ] import itertools as it import operator as op import re from collections.abc import Iterable, Sequence from functools import reduce from textwrap import dedent from typing import Any from typing_extensions import Self from manim import config, logger from manim.constants import * from manim.mobject.geometry.line import Line from manim.mobject.svg.svg_mobject import SVGMobject from manim.mobject.types.vectorized_mobject import VGroup, VMobject from manim.utils.tex import TexTemplate from manim.utils.tex_file_writing import tex_to_svg_file class SingleStringMathTex(SVGMobject): """Elementary building block for rendering text with LaTeX. Tests ----- Check that creating a :class:`~.SingleStringMathTex` object works:: >>> SingleStringMathTex('Test') #
import config, logger from manim.constants import * from manim.mobject.geometry.line import Line from manim.mobject.svg.svg_mobject import SVGMobject from manim.mobject.types.vectorized_mobject import VGroup, VMobject from manim.utils.tex import TexTemplate from manim.utils.tex_file_writing import tex_to_svg_file class SingleStringMathTex(SVGMobject): """Elementary building block for rendering text with LaTeX. Tests ----- Check that creating a :class:`~.SingleStringMathTex` object works:: >>> SingleStringMathTex('Test') # doctest: +SKIP SingleStringMathTex('Test') """ def __init__( self, tex_string: str, stroke_width: float = 0, should_center: bool = True, height: float | None = None, organize_left_to_right: bool = False, tex_environment: str | None = "align*", tex_template: TexTemplate | None = None, font_size: float = DEFAULT_FONT_SIZE, color: ParsableManimColor | None = None, **kwargs: Any, ): if color is None: color = VMobject().color self._font_size = font_size self.organize_left_to_right = organize_left_to_right self.tex_environment = tex_environment if tex_template is None: tex_template = config["tex_template"] self.tex_template: TexTemplate = tex_template self.tex_string = tex_string file_name = tex_to_svg_file( self._get_modified_expression(tex_string), environment=self.tex_environment, tex_template=self.tex_template, ) super().__init__( file_name=file_name, should_center=should_center, stroke_width=stroke_width, height=height, color=color, path_string_config={ "should_subdivide_sharp_curves": True, "should_remove_null_curves": True, }, **kwargs, ) self.init_colors() # used for scaling via font_size.setter self.initial_height = self.height if height is None: self.font_size = self._font_size if self.organize_left_to_right: self._organize_submobjects_left_to_right() def __repr__(self) -> str: return f"{type(self).__name__}({repr(self.tex_string)})" @property def font_size(self) -> float: """The font size of the tex mobject.""" return self.height / self.initial_height / SCALE_FACTOR_PER_FONT_POINT @font_size.setter def font_size(self, font_val: float) -> None: if font_val <= 0: raise ValueError("font_size must be greater than 0.") elif self.height > 0: # sometimes manim generates a SingleStringMathex mobject with 0 height. # can't be scaled regardless and will error without the elif. # scale to a factor of the initial height so that setting # font_size does not depend on current size. self.scale(font_val / self.font_size) def _get_modified_expression(self, tex_string: str) -> str: result = tex_string result = result.strip() result = self._modify_special_strings(result) return result def _modify_special_strings(self, tex: str) -> str: tex = tex.strip() should_add_filler = reduce( op.or_, [ # Fraction line needs something to be over tex == "\\over", tex == "\\overline", # Make sure sqrt has overbar tex == "\\sqrt", tex == "\\sqrt{", # Need to add blank subscript or superscript tex.endswith("_"), tex.endswith("^"), tex.endswith("dot"), ], ) if should_add_filler: filler = "{\\quad}" tex += filler if tex == "\\substack": tex = "\\quad" if tex == "": tex = "\\quad" # To keep files from starting with a line break if tex.startswith("\\\\"): tex = tex.replace("\\\\", "\\quad\\\\") # Handle imbalanced \left and \right num_lefts, num_rights = ( len([s for s in tex.split(substr)[1:] if s and s[0] in "(){}[]|.\\"]) for substr in ("\\left", "\\right") ) if num_lefts != num_rights: tex = tex.replace("\\left", "\\big") tex = tex.replace("\\right", "\\big") tex = self._remove_stray_braces(tex) for context in ["array"]: begin_in = ("\\begin{%s}" % context) in tex # noqa: UP031 end_in = ("\\end{%s}" % context) in tex # noqa: UP031 if begin_in ^ end_in: # Just turn this into a blank string, # which means caller should leave a # stray \\begin{...} with other symbols tex = "" return tex def _remove_stray_braces(self, tex: str) -> str: r""" Makes :class:`~.MathTex` resilient to unmatched braces. This is important when the braces in the TeX code are spread over multiple arguments as in, e.g., ``MathTex(r"e^{i", r"\tau}
which means caller should leave a # stray \\begin{...} with other symbols tex = "" return tex def _remove_stray_braces(self, tex: str) -> str: r""" Makes :class:`~.MathTex` resilient to unmatched braces. This is important when the braces in the TeX code are spread over multiple arguments as in, e.g., ``MathTex(r"e^{i", r"\tau} = 1")``. """ # "\{" does not count (it's a brace literal), but "\\{" counts (it's a new line and then brace) num_lefts = tex.count("{") - tex.count("\\{") + tex.count("\\\\{") num_rights = tex.count("}") - tex.count("\\}") + tex.count("\\\\}") while num_rights > num_lefts: tex = "{" + tex num_lefts += 1 while num_lefts > num_rights: tex = tex + "}" num_rights += 1 return tex def _organize_submobjects_left_to_right(self) -> Self: self.sort(lambda p: p[0]) return self def get_tex_string(self) -> str: return self.tex_string def init_colors(self, propagate_colors: bool = True) -> Self: for submobject in self.submobjects: # needed to preserve original (non-black) # TeX colors of individual submobjects if submobject.color != BLACK: continue submobject.color = self.color if config.renderer == RendererType.OPENGL: submobject.init_colors() elif config.renderer == RendererType.CAIRO: submobject.init_colors(propagate_colors=propagate_colors) return self class MathTex(SingleStringMathTex): r"""A string compiled with LaTeX in math mode. Examples -------- .. manim:: Formula :save_last_frame: class Formula(Scene): def construct(self): t = MathTex(r"\int_a^b f'(x) dx = f(b)- f(a)") self.add(t) Tests ----- Check that creating a :class:`~.MathTex` works:: >>> MathTex('a^2 + b^2 = c^2') # doctest: +SKIP MathTex('a^2 + b^2 = c^2') Check that double brace group splitting works correctly:: >>> t1 = MathTex('{{ a }} + {{ b }} = {{ c }}') # doctest: +SKIP >>> len(t1.submobjects) # doctest: +SKIP 5 >>> t2 = MathTex(r"\frac{1}{a+b\sqrt{2}}") # doctest: +SKIP >>> len(t2.submobjects) # doctest: +SKIP 1 """ def __init__( self, *tex_strings: str, arg_separator: str = " ", substrings_to_isolate: Iterable[str] | None = None, tex_to_color_map: dict[str, ParsableManimColor] | None = None, tex_environment: str | None = "align*", **kwargs: Any, ): self.tex_template = kwargs.pop("tex_template", config["tex_template"]) self.arg_separator = arg_separator self.substrings_to_isolate = ( [] if substrings_to_isolate is None else substrings_to_isolate ) if tex_to_color_map is None: self.tex_to_color_map: dict[str, ParsableManimColor] = {} else: self.tex_to_color_map = tex_to_color_map self.tex_environment = tex_environment self.brace_notation_split_occurred = False self.tex_strings = self._break_up_tex_strings(tex_strings) try: super().__init__( self.arg_separator.join(self.tex_strings), tex_environment=self.tex_environment, tex_template=self.tex_template, **kwargs, ) self._break_up_by_substrings() except ValueError as compilation_error: if self.brace_notation_split_occurred: logger.error( dedent( """\ A group of double braces, {{ ... }}, was detected in your string. Manim splits TeX strings at the double braces, which might have caused the current compilation error. If you didn't use the double brace split intentionally, add spaces between the braces to avoid the automatic splitting: {{ ... }} --> { { ... } }. """, ), ) raise compilation_error self.set_color_by_tex_to_color_map(self.tex_to_color_map) if self.organize_left_to_right: self._organize_submobjects_left_to_right() def _break_up_tex_strings(self, tex_strings: Sequence[str]) -> list[str]: # Separate out anything surrounded in double braces pre_split_length = len(tex_strings) tex_strings_brace_splitted = [ re.split("{{(.*?)}}", str(t)) for t in tex_strings ] tex_strings_combined = sum(tex_strings_brace_splitted, []) if len(tex_strings_combined) > pre_split_length: self.brace_notation_split_occurred = True # Separate out any strings specified in the isolate # or tex_to_color_map lists. patterns = [] patterns.extend( [ f"({re.escape(ss)})" for ss in it.chain( self.substrings_to_isolate, self.tex_to_color_map.keys(), ) ], ) pattern = "|".join(patterns) if pattern: pieces = [] for s in tex_strings_combined:
= sum(tex_strings_brace_splitted, []) if len(tex_strings_combined) > pre_split_length: self.brace_notation_split_occurred = True # Separate out any strings specified in the isolate # or tex_to_color_map lists. patterns = [] patterns.extend( [ f"({re.escape(ss)})" for ss in it.chain( self.substrings_to_isolate, self.tex_to_color_map.keys(), ) ], ) pattern = "|".join(patterns) if pattern: pieces = [] for s in tex_strings_combined: pieces.extend(re.split(pattern, s)) else: pieces = tex_strings_combined return [p for p in pieces if p] def _break_up_by_substrings(self) -> Self: """ Reorganize existing submobjects one layer deeper based on the structure of tex_strings (as a list of tex_strings) """ new_submobjects: list[VMobject] = [] curr_index = 0 for tex_string in self.tex_strings: sub_tex_mob = SingleStringMathTex( tex_string, tex_environment=self.tex_environment, tex_template=self.tex_template, ) num_submobs = len(sub_tex_mob.submobjects) new_index = ( curr_index + num_submobs + len("".join(self.arg_separator.split())) ) if num_submobs == 0: last_submob_index = min(curr_index, len(self.submobjects) - 1) sub_tex_mob.move_to(self.submobjects[last_submob_index], RIGHT) else: sub_tex_mob.submobjects = self.submobjects[curr_index:new_index] new_submobjects.append(sub_tex_mob) curr_index = new_index self.submobjects = new_submobjects return self def get_parts_by_tex( self, tex: str, substring: bool = True, case_sensitive: bool = True ) -> VGroup: def test(tex1: str, tex2: str) -> bool: if not case_sensitive: tex1 = tex1.lower() tex2 = tex2.lower() if substring: return tex1 in tex2 else: return tex1 == tex2 return VGroup(*(m for m in self.submobjects if test(tex, m.get_tex_string()))) def get_part_by_tex(self, tex: str, **kwargs: Any) -> MathTex | None: all_parts = self.get_parts_by_tex(tex, **kwargs) return all_parts[0] if all_parts else None def set_color_by_tex( self, tex: str, color: ParsableManimColor, **kwargs: Any ) -> Self: parts_to_color = self.get_parts_by_tex(tex, **kwargs) for part in parts_to_color: part.set_color(color) return self def set_opacity_by_tex( self, tex: str, opacity: float = 0.5, remaining_opacity: float | None = None, **kwargs: Any, ) -> Self: """ Sets the opacity of the tex specified. If 'remaining_opacity' is specified, then the remaining tex will be set to that opacity. Parameters ---------- tex The tex to set the opacity of. opacity Default 0.5. The opacity to set the tex to remaining_opacity Default None. The opacity to set the remaining tex to. If None, then the remaining tex will not be changed """ if remaining_opacity is not None: self.set_opacity(opacity=remaining_opacity) for part in self.get_parts_by_tex(tex): part.set_opacity(opacity) return self def set_color_by_tex_to_color_map( self, texs_to_color_map: dict[str, ParsableManimColor], **kwargs: Any ) -> Self: for texs, color in list(texs_to_color_map.items()): try: # If the given key behaves like tex_strings texs + "" self.set_color_by_tex(texs, ManimColor(color), **kwargs) except TypeError: # If the given key is a tuple for tex in texs: self.set_color_by_tex(tex, ManimColor(color), **kwargs) return self def index_of_part(self, part: MathTex) -> int: split_self = self.split() if part not in split_self: raise ValueError("Trying to get index of part not in MathTex") return split_self.index(part) def index_of_part_by_tex(self, tex: str, **kwargs: Any) -> int: part = self.get_part_by_tex(tex, **kwargs) if part is None: return -1 return self.index_of_part(part) def sort_alphabetically(self) -> None: self.submobjects.sort(key=lambda m: m.get_tex_string()) class Tex(MathTex): r"""A string compiled with LaTeX in normal mode. The color can be set using the ``color`` argument. Any parts of the ``tex_string`` that are colored by the TeX commands ``\color`` or ``\textcolor`` will retain their original color. Tests ----- Check whether writing a LaTeX string works:: >>> Tex('The horse does not eat cucumber salad.') # doctest: +SKIP Tex('The horse does not
be set using the ``color`` argument. Any parts of the ``tex_string`` that are colored by the TeX commands ``\color`` or ``\textcolor`` will retain their original color. Tests ----- Check whether writing a LaTeX string works:: >>> Tex('The horse does not eat cucumber salad.') # doctest: +SKIP Tex('The horse does not eat cucumber salad.') """ def __init__( self, *tex_strings: str, arg_separator: str = "", tex_environment: str | None = "center", **kwargs: Any, ): super().__init__( *tex_strings, arg_separator=arg_separator, tex_environment=tex_environment, **kwargs, ) class BulletedList(Tex): """A bulleted list. Examples -------- .. manim:: BulletedListExample :save_last_frame: class BulletedListExample(Scene): def construct(self): blist = BulletedList("Item 1", "Item 2", "Item 3", height=2, width=2) blist.set_color_by_tex("Item 1", RED) blist.set_color_by_tex("Item 2", GREEN) blist.set_color_by_tex("Item 3", BLUE) self.add(blist) """ def __init__( self, *items: str, buff: float = MED_LARGE_BUFF, dot_scale_factor: float = 2, tex_environment: str | None = None, **kwargs: Any, ): self.buff = buff self.dot_scale_factor = dot_scale_factor self.tex_environment = tex_environment line_separated_items = [s + "\\\\" for s in items] super().__init__( *line_separated_items, tex_environment=tex_environment, **kwargs, ) for part in self: dot = MathTex("\\cdot").scale(self.dot_scale_factor) dot.next_to(part[0], LEFT, SMALL_BUFF) part.add_to_back(dot) self.arrange(DOWN, aligned_edge=LEFT, buff=self.buff) def fade_all_but(self, index_or_string: int | str, opacity: float = 0.5) -> None: arg = index_or_string if isinstance(arg, str): part: VGroup | VMobject | None = self.get_part_by_tex(arg) if part is None: raise Exception( f"Could not locate part by provided tex string '{arg}'." ) elif isinstance(arg, int): part = self.submobjects[arg] else: raise TypeError(f"Expected int or string, got {arg}") for other_part in self.submobjects: if other_part is part: other_part.set_fill(opacity=1) else: other_part.set_fill(opacity=opacity) class Title(Tex): """A mobject representing an underlined title. Examples -------- .. manim:: TitleExample :save_last_frame: import manim class TitleExample(Scene): def construct(self): banner = ManimBanner() title = Title(f"Manim version {manim.__version__}") self.add(banner, title) """ def __init__( self, *text_parts: str, include_underline: bool = True, match_underline_width_to_text: bool = False, underline_buff: float = MED_SMALL_BUFF, **kwargs: Any, ): self.include_underline = include_underline self.match_underline_width_to_text = match_underline_width_to_text self.underline_buff = underline_buff super().__init__(*text_parts, **kwargs) self.to_edge(UP) if self.include_underline: underline_width = config["frame_width"] - 2 underline = Line(LEFT, RIGHT) underline.next_to(self, DOWN, buff=self.underline_buff) if self.match_underline_width_to_text: underline.match_width(self) else: underline.width = underline_width self.add(underline) self.underline = underline ================================================ FILE: manim/mobject/three_d/__init__.py ================================================ """Three-dimensional mobjects. Modules ======= .. autosummary:: :toctree: ../reference ~polyhedra ~three_d_utils ~three_dimensions """ ================================================ FILE: manim/mobject/three_d/polyhedra.py ================================================ """General polyhedral class and platonic solids.""" from __future__ import annotations from collections.abc import Hashable from typing import TYPE_CHECKING, Any import numpy as np from manim.mobject.geometry.polygram import Polygon from manim.mobject.graph import Graph from manim.mobject.three_d.three_dimensions import Dot3D from manim.mobject.types.vectorized_mobject import VGroup from manim.utils.qhull import QuickHull if TYPE_CHECKING: from manim.mobject.mobject import Mobject from manim.typing import Point3D, Point3DLike_Array __all__ = [ "Polyhedron", "Tetrahedron", "Octahedron", "Icosahedron", "Dodecahedron", "ConvexHull3D", ] class Polyhedron(VGroup): """An abstract polyhedra class. In this implementation, polyhedra are defined with a list of vertex coordinates in space, and a list of faces. This implementation mirrors that of a standard polyhedral data format (OFF, object file format). Parameters ---------- vertex_coords A list of coordinates of the corresponding vertices in the polyhedron. Each coordinate will correspond to a vertex. The vertices are indexed with the usual indexing of Python. faces_list A list of faces. Each face is a sublist containing the indices of the vertices that form
format). Parameters ---------- vertex_coords A list of coordinates of the corresponding vertices in the polyhedron. Each coordinate will correspond to a vertex. The vertices are indexed with the usual indexing of Python. faces_list A list of faces. Each face is a sublist containing the indices of the vertices that form the corners of that face. faces_config Configuration for the polygons representing the faces of the polyhedron. graph_config Configuration for the graph containing the vertices and edges of the polyhedron. Examples -------- To understand how to create a custom polyhedra, let's use the example of a rather simple one - a square pyramid. .. manim:: SquarePyramidScene :save_last_frame: class SquarePyramidScene(ThreeDScene): def construct(self): self.set_camera_orientation(phi=75 * DEGREES, theta=30 * DEGREES) vertex_coords = [ [1, 1, 0], [1, -1, 0], [-1, -1, 0], [-1, 1, 0], [0, 0, 2] ] faces_list = [ [0, 1, 4], [1, 2, 4], [2, 3, 4], [3, 0, 4], [0, 1, 2, 3] ] pyramid = Polyhedron(vertex_coords, faces_list) self.add(pyramid) In defining the polyhedron above, we first defined the coordinates of the vertices. These are the corners of the square base, given as the first four coordinates in the vertex list, and the apex, the last coordinate in the list. Next, we define the faces of the polyhedron. The triangular surfaces of the pyramid are polygons with two adjacent vertices in the base and the vertex at the apex as corners. We thus define these surfaces in the first four elements of our face list. The last element defines the base of the pyramid. The graph and faces of polyhedra can also be accessed and modified directly, after instantiation. They are stored in the `graph` and `faces` attributes respectively. .. manim:: PolyhedronSubMobjects :save_last_frame: class PolyhedronSubMobjects(ThreeDScene): def construct(self): self.set_camera_orientation(phi=75 * DEGREES, theta=30 * DEGREES) octahedron = Octahedron(edge_length = 3) octahedron.graph[0].set_color(RED) octahedron.faces[2].set_color(YELLOW) self.add(octahedron) """ def __init__( self, vertex_coords: Point3DLike_Array, faces_list: list[list[int]], faces_config: dict[str, str | int | float | bool] = {}, graph_config: dict[str, Any] = {}, ): super().__init__() self.faces_config = dict( {"fill_opacity": 0.5, "shade_in_3d": True}, **faces_config ) self.graph_config = dict( { "vertex_type": Dot3D, "edge_config": { "stroke_opacity": 0, # I find that having the edges visible makes the polyhedra look weird }, }, **graph_config, ) self.vertex_coords = vertex_coords self.vertex_indices = list(range(len(self.vertex_coords))) self.layout: dict[Hashable, Any] = dict(enumerate(self.vertex_coords)) self.faces_list = faces_list self.face_coords = [[self.layout[j] for j in i] for i in faces_list] self.edges = self.get_edges(self.faces_list) self.faces = self.create_faces(self.face_coords) self.graph = Graph( self.vertex_indices, self.edges, layout=self.layout, **self.graph_config ) self.add(self.faces, self.graph) self.add_updater(self.update_faces) def get_edges(self, faces_list: list[list[int]]) -> list[tuple[int, int]]: """Creates list of cyclic pairwise tuples.""" edges: list[tuple[int, int]] = [] for face in faces_list: edges += zip(face, face[1:] + face[:1]) return edges def create_faces( self, face_coords: Point3DLike_Array, ) -> VGroup: """Creates VGroup of faces from a list of face coordinates.""" face_group = VGroup() for face in face_coords: face_group.add(Polygon(*face, **self.faces_config)) return face_group def update_faces(self, m: Mobject) -> None: face_coords = self.extract_face_coords() new_faces = self.create_faces(face_coords) self.faces.match_points(new_faces) def extract_face_coords(self) -> Point3DLike_Array: """Extracts the coordinates of the vertices in the graph. Used for updating faces. """ new_vertex_coords = [] for v
of face coordinates.""" face_group = VGroup() for face in face_coords: face_group.add(Polygon(*face, **self.faces_config)) return face_group def update_faces(self, m: Mobject) -> None: face_coords = self.extract_face_coords() new_faces = self.create_faces(face_coords) self.faces.match_points(new_faces) def extract_face_coords(self) -> Point3DLike_Array: """Extracts the coordinates of the vertices in the graph. Used for updating faces. """ new_vertex_coords = [] for v in self.graph.vertices: new_vertex_coords.append(self.graph[v].get_center()) layout = dict(enumerate(new_vertex_coords)) return [[layout[j] for j in i] for i in self.faces_list] class Tetrahedron(Polyhedron): """A tetrahedron, one of the five platonic solids. It has 4 faces, 6 edges, and 4 vertices. Parameters ---------- edge_length The length of an edge between any two vertices. Examples -------- .. manim:: TetrahedronScene :save_last_frame: class TetrahedronScene(ThreeDScene): def construct(self): self.set_camera_orientation(phi=75 * DEGREES, theta=30 * DEGREES) obj = Tetrahedron() self.add(obj) """ def __init__(self, edge_length: float = 1, **kwargs: Any): unit = edge_length * np.sqrt(2) / 4 super().__init__( vertex_coords=[ np.array([unit, unit, unit]), np.array([unit, -unit, -unit]), np.array([-unit, unit, -unit]), np.array([-unit, -unit, unit]), ], faces_list=[[0, 1, 2], [3, 0, 2], [0, 1, 3], [3, 1, 2]], **kwargs, ) class Octahedron(Polyhedron): """An octahedron, one of the five platonic solids. It has 8 faces, 12 edges and 6 vertices. Parameters ---------- edge_length The length of an edge between any two vertices. Examples -------- .. manim:: OctahedronScene :save_last_frame: class OctahedronScene(ThreeDScene): def construct(self): self.set_camera_orientation(phi=75 * DEGREES, theta=30 * DEGREES) obj = Octahedron() self.add(obj) """ def __init__(self, edge_length: float = 1, **kwargs: Any): unit = edge_length * np.sqrt(2) / 2 super().__init__( vertex_coords=[ np.array([unit, 0, 0]), np.array([-unit, 0, 0]), np.array([0, unit, 0]), np.array([0, -unit, 0]), np.array([0, 0, unit]), np.array([0, 0, -unit]), ], faces_list=[ [2, 4, 1], [0, 4, 2], [4, 3, 0], [1, 3, 4], [3, 5, 0], [1, 5, 3], [2, 5, 1], [0, 5, 2], ], **kwargs, ) class Icosahedron(Polyhedron): """An icosahedron, one of the five platonic solids. It has 20 faces, 30 edges and 12 vertices. Parameters ---------- edge_length The length of an edge between any two vertices. Examples -------- .. manim:: IcosahedronScene :save_last_frame: class IcosahedronScene(ThreeDScene): def construct(self): self.set_camera_orientation(phi=75 * DEGREES, theta=30 * DEGREES) obj = Icosahedron() self.add(obj) """ def __init__(self, edge_length: float = 1, **kwargs: Any): unit_a = edge_length * ((1 + np.sqrt(5)) / 4) unit_b = edge_length * (1 / 2) super().__init__( vertex_coords=[ np.array([0, unit_b, unit_a]), np.array([0, -unit_b, unit_a]), np.array([0, unit_b, -unit_a]), np.array([0, -unit_b, -unit_a]), np.array([unit_b, unit_a, 0]), np.array([unit_b, -unit_a, 0]), np.array([-unit_b, unit_a, 0]), np.array([-unit_b, -unit_a, 0]), np.array([unit_a, 0, unit_b]), np.array([unit_a, 0, -unit_b]), np.array([-unit_a, 0, unit_b]), np.array([-unit_a, 0, -unit_b]), ], faces_list=[ [1, 8, 0], [1, 5, 7], [8, 5, 1], [7, 3, 5], [5, 9, 3], [8, 9, 5], [3, 2, 9], [9, 4, 2], [8, 4, 9], [0, 4, 8], [6, 4, 0], [6, 2, 4], [11, 2, 6], [3, 11, 2], [0, 6, 10], [10, 1, 0], [10, 7, 1], [11, 7, 3], [10, 11, 7], [10, 11, 6], ], **kwargs, ) class Dodecahedron(Polyhedron): """A dodecahedron, one of the five platonic solids. It has 12 faces, 30 edges and 20 vertices. Parameters ---------- edge_length The length of an edge between any two vertices. Examples -------- .. manim:: DodecahedronScene :save_last_frame: class DodecahedronScene(ThreeDScene): def construct(self): self.set_camera_orientation(phi=75 *
7], [10, 11, 6], ], **kwargs, ) class Dodecahedron(Polyhedron): """A dodecahedron, one of the five platonic solids. It has 12 faces, 30 edges and 20 vertices. Parameters ---------- edge_length The length of an edge between any two vertices. Examples -------- .. manim:: DodecahedronScene :save_last_frame: class DodecahedronScene(ThreeDScene): def construct(self): self.set_camera_orientation(phi=75 * DEGREES, theta=30 * DEGREES) obj = Dodecahedron() self.add(obj) """ def __init__(self, edge_length: float = 1, **kwargs: Any): unit_a = edge_length * ((1 + np.sqrt(5)) / 4) unit_b = edge_length * ((3 + np.sqrt(5)) / 4) unit_c = edge_length * (1 / 2) super().__init__( vertex_coords=[ np.array([unit_a, unit_a, unit_a]), np.array([unit_a, unit_a, -unit_a]), np.array([unit_a, -unit_a, unit_a]), np.array([unit_a, -unit_a, -unit_a]), np.array([-unit_a, unit_a, unit_a]), np.array([-unit_a, unit_a, -unit_a]), np.array([-unit_a, -unit_a, unit_a]), np.array([-unit_a, -unit_a, -unit_a]), np.array([0, unit_c, unit_b]), np.array([0, unit_c, -unit_b]), np.array([0, -unit_c, -unit_b]), np.array([0, -unit_c, unit_b]), np.array([unit_c, unit_b, 0]), np.array([-unit_c, unit_b, 0]), np.array([unit_c, -unit_b, 0]), np.array([-unit_c, -unit_b, 0]), np.array([unit_b, 0, unit_c]), np.array([-unit_b, 0, unit_c]), np.array([unit_b, 0, -unit_c]), np.array([-unit_b, 0, -unit_c]), ], faces_list=[ [18, 16, 0, 12, 1], [3, 18, 16, 2, 14], [3, 10, 9, 1, 18], [1, 9, 5, 13, 12], [0, 8, 4, 13, 12], [2, 16, 0, 8, 11], [4, 17, 6, 11, 8], [17, 19, 5, 13, 4], [19, 7, 15, 6, 17], [6, 15, 14, 2, 11], [19, 5, 9, 10, 7], [7, 10, 3, 14, 15], ], **kwargs, ) class ConvexHull3D(Polyhedron): """A convex hull for a set of points Parameters ---------- points The points to consider. tolerance The tolerance used for quickhull. kwargs Forwarded to the parent constructor. Examples -------- .. manim:: ConvexHull3DExample :save_last_frame: :quality: high class ConvexHull3DExample(ThreeDScene): def construct(self): self.set_camera_orientation(phi=75 * DEGREES, theta=30 * DEGREES) points = [ [ 1.93192757, 0.44134585, -1.52407061], [-0.93302521, 1.23206983, 0.64117067], [-0.44350918, -0.61043677, 0.21723705], [-0.42640268, -1.05260843, 1.61266094], [-1.84449637, 0.91238739, -1.85172623], [ 1.72068132, -0.11880457, 0.51881751], [ 0.41904805, 0.44938012, -1.86440686], [ 0.83864666, 1.66653337, 1.88960123], [ 0.22240514, -0.80986286, 1.34249326], [-1.29585759, 1.01516189, 0.46187522], [ 1.7776499, -1.59550796, -1.70240747], [ 0.80065226, -0.12530398, 1.70063977], [ 1.28960948, -1.44158255, 1.39938582], [-0.93538943, 1.33617705, -0.24852643], [-1.54868271, 1.7444399, -0.46170734] ] hull = ConvexHull3D( *points, faces_config = {"stroke_opacity": 0}, graph_config = { "vertex_type": Dot3D, "edge_config": { "stroke_color": BLUE, "stroke_width": 2, "stroke_opacity": 0.05, } } ) dots = VGroup(*[Dot3D(point) for point in points]) self.add(hull) self.add(dots) """ def __init__(self, *points: Point3D, tolerance: float = 1e-5, **kwargs: Any): # Build Convex Hull array = np.array(points) hull = QuickHull(tolerance) hull.build(array) # Setup Lists vertices = [] faces = [] # Extract Faces c = 0 d = {} facets = set(hull.facets) - hull.removed for facet in facets: tmp = set() for subfacet in facet.subfacets: for point in subfacet.points: if point not in d: vertices.append(point.coordinates) d[point] = c c += 1 tmp.add(point) faces.append([d[point] for point in tmp]) # Call Polyhedron super().__init__( vertex_coords=vertices, faces_list=faces, **kwargs, ) ================================================ FILE: manim/mobject/three_d/three_d_utils.py ================================================ """Utility functions for three-dimensional mobjects.""" from __future__ import annotations __all__ = [ "get_3d_vmob_gradient_start_and_end_points", "get_3d_vmob_start_corner_index", "get_3d_vmob_end_corner_index", "get_3d_vmob_start_corner", "get_3d_vmob_end_corner", "get_3d_vmob_unit_normal", "get_3d_vmob_start_corner_unit_normal", "get_3d_vmob_end_corner_unit_normal", ] from typing import TYPE_CHECKING, Literal import numpy as np from manim.constants import ORIGIN, UP from manim.utils.space_ops import get_unit_normal if TYPE_CHECKING: from manim.typing import Point3D, Vector3D from ..types.vectorized_mobject import VMobject def get_3d_vmob_gradient_start_and_end_points( vmob: VMobject,
mobjects.""" from __future__ import annotations __all__ = [ "get_3d_vmob_gradient_start_and_end_points", "get_3d_vmob_start_corner_index", "get_3d_vmob_end_corner_index", "get_3d_vmob_start_corner", "get_3d_vmob_end_corner", "get_3d_vmob_unit_normal", "get_3d_vmob_start_corner_unit_normal", "get_3d_vmob_end_corner_unit_normal", ] from typing import TYPE_CHECKING, Literal import numpy as np from manim.constants import ORIGIN, UP from manim.utils.space_ops import get_unit_normal if TYPE_CHECKING: from manim.typing import Point3D, Vector3D from ..types.vectorized_mobject import VMobject def get_3d_vmob_gradient_start_and_end_points( vmob: VMobject, ) -> tuple[Point3D, Point3D]: return ( get_3d_vmob_start_corner(vmob), get_3d_vmob_end_corner(vmob), ) def get_3d_vmob_start_corner_index(vmob: VMobject) -> Literal[0]: return 0 def get_3d_vmob_end_corner_index(vmob: VMobject) -> int: return ((len(vmob.points) - 1) // 6) * 3 def get_3d_vmob_start_corner(vmob: VMobject) -> Point3D: if vmob.get_num_points() == 0: return np.array(ORIGIN) return vmob.points[get_3d_vmob_start_corner_index(vmob)] def get_3d_vmob_end_corner(vmob: VMobject) -> Point3D: if vmob.get_num_points() == 0: return np.array(ORIGIN) return vmob.points[get_3d_vmob_end_corner_index(vmob)] def get_3d_vmob_unit_normal(vmob: VMobject, point_index: int) -> Vector3D: n_points = vmob.get_num_points() if len(vmob.get_anchors()) <= 2: return np.array(UP) i = point_index im3 = i - 3 if i > 2 else (n_points - 4) ip3 = i + 3 if i < (n_points - 3) else 3 unit_normal = get_unit_normal( vmob.points[ip3] - vmob.points[i], vmob.points[im3] - vmob.points[i], ) if np.linalg.norm(unit_normal) == 0: return np.array(UP) return unit_normal def get_3d_vmob_start_corner_unit_normal(vmob: VMobject) -> Vector3D: return get_3d_vmob_unit_normal(vmob, get_3d_vmob_start_corner_index(vmob)) def get_3d_vmob_end_corner_unit_normal(vmob: VMobject) -> Vector3D: return get_3d_vmob_unit_normal(vmob, get_3d_vmob_end_corner_index(vmob)) ================================================ FILE: manim/mobject/three_d/three_dimensions.py ================================================ """Three-dimensional mobjects.""" from __future__ import annotations __all__ = [ "ThreeDVMobject", "Surface", "Sphere", "Dot3D", "Cube", "Prism", "Cone", "Arrow3D", "Cylinder", "Line3D", "Torus", ] from collections.abc import Callable, Iterable, Sequence from typing import TYPE_CHECKING, Any import numpy as np from typing_extensions import Self from manim import config, logger from manim.constants import * from manim.mobject.geometry.arc import Circle from manim.mobject.geometry.polygram import Square from manim.mobject.mobject import * from manim.mobject.opengl.opengl_compatibility import ConvertToOpenGL from manim.mobject.opengl.opengl_mobject import OpenGLMobject from manim.mobject.types.vectorized_mobject import VectorizedPoint, VGroup, VMobject from manim.utils.color import ( BLUE, BLUE_D, BLUE_E, LIGHT_GREY, WHITE, ManimColor, ParsableManimColor, interpolate_color, ) from manim.utils.iterables import tuplify from manim.utils.space_ops import normalize, perpendicular_bisector, z_to_vector if TYPE_CHECKING: from manim.typing import Point3D, Point3DLike, Vector3DLike class ThreeDVMobject(VMobject, metaclass=ConvertToOpenGL): def __init__(self, shade_in_3d: bool = True, **kwargs): super().__init__(shade_in_3d=shade_in_3d, **kwargs) class Surface(VGroup, metaclass=ConvertToOpenGL): """Creates a Parametric Surface using a checkerboard pattern. Parameters ---------- func The function defining the :class:`Surface`. u_range The range of the ``u`` variable: ``(u_min, u_max)``. v_range The range of the ``v`` variable: ``(v_min, v_max)``. resolution The number of samples taken of the :class:`Surface`. A tuple can be used to define different resolutions for ``u`` and ``v`` respectively. fill_color The color of the :class:`Surface`. Ignored if ``checkerboard_colors`` is set. fill_opacity The opacity of the :class:`Surface`, from 0 being fully transparent to 1 being fully opaque. Defaults to 1. checkerboard_colors ng individual faces alternating colors. Overrides ``fill_color``. stroke_color Color of the stroke surrounding each face of :class:`Surface`. stroke_width Width of the stroke surrounding each face of :class:`Surface`. Defaults to 0.5. should_make_jagged Changes the anchor mode of the Bézier curves from smooth to jagged. Defaults to ``False``. Examples -------- .. manim:: PaaSurface :save_last_frame: class ParaSurface(ThreeDScene): def func(self, u, v): return np.array([np.cos(u) * np.cos(v), np.cos(u) * np.sin(v), u]) def construct(self): axes = ThreeDAxes(x_range=[-4,4], x_length=8) surface = Surface( lambda u, v: axes.c2p(*self.func(u, v)), u_range=[-PI, PI], v_range=[0, TAU], resolution=8, ) self.set_camera_orientation(theta=70 * DEGREES, phi=75 * DEGREES) self.add(axes, surface) """ def __init__( self, func: Callable[[float, float], np.ndarray], u_range:
ParaSurface(ThreeDScene): def func(self, u, v): return np.array([np.cos(u) * np.cos(v), np.cos(u) * np.sin(v), u]) def construct(self): axes = ThreeDAxes(x_range=[-4,4], x_length=8) surface = Surface( lambda u, v: axes.c2p(*self.func(u, v)), u_range=[-PI, PI], v_range=[0, TAU], resolution=8, ) self.set_camera_orientation(theta=70 * DEGREES, phi=75 * DEGREES) self.add(axes, surface) """ def __init__( self, func: Callable[[float, float], np.ndarray], u_range: Sequence[float] = [0, 1], v_range: Sequence[float] = [0, 1], resolution: Sequence[int] = 32, surface_piece_config: dict = {}, fill_color: ParsableManimColor = BLUE_D, fill_opacity: float = 1.0, checkerboard_colors: Sequence[ParsableManimColor] | bool = [BLUE_D, BLUE_E], stroke_color: ParsableManimColor = LIGHT_GREY, stroke_width: float = 0.5, should_make_jagged: bool = False, pre_function_handle_to_anchor_scale_factor: float = 0.00001, **kwargs: Any, ) -> None: self.u_range = u_range self.v_range = v_range super().__init__( fill_color=fill_color, fill_opacity=fill_opacity, stroke_color=stroke_color, stroke_width=stroke_width, **kwargs, ) self.resolution = resolution self.surface_piece_config = surface_piece_config if checkerboard_colors: self.checkerboard_colors: list[ManimColor] = [ ManimColor(x) for x in checkerboard_colors ] else: self.checkerboard_colors = checkerboard_colors self.should_make_jagged = should_make_jagged self.pre_function_handle_to_anchor_scale_factor = ( pre_function_handle_to_anchor_scale_factor ) self._func = func self._setup_in_uv_space() self.apply_function(lambda p: func(p[0], p[1])) if self.should_make_jagged: self.make_jagged() def func(self, u: float, v: float) -> np.ndarray: return self._func(u, v) def _get_u_values_and_v_values(self) -> tuple[np.ndarray, np.ndarray]: res = tuplify(self.resolution) if len(res) == 1: u_res = v_res = res[0] else: u_res, v_res = res u_values = np.linspace(*self.u_range, u_res + 1) v_values = np.linspace(*self.v_range, v_res + 1) return u_values, v_values def _setup_in_uv_space(self) -> None: u_values, v_values = self._get_u_values_and_v_values() faces = VGroup() for i in range(len(u_values) - 1): for j in range(len(v_values) - 1): u1, u2 = u_values[i : i + 2] v1, v2 = v_values[j : j + 2] face = ThreeDVMobject() face.set_points_as_corners( [ [u1, v1, 0], [u2, v1, 0], [u2, v2, 0], [u1, v2, 0], [u1, v1, 0], ], ) faces.add(face) face.u_index = i face.v_index = j face.u1 = u1 face.u2 = u2 face.v1 = v1 face.v2 = v2 faces.set_fill(color=self.fill_color, opacity=self.fill_opacity) faces.set_stroke( color=self.stroke_color, width=self.stroke_width, opacity=self.stroke_opacity, ) self.add(*faces) if self.checkerboard_colors: self.set_fill_by_checkerboard(*self.checkerboard_colors) def set_fill_by_checkerboard( self, *colors: Iterable[ParsableManimColor], opacity: float | None = None ) -> Self: """Sets the fill_color of each face of :class:`Surface` in an alternating pattern. Parameters ---------- colors List of colors for alternating pattern. opacity The fill_opacity of :class:`Surface`, from 0 being fully transparent to 1 being fully opaque. Returns ------- :class:`~.Surface` The parametric surface with an alternating pattern. """ n_colors = len(colors) for face in self: c_index = (face.u_index + face.v_index) % n_colors face.set_fill(colors[c_index], opacity=opacity) return self def set_fill_by_value( self, axes: Mobject, colorscale: list[ParsableManimColor] | ParsableManimColor | None = None, axis: int = 2, **kwargs, ) -> Self: """Sets the color of each mobject of a parametric surface to a color relative to its axis-value. Parameters ---------- axes The axes for the parametric surface, which will be used to map axis-values to colors. colorscale A list of colors, ordered from lower axis-values to higher axis-values. If a list of tuples is passed containing colors paired with numbers, then those numbers will be used as the pivots. axis The chosen axis to use for the color mapping. (0 = x, 1 = y, 2 = z) Returns ------- :class:`~.Surface` The parametric surface with a gradient applied by value. For chaining. Examples -------- ..
containing colors paired with numbers, then those numbers will be used as the pivots. axis The chosen axis to use for the color mapping. (0 = x, 1 = y, 2 = z) Returns ------- :class:`~.Surface` The parametric surface with a gradient applied by value. For chaining. Examples -------- .. manim:: FillByValueExample :save_last_frame: class FillByValueExample(ThreeDScene): def construct(self): resolution_fa = 8 self.set_camera_orientation(phi=75 * DEGREES, theta=-160 * DEGREES) axes = ThreeDAxes(x_range=(0, 5, 1), y_range=(0, 5, 1), z_range=(-1, 1, 0.5)) def param_surface(u, v): x = u y = v z = np.sin(x) * np.cos(y) return z surface_plane = Surface( lambda u, v: axes.c2p(u, v, param_surface(u, v)), resolution=(resolution_fa, resolution_fa), v_range=[0, 5], u_range=[0, 5], ) surface_plane.set_style(fill_opacity=1) surface_plane.set_fill_by_value(axes=axes, colorscale=[(RED, -0.5), (YELLOW, 0), (GREEN, 0.5)], axis=2) self.add(axes, surface_plane) """ if "colors" in kwargs and colorscale is None: colorscale = kwargs.pop("colors") if kwargs: raise ValueError( "Unsupported keyword argument(s): " f"{', '.join(str(key) for key in kwargs)}" ) if colorscale is None: logger.warning( "The value passed to the colorscale keyword argument was None, " "the surface fill color has not been changed" ) return self ranges = [axes.x_range, axes.y_range, axes.z_range] if type(colorscale[0]) is tuple: new_colors, pivots = [ [i for i, j in colorscale], [j for i, j in colorscale], ] else: new_colors = colorscale pivot_min = ranges[axis][0] pivot_max = ranges[axis][1] pivot_frequency = (pivot_max - pivot_min) / (len(new_colors) - 1) pivots = np.arange( start=pivot_min, stop=pivot_max + pivot_frequency, step=pivot_frequency, ) for mob in self.family_members_with_points(): axis_value = axes.point_to_coords(mob.get_midpoint())[axis] if axis_value <= pivots[0]: mob.set_color(new_colors[0]) elif axis_value >= pivots[-1]: mob.set_color(new_colors[-1]) else: for i, pivot in enumerate(pivots): if pivot > axis_value: color_index = (axis_value - pivots[i - 1]) / ( pivots[i] - pivots[i - 1] ) color_index = min(color_index, 1) mob_color = interpolate_color( new_colors[i - 1], new_colors[i], color_index, ) if config.renderer == RendererType.OPENGL: mob.set_color(mob_color, recurse=False) elif config.renderer == RendererType.CAIRO: mob.set_color(mob_color, family=False) break return self # Specific shapes class Sphere(Surface): """A three-dimensional sphere. Parameters ---------- center Center of the :class:`Sphere`. radius The radius of the :class:`Sphere`. resolution The number of samples taken of the :class:`Sphere`. A tuple can be used to define different resolutions for ``u`` and ``v`` respectively. u_range The range of the ``u`` variable: ``(u_min, u_max)``. v_range The range of the ``v`` variable: ``(v_min, v_max)``. Examples -------- .. manim:: ExampleSphere :save_last_frame: class ExampleSphere(ThreeDScene): def construct(self): self.set_camera_orientation(phi=PI / 6, theta=PI / 6) sphere1 = Sphere( center=(3, 0, 0), radius=1, resolution=(20, 20), u_range=[0.001, PI - 0.001], v_range=[0, TAU] ) sphere1.set_color(RED) self.add(sphere1) sphere2 = Sphere(center=(-1, -3, 0), radius=2, resolution=(18, 18)) sphere2.set_color(GREEN) self.add(sphere2) sphere3 = Sphere(center=(-1, 2, 0), radius=2, resolution=(16, 16)) sphere3.set_color(BLUE) self.add(sphere3) """ def __init__( self, center: Point3DLike = ORIGIN, radius: float = 1, resolution: Sequence[int] | None = None, u_range: Sequence[float] = (0, TAU), v_range: Sequence[float] = (0, PI), **kwargs, ) -> None: if config.renderer == RendererType.OPENGL: res_value = (101, 51) elif config.renderer == RendererType.CAIRO: res_value = (24, 12) else: raise Exception("Unknown renderer") resolution = resolution if resolution is not None else res_value self.radius = radius super().__init__( self.func, resolution=resolution, u_range=u_range, v_range=v_range, **kwargs, ) self.shift(center) def func(self, u: float, v: float) -> np.ndarray: """The z values defining
RendererType.OPENGL: res_value = (101, 51) elif config.renderer == RendererType.CAIRO: res_value = (24, 12) else: raise Exception("Unknown renderer") resolution = resolution if resolution is not None else res_value self.radius = radius super().__init__( self.func, resolution=resolution, u_range=u_range, v_range=v_range, **kwargs, ) self.shift(center) def func(self, u: float, v: float) -> np.ndarray: """The z values defining the :class:`Sphere` being plotted. Returns ------- :class:`numpy.array` The z values defining the :class:`Sphere`. """ return self.radius * np.array( [np.cos(u) * np.sin(v), np.sin(u) * np.sin(v), -np.cos(v)], ) class Dot3D(Sphere): """A spherical dot. Parameters ---------- point The location of the dot. radius The radius of the dot. color The color of the :class:`Dot3D`. resolution The number of samples taken of the :class:`Dot3D`. A tuple can be used to define different resolutions for ``u`` and ``v`` respectively. Examples -------- .. manim:: Dot3DExample :save_last_frame: class Dot3DExample(ThreeDScene): def construct(self): self.set_camera_orientation(phi=75*DEGREES, theta=-45*DEGREES) axes = ThreeDAxes() dot_1 = Dot3D(point=axes.coords_to_point(0, 0, 1), color=RED) dot_2 = Dot3D(point=axes.coords_to_point(2, 0, 0), radius=0.1, color=BLUE) dot_3 = Dot3D(point=[0, 0, 0], radius=0.1, color=ORANGE) self.add(axes, dot_1, dot_2,dot_3) """ def __init__( self, point: list | np.ndarray = ORIGIN, radius: float = DEFAULT_DOT_RADIUS, color: ParsableManimColor = WHITE, resolution: tuple[int, int] = (8, 8), **kwargs, ) -> None: super().__init__(center=point, radius=radius, resolution=resolution, **kwargs) self.set_color(color) class Cube(VGroup): """A three-dimensional cube. Parameters ---------- side_length Length of each side of the :class:`Cube`. fill_opacity The opacity of the :class:`Cube`, from 0 being fully transparent to 1 being fully opaque. Defaults to 0.75. fill_color The color of the :class:`Cube`. stroke_width The width of the stroke surrounding each face of the :class:`Cube`. Examples -------- .. manim:: CubeExample :save_last_frame: class CubeExample(ThreeDScene): def construct(self): self.set_camera_orientation(phi=75*DEGREES, theta=-45*DEGREES) axes = ThreeDAxes() cube = Cube(side_length=3, fill_opacity=0.7, fill_color=BLUE) self.add(cube) """ def __init__( self, side_length: float = 2, fill_opacity: float = 0.75, fill_color: ParsableManimColor = BLUE, stroke_width: float = 0, **kwargs, ) -> None: self.side_length = side_length super().__init__( fill_color=fill_color, fill_opacity=fill_opacity, stroke_width=stroke_width, **kwargs, ) def generate_points(self) -> None: """Creates the sides of the :class:`Cube`.""" for vect in IN, OUT, LEFT, RIGHT, UP, DOWN: face = Square( side_length=self.side_length, shade_in_3d=True, joint_type=LineJointType.BEVEL, ) face.flip() face.shift(self.side_length * OUT / 2.0) face.apply_matrix(z_to_vector(vect)) self.add(face) def init_points(self) -> None: self.generate_points() class Prism(Cube): """A right rectangular prism (or rectangular cuboid). Defined by the length of each side in ``[x, y, z]`` format. Parameters ---------- dimensions Dimensions of the :class:`Prism` in ``[x, y, z]`` format. Examples -------- .. manim:: ExamplePrism :save_last_frame: class ExamplePrism(ThreeDScene): def construct(self): self.set_camera_orientation(phi=60 * DEGREES, theta=150 * DEGREES) prismSmall = Prism(dimensions=[1, 2, 3]).rotate(PI / 2) prismLarge = Prism(dimensions=[1.5, 3, 4.5]).move_to([2, 0, 0]) self.add(prismSmall, prismLarge) """ def __init__( self, dimensions: tuple[float, float, float] | np.ndarray = [3, 2, 1], **kwargs ) -> None: self.dimensions = dimensions super().__init__(**kwargs) def generate_points(self) -> None: """Creates the sides of the :class:`Prism`.""" super().generate_points() for dim, value in enumerate(self.dimensions): self.rescale_to_fit(value, dim, stretch=True) class Cone(Surface): """A circular cone. Can be defined using 2 parameters: its height, and its base radius. The polar angle, theta, can be calculated using arctan(base_radius / height) The spherical radius, r, is calculated using the pythagorean theorem. Parameters ---------- base_radius The base radius from which the cone tapers. height The height measured from
cone. Can be defined using 2 parameters: its height, and its base radius. The polar angle, theta, can be calculated using arctan(base_radius / height) The spherical radius, r, is calculated using the pythagorean theorem. Parameters ---------- base_radius The base radius from which the cone tapers. height The height measured from the plane formed by the base_radius to the apex of the cone. direction The direction of the apex. show_base Whether to show the base plane or not. v_range The azimuthal angle to start and end at. u_min The radius at the apex. checkerboard_colors Show checkerboard grid texture on the cone. Examples -------- .. manim:: ExampleCone :save_last_frame: class ExampleCone(ThreeDScene): def construct(self): axes = ThreeDAxes() cone = Cone(direction=X_AXIS+Y_AXIS+2*Z_AXIS, resolution=8) self.set_camera_orientation(phi=5*PI/11, theta=PI/9) self.add(axes, cone) """ def __init__( self, base_radius: float = 1, height: float = 1, direction: np.ndarray = Z_AXIS, show_base: bool = False, v_range: Sequence[float] = [0, TAU], u_min: float = 0, checkerboard_colors: bool = False, **kwargs: Any, ) -> None: self.direction = direction self.theta = PI - np.arctan(base_radius / height) super().__init__( self.func, v_range=v_range, u_range=[u_min, np.sqrt(base_radius**2 + height**2)], checkerboard_colors=checkerboard_colors, **kwargs, ) # used for rotations self.new_height = height self._current_theta = 0 self._current_phi = 0 self.base_circle = Circle( radius=base_radius, color=self.fill_color, fill_opacity=self.fill_opacity, stroke_width=0, ) self.base_circle.shift(height * IN) self._set_start_and_end_attributes(direction) if show_base: self.add(self.base_circle) self._rotate_to_direction() def func(self, u: float, v: float) -> np.ndarray: """Converts from spherical coordinates to cartesian. Parameters ---------- u The radius. v The azimuthal angle. Returns ------- :class:`numpy.array` Points defining the :class:`Cone`. """ r = u phi = v return np.array( [ r * np.sin(self.theta) * np.cos(phi), r * np.sin(self.theta) * np.sin(phi), r * np.cos(self.theta), ], ) def get_start(self) -> np.ndarray: return self.start_point.get_center() def get_end(self) -> np.ndarray: return self.end_point.get_center() def _rotate_to_direction(self) -> None: x, y, z = self.direction r = np.sqrt(x**2 + y**2 + z**2) theta = np.arccos(z / r) if r > 0 else 0 if x == 0: if y == 0: # along the z axis phi = 0 else: phi = np.arctan(np.inf) if y < 0: phi += PI else: phi = np.arctan(y / x) if x < 0: phi += PI # Undo old rotation (in reverse order) self.rotate(-self._current_phi, Z_AXIS, about_point=ORIGIN) self.rotate(-self._current_theta, Y_AXIS, about_point=ORIGIN) # Do new rotation self.rotate(theta, Y_AXIS, about_point=ORIGIN) self.rotate(phi, Z_AXIS, about_point=ORIGIN) # Store values self._current_theta = theta self._current_phi = phi def set_direction(self, direction: np.ndarray) -> None: """Changes the direction of the apex of the :class:`Cone`. Parameters ---------- direction The direction of the apex. """ self.direction = direction self._rotate_to_direction() def get_direction(self) -> np.ndarray: """Returns the current direction of the apex of the :class:`Cone`. Returns ------- direction : :class:`numpy.array` The direction of the apex. """ return self.direction def _set_start_and_end_attributes(self, direction): normalized_direction = direction * np.linalg.norm(direction) start = self.base_circle.get_center() end = start + normalized_direction * self.new_height self.start_point = VectorizedPoint(start) self.end_point = VectorizedPoint(end) self.add(self.start_point, self.end_point) class Cylinder(Surface): """A cylinder, defined by its height, radius and direction, Parameters ---------- radius The radius of the cylinder. height The height of the cylinder. direction The direction of the central axis of the cylinder. v_range The height along the height axis (given by direction)
self.end_point = VectorizedPoint(end) self.add(self.start_point, self.end_point) class Cylinder(Surface): """A cylinder, defined by its height, radius and direction, Parameters ---------- radius The radius of the cylinder. height The height of the cylinder. direction The direction of the central axis of the cylinder. v_range The height along the height axis (given by direction) to start and end on. show_ends Whether to show the end caps or not. resolution The number of samples taken of the :class:`Cylinder`. A tuple can be used to define different resolutions for ``u`` and ``v`` respectively. Examples -------- .. manim:: ExampleCylinder :save_last_frame: class ExampleCylinder(ThreeDScene): def construct(self): axes = ThreeDAxes() cylinder = Cylinder(radius=2, height=3) self.set_camera_orientation(phi=75 * DEGREES, theta=30 * DEGREES) self.add(axes, cylinder) """ def __init__( self, radius: float = 1, height: float = 2, direction: np.ndarray = Z_AXIS, v_range: Sequence[float] = [0, TAU], show_ends: bool = True, resolution: Sequence[int] = (24, 24), **kwargs, ) -> None: self._height = height self.radius = radius super().__init__( self.func, resolution=resolution, u_range=[-self._height / 2, self._height / 2], v_range=v_range, **kwargs, ) if show_ends: self.add_bases() self._current_phi = 0 self._current_theta = 0 self.set_direction(direction) def func(self, u: float, v: float) -> np.ndarray: """Converts from cylindrical coordinates to cartesian. Parameters ---------- u The height. v The azimuthal angle. Returns ------- :class:`numpy.ndarray` Points defining the :class:`Cylinder`. """ height = u phi = v r = self.radius return np.array([r * np.cos(phi), r * np.sin(phi), height]) def add_bases(self) -> None: """Adds the end caps of the cylinder.""" if config.renderer == RendererType.OPENGL: color = self.color opacity = self.opacity elif config.renderer == RendererType.CAIRO: color = self.fill_color opacity = self.fill_opacity self.base_top = Circle( radius=self.radius, color=color, fill_opacity=opacity, shade_in_3d=True, stroke_width=0, ) self.base_top.shift(self.u_range[1] * IN) self.base_bottom = Circle( radius=self.radius, color=color, fill_opacity=opacity, shade_in_3d=True, stroke_width=0, ) self.base_bottom.shift(self.u_range[0] * IN) self.add(self.base_top, self.base_bottom) def _rotate_to_direction(self) -> None: x, y, z = self.direction r = np.sqrt(x**2 + y**2 + z**2) theta = np.arccos(z / r) if r > 0 else 0 if x == 0: if y == 0: # along the z axis phi = 0 else: # along the x axis phi = np.arctan(np.inf) if y < 0: phi += PI else: phi = np.arctan(y / x) if x < 0: phi += PI # undo old rotation (in reverse direction) self.rotate(-self._current_phi, Z_AXIS, about_point=ORIGIN) self.rotate(-self._current_theta, Y_AXIS, about_point=ORIGIN) # do new rotation self.rotate(theta, Y_AXIS, about_point=ORIGIN) self.rotate(phi, Z_AXIS, about_point=ORIGIN) # store new values self._current_theta = theta self._current_phi = phi def set_direction(self, direction: np.ndarray) -> None: """Sets the direction of the central axis of the :class:`Cylinder`. Parameters ---------- direction : :class:`numpy.array` The direction of the central axis of the :class:`Cylinder`. """ # if get_norm(direction) is get_norm(self.direction): # pass self.direction = direction self._rotate_to_direction() def get_direction(self) -> np.ndarray: """Returns the direction of the central axis of the :class:`Cylinder`. Returns ------- direction : :class:`numpy.array` The direction of the central axis of the :class:`Cylinder`. """ return self.direction class Line3D(Cylinder): """A cylindrical line, for use in ThreeDScene. Parameters ---------- start The start point of the line. end The end point of the line. thickness The thickness of the line. color The color of the line. resolution The resolution of the line.
axis of the :class:`Cylinder`. """ return self.direction class Line3D(Cylinder): """A cylindrical line, for use in ThreeDScene. Parameters ---------- start The start point of the line. end The end point of the line. thickness The thickness of the line. color The color of the line. resolution The resolution of the line. By default this value is the number of points the line will sampled at. If you want the line to also come out checkered, use a tuple. For example, for a line made of 24 points with 4 checker points on each cylinder, pass the tuple (4, 24). Examples -------- .. manim:: ExampleLine3D :save_last_frame: class ExampleLine3D(ThreeDScene): def construct(self): axes = ThreeDAxes() line = Line3D(start=np.array([0, 0, 0]), end=np.array([2, 2, 2])) self.set_camera_orientation(phi=75 * DEGREES, theta=30 * DEGREES) self.add(axes, line) """ def __init__( self, start: np.ndarray = LEFT, end: np.ndarray = RIGHT, thickness: float = 0.02, color: ParsableManimColor | None = None, resolution: int | Sequence[int] = 24, **kwargs, ): self.thickness = thickness self.resolution = (2, resolution) if isinstance(resolution, int) else resolution self.set_start_and_end_attrs(start, end, **kwargs) if color is not None: self.set_color(color) def set_start_and_end_attrs( self, start: np.ndarray, end: np.ndarray, **kwargs ) -> None: """Sets the start and end points of the line. If either ``start`` or ``end`` are :class:`Mobjects <.Mobject>`, this gives their centers. Parameters ---------- start Starting point or :class:`Mobject`. end Ending point or :class:`Mobject`. """ rough_start = self.pointify(start) rough_end = self.pointify(end) self.vect = rough_end - rough_start self.length = np.linalg.norm(self.vect) self.direction = normalize(self.vect) # Now that we know the direction between them, # we can the appropriate boundary point from # start and end, if they're mobjects self.start = self.pointify(start, self.direction) self.end = self.pointify(end, -self.direction) super().__init__( height=np.linalg.norm(self.vect), radius=self.thickness, direction=self.direction, resolution=self.resolution, **kwargs, ) self.shift((self.start + self.end) / 2) def pointify( self, mob_or_point: Mobject | Point3DLike, direction: Vector3DLike | None = None, ) -> Point3D: """Gets a point representing the center of the :class:`Mobjects <.Mobject>`. Parameters ---------- mob_or_point :class:`Mobjects <.Mobject>` or point whose center should be returned. direction If an edge of a :class:`Mobjects <.Mobject>` should be returned, the direction of the edge. Returns ------- :class:`numpy.array` Center of the :class:`Mobjects <.Mobject>` or point, or edge if direction is given. """ if isinstance(mob_or_point, (Mobject, OpenGLMobject)): mob = mob_or_point if direction is None: return mob.get_center() else: return mob.get_boundary_point(direction) return np.array(mob_or_point) def get_start(self) -> np.ndarray: """Returns the starting point of the :class:`Line3D`. Returns ------- start : :class:`numpy.array` Starting point of the :class:`Line3D`. """ return self.start def get_end(self) -> np.ndarray: """Returns the ending point of the :class:`Line3D`. Returns ------- end : :class:`numpy.array` Ending point of the :class:`Line3D`. """ return self.end @classmethod def parallel_to( cls, line: Line3D, point: Point3DLike = ORIGIN, length: float = 5, **kwargs, ) -> Line3D: """Returns a line parallel to another line going through a given point. Parameters ---------- line The line to be parallel to. point The point to pass through. length Length of the parallel line. kwargs Additional parameters to be passed to the class. Returns ------- :class:`Line3D` Line parallel to ``line``. Examples -------- .. manim:: ParallelLineExample :save_last_frame: class ParallelLineExample(ThreeDScene): def construct(self): self.set_camera_orientation(PI /
point. Parameters ---------- line The line to be parallel to. point The point to pass through. length Length of the parallel line. kwargs Additional parameters to be passed to the class. Returns ------- :class:`Line3D` Line parallel to ``line``. Examples -------- .. manim:: ParallelLineExample :save_last_frame: class ParallelLineExample(ThreeDScene): def construct(self): self.set_camera_orientation(PI / 3, -PI / 4) ax = ThreeDAxes((-5, 5), (-5, 5), (-5, 5), 10, 10, 10) line1 = Line3D(RIGHT * 2, UP + OUT, color=RED) line2 = Line3D.parallel_to(line1, color=YELLOW) self.add(ax, line1, line2) """ np_point = np.asarray(point) vect = normalize(line.vect) return cls( np_point + vect * length / 2, np_point - vect * length / 2, **kwargs, ) @classmethod def perpendicular_to( cls, line: Line3D, point: Vector3DLike = ORIGIN, length: float = 5, **kwargs, ) -> Line3D: """Returns a line perpendicular to another line going through a given point. Parameters ---------- line The line to be perpendicular to. point The point to pass through. length Length of the perpendicular line. kwargs Additional parameters to be passed to the class. Returns ------- :class:`Line3D` Line perpendicular to ``line``. Examples -------- .. manim:: PerpLineExample :save_last_frame: class PerpLineExample(ThreeDScene): def construct(self): self.set_camera_orientation(PI / 3, -PI / 4) ax = ThreeDAxes((-5, 5), (-5, 5), (-5, 5), 10, 10, 10) line1 = Line3D(RIGHT * 2, UP + OUT, color=RED) line2 = Line3D.perpendicular_to(line1, color=BLUE) self.add(ax, line1, line2) """ np_point = np.asarray(point) norm = np.cross(line.vect, np_point - line.start) if all(np.linalg.norm(norm) == np.zeros(3)): raise ValueError("Could not find the perpendicular.") start, end = perpendicular_bisector([line.start, line.end], norm) vect = normalize(end - start) return cls( np_point + vect * length / 2, np_point - vect * length / 2, **kwargs, ) class Arrow3D(Line3D): """An arrow made out of a cylindrical line and a conical tip. Parameters ---------- start The start position of the arrow. end The end position of the arrow. thickness The thickness of the arrow. height The height of the conical tip. base_radius The base radius of the conical tip. color The color of the arrow. resolution The resolution of the arrow line. Examples -------- .. manim:: ExampleArrow3D :save_last_frame: class ExampleArrow3D(ThreeDScene): def construct(self): axes = ThreeDAxes() arrow = Arrow3D( start=np.array([0, 0, 0]), end=np.array([2, 2, 2]), resolution=8 ) self.set_camera_orientation(phi=75 * DEGREES, theta=30 * DEGREES) self.add(axes, arrow) """ def __init__( self, start: np.ndarray = LEFT, end: np.ndarray = RIGHT, thickness: float = 0.02, height: float = 0.3, base_radius: float = 0.08, color: ParsableManimColor = WHITE, resolution: int | Sequence[int] = 24, **kwargs, ) -> None: super().__init__( start=start, end=end, thickness=thickness, color=color, resolution=resolution, **kwargs, ) self.length = np.linalg.norm(self.vect) self.set_start_and_end_attrs( self.start, self.end - height * self.direction, **kwargs, ) self.cone = Cone( direction=self.direction, base_radius=base_radius, height=height, **kwargs, ) self.cone.shift(end) self.end_point = VectorizedPoint(end) self.add(self.end_point, self.cone) self.set_color(color) def get_end(self) -> np.ndarray: return self.end_point.get_center() class Torus(Surface): """A torus. Parameters ---------- major_radius Distance from the center of the tube to the center of the torus. minor_radius Radius of the tube. u_range The range of the ``u`` variable: ``(u_min, u_max)``. v_range The range of the ``v`` variable: ``(v_min, v_max)``. resolution The number of samples taken of the :class:`Torus`. A tuple can be used to define different
center of the tube to the center of the torus. minor_radius Radius of the tube. u_range The range of the ``u`` variable: ``(u_min, u_max)``. v_range The range of the ``v`` variable: ``(v_min, v_max)``. resolution The number of samples taken of the :class:`Torus`. A tuple can be used to define different resolutions for ``u`` and ``v`` respectively. Examples -------- .. manim :: ExampleTorus :save_last_frame: class ExampleTorus(ThreeDScene): def construct(self): axes = ThreeDAxes() torus = Torus() self.set_camera_orientation(phi=75 * DEGREES, theta=30 * DEGREES) self.add(axes, torus) """ def __init__( self, major_radius: float = 3, minor_radius: float = 1, u_range: Sequence[float] = (0, TAU), v_range: Sequence[float] = (0, TAU), resolution: tuple[int, int] | None = None, **kwargs, ) -> None: if config.renderer == RendererType.OPENGL: res_value = (101, 101) elif config.renderer == RendererType.CAIRO: res_value = (24, 24) resolution = resolution if resolution is not None else res_value self.R = major_radius self.r = minor_radius super().__init__( self.func, u_range=u_range, v_range=v_range, resolution=resolution, **kwargs, ) def func(self, u: float, v: float) -> np.ndarray: """The z values defining the :class:`Torus` being plotted. Returns ------- :class:`numpy.ndarray` The z values defining the :class:`Torus`. """ P = np.array([np.cos(u), np.sin(u), 0]) return (self.R - self.r * np.cos(v)) * P - self.r * np.sin(v) * OUT ================================================ FILE: manim/mobject/types/__init__.py ================================================ """Specialized mobject base classes. Modules ======= .. autosummary:: :toctree: ../reference ~image_mobject ~point_cloud_mobject ~vectorized_mobject """ ================================================ FILE: manim/mobject/types/image_mobject.py ================================================ """Mobjects representing raster images.""" from __future__ import annotations __all__ = ["AbstractImageMobject", "ImageMobject", "ImageMobjectFromCamera"] import pathlib from typing import TYPE_CHECKING, Any import numpy as np from PIL import Image from PIL.Image import Resampling from manim.mobject.geometry.shape_matchers import SurroundingRectangle from ... import config from ...camera.moving_camera import MovingCamera from ...constants import * from ...mobject.mobject import Mobject from ...utils.bezier import interpolate from ...utils.color import WHITE, ManimColor, color_to_int_rgb from ...utils.images import change_to_rgba_array, get_full_raster_image_path __all__ = ["ImageMobject", "ImageMobjectFromCamera"] if TYPE_CHECKING: import numpy.typing as npt from typing_extensions import Self from manim.typing import PixelArray, StrPath from ...camera.moving_camera import MovingCamera class AbstractImageMobject(Mobject): """ Automatically filters out black pixels Parameters ---------- scale_to_resolution At this resolution the image is placed pixel by pixel onto the screen, so it will look the sharpest and best. This is a custom parameter of ImageMobject so that rendering a scene with e.g. the ``--quality low`` or ``--quality medium`` flag for faster rendering won't effect the position of the image on the screen. """ def __init__( self, scale_to_resolution: int, pixel_array_dtype: str = "uint8", resampling_algorithm: Resampling = Resampling.BICUBIC, **kwargs: Any, ) -> None: self.pixel_array_dtype = pixel_array_dtype self.scale_to_resolution = scale_to_resolution self.set_resampling_algorithm(resampling_algorithm) super().__init__(**kwargs) def get_pixel_array(self) -> PixelArray: raise NotImplementedError() def set_color(self, color, alpha=None, family=True): # Likely to be implemented in subclasses, but no obligation pass def set_resampling_algorithm(self, resampling_algorithm: int) -> Self: """ Sets the interpolation method for upscaling the image. By default the image is interpolated using bicubic algorithm. This method lets you change it. Interpolation is done internally using Pillow, and the function besides the string constants describing the algorithm accepts the Pillow integer constants. Parameters ---------- resampling_algorithm An integer constant described in the Pillow library, or one from the RESAMPLING_ALGORITHMS global dictionary, under the following keys: * 'bicubic'
method lets you change it. Interpolation is done internally using Pillow, and the function besides the string constants describing the algorithm accepts the Pillow integer constants. Parameters ---------- resampling_algorithm An integer constant described in the Pillow library, or one from the RESAMPLING_ALGORITHMS global dictionary, under the following keys: * 'bicubic' or 'cubic' * 'nearest' or 'none' * 'box' * 'bilinear' or 'linear' * 'hamming' * 'lanczos' or 'antialias' """ if isinstance(resampling_algorithm, int): self.resampling_algorithm = resampling_algorithm else: raise ValueError( "resampling_algorithm has to be an int, one of the values defined in " "RESAMPLING_ALGORITHMS or a Pillow resampling filter constant. " "Available algorithms: 'bicubic', 'nearest', 'box', 'bilinear', " "'hamming', 'lanczos'.", ) return self def reset_points(self) -> None: """Sets :attr:`points` to be the four image corners.""" self.points = np.array( [ UP + LEFT, UP + RIGHT, DOWN + LEFT, DOWN + RIGHT, ], ) self.center() h, w = self.get_pixel_array().shape[:2] if self.scale_to_resolution: height = h / self.scale_to_resolution * config["frame_height"] else: height = 3 # this is the case for ImageMobjectFromCamera self.stretch_to_fit_height(height) self.stretch_to_fit_width(height * w / h) class ImageMobject(AbstractImageMobject): """Displays an Image from a numpy array or a file. Parameters ---------- scale_to_resolution At this resolution the image is placed pixel by pixel onto the screen, so it will look the sharpest and best. This is a custom parameter of ImageMobject so that rendering a scene with e.g. the ``--quality low`` or ``--quality medium`` flag for faster rendering won't effect the position of the image on the screen. Example ------- .. manim:: ImageFromArray :save_last_frame: class ImageFromArray(Scene): def construct(self): image = ImageMobject(np.uint8([[0, 100, 30, 200], [255, 0, 5, 33]])) image.height = 7 self.add(image) Changing interpolation style: .. manim:: ImageInterpolationEx :save_last_frame: class ImageInterpolationEx(Scene): def construct(self): img = ImageMobject(np.uint8([[63, 0, 0, 0], [0, 127, 0, 0], [0, 0, 191, 0], [0, 0, 0, 255] ])) img.height = 2 img1 = img.copy() img2 = img.copy() img3 = img.copy() img4 = img.copy() img5 = img.copy() img1.set_resampling_algorithm(RESAMPLING_ALGORITHMS["nearest"]) img2.set_resampling_algorithm(RESAMPLING_ALGORITHMS["lanczos"]) img3.set_resampling_algorithm(RESAMPLING_ALGORITHMS["linear"]) img4.set_resampling_algorithm(RESAMPLING_ALGORITHMS["cubic"]) img5.set_resampling_algorithm(RESAMPLING_ALGORITHMS["box"]) img1.add(Text("nearest").scale(0.5).next_to(img1,UP)) img2.add(Text("lanczos").scale(0.5).next_to(img2,UP)) img3.add(Text("linear").scale(0.5).next_to(img3,UP)) img4.add(Text("cubic").scale(0.5).next_to(img4,UP)) img5.add(Text("box").scale(0.5).next_to(img5,UP)) x= Group(img1,img2,img3,img4,img5) x.arrange() self.add(x) """ def __init__( self, filename_or_array: StrPath | npt.NDArray, scale_to_resolution: int = QUALITIES[DEFAULT_QUALITY]["pixel_height"], invert: bool = False, image_mode: str = "RGBA", **kwargs: Any, ) -> None: self.fill_opacity: float = 1 self.stroke_opacity: float = 1 self.invert_image = invert self.image_mode = image_mode if isinstance(filename_or_array, (str, pathlib.PurePath)): path = get_full_raster_image_path(filename_or_array) image = Image.open(path).convert(self.image_mode) self.pixel_array = np.array(image) self.path = path else: self.pixel_array = np.array(filename_or_array) self.pixel_array_dtype = kwargs.get("pixel_array_dtype", "uint8") self.pixel_array = change_to_rgba_array( self.pixel_array, self.pixel_array_dtype ) if self.invert_image: self.pixel_array[:, :, :3] = ( np.iinfo(self.pixel_array_dtype).max - self.pixel_array[:, :, :3] ) self.orig_alpha_pixel_array = self.pixel_array[:, :, 3].copy() super().__init__(scale_to_resolution, **kwargs) def get_pixel_array(self): """A simple getter method.""" return self.pixel_array def set_color(self, color, alpha=None, family=True): rgb = color_to_int_rgb(color) self.pixel_array[:, :, :3] = rgb if alpha is not None: self.pixel_array[:, :, 3] = int(255 * alpha) for submob in self.submobjects: submob.set_color(color, alpha, family) self.color = color return self def set_opacity(self, alpha: float) -> Self: """Sets the image's opacity. Parameters ---------- alpha The alpha value of the object, 1 being opaque and 0 being transparent. """ self.pixel_array[:, :, 3] = self.orig_alpha_pixel_array * alpha self.stroke_opacity = alpha return
for submob in self.submobjects: submob.set_color(color, alpha, family) self.color = color return self def set_opacity(self, alpha: float) -> Self: """Sets the image's opacity. Parameters ---------- alpha The alpha value of the object, 1 being opaque and 0 being transparent. """ self.pixel_array[:, :, 3] = self.orig_alpha_pixel_array * alpha self.stroke_opacity = alpha return self def fade(self, darkness: float = 0.5, family: bool = True) -> Self: """Sets the image's opacity using a 1 - alpha relationship. Parameters ---------- darkness The alpha value of the object, 1 being transparent and 0 being opaque. family Whether the submobjects of the ImageMobject should be affected. """ self.set_opacity(1 - darkness) super().fade(darkness, family) return self def interpolate_color( self, mobject1: ImageMobject, mobject2: ImageMobject, alpha: float ) -> None: """Interpolates the array of pixel color values from one ImageMobject into an array of equal size in the target ImageMobject. Parameters ---------- mobject1 The ImageMobject to transform from. mobject2 The ImageMobject to transform into. alpha Used to track the lerp relationship. Not opacity related. """ assert mobject1.pixel_array.shape == mobject2.pixel_array.shape, ( f"Mobject pixel array shapes incompatible for interpolation.\n" f"Mobject 1 ({mobject1}) : {mobject1.pixel_array.shape}\n" f"Mobject 2 ({mobject2}) : {mobject2.pixel_array.shape}" ) self.fill_opacity = interpolate( mobject1.fill_opacity, mobject2.fill_opacity, alpha, ) self.stroke_opacity = interpolate( mobject1.stroke_opacity, mobject2.stroke_opacity, alpha, ) self.pixel_array = interpolate( mobject1.pixel_array, mobject2.pixel_array, alpha, ).astype(self.pixel_array_dtype) def get_style(self) -> dict[str, Any]: return { "fill_color": ManimColor(self.color.get_rgb()).to_hex(), "fill_opacity": self.fill_opacity, } # TODO, add the ability to have the dimensions/orientation of this # mobject more strongly tied to the frame of the camera it contains, # in the case where that's a MovingCamera class ImageMobjectFromCamera(AbstractImageMobject): def __init__( self, camera: MovingCamera, default_display_frame_config: dict[str, Any] | None = None, **kwargs: Any, ) -> None: self.camera = camera if default_display_frame_config is None: default_display_frame_config = { "stroke_width": 3, "stroke_color": WHITE, "buff": 0, } self.default_display_frame_config = default_display_frame_config self.pixel_array = self.camera.pixel_array super().__init__(scale_to_resolution=False, **kwargs) # TODO: Get rid of this. def get_pixel_array(self): self.pixel_array = self.camera.pixel_array return self.pixel_array def add_display_frame(self, **kwargs: Any) -> Self: config = dict(self.default_display_frame_config) config.update(kwargs) self.display_frame = SurroundingRectangle(self, **config) self.add(self.display_frame) return self def interpolate_color(self, mobject1, mobject2, alpha) -> None: assert mobject1.pixel_array.shape == mobject2.pixel_array.shape, ( f"Mobject pixel array shapes incompatible for interpolation.\n" f"Mobject 1 ({mobject1}) : {mobject1.pixel_array.shape}\n" f"Mobject 2 ({mobject2}) : {mobject2.pixel_array.shape}" ) self.pixel_array = interpolate( mobject1.pixel_array, mobject2.pixel_array, alpha, ).astype(self.pixel_array_dtype) ================================================ FILE: manim/mobject/types/point_cloud_mobject.py ================================================ """Mobjects representing point clouds.""" from __future__ import annotations __all__ = ["PMobject", "Mobject1D", "Mobject2D", "PGroup", "PointCloudDot", "Point"] from collections.abc import Callable from typing import TYPE_CHECKING, Any import numpy as np from manim.mobject.opengl.opengl_compatibility import ConvertToOpenGL from manim.mobject.opengl.opengl_point_cloud_mobject import OpenGLPMobject from ...constants import * from ...mobject.mobject import Mobject from ...utils.bezier import interpolate from ...utils.color import ( BLACK, WHITE, YELLOW, ManimColor, ParsableManimColor, color_gradient, color_to_rgba, rgba_to_color, ) from ...utils.iterables import stretch_array_to_length __all__ = ["PMobject", "Mobject1D", "Mobject2D", "PGroup", "PointCloudDot", "Point"] if TYPE_CHECKING: import numpy.typing as npt from typing_extensions import Self from manim.typing import ( FloatRGBA_Array, FloatRGBALike_Array, ManimFloat, Point3D_Array, Point3DLike, Point3DLike_Array, ) class PMobject(Mobject, metaclass=ConvertToOpenGL): """A disc made of a cloud of Dots Examples -------- .. manim:: PMobjectExample :save_last_frame: class PMobjectExample(Scene): def construct(self): pG = PGroup() # This is just a collection of PMobject's # As the scale factor increases,
Self from manim.typing import ( FloatRGBA_Array, FloatRGBALike_Array, ManimFloat, Point3D_Array, Point3DLike, Point3DLike_Array, ) class PMobject(Mobject, metaclass=ConvertToOpenGL): """A disc made of a cloud of Dots Examples -------- .. manim:: PMobjectExample :save_last_frame: class PMobjectExample(Scene): def construct(self): pG = PGroup() # This is just a collection of PMobject's # As the scale factor increases, the number of points # removed increases. for sf in range(1, 9 + 1): p = PointCloudDot(density=20, radius=1).thin_out(sf) # PointCloudDot is a type of PMobject # and can therefore be added to a PGroup pG.add(p) # This organizes all the shapes in a grid. pG.arrange_in_grid() self.add(pG) """ def __init__(self, stroke_width: int = DEFAULT_STROKE_WIDTH, **kwargs: Any) -> None: self.stroke_width = stroke_width super().__init__(**kwargs) def reset_points(self) -> Self: self.rgbas: FloatRGBA_Array = np.zeros((0, 4)) self.points: Point3D_Array = np.zeros((0, 3)) return self def get_array_attrs(self) -> list[str]: return super().get_array_attrs() + ["rgbas"] def add_points( self, points: Point3DLike_Array, rgbas: FloatRGBALike_Array | None = None, color: ParsableManimColor | None = None, alpha: float = 1.0, ) -> Self: """Add points. Points must be a Nx3 numpy array. Rgbas must be a Nx4 numpy array if it is not None. """ if not isinstance(points, np.ndarray): points = np.array(points) num_new_points = len(points) self.points = np.append(self.points, points, axis=0) if rgbas is None: color = ManimColor(color) if color else self.color rgbas = np.repeat([color_to_rgba(color, alpha)], num_new_points, axis=0) elif len(rgbas) != len(points): raise ValueError("points and rgbas must have same length") self.rgbas = np.append(self.rgbas, rgbas, axis=0) return self def set_color( self, color: ParsableManimColor = YELLOW, family: bool = True ) -> Self: rgba = color_to_rgba(color) mobs = self.family_members_with_points() if family else [self] for mob in mobs: mob.rgbas[:, :] = rgba self.color = ManimColor.parse(color) return self def get_stroke_width(self) -> int: return self.stroke_width def set_stroke_width(self, width: int, family: bool = True) -> Self: mobs = self.family_members_with_points() if family else [self] for mob in mobs: mob.stroke_width = width return self def set_color_by_gradient(self, *colors: ParsableManimColor) -> Self: self.rgbas = np.array( list(map(color_to_rgba, color_gradient(*colors, len(self.points)))), ) return self def set_colors_by_radial_gradient( self, center: Point3DLike | None = None, radius: float = 1, inner_color: ParsableManimColor = WHITE, outer_color: ParsableManimColor = BLACK, ) -> Self: start_rgba, end_rgba = list(map(color_to_rgba, [inner_color, outer_color])) if center is None: center = self.get_center() for mob in self.family_members_with_points(): distances = np.abs(self.points - center) alphas = np.linalg.norm(distances, axis=1) / radius mob.rgbas = np.array( np.array( [interpolate(start_rgba, end_rgba, alpha) for alpha in alphas], ), ) return self def match_colors(self, mobject: Mobject) -> Self: Mobject.align_data(self, mobject) self.rgbas = np.array(mobject.rgbas) return self def filter_out(self, condition: npt.NDArray) -> Self: for mob in self.family_members_with_points(): to_eliminate = ~np.apply_along_axis(condition, 1, mob.points) mob.points = mob.points[to_eliminate] mob.rgbas = mob.rgbas[to_eliminate] return self def thin_out(self, factor: int = 5) -> Self: """Removes all but every nth point for n = factor""" for mob in self.family_members_with_points(): num_points = self.get_num_points() mob.apply_over_attr_arrays( lambda arr, n=num_points: arr[np.arange(0, n, factor)], ) return self def sort_points( self, function: Callable[[npt.NDArray[ManimFloat]], float] = lambda p: p[0] ) -> Self: """Function is any map from R^3 to R""" for mob in self.family_members_with_points(): indices = np.argsort(np.apply_along_axis(function, 1, mob.points)) mob.apply_over_attr_arrays(lambda arr, idx=indices: arr[idx]) return self def fade_to( self, color: ParsableManimColor, alpha: float, family: bool =
factor)], ) return self def sort_points( self, function: Callable[[npt.NDArray[ManimFloat]], float] = lambda p: p[0] ) -> Self: """Function is any map from R^3 to R""" for mob in self.family_members_with_points(): indices = np.argsort(np.apply_along_axis(function, 1, mob.points)) mob.apply_over_attr_arrays(lambda arr, idx=indices: arr[idx]) return self def fade_to( self, color: ParsableManimColor, alpha: float, family: bool = True ) -> Self: self.rgbas = interpolate(self.rgbas, color_to_rgba(color), alpha) for mob in self.submobjects: mob.fade_to(color, alpha, family) return self def get_all_rgbas(self) -> npt.NDArray: return self.get_merged_array("rgbas") def ingest_submobjects(self) -> Self: attrs = self.get_array_attrs() arrays = list(map(self.get_merged_array, attrs)) for attr, array in zip(attrs, arrays): setattr(self, attr, array) self.submobjects = [] return self def get_color(self) -> ManimColor: return rgba_to_color(self.rgbas[0, :]) def point_from_proportion(self, alpha: float) -> Any: index = alpha * (self.get_num_points() - 1) return self.points[np.floor(index)] @staticmethod def get_mobject_type_class() -> type[PMobject]: return PMobject # Alignment def align_points_with_larger(self, larger_mobject: Mobject) -> None: assert isinstance(larger_mobject, PMobject) self.apply_over_attr_arrays( lambda a: stretch_array_to_length(a, larger_mobject.get_num_points()), ) def get_point_mobject(self, center: Point3DLike | None = None) -> Point: if center is None: center = self.get_center() return Point(center) def interpolate_color( self, mobject1: Mobject, mobject2: Mobject, alpha: float ) -> Self: self.rgbas = interpolate(mobject1.rgbas, mobject2.rgbas, alpha) self.set_stroke_width( interpolate( mobject1.get_stroke_width(), mobject2.get_stroke_width(), alpha, ), ) return self def pointwise_become_partial(self, mobject: Mobject, a: float, b: float) -> None: lower_index, upper_index = (int(x * mobject.get_num_points()) for x in (a, b)) for attr in self.get_array_attrs(): full_array = getattr(mobject, attr) partial_array = full_array[lower_index:upper_index] setattr(self, attr, partial_array) # TODO, Make the two implementations below non-redundant class Mobject1D(PMobject, metaclass=ConvertToOpenGL): def __init__(self, density: int = DEFAULT_POINT_DENSITY_1D, **kwargs: Any) -> None: self.density = density self.epsilon = 1.0 / self.density super().__init__(**kwargs) def add_line( self, start: npt.NDArray, end: npt.NDArray, color: ParsableManimColor | None = None, ) -> None: start, end = list(map(np.array, [start, end])) length = np.linalg.norm(end - start) if length == 0: points = np.array([start]) else: epsilon = self.epsilon / length points = np.array( [interpolate(start, end, t) for t in np.arange(0, 1, epsilon)] ) self.add_points(points, color=color) class Mobject2D(PMobject, metaclass=ConvertToOpenGL): def __init__(self, density: int = DEFAULT_POINT_DENSITY_2D, **kwargs: Any) -> None: self.density = density self.epsilon = 1.0 / self.density super().__init__(**kwargs) class PGroup(PMobject): """A group for several point mobjects. Examples -------- .. manim:: PgroupExample :save_last_frame: class PgroupExample(Scene): def construct(self): p1 = PointCloudDot(radius=1, density=20, color=BLUE) p1.move_to(4.5 * LEFT) p2 = PointCloudDot() p3 = PointCloudDot(radius=1.5, stroke_width=2.5, color=PINK) p3.move_to(4.5 * RIGHT) pList = PGroup(p1, p2, p3) self.add(pList) """ def __init__(self, *pmobs: Any, **kwargs: Any) -> None: if not all(isinstance(m, (PMobject, OpenGLPMobject)) for m in pmobs): raise ValueError( "All submobjects must be of type PMobject or OpenGLPMObject" " if using the opengl renderer", ) super().__init__(**kwargs) self.add(*pmobs) def fade_to( self, color: ParsableManimColor, alpha: float, family: bool = True ) -> Self: if family: for mob in self.submobjects: mob.fade_to(color, alpha, family) return self class PointCloudDot(Mobject1D): """A disc made of a cloud of dots. Examples -------- .. manim:: PointCloudDotExample :save_last_frame: class PointCloudDotExample(Scene): def construct(self): cloud_1 = PointCloudDot(color=RED) cloud_2 = PointCloudDot(stroke_width=4, radius=1) cloud_3 = PointCloudDot(density=15) group = Group(cloud_1, cloud_2, cloud_3).arrange() self.add(group) .. manim:: PointCloudDotExample2 class PointCloudDotExample2(Scene): def construct(self): plane = ComplexPlane() cloud = PointCloudDot(color=RED) self.add( plane, cloud ) self.wait() self.play( cloud.animate.apply_complex_function(lambda z: np.exp(z)) ) """ def __init__(
.. manim:: PointCloudDotExample :save_last_frame: class PointCloudDotExample(Scene): def construct(self): cloud_1 = PointCloudDot(color=RED) cloud_2 = PointCloudDot(stroke_width=4, radius=1) cloud_3 = PointCloudDot(density=15) group = Group(cloud_1, cloud_2, cloud_3).arrange() self.add(group) .. manim:: PointCloudDotExample2 class PointCloudDotExample2(Scene): def construct(self): plane = ComplexPlane() cloud = PointCloudDot(color=RED) self.add( plane, cloud ) self.wait() self.play( cloud.animate.apply_complex_function(lambda z: np.exp(z)) ) """ def __init__( self, center: Point3DLike = ORIGIN, radius: float = 2.0, stroke_width: int = 2, density: int = DEFAULT_POINT_DENSITY_1D, color: ManimColor = YELLOW, **kwargs: Any, ) -> None: self.radius = radius self.epsilon = 1.0 / density super().__init__( stroke_width=stroke_width, density=density, color=color, **kwargs ) self.shift(center) def init_points(self) -> None: self.reset_points() self.generate_points() def generate_points(self) -> None: self.add_points( np.array( [ r * (np.cos(theta) * RIGHT + np.sin(theta) * UP) for r in np.arange(self.epsilon, self.radius, self.epsilon) # Num is equal to int(stop - start)/ (step + 1) reformulated. for theta in np.linspace( 0, 2 * np.pi, num=int(2 * np.pi * (r + self.epsilon) / self.epsilon), ) ] ), ) class Point(PMobject): """A mobject representing a point. Examples -------- .. manim:: ExamplePoint :save_last_frame: class ExamplePoint(Scene): def construct(self): colorList = [RED, GREEN, BLUE, YELLOW] for i in range(200): point = Point(location=[0.63 * np.random.randint(-4, 4), 0.37 * np.random.randint(-4, 4), 0], color=np.random.choice(colorList)) self.add(point) for i in range(200): point = Point(location=[0.37 * np.random.randint(-4, 4), 0.63 * np.random.randint(-4, 4), 0], color=np.random.choice(colorList)) self.add(point) self.add(point) """ def __init__( self, location: Point3DLike = ORIGIN, color: ManimColor = BLACK, **kwargs: Any ) -> None: self.location = location super().__init__(color=color, **kwargs) def init_points(self) -> None: self.reset_points() self.generate_points() self.set_points([self.location]) def generate_points(self) -> None: self.add_points(np.array([self.location])) ================================================ FILE: manim/opengl/__init__.py ================================================ from __future__ import annotations import contextlib with contextlib.suppress(ImportError): from dearpygui import dearpygui as dpg from manim.mobject.opengl.dot_cloud import * from manim.mobject.opengl.opengl_image_mobject import * from manim.mobject.opengl.opengl_mobject import * from manim.mobject.opengl.opengl_point_cloud_mobject import * from manim.mobject.opengl.opengl_surface import * from manim.mobject.opengl.opengl_three_dimensions import * from manim.mobject.opengl.opengl_vectorized_mobject import * from ..renderer.shader import * from ..utils.opengl import * ================================================ FILE: manim/plugins/__init__.py ================================================ from __future__ import annotations from manim._config import config, logger from manim.plugins.plugins_flags import get_plugins, list_plugins __all__ = [ "get_plugins", "list_plugins", ] requested_plugins: set[str] = set(config["plugins"]) missing_plugins = requested_plugins - set(get_plugins().keys()) if missing_plugins: logger.warning("Missing Plugins: %s", missing_plugins) ================================================ FILE: manim/plugins/plugins_flags.py ================================================ """Plugin Managing Utility""" from __future__ import annotations import sys from typing import Any if sys.version_info < (3, 10): from importlib_metadata import entry_points else: from importlib.metadata import entry_points from manim._config import console __all__ = ["list_plugins"] def get_plugins() -> dict[str, Any]: plugins: dict[str, Any] = { entry_point.name: entry_point.load() for entry_point in entry_points(group="manim.plugins") } return plugins def list_plugins() -> None: console.print("[green bold]Plugins:[/green bold]", justify="left") plugins = get_plugins() for plugin_name in plugins: console.print(f" • {plugin_name}") ================================================ FILE: manim/renderer/__init__.py ================================================ [Empty file] ================================================ FILE: manim/renderer/cairo_renderer.py ================================================ from __future__ import annotations from collections.abc import Iterable from typing import TYPE_CHECKING, Any import numpas np from manim.utils.hashing import get_hash_from_play_call from .. import config, logger from ..camera.camera import Camera from ..mobject.mobject import Mobject, _AnimationBuilder from ..scene.scene_file_writer import SceneFileWriter from ..utils.exceptions import EndSceneEarlyException from ..utils.iterables import list_update if TYPE_CHECKING: from manim.animation.animation import Animation from manim.scene.scene import Scene from ..typing import PixelArray __all__ = ["CairoRenderer"] class CairoRenderer: """A renderer using Cairo. Attributes ---------- num_plays : int Number of play() functions
Camera from ..mobject.mobject import Mobject, _AnimationBuilder from ..scene.scene_file_writer import SceneFileWriter from ..utils.exceptions import EndSceneEarlyException from ..utils.iterables import list_update if TYPE_CHECKING: from manim.animation.animation import Animation from manim.scene.scene import Scene from ..typing import PixelArray __all__ = ["CairoRenderer"] class CairoRenderer: """A renderer using Cairo. Attributes ---------- num_plays : int Number of play() functions in the scene. time : float Time elapsed since initialisation of scene. """ def __init__( self, file_writer_class: type[SceneFileWriter] = SceneFileWriter, camera_class: type[Camera] | None = None, skip_animations: bool = False, **kwargs: Any, ) -> None: # All of the following are set to EITHER the value passed via kwargs, # OR the value stored in the global config dict at the time of # _instance construction_. self._file_writer_class = file_writer_class camera_cls = camera_class if camera_class is not None else Camera self.camera = camera_cls() self._original_skipping_status = skip_animations self.skip_animations = skip_animations self.animations_hashes = [] self.num_plays = 0 self.time = 0 self.static_image = None def init_scene(self, scene: Scene) -> None: self.file_writer: Any = self._file_writer_class( self, scene.__class__.__name__, ) def play( self, scene: Scene, *args: Animation | Mobject | _AnimationBuilder, **kwargs, ): # Reset skip_animations to the original state. # Needed when rendering only some animations, and skipping others. self.skip_animations = self._original_skipping_status self.update_skipping_status() scene.compile_animation_data(*args, **kwargs) if self.skip_animations: logger.debug(f"Skipping animation {self.num_plays}") hash_current_animation = None self.time += scene.duration else: if config["disable_caching"]: logger.info("Caching disabled.") hash_current_animation = f"uncached_{self.num_plays:05}" else: hash_current_animation = get_hash_from_play_call( scene, self.camera, scene.animations, scene.mobjects, ) if self.file_writer.is_already_cached(hash_current_animation): logger.info( f"Animation {self.num_plays} : Using cached data (hash : %(hash_current_animation)s)", {"hash_current_animation": hash_current_animation}, ) self.skip_animations = True self.time += scene.duration # adding None as a partial movie file will make file_writer ignore the latter. self.file_writer.add_partial_movie_file(hash_current_animation) self.animations_hashes.append(hash_current_animation) logger.debug( "List of the first few animation hashes of the scene: %(h)s", {"h": str(self.animations_hashes[:5])}, ) self.file_writer.begin_animation(not self.skip_animations) scene.begin_animations() # Save a static image, to avoid rendering non moving objects. self.save_static_frame_data(scene, scene.static_mobjects) if scene.is_current_animation_frozen_frame(): self.update_frame(scene, mobjects=scene.moving_mobjects) # self.duration stands for the total run time of all the animations. # In this case, as there is only a wait, it will be the length of the wait. self.freeze_current_frame(scene.duration) else: scene.play_internal() self.file_writer.end_animation(not self.skip_animations) self.num_plays += 1 def update_frame( # TODO Description in Docstring self, scene: Scene, mobjects: Iterable[Mobject] | None = None, include_submobjects: bool = True, ignore_skipping: bool = True, **kwargs: Any, ) -> None: """Update the frame. Parameters ---------- scene mobjects list of mobjects include_submobjects ignore_skipping **kwargs """ if self.skip_animations and not ignore_skipping: return if not mobjects: mobjects = list_update( scene.mobjects, scene.foreground_mobjects, ) if self.static_image is not None: self.camera.set_frame_to_background(self.static_image) else: self.camera.reset() kwargs["include_submobjects"] = include_submobjects self.camera.capture_mobjects(mobjects, **kwargs) def render(self, scene, time, moving_mobjects): self.update_frame(scene, moving_mobjects) self.add_frame(self.get_frame()) def get_frame(self) -> PixelArray: """Gets the current frame as NumPy array. Returns ------- np.array NumPy array of pixel values of each pixel in screen. The shape of the array is height x width x 3. """ return np.array(self.camera.pixel_array) def add_frame(self, frame: np.ndarray, num_frames: int = 1): """Adds a frame to the video_file_stream Parameters ---------- frame The frame to add, as a pixel array. num_frames The number of times to add frame. """ dt = 1 / self.camera.frame_rate if self.skip_animations: return self.time += num_frames *
3. """ return np.array(self.camera.pixel_array) def add_frame(self, frame: np.ndarray, num_frames: int = 1): """Adds a frame to the video_file_stream Parameters ---------- frame The frame to add, as a pixel array. num_frames The number of times to add frame. """ dt = 1 / self.camera.frame_rate if self.skip_animations: return self.time += num_frames * dt self.file_writer.write_frame(frame, num_frames=num_frames) def freeze_current_frame(self, duration: float): """Adds a static frame to the movie for a given duration. The static frame is the current frame. Parameters ---------- duration [description] """ dt = 1 / self.camera.frame_rate self.add_frame( self.get_frame(), num_frames=int(duration / dt), ) def show_frame(self): """Opens the current frame in the Default Image Viewer of your system.""" self.update_frame(ignore_skipping=True) self.camera.get_image().show() def save_static_frame_data( self, scene: Scene, static_mobjects: Iterable[Mobject], ) -> Iterable[Mobject] | None: """Compute and save the static frame, that will be reused at each frame to avoid unnecessarily computing static mobjects. Parameters ---------- scene The scene played. static_mobjects Static mobjects of the scene. If None, self.static_image is set to None. Returns ------- typing.Iterable[Mobject] The static image computed. """ self.static_image = None if not static_mobjects: return None self.update_frame(scene, mobjects=static_mobjects) self.static_image = self.get_frame() return self.static_image def update_skipping_status(self): """ This method is used internally to check if the current animation needs to be skipped or not. It also checks if the number of animations that were played correspond to the number of animations that need to be played, and raises an EndSceneEarlyException if they don't correspond. """ # there is always at least one section -> no out of bounds here if self.file_writer.sections[-1].skip_animations: self.skip_animations = True if config["save_last_frame"]: self.skip_animations = True if ( config.from_animation_number > 0 and self.num_plays < config.from_animation_number ): self.skip_animations = True if ( config.upto_animation_number >= 0 and self.num_plays > config.upto_animation_number ): self.skip_animations = True raise EndSceneEarlyException() def scene_finished(self, scene: Scene) -> None: # If no animations in scene, render an image instead if self.num_plays: self.file_writer.finish() elif config.write_to_movie: config.save_last_frame = True config.write_to_movie = False else: self.static_image = None self.update_frame(scene) if config["save_last_frame"]: self.static_image = None self.update_frame(scene) self.file_writer.save_image(self.camera.get_image()) ================================================ FILE: manim/renderer/opengl_renderer.py ================================================ from __future__ import annotations import contextlib import itertools as it import time from functools import cached_property from typing import TYPE_CHECKING, Any import moderngl import numpy as np from PIL import Image from manim import config, logger from manim.mobject.opengl.opengl_mobject import ( OpenGLMobject, OpenGLPoint, _AnimationBuilder, ) from manim.mobject.opengl.opengl_vectorized_mobject import OpenGLVMobject from manim.utils.caching import handle_caching_play from manim.utils.color import color_to_rgba from manim.utils.exceptions import EndSceneEarlyException from ..constants import * from ..scene.scene_file_writer import SceneFileWriter from ..utils import opengl from ..utils.config_ops import _Data from ..utils.simple_functions import clip from ..utils.space_ops import ( angle_of_vector, quaternion_from_angle_axis, quaternion_mult, rotation_matrix_transpose, rotation_matrix_transpose_from_quaternion, ) from .shader import Mesh, Shader from .vectorized_mobject_rendering import ( render_opengl_vectorized_mobject_fill, render_opengl_vectorized_mobject_stroke, ) if TYPE_CHECKING: from typing_extensions import Self from manim.animation.animation import Animation from manim.mobject.mobject import Mobject from manim.scene.scene import Scene from manim.typing import Point3D __all__ = ["OpenGLCamera", "OpenGLRenderer"] class OpenGLCamera(OpenGLMobject): euler_angles = _Data() def __init__( self, frame_shape=None, center_point=None, # Theta, phi, gamma euler_angles=[0, 0, 0], focal_distance=2, light_source_position=[-10, 10, 10], orthographic=False, minimum_polar_angle=-PI / 2, maximum_polar_angle=PI / 2, model_matrix=None, **kwargs, ): self.use_z_index = True self.frame_rate = 60 self.orthographic = orthographic self.minimum_polar_angle = minimum_polar_angle self.maximum_polar_angle = maximum_polar_angle
__all__ = ["OpenGLCamera", "OpenGLRenderer"] class OpenGLCamera(OpenGLMobject): euler_angles = _Data() def __init__( self, frame_shape=None, center_point=None, # Theta, phi, gamma euler_angles=[0, 0, 0], focal_distance=2, light_source_position=[-10, 10, 10], orthographic=False, minimum_polar_angle=-PI / 2, maximum_polar_angle=PI / 2, model_matrix=None, **kwargs, ): self.use_z_index = True self.frame_rate = 60 self.orthographic = orthographic self.minimum_polar_angle = minimum_polar_angle self.maximum_polar_angle = maximum_polar_angle if self.orthographic: self.projection_matrix = opengl.orthographic_projection_matrix() self.unformatted_projection_matrix = opengl.orthographic_projection_matrix( format_=False, ) else: self.projection_matrix = opengl.perspective_projection_matrix() self.unformatted_projection_matrix = opengl.perspective_projection_matrix( format_=False, ) if frame_shape is None: self.frame_shape = (config["frame_width"], config["frame_height"]) else: self.frame_shape = frame_shape if center_point is None: self.center_point = ORIGIN else: self.center_point = center_point if model_matrix is None: model_matrix = opengl.translation_matrix(0, 0, 11) self.focal_distance = focal_distance if light_source_position is None: self.light_source_position = [-10, 10, 10] else: self.light_source_position = light_source_position self.light_source = OpenGLPoint(self.light_source_position) self.default_model_matrix = model_matrix super().__init__(model_matrix=model_matrix, should_render=False, **kwargs) if euler_angles is None: euler_angles = [0, 0, 0] euler_angles = np.array(euler_angles, dtype=float) self.euler_angles = euler_angles self.refresh_rotation_matrix() def get_position(self) -> Point3D: return self.model_matrix[:, 3][:3] def set_position(self, position): self.model_matrix[:, 3][:3] = position return self @cached_property def formatted_view_matrix(self): return opengl.matrix_to_shader_input(np.linalg.inv(self.model_matrix)) @cached_property def unformatted_view_matrix(self): return np.linalg.inv(self.model_matrix) def init_points(self): self.set_points([ORIGIN, LEFT, RIGHT, DOWN, UP]) self.set_width(self.frame_shape[0], stretch=True) self.set_height(self.frame_shape[1], stretch=True) self.move_to(self.center_point) def to_default_state(self) -> Self: self.center() self.set_height(config["frame_height"]) self.set_width(config["frame_width"]) self.set_euler_angles(0, 0, 0) self.model_matrix = self.default_model_matrix return self def refresh_rotation_matrix(self): # Rotate based on camera orientation theta, phi, gamma = self.euler_angles quat = quaternion_mult( quaternion_from_angle_axis(theta, OUT, axis_normalized=True), quaternion_from_angle_axis(phi, RIGHT, axis_normalized=True), quaternion_from_angle_axis(gamma, OUT, axis_normalized=True), ) self.inverse_rotation_matrix = rotation_matrix_transpose_from_quaternion(quat) def rotate(self, angle, axis=OUT, **kwargs): curr_rot_T = self.inverse_rotation_matrix added_rot_T = rotation_matrix_transpose(angle, axis) new_rot_T = np.dot(curr_rot_T, added_rot_T) Fz = new_rot_T[2] phi = np.arccos(Fz[2]) theta = angle_of_vector(Fz[:2]) + PI / 2 partial_rot_T = np.dot( rotation_matrix_transpose(phi, RIGHT), rotation_matrix_transpose(theta, OUT), ) gamma = angle_of_vector(np.dot(partial_rot_T, new_rot_T.T)[:, 0]) self.set_euler_angles(theta, phi, gamma) return self def set_euler_angles(self, theta=None, phi=None, gamma=None): if theta is not None: self.euler_angles[0] = theta if phi is not None: self.euler_angles[1] = phi if gamma is not None: self.euler_angles[2] = gamma self.refresh_rotation_matrix() return self def set_theta(self, theta: float) -> Self: return self.set_euler_angles(theta=theta) def set_phi(self, phi: float) -> Self: return self.set_euler_angles(phi=phi) def set_gamma(self, gamma: float) -> Self: return self.set_euler_angles(gamma=gamma) def increment_theta(self, dtheta: float) -> Self: self.euler_angles[0] += dtheta self.refresh_rotation_matrix() return self def increment_phi(self, dphi: float) -> Self: phi = self.euler_angles[1] new_phi = clip(phi + dphi, -PI / 2, PI / 2) self.euler_angles[1] = new_phi self.refresh_rotation_matrix() return self def increment_gamma(self, dgamma: float) -> Self: self.euler_angles[2] += dgamma self.refresh_rotation_matrix() return self def get_shape(self): return (self.get_width(), self.get_height()) def get_center(self): # Assumes first point is at the center return self.points[0] def get_width(self) -> float: points = self.points return points[2, 0] - points[1, 0] def get_height(self) -> float: points = self.points return points[4, 1] - points[3, 1] def get_focal_distance(self) -> float: return self.focal_distance * self.get_height() def interpolate(self, *args, **kwargs): super().interpolate(*args, **kwargs) self.refresh_rotation_matrix() class OpenGLRenderer: def __init__( self, file_writer_class: type[SceneFileWriter] = SceneFileWriter, skip_animations: bool = False, ) -> None: # Measured in pixel widths, used for vector graphics self.anti_alias_width = 1.5 self._file_writer_class = file_writer_class self._original_skipping_status = skip_animations self.skip_animations = skip_animations self.animation_start_time = 0 self.animation_elapsed_time = 0 self.time = 0 self.animations_hashes = [] self.num_plays = 0 self.camera = OpenGLCamera() self.pressed_keys = set() self.window = None # Initialize texture
-> None: # Measured in pixel widths, used for vector graphics self.anti_alias_width = 1.5 self._file_writer_class = file_writer_class self._original_skipping_status = skip_animations self.skip_animations = skip_animations self.animation_start_time = 0 self.animation_elapsed_time = 0 self.time = 0 self.animations_hashes = [] self.num_plays = 0 self.camera = OpenGLCamera() self.pressed_keys = set() self.window = None # Initialize texture map. self.path_to_texture_id = {} self.background_color = config["background_color"] def init_scene(self, scene: Scene) -> None: self.partial_movie_files = [] self.file_writer: Any = self._file_writer_class( self, scene.__class__.__name__, ) self.scene = scene self.background_color = config["background_color"] if self.should_create_window(): from .opengl_renderer_window import Window self.window = Window(self) self.context = self.window.ctx self.frame_buffer_object = self.context.detect_framebuffer() else: # self.window = None try: self.context = moderngl.create_context(standalone=True) except Exception: self.context = moderngl.create_context( standalone=True, backend="egl", ) self.frame_buffer_object = self.get_frame_buffer_object(self.context, 0) self.frame_buffer_object.use() self.context.enable(moderngl.BLEND) self.context.wireframe = config["enable_wireframe"] self.context.blend_func = ( moderngl.SRC_ALPHA, moderngl.ONE_MINUS_SRC_ALPHA, moderngl.ONE, moderngl.ONE, ) def should_create_window(self): if config["force_window"]: logger.warning( "'--force_window' is enabled, this is intended for debugging purposes " "and may impact performance if used when outputting files", ) return True return ( config["preview"] and not config["save_last_frame"] and not config["format"] and not config["write_to_movie"] and not config["dry_run"] ) def get_pixel_shape(self): if hasattr(self, "frame_buffer_object"): return self.frame_buffer_object.viewport[2:4] else: return None def refresh_perspective_uniforms(self, camera): pw, ph = self.get_pixel_shape() fw, fh = camera.get_shape() # TODO, this should probably be a mobject uniform, with # the camera taking care of the conversion factor anti_alias_width = self.anti_alias_width / (ph / fh) # Orient light rotation = camera.inverse_rotation_matrix light_pos = camera.light_source.get_location() light_pos = np.dot(rotation, light_pos) self.perspective_uniforms = { "frame_shape": camera.get_shape(), "anti_alias_width": anti_alias_width, "camera_center": tuple(camera.get_center()), "camera_rotation": tuple(np.array(rotation).T.flatten()), "light_source_position": tuple(light_pos), "focal_distance": camera.get_focal_distance(), } def render_mobject(self, mobject): if isinstance(mobject, OpenGLVMobject): if config["use_projection_fill_shaders"]: render_opengl_vectorized_mobject_fill(self, mobject) if config["use_projection_stroke_shaders"]: render_opengl_vectorized_mobject_stroke(self, mobject) shader_wrapper_list = mobject.get_shader_wrapper_list() # Convert ShaderWrappers to Meshes. for shader_wrapper in shader_wrapper_list: shader = Shader(self.context, shader_wrapper.shader_folder) # Set textures. for name, path in shader_wrapper.texture_paths.items(): tid = self.get_texture_id(path) shader.shader_program[name].value = tid # Set uniforms. for name, value in it.chain( shader_wrapper.uniforms.items(), self.perspective_uniforms.items(), ): with contextlib.suppress(KeyError): shader.set_uniform(name, value) try: shader.set_uniform( "u_view_matrix", self.scene.camera.formatted_view_matrix ) shader.set_uniform( "u_projection_matrix", self.scene.camera.projection_matrix, ) except KeyError: pass # Set depth test. if shader_wrapper.depth_test: self.context.enable(moderngl.DEPTH_TEST) else: self.context.disable(moderngl.DEPTH_TEST) # Render. mesh = Mesh( shader, shader_wrapper.vert_data, indices=shader_wrapper.vert_indices, use_depth_test=shader_wrapper.depth_test, primitive=mobject.render_primitive, ) mesh.set_uniforms(self) mesh.render() def get_texture_id(self, path): if repr(path) not in self.path_to_texture_id: tid = len(self.path_to_texture_id) texture = self.context.texture( size=path.size, components=len(path.getbands()), data=path.tobytes(), ) texture.repeat_x = False texture.repeat_y = False texture.filter = (moderngl.NEAREST, moderngl.NEAREST) texture.swizzle = "RRR1" if path.mode == "L" else "RGBA" texture.use(location=tid) self.path_to_texture_id[repr(path)] = tid return self.path_to_texture_id[repr(path)] def update_skipping_status(self) -> None: """This method is used internally to check if the current animation needs to be skipped or not. It also checks if the number of animations that were played correspond to the number of animations that need to be played, and raises an EndSceneEarlyException if they don't correspond. """ # there is always at least one section -> no out of bounds here if self.file_writer.sections[-1].skip_animations: self.skip_animations = True if ( config.from_animation_number > 0 and self.num_plays < config.from_animation_number ): self.skip_animations = True if ( config.upto_animation_number >= 0 and self.num_plays > config.upto_animation_number ): self.skip_animations = True raise EndSceneEarlyException() @handle_caching_play def play( self, scene: Scene, *args: Animation | Mobject | _AnimationBuilder, **kwargs: Any, ) -> None: #
self.file_writer.sections[-1].skip_animations: self.skip_animations = True if ( config.from_animation_number > 0 and self.num_plays < config.from_animation_number ): self.skip_animations = True if ( config.upto_animation_number >= 0 and self.num_plays > config.upto_animation_number ): self.skip_animations = True raise EndSceneEarlyException() @handle_caching_play def play( self, scene: Scene, *args: Animation | Mobject | _AnimationBuilder, **kwargs: Any, ) -> None: # TODO: Handle data locking / unlocking. self.animation_start_time = time.time() self.file_writer.begin_animation(not self.skip_animations) scene.compile_animation_data(*args, **kwargs) scene.begin_animations() if scene.is_current_animation_frozen_frame(): self.update_frame(scene) if not self.skip_animations: self.file_writer.write_frame( self, num_frames=int(config.frame_rate * scene.duration) ) if self.window is not None: self.window.swap_buffers() while time.time() - self.animation_start_time < scene.duration: pass self.animation_elapsed_time = scene.duration else: scene.play_internal() self.file_writer.end_animation(not self.skip_animations) self.time += scene.duration self.num_plays += 1 def clear_screen(self) -> None: self.frame_buffer_object.clear(*self.background_color) self.window.swap_buffers() def render( self, scene: Scene, frame_offset, moving_mobjects: list[Mobject] ) -> None: self.update_frame(scene) if self.skip_animations: return self.file_writer.write_frame(self) if self.window is not None: self.window.swap_buffers() while self.animation_elapsed_time < frame_offset: self.update_frame(scene) self.window.swap_buffers() def update_frame(self, scene): self.frame_buffer_object.clear(*self.background_color) self.refresh_perspective_uniforms(scene.camera) for mobject in scene.mobjects: if not mobject.should_render: continue self.render_mobject(mobject) for obj in scene.meshes: for mesh in obj.get_meshes(): mesh.set_uniforms(self) mesh.render() self.animation_elapsed_time = time.time() - self.animation_start_time def scene_finished(self, scene): # When num_plays is 0, no images have been output, so output a single # image in this case if self.num_plays > 0: self.file_writer.finish() elif self.num_plays == 0 and config.write_to_movie: config.write_to_movie = False if self.should_save_last_frame(): config.save_last_frame = True self.update_frame(scene) self.file_writer.save_image(self.get_image()) def should_save_last_frame(self): if config["save_last_frame"]: return True if self.scene.interactive_mode: return False return self.num_plays == 0 def get_image(self) -> Image.Image: """Returns an image from the current frame. The first argument passed to image represents the mode RGB with the alpha channel A. The data we read is from the currently bound frame buffer. We pass in 'raw' as the name of the decoder, 0 and -1 args are specifically used for the decoder tand represent the stride and orientation. 0 means there is no padding expected between bytes and -1 represents the orientation and means the first line of the image is the bottom line on the screen. Returns ------- PIL.Image The PIL image of the array. """ raw_buffer_data = self.get_raw_frame_buffer_object_data() image = Image.frombytes( "RGBA", self.get_pixel_shape(), raw_buffer_data, "raw", "RGBA", 0, -1, ) return image def save_static_frame_data(self, scene, static_mobjects): pass def get_frame_buffer_object(self, context, samples=0): pixel_width = config["pixel_width"] pixel_height = config["pixel_height"] num_channels = 4 return context.framebuffer( color_attachments=context.texture( (pixel_width, pixel_height), components=num_channels, samples=samples, ), depth_attachment=context.depth_renderbuffer( (pixel_width, pixel_height), samples=samples, ), ) def get_raw_frame_buffer_object_data(self, dtype="f1"): # Copy blocks from the fbo_msaa to the drawn fbo using Blit # pw, ph = self.get_pixel_shape() # gl.glBindFramebuffer(gl.GL_READ_FRAMEBUFFER, self.fbo_msaa.glo) # gl.glBindFramebuffer(gl.GL_DRAW_FRAMEBUFFER, self.fbo.glo) # gl.glBlitFramebuffer( # 0, 0, pw, ph, 0, 0, pw, ph, gl.GL_COLOR_BUFFER_BIT, gl.GL_LINEAR # ) num_channels = 4 ret = self.frame_buffer_object.read( viewport=self.frame_buffer_object.viewport, components=num_channels, dtype=dtype, ) return ret def get_frame(self): # get current pixel values as numpy data in order to test output raw = self.get_raw_frame_buffer_object_data(dtype="f1") pixel_shape = self.get_pixel_shape() result_dimensions = (pixel_shape[1], pixel_shape[0], 4) np_buf = np.frombuffer(raw, dtype="uint8").reshape(result_dimensions) np_buf = np.flipud(np_buf) return np_buf # Returns offset from the bottom left corner in pixels. # top_left flag should be set to True when using a GUI framework # where the (0,0) is at the top left: e.g. PySide6 def pixel_coords_to_space_coords( self, px: float, py:
4) np_buf = np.frombuffer(raw, dtype="uint8").reshape(result_dimensions) np_buf = np.flipud(np_buf) return np_buf # Returns offset from the bottom left corner in pixels. # top_left flag should be set to True when using a GUI framework # where the (0,0) is at the top left: e.g. PySide6 def pixel_coords_to_space_coords( self, px: float, py: float, relative: bool = False, top_left: bool = False ) -> Point3D: pixel_shape = self.get_pixel_shape() if pixel_shape is None: return np.array([0, 0, 0]) pw, ph = pixel_shape fh = config["frame_height"] fc = self.camera.get_center() if relative: return 2 * np.array([px / pw, py / ph, 0]) else: # Only scale wrt one axis scale = fh / ph return fc + scale * np.array( [(px - pw / 2), (-1 if top_left else 1) * (py - ph / 2), 0] ) @property def background_color(self): return self._background_color @background_color.setter def background_color(self, value): self._background_color = color_to_rgba(value, 1.0) ================================================ FILE: manim/renderer/opengl_renderer_window.py ================================================ from __future__ import annotations from typing import TYPE_CHECKING, Any import moderngl_window as mglw from moderngl_window.context.pyglet.window import Window as PygletWindow from moderngl_window.timers.clock import Timer from screeninfo import Monitor, get_monitors from .. import __version__, config if TYPE_CHECKING: from .opengl_renderer import OpenGLRenderer __all__ = ["Window"] class Window(PygletWindow): fullscreen = False resizable = True gl_version = (3, 3) vsync = True cursor = True def __init__( self, renderer: OpenGLRenderer, window_size: str = config.window_size, **kwargs: Any, ) -> None: monitors = get_monitors() mon_index = config.window_monitor monitor = monitors[min(mon_index, len(monitors) - 1)] if window_size == "default": # make window_width half the width of the monitor # but make it full screen if --fullscreen window_width = monitor.width if not config.fullscreen: window_width //= 2 # by default window_height = 9/16 * window_width window_height = int( window_width * config.frame_height // config.frame_width, ) size = (window_width, window_height) elif len(window_size.split(",")) == 2: (window_width, window_height) = tuple(map(int, window_size.split(","))) size = (window_width, window_height) else: raise ValueError( "Window_size must be specified as 'width,height' or 'default'.", ) super().__init__(size=size) self.title = f"Manim Community {__version__}" self.size = size self.renderer = renderer mglw.activate_context(window=self) self.timer = Timer() self.config = mglw.WindowConfig(ctx=self.ctx, wnd=self, timer=self.timer) self.timer.start() self.swap_buffers() initial_position = self.find_initial_position(size, monitor) self.position = initial_position # Delegate event handling to scene. def on_mouse_motion(self, x: int, y: int, dx: int, dy: int) -> None: super().on_mouse_motion(x, y, dx, dy) point = self.renderer.pixel_coords_to_space_coords(x, y) d_point = self.renderer.pixel_coords_to_space_coords(dx, dy, relative=True) self.renderer.scene.on_mouse_motion(point, d_point) def on_mouse_scroll(self, x: int, y: int, x_offset: float, y_offset: float) -> None: super().on_mouse_scroll(x, y, x_offset, y_offset) point = self.renderer.pixel_coords_to_space_coords(x, y) offset = self.renderer.pixel_coords_to_space_coords( x_offset, y_offset, relative=True, ) self.renderer.scene.on_mouse_scroll(point, offset) def on_key_press(self, symbol: int, modifiers: int) -> bool: self.renderer.pressed_keys.add(symbol) event_handled: bool = super().on_key_press(symbol, modifiers) self.renderer.scene.on_key_press(symbol, modifiers) return event_handled def on_key_release(self, symbol: int, modifiers: int) -> None: if symbol in self.renderer.pressed_keys: self.renderer.pressed_keys.remove(symbol) super().on_key_release(symbol, modifiers) self.renderer.scene.on_key_release(symbol, modifiers) def on_mouse_drag( self, x: int, y: int, dx: int, dy: int, buttons: int, modifiers: int ) -> None: super().on_mouse_drag(x, y, dx, dy, buttons, modifiers) point = self.renderer.pixel_coords_to_space_coords(x, y) d_point = self.renderer.pixel_coords_to_space_coords(dx, dy, relative=True) self.renderer.scene.on_mouse_drag(point, d_point, buttons, modifiers) def find_initial_position( self, size: tuple[int, int], monitor: Monitor ) -> tuple[int, int]: custom_position = config.window_position window_width, window_height = size # Position might be specified with a
modifiers: int ) -> None: super().on_mouse_drag(x, y, dx, dy, buttons, modifiers) point = self.renderer.pixel_coords_to_space_coords(x, y) d_point = self.renderer.pixel_coords_to_space_coords(dx, dy, relative=True) self.renderer.scene.on_mouse_drag(point, d_point, buttons, modifiers) def find_initial_position( self, size: tuple[int, int], monitor: Monitor ) -> tuple[int, int]: custom_position = config.window_position window_width, window_height = size # Position might be specified with a string of the form x,y for integers x and y if len(custom_position) == 1: raise ValueError( "window_position must specify both Y and X positions (Y/X -> UR). Also accepts LEFT/RIGHT/ORIGIN/UP/DOWN.", ) # in the form Y/X (UR) if custom_position in ["LEFT", "RIGHT"]: custom_position = "O" + custom_position[0] elif custom_position in ["UP", "DOWN"]: custom_position = custom_position[0] + "O" elif custom_position == "ORIGIN": custom_position = "O" * 2 elif "," in custom_position: pos_y, pos_x = tuple(map(int, custom_position.split(","))) return (pos_x, pos_y) # Alternatively, it might be specified with a string like # UR, OO, DL, etc. specifying what corner it should go to char_to_n = {"L": 0, "U": 0, "O": 1, "R": 2, "D": 2} width_diff: int = monitor.width - window_width height_diff: int = monitor.height - window_height return ( monitor.x + char_to_n[custom_position[1]] * width_diff // 2, -monitor.y + char_to_n[custom_position[0]] * height_diff // 2, ) def on_mouse_press(self, x: int, y: int, button: int, modifiers: int) -> None: super().on_mouse_press(x, y, button, modifiers) point = self.renderer.pixel_coords_to_space_coords(x, y) mouse_button_map = { 1: "LEFT", 2: "MOUSE", 4: "RIGHT", } self.renderer.scene.on_mouse_press(point, mouse_button_map[button], modifiers) ================================================ FILE: manim/renderer/shader.py ================================================ from __future__ import annotations import contextlib import inspect import re import textwrap from collections.abc import Callable, Iterator, Sequence from pathlib import Path from typing import TYPE_CHECKING, Any import moderngl import numpy as np import numpy.typing as npt from typing_extensions import Self, TypeAlias if TYPE_CHECKING: from manim.renderer.opengl_renderer import OpenGLRenderer MeshTimeBasedUpdater: TypeAlias = Callable[["Object3D", float], None] MeshNonTimeBasedUpdater: TypeAlias = Callable[["Object3D"], None] MeshUpdater: TypeAlias = MeshNonTimeBasedUpdater | MeshTimeBasedUpdater from manim.typing import MatrixMN, Point3D from .. import config from ..utils import opengl SHADER_FOLDER = Path(__file__).parent / "shaders" shader_program_cache: dict[str, moderngl.Program] = {} file_path_to_code_map: dict[Path, str] = {} __all__ = [ "Object3D", "Mesh", "Shader", "FullScreenQuad", ] def get_shader_code_from_file(file_path: Path) -> str: if file_path in file_path_to_code_map: return file_path_to_code_map[file_path] source = file_path.read_text() include_lines = re.finditer( r"^#include (?P<include_path>.*\.glsl)$", source, flags=re.MULTILINE, ) for match in include_lines: include_path = match.group("include_path") included_code = get_shader_code_from_file( file_path.parent / include_path, ) source = source.replace(match.group(0), included_code) file_path_to_code_map[file_path] = source return source def filter_attributes( unfiltered_attributes: npt.NDArray, attributes: Sequence[str] ) -> npt.NDArray: # Construct attributes for only those needed by the shader. filtered_attributes_dtype = [] for i, dtype_name in enumerate(unfiltered_attributes.dtype.names): if dtype_name in attributes: filtered_attributes_dtype.append( ( dtype_name, unfiltered_attributes.dtype[i].subdtype[0].str, unfiltered_attributes.dtype[i].shape, ), ) filtered_attributes = np.zeros( unfiltered_attributes[unfiltered_attributes.dtype.names[0]].shape[0], dtype=filtered_attributes_dtype, ) for dtype_name in unfiltered_attributes.dtype.names: if dtype_name in attributes: filtered_attributes[dtype_name] = unfiltered_attributes[dtype_name] return filtered_attributes class Object3D: def __init__(self, *children: Object3D): self.model_matrix = np.eye(4) self.normal_matrix = np.eye(4) self.children: list[Object3D] = [] self.parent: Object3D | None = None self.add(*children) self.init_updaters() # TODO: Use path_func. def interpolate(self, start: Object3D, end: Object3D, alpha: float, _: Any) -> None: self.model_matrix = (1 - alpha) * start.model_matrix + alpha * end.model_matrix self.normal_matrix = ( 1 - alpha ) * start.normal_matrix + alpha * end.normal_matrix def single_copy(self) -> Object3D: copy
None = None self.add(*children) self.init_updaters() # TODO: Use path_func. def interpolate(self, start: Object3D, end: Object3D, alpha: float, _: Any) -> None: self.model_matrix = (1 - alpha) * start.model_matrix + alpha * end.model_matrix self.normal_matrix = ( 1 - alpha ) * start.normal_matrix + alpha * end.normal_matrix def single_copy(self) -> Object3D: copy = Object3D() copy.model_matrix = self.model_matrix.copy() copy.normal_matrix = self.normal_matrix.copy() return copy def copy(self) -> Object3D: node_to_copy = {} bfs = [self] while bfs: node = bfs.pop(0) bfs.extend(node.children) node_copy = node.single_copy() node_to_copy[node] = node_copy # Add the copy to the copy of the parent. if node.parent is not None and node is not self: node_to_copy[node.parent].add(node_copy) return node_to_copy[self] def add(self, *children: Object3D) -> None: for child in children: if child.parent is not None: raise Exception( "Attempt to add child that's already added to another Object3D", ) self.remove(*children, current_children_only=False) self.children.extend(children) for child in children: child.parent = self def remove(self, *children: Object3D, current_children_only: bool = True) -> None: if current_children_only: for child in children: if child.parent != self: raise Exception( "Attempt to remove child that isn't added to this Object3D", ) self.children = list(filter(lambda child: child not in children, self.children)) for child in children: child.parent = None def get_position(self) -> Point3D: return self.model_matrix[:, 3][:3] def set_position(self, position: Point3D) -> Self: self.model_matrix[:, 3][:3] = position return self def get_meshes(self) -> Iterator[Mesh]: dfs = [self] while dfs: parent = dfs.pop() if isinstance(parent, Mesh): yield parent dfs.extend(parent.children) def get_family(self) -> Iterator[Object3D]: dfs = [self] while dfs: parent = dfs.pop() yield parent dfs.extend(parent.children) def align_data_and_family(self, _: Any) -> None: pass def hierarchical_model_matrix(self) -> MatrixMN: if self.parent is None: return self.model_matrix model_matrices = [self.model_matrix] current_object = self while current_object.parent is not None: model_matrices.append(current_object.parent.model_matrix) current_object = current_object.parent return np.linalg.multi_dot(list(reversed(model_matrices))) def hierarchical_normal_matrix(self) -> MatrixMN: if self.parent is None: return self.normal_matrix[:3, :3] normal_matrices = [self.normal_matrix] current_object = self while current_object.parent is not None: normal_matrices.append(current_object.parent.model_matrix) current_object = current_object.parent return np.linalg.multi_dot(list(reversed(normal_matrices)))[:3, :3] def init_updaters(self) -> None: self.time_based_updaters: list[MeshTimeBasedUpdater] = [] self.non_time_updaters: list[MeshNonTimeBasedUpdater] = [] self.has_updaters = False self.updating_suspended = False def update(self, dt: float = 0) -> Self: if not self.has_updaters or self.updating_suspended: return self for time_based_updater in self.time_based_updaters: time_based_updater(self, dt) for non_time_based_updater in self.non_time_updaters: non_time_based_updater(self) return self def get_time_based_updaters(self) -> list[MeshTimeBasedUpdater]: return self.time_based_updaters def has_time_based_updater(self) -> bool: return len(self.time_based_updaters) > 0 def get_updaters(self) -> list[MeshUpdater]: return self.time_based_updaters + self.non_time_updaters def add_updater( self, update_function: MeshUpdater, index: int | None = None, call_updater: bool = True, ) -> Self: if "dt" in inspect.signature(update_function).parameters: self._add_time_based_updater(update_function, index) # type: ignore[arg-type] else: self._add_non_time_updater(update_function, index) # type: ignore[arg-type] self.refresh_has_updater_status() if call_updater: self.update() return self def _add_time_based_updater( self, update_function: MeshTimeBasedUpdater, index: int | None = None ) -> None: if index is None: self.time_based_updaters.append(update_function) else: self.time_based_updaters.insert(index, update_function) def _add_non_time_updater( self, update_function: MeshNonTimeBasedUpdater, index: int | None = None ) -> None: if index is None: self.non_time_updaters.append(update_function) else: self.non_time_updaters.insert(index, update_function) def remove_updater(self, update_function: MeshUpdater) -> Self: while update_function in self.time_based_updaters: self.time_based_updaters.remove(update_function) # type: ignore[arg-type] while update_function in self.non_time_updaters: self.non_time_updaters.remove(update_function) # type: ignore[arg-type] self.refresh_has_updater_status() return self def clear_updaters(self) -> Self: self.time_based_updaters = [] self.non_time_updaters = [] self.refresh_has_updater_status() return self def match_updaters(self, mesh: Object3D)
if index is None: self.non_time_updaters.append(update_function) else: self.non_time_updaters.insert(index, update_function) def remove_updater(self, update_function: MeshUpdater) -> Self: while update_function in self.time_based_updaters: self.time_based_updaters.remove(update_function) # type: ignore[arg-type] while update_function in self.non_time_updaters: self.non_time_updaters.remove(update_function) # type: ignore[arg-type] self.refresh_has_updater_status() return self def clear_updaters(self) -> Self: self.time_based_updaters = [] self.non_time_updaters = [] self.refresh_has_updater_status() return self def match_updaters(self, mesh: Object3D) -> Self: self.clear_updaters() for updater in mesh.get_updaters(): self.add_updater(updater) return self def suspend_updating(self) -> Self: self.updating_suspended = True return self def resume_updating(self, call_updater: bool = True) -> Self: self.updating_suspended = False if call_updater: self.update(dt=0) return self def refresh_has_updater_status(self) -> Self: self.has_updaters = len(self.get_updaters()) > 0 return self class Mesh(Object3D): def __init__( self, shader: Shader | None = None, attributes: npt.NDArray | None = None, geometry: Mesh | None = None, material: Shader | None = None, indices: npt.NDArray | None = None, use_depth_test: bool = True, primitive: int = moderngl.TRIANGLES, ): super().__init__() if shader is not None and attributes is not None: self.shader: Shader = shader self.attributes = attributes self.indices = indices elif geometry is not None and material is not None: self.shader = material self.attributes = geometry.attributes self.indices = geometry.indices else: raise Exception( "Mesh requires either attributes and a Shader or a Geometry and a " "Material", ) self.use_depth_test = use_depth_test self.primitive = primitive self.skip_render: bool = False self.init_updaters() def single_copy(self) -> Mesh: copy = Mesh( attributes=self.attributes.copy(), shader=self.shader, indices=self.indices.copy() if self.indices is not None else None, use_depth_test=self.use_depth_test, primitive=self.primitive, ) copy.skip_render = self.skip_render copy.model_matrix = self.model_matrix.copy() copy.normal_matrix = self.normal_matrix.copy() # TODO: Copy updaters? return copy def set_uniforms(self, renderer: OpenGLRenderer) -> None: self.shader.set_uniform( "u_model_matrix", opengl.matrix_to_shader_input(self.model_matrix), ) self.shader.set_uniform("u_view_matrix", renderer.camera.formatted_view_matrix) self.shader.set_uniform( "u_projection_matrix", renderer.camera.projection_matrix, ) def render(self) -> None: if self.skip_render: return if self.use_depth_test: self.shader.context.enable(moderngl.DEPTH_TEST) else: self.shader.context.disable(moderngl.DEPTH_TEST) shader_attribute_names: list[str] = [] for member_name, member in self.shader.shader_program._members.items(): if isinstance(member, moderngl.Attribute): shader_attribute_names.append(member_name) filtered_shader_attributes = filter_attributes( self.attributes, shader_attribute_names ) vertex_buffer_object = self.shader.context.buffer( filtered_shader_attributes.tobytes() ) if self.indices is None: index_buffer_object = None else: vert_index_data = self.indices.astype("i4").tobytes() if vert_index_data: index_buffer_object = self.shader.context.buffer(vert_index_data) else: index_buffer_object = None vertex_array_object = self.shader.context.simple_vertex_array( self.shader.shader_program, vertex_buffer_object, *filtered_shader_attributes.dtype.names, index_buffer=index_buffer_object, ) vertex_array_object.render(self.primitive) vertex_buffer_object.release() vertex_array_object.release() if index_buffer_object is not None: index_buffer_object.release() class Shader: def __init__( self, context: moderngl.Context, name: str | None = None, source: dict[str, Any] | None = None, ): global shader_program_cache self.context = context self.name = name self.source = source # See if the program is cached. if ( self.name in shader_program_cache and shader_program_cache[self.name].ctx == self.context ): self.shader_program = shader_program_cache[self.name] elif self.source is not None: # Generate the shader from inline code if it was passed. self.shader_program = context.program(**self.source) elif self.name is not None: # Search for a file containing the shader. source_dict = {} source_dict_key = { "vert": "vertex_shader", "frag": "fragment_shader", "geom": "geometry_shader", } shader_folder = SHADER_FOLDER / self.name for shader_file in shader_folder.iterdir(): shader_file_path = shader_folder / shader_file shader_source = get_shader_code_from_file(shader_file_path) source_dict[source_dict_key[shader_file_path.stem]] = shader_source self.shader_program = context.program(**source_dict) else: raise Exception("Must either pass shader name or shader source.") # Cache the shader. if self.name is not None and self.name not in shader_program_cache: shader_program_cache[self.name] = self.shader_program def set_uniform(self, name: str, value: Any) -> None: with contextlib.suppress(KeyError): self.shader_program[name] = value class FullScreenQuad(Mesh): def __init__( self, context: moderngl.Context,
self.shader_program = context.program(**source_dict) else: raise Exception("Must either pass shader name or shader source.") # Cache the shader. if self.name is not None and self.name not in shader_program_cache: shader_program_cache[self.name] = self.shader_program def set_uniform(self, name: str, value: Any) -> None: with contextlib.suppress(KeyError): self.shader_program[name] = value class FullScreenQuad(Mesh): def __init__( self, context: moderngl.Context, fragment_shader_source: str | None = None, fragment_shader_name: str | None = None, ): if fragment_shader_source is None and fragment_shader_name is None: raise Exception("Must either pass shader name or shader source.") if fragment_shader_name is not None: # Use the name. shader_file_path = SHADER_FOLDER / f"{fragment_shader_name}.frag" fragment_shader_source = get_shader_code_from_file(shader_file_path) elif fragment_shader_source is not None: fragment_shader_source = textwrap.dedent(fragment_shader_source.lstrip()) shader = Shader( context, source={ "vertex_shader": """ #version 330 in vec4 in_vert; uniform mat4 u_model_view_matrix; uniform mat4 u_projection_matrix; void main() {{ vec4 camera_space_vertex = u_model_view_matrix * in_vert; vec4 clip_space_vertex = u_projection_matrix * camera_space_vertex; gl_Position = clip_space_vertex; }} """, "fragment_shader": fragment_shader_source, }, ) attributes = np.zeros(6, dtype=[("in_vert", np.float32, (4,))]) attributes["in_vert"] = np.array( [ [-config["frame_x_radius"], -config["frame_y_radius"], 0, 1], [-config["frame_x_radius"], config["frame_y_radius"], 0, 1], [config["frame_x_radius"], config["frame_y_radius"], 0, 1], [-config["frame_x_radius"], -config["frame_y_radius"], 0, 1], [config["frame_x_radius"], -config["frame_y_radius"], 0, 1], [config["frame_x_radius"], config["frame_y_radius"], 0, 1], ], ) shader.set_uniform("u_model_view_matrix", opengl.view_matrix()) shader.set_uniform( "u_projection_matrix", opengl.orthographic_projection_matrix(), ) super().__init__(shader, attributes) def render(self) -> None: super().render() ================================================ FILE: manim/renderer/shader_wrapper.py ================================================ from __future__ import annotations import copy import logging import re from collections.abc import Mapping, Sequence from pathlib import Path from typing import TYPE_CHECKING import moderngl import numpy as np import numpy.typing as npt from typing_extensions import Self, TypeAlias if TYPE_CHECKING: from manim.typing import FloatRGBLike_Array # Mobjects that should be rendered with # the same shader will be organized and # clumped together based on keeping track # of a dict holding all the relevant information # to that shader __all__ = ["ShaderWrapper"] logger = logging.getLogger("manim") def get_shader_dir(): return Path(__file__).parent / "shaders" def find_file(file_name: Path, directories: list[Path]) -> Path: # Check if what was passed in is already a valid path to a file if file_name.exists(): return file_name possible_paths = (directory / file_name for directory in directories) for path in possible_paths: if path.exists(): return path else: logger.debug(f"{path} does not exist.") raise OSError(f"{file_name} not Found") _ShaderDType: TypeAlias = np.void _ShaderData: TypeAlias = npt.NDArray[_ShaderDType] class ShaderWrapper: def __init__( self, vert_data: _ShaderData = None, vert_indices: Sequence[int] | None = None, shader_folder: Path | str | None = None, # A dictionary mapping names of uniform variables uniforms: dict[str, float | tuple[float, ...]] | None = None, # A dictionary mapping names to filepaths for textures. texture_paths: Mapping[str, Path | str] | None = None, depth_test: bool = False, render_primitive: int | str = moderngl.TRIANGLE_STRIP, ): self.vert_data: _ShaderData = vert_data self.vert_indices: Sequence[int] | None = vert_indices self.vert_attributes: tuple[str, ...] | None = vert_data.dtype.names self.shader_folder: Path = Path(shader_folder or "") self.uniforms: dict[str, float | tuple[float, ...]] = uniforms or {} self.texture_paths: Mapping[str, str | Path] = texture_paths or {} self.depth_test: bool = depth_test self.render_primitive: str = str(render_primitive) self.init_program_code() self.refresh_id() def copy(self): result = copy.copy(self) result.vert_data = np.array(self.vert_data) if result.vert_indices is not None: result.vert_indices = np.array(self.vert_indices) if self.uniforms: result.uniforms = dict(self.uniforms) if self.texture_paths: result.texture_paths = dict(self.texture_paths) return
= uniforms or {} self.texture_paths: Mapping[str, str | Path] = texture_paths or {} self.depth_test: bool = depth_test self.render_primitive: str = str(render_primitive) self.init_program_code() self.refresh_id() def copy(self): result = copy.copy(self) result.vert_data = np.array(self.vert_data) if result.vert_indices is not None: result.vert_indices = np.array(self.vert_indices) if self.uniforms: result.uniforms = dict(self.uniforms) if self.texture_paths: result.texture_paths = dict(self.texture_paths) return result def is_valid(self) -> bool: return all( [ self.vert_data is not None, self.program_code["vertex_shader"] is not None, self.program_code["fragment_shader"] is not None, ], ) def get_id(self) -> str: return self.id def get_program_id(self) -> int: return self.program_id def create_id(self): # A unique id for a shader return "|".join( map( str, [ self.program_id, self.uniforms, self.texture_paths, self.depth_test, self.render_primitive, ], ), ) def refresh_id(self) -> None: self.program_id: int = self.create_program_id() self.id: str = self.create_id() def create_program_id(self): return hash( "".join( self.program_code[f"{name}_shader"] or "" for name in ("vertex", "geometry", "fragment") ), ) def init_program_code(self): def get_code(name: str) -> str | None: return get_shader_code_from_file( self.shader_folder / f"{name}.glsl", ) self.program_code: dict[str, str | None] = { "vertex_shader": get_code("vert"), "geometry_shader": get_code("geom"), "fragment_shader": get_code("frag"), } def get_program_code(self): return self.program_code def replace_code(self, old: str, new: str) -> None: code_map = self.program_code for name, _code in code_map.items(): if code_map[name] is None: continue code_map[name] = re.sub(old, new, code_map[name]) self.refresh_id() def combine_with(self, *shader_wrappers: "ShaderWrapper") -> Self: # noqa: UP037 # Assume they are of the same type if len(shader_wrappers) == 0: return self if self.vert_indices is not None: num_verts = len(self.vert_data) indices_list = [self.vert_indices] data_list = [self.vert_data] for sw in shader_wrappers: indices_list.append(sw.vert_indices + num_verts) data_list.append(sw.vert_data) num_verts += len(sw.vert_data) self.vert_indices = np.hstack(indices_list) self.vert_data = np.hstack(data_list) else: self.vert_data = np.hstack( [self.vert_data, *(sw.vert_data for sw in shader_wrappers)], ) return self # For caching filename_to_code_map: dict = {} def get_shader_code_from_file(filename: Path) -> str | None: if filename in filename_to_code_map: return filename_to_code_map[filename] try: filepath = find_file( filename, directories=[get_shader_dir(), Path("/")], ) except OSError: return None result = filepath.read_text() # To share functionality between shaders, some functions are read in # from other files an inserted into the relevant strings before # passing to ctx.program for compiling # Replace "#INSERT " lines with relevant code insertions = re.findall( r"^#include ../include/.*\.glsl$", result, flags=re.MULTILINE, ) for line in insertions: inserted_code = get_shader_code_from_file( Path() / "include" / line.replace("#include ../include/", ""), ) if inserted_code is None: return None result = result.replace(line, inserted_code) filename_to_code_map[filename] = result return result def get_colormap_code(rgb_list: FloatRGBLike_Array) -> str: data = ",".join("vec3({}, {}, {})".format(*rgb) for rgb in rgb_list) return f"vec3[{len(rgb_list)}]({data})" ================================================ FILE: manim/renderer/vectorized_mobject_rendering.py ================================================ from __future__ import annotations from collections import defaultdict from collections.abc import Iterable, Sequence from typing import TYPE_CHECKING import numpy as np if TYPE_CHECKING: from manim.renderer.opengl_renderer import ( OpenGLRenderer, OpenGLVMobject, ) from manim.typing import MatrixMN from ..utils import opengl from ..utils.space_ops import cross2d, earclip_triangulation from .shader import Shader __all__ = [ "render_opengl_vectorized_mobject_fill", "render_opengl_vectorized_mobject_stroke", ] def build_matrix_lists( mob: OpenGLVMobject, ) -> defaultdict[tuple[float, ...], list[OpenGLVMobject]]: root_hierarchical_matrix = mob.hierarchical_model_matrix() matrix_to_mobject_list = defaultdict(list) if mob.has_points(): matrix_to_mobject_list[tuple(root_hierarchical_matrix.ravel())].append(mob) mobject_to_hierarchical_matrix = {mob: root_hierarchical_matrix} dfs = [mob] while dfs: parent = dfs.pop() for child in parent.submobjects: child_hierarchical_matrix = ( mobject_to_hierarchical_matrix[parent] @ child.model_matrix ) mobject_to_hierarchical_matrix[child] = child_hierarchical_matrix if child.has_points(): matrix_to_mobject_list[tuple(child_hierarchical_matrix.ravel())].append( child, ) dfs.append(child) return matrix_to_mobject_list def render_opengl_vectorized_mobject_fill( renderer: OpenGLRenderer, mobject:
...], list[OpenGLVMobject]]: root_hierarchical_matrix = mob.hierarchical_model_matrix() matrix_to_mobject_list = defaultdict(list) if mob.has_points(): matrix_to_mobject_list[tuple(root_hierarchical_matrix.ravel())].append(mob) mobject_to_hierarchical_matrix = {mob: root_hierarchical_matrix} dfs = [mob] while dfs: parent = dfs.pop() for child in parent.submobjects: child_hierarchical_matrix = ( mobject_to_hierarchical_matrix[parent] @ child.model_matrix ) mobject_to_hierarchical_matrix[child] = child_hierarchical_matrix if child.has_points(): matrix_to_mobject_list[tuple(child_hierarchical_matrix.ravel())].append( child, ) dfs.append(child) return matrix_to_mobject_list def render_opengl_vectorized_mobject_fill( renderer: OpenGLRenderer, mobject: OpenGLVMobject ) -> None: matrix_to_mobject_list = build_matrix_lists(mobject) for matrix_tuple, mobject_list in matrix_to_mobject_list.items(): model_matrix = np.array(matrix_tuple).reshape((4, 4)) render_mobject_fills_with_matrix(renderer, model_matrix, mobject_list) def render_mobject_fills_with_matrix( renderer: OpenGLRenderer, model_matrix: MatrixMN, mobjects: Iterable[OpenGLVMobject], ) -> None: # Precompute the total number of vertices for which to reserve space. # Note that triangulate_mobject() will cache its results. total_size = 0 for submob in mobjects: total_size += triangulate_mobject(submob).shape[0] attributes = np.empty( total_size, dtype=[ ("in_vert", np.float32, (3,)), ("in_color", np.float32, (4,)), ("texture_coords", np.float32, (2,)), ("texture_mode", np.int32), ], ) write_offset = 0 for submob in mobjects: if not submob.has_points(): continue mobject_triangulation = triangulate_mobject(submob) end_offset = write_offset + mobject_triangulation.shape[0] attributes[write_offset:end_offset] = mobject_triangulation attributes["in_color"][write_offset:end_offset] = np.repeat( submob.fill_rgba, mobject_triangulation.shape[0], axis=0, ) write_offset = end_offset fill_shader = Shader(renderer.context, name="vectorized_mobject_fill") fill_shader.set_uniform( "u_model_view_matrix", opengl.matrix_to_shader_input( renderer.camera.unformatted_view_matrix @ model_matrix, ), ) fill_shader.set_uniform( "u_projection_matrix", renderer.camera.projection_matrix, ) vbo = renderer.context.buffer(attributes.tobytes()) vao = renderer.context.simple_vertex_array( fill_shader.shader_program, vbo, *attributes.dtype.names, ) vao.render() vao.release() vbo.release() def triangulate_mobject(mob: OpenGLVMobject) -> np.ndarray: if not mob.needs_new_triangulation: return mob.triangulation # Figure out how to triangulate the interior to know # how to send the points as to the vertex shader. # First triangles come directly from the points # normal_vector = mob.get_unit_normal() points = mob.points b0s = points[0::3] b1s = points[1::3] b2s = points[2::3] v01s = b1s - b0s v12s = b2s - b1s crosses = cross2d(v01s, v12s) convexities = np.sign(crosses) if mob.orientation == 1: concave_parts = convexities > 0 convex_parts = convexities <= 0 else: concave_parts = convexities < 0 convex_parts = convexities >= 0 # These are the vertices to which we'll apply a polygon triangulation atol = mob.tolerance_for_point_equality end_of_loop = np.zeros(len(b0s), dtype=bool) end_of_loop[:-1] = (np.abs(b2s[:-1] - b0s[1:]) > atol).any(1) end_of_loop[-1] = True indices = np.arange(len(points), dtype=int) inner_vert_indices = np.hstack( [ indices[0::3], indices[1::3][concave_parts], indices[2::3][end_of_loop], ], ) inner_vert_indices.sort() rings = np.arange(1, len(inner_vert_indices) + 1)[inner_vert_indices % 3 == 2] # Triangulate inner_verts = points[inner_vert_indices] inner_tri_indices = inner_vert_indices[earclip_triangulation(inner_verts, rings)] bezier_triangle_indices = np.reshape(indices, (-1, 3)) concave_triangle_indices = np.reshape(bezier_triangle_indices[concave_parts], (-1)) convex_triangle_indices = np.reshape(bezier_triangle_indices[convex_parts], (-1)) points = points[ np.hstack( [ concave_triangle_indices, convex_triangle_indices, inner_tri_indices, ], ) ] texture_coords = np.tile( [ [0.0, 0.0], [0.5, 0.0], [1.0, 1.0], ], (points.shape[0] // 3, 1), ) texture_mode = np.hstack( ( np.ones(concave_triangle_indices.shape[0]), -1 * np.ones(convex_triangle_indices.shape[0]), np.zeros(inner_tri_indices.shape[0]), ), ) attributes = np.zeros( points.shape[0], dtype=[ ("in_vert", np.float32, (3,)), ("in_color", np.float32, (4,)), ("texture_coords", np.float32, (2,)), ("texture_mode", np.int32), ], ) attributes["in_vert"] = points attributes["texture_coords"] = texture_coords attributes["texture_mode"] = texture_mode mob.triangulation = attributes mob.needs_new_triangulation = False return attributes def render_opengl_vectorized_mobject_stroke( renderer: OpenGLRenderer, mobject: OpenGLVMobject ) -> None: matrix_to_mobject_list = build_matrix_lists(mobject) for matrix_tuple, mobject_list in matrix_to_mobject_list.items(): model_matrix = np.array(matrix_tuple).reshape((4, 4)) render_mobject_strokes_with_matrix(renderer, model_matrix, mobject_list) def render_mobject_strokes_with_matrix( renderer: OpenGLRenderer, model_matrix: MatrixMN, mobjects: Sequence[OpenGLVMobject], ) -> None: # Precompute the total number of vertices for which to reserve space. total_size = 0 for submob in mobjects: total_size += submob.points.shape[0] points = np.empty((total_size, 3)) colors = np.empty((total_size, 4)) widths
matrix_to_mobject_list.items(): model_matrix = np.array(matrix_tuple).reshape((4, 4)) render_mobject_strokes_with_matrix(renderer, model_matrix, mobject_list) def render_mobject_strokes_with_matrix( renderer: OpenGLRenderer, model_matrix: MatrixMN, mobjects: Sequence[OpenGLVMobject], ) -> None: # Precompute the total number of vertices for which to reserve space. total_size = 0 for submob in mobjects: total_size += submob.points.shape[0] points = np.empty((total_size, 3)) colors = np.empty((total_size, 4)) widths = np.empty(total_size) write_offset = 0 for submob in mobjects: if not submob.has_points(): continue end_offset = write_offset + submob.points.shape[0] points[write_offset:end_offset] = submob.points if submob.stroke_rgba.shape[0] == points[write_offset:end_offset].shape[0]: colors[write_offset:end_offset] = submob.stroke_rgba else: colors[write_offset:end_offset] = np.repeat( submob.stroke_rgba, submob.points.shape[0], axis=0, ) widths[write_offset:end_offset] = np.repeat( submob.stroke_width, submob.points.shape[0], ) write_offset = end_offset stroke_data = np.zeros( len(points), dtype=[ # ("previous_curve", np.float32, (3, 3)), ("current_curve", np.float32, (3, 3)), # ("next_curve", np.float32, (3, 3)), ("tile_coordinate", np.float32, (2,)), ("in_color", np.float32, (4,)), ("in_width", np.float32), ], ) stroke_data["in_color"] = colors stroke_data["in_width"] = widths curves = np.reshape(points, (-1, 3, 3)) # stroke_data["previous_curve"] = np.repeat(np.roll(curves, 1, axis=0), 3, axis=0) stroke_data["current_curve"] = np.repeat(curves, 3, axis=0) # stroke_data["next_curve"] = np.repeat(np.roll(curves, -1, axis=0), 3, axis=0) # Repeat each vertex in order to make a tile. stroke_data = np.tile(stroke_data, 2) stroke_data["tile_coordinate"] = np.vstack( ( np.tile( [ [0.0, 0.0], [0.0, 1.0], [1.0, 1.0], ], (len(points) // 3, 1), ), np.tile( [ [0.0, 0.0], [1.0, 0.0], [1.0, 1.0], ], (len(points) // 3, 1), ), ), ) shader = Shader(renderer.context, "vectorized_mobject_stroke") shader.set_uniform( "u_model_view_matrix", opengl.matrix_to_shader_input( renderer.camera.unformatted_view_matrix @ model_matrix, ), ) shader.set_uniform("u_projection_matrix", renderer.camera.projection_matrix) shader.set_uniform("manim_unit_normal", tuple(-mobjects[0].unit_normal[0])) vbo = renderer.context.buffer(stroke_data.tobytes()) vao = renderer.context.simple_vertex_array( shader.shader_program, vbo, *stroke_data.dtype.names ) renderer.frame_buffer_object.use() vao.render() vao.release() vbo.release() ================================================ FILE: manim/renderer/shaders/design.frag ================================================ #version 330 out vec4 frag_color; void main() { vec2 st = gl_FragCoord.xy / vec2(854, 360); vec3 color = vec3(0.0); st *= 3.0; st = fract(st); color = vec3(st, 0.0); frag_color = vec4(color, 1.0); } ================================================ FILE: manim/renderer/shaders/design_2.frag ================================================ #version 330 uniform vec2 u_resolution; out vec4 frag_color; #define PI 3.14159265358979323846 vec2 rotate2D(vec2 _st, float _angle){ _st -= 0.5; _st = mat2(cos(_angle),-sin(_angle), sin(_angle),cos(_angle)) * _st; _st += 0.5; return _st; } vec2 tile(vec2 _st, float _zoom){ _st *= _zoom; return fract(_st); } float box(vec2 _st, vec2 _size, float _smoothEdges){ _size = vec2(0.5)-_size*0.5; vec2 aa = vec2(_smoothEdges*0.5); vec2 uv = smoothstep(_size,_size+aa,_st); uv *= smoothstep(_size,_size+aa,vec2(1.0)-_st); return uv.x*uv.y; } void main(void){ vec2 st = gl_FragCoord.xy/u_resolution.xy; vec3 color = vec3(0.0); // Divide the space in 4 st = tile(st,4.); // Use a matrix to rotate the space 45 degrees st = rotate2D(st,PI*0.25); // Draw a square color = vec3(box(st,vec2(0.7),0.01)); // color = vec3(st,0.0); frag_color = vec4(color,1.0); } ================================================ FILE: manim/renderer/shaders/design_3.frag ================================================ #version 330 uniform vec3 u_resolution; uniform float u_time; out vec4 frag_color; vec3 palette(float d){ return mix(vec3(0.2,0.7,0.9),vec3(1.,0.,1.),d); } vec2 rotate(vec2 p,float a){ float c = cos(a); float s = sin(a); return p*mat2(c,s,-s,c); } float map(vec3 p){ for( int i = 0; i<8; ++i){ float t = u_time*0.1; p.xz =rotate(p.xz,t); p.xy =rotate(p.xy,t*1.89); p.xz = abs(p.xz); p.xz-=.5; } return dot(sign(p),p)/5.; } vec4 rm (vec3 ro, vec3 rd){ float t = 0.; vec3 col = vec3(0.); float d; for(float i =0.; i<64.; i++){ vec3 p = ro + rd*t; d = map(p)*.5; if(d<0.02){ break; } if(d>100.){ break; } //col+=vec3(0.6,0.8,0.8)/(400.*(d)); col+=palette(length(p)*.1)/(400.*(d)); t+=d; } return vec4(col,1./(d*100.)); } void main(void){ vec2 uv =
dot(sign(p),p)/5.; } vec4 rm (vec3 ro, vec3 rd){ float t = 0.; vec3 col = vec3(0.); float d; for(float i =0.; i<64.; i++){ vec3 p = ro + rd*t; d = map(p)*.5; if(d<0.02){ break; } if(d>100.){ break; } //col+=vec3(0.6,0.8,0.8)/(400.*(d)); col+=palette(length(p)*.1)/(400.*(d)); t+=d; } return vec4(col,1./(d*100.)); } void main(void){ vec2 uv = (gl_FragCoord.xy-(u_resolution.xy/2.))/u_resolution.x; vec3 ro = vec3(0.,0.,-50.); ro.xz = rotate(ro.xz,u_time); vec3 cf = normalize(-ro); vec3 cs = normalize(cross(cf,vec3(0.,1.,0.))); vec3 cu = normalize(cross(cf,cs)); vec3 uuv = ro+cf*3. + uv.x*cs + uv.y*cu; vec3 rd = normalize(uuv-ro); vec4 col = rm(ro,rd); frag_color = vec4(col.xyz, 1); } ================================================ FILE: manim/renderer/shaders/simple_vert.glsl ================================================ #version 330 #include ../include/camera_uniform_declarations.glsl in vec3 point; // Analog of import for manim only #include ../include/get_gl_Position.glsl #include ../include/position_point_into_frame.glsl void main(){ gl_Position = get_gl_Position(position_point_into_frame(point)); } ================================================ FILE: manim/renderer/shaders/default/frag.glsl ================================================ #version 330 uniform vec4 u_color; out vec4 frag_color; void main() { frag_color = u_color; } ================================================ FILE: manim/renderer/shaders/default/vert.glsl ================================================ #version 330 in vec3 in_vert; uniform mat4 u_model_matrix; uniform mat4 u_view_matrix; uniform mat4 u_projection_matrix; void main() { gl_Position = u_projection_matrix * u_view_matrix * u_model_matrix * vec4(in_vert, 1.0); } ================================================ FILE: manim/renderer/shaders/image/frag.glsl ================================================ #version 330 uniform sampler2D Texture; in vec2 v_im_coords; in float v_opacity; out vec4 frag_color; void main() { frag_color = texture(Texture, v_im_coords); frag_color.a = v_opacity; } ================================================ FILE: manim/renderer/shaders/image/vert.glsl ================================================ #version 330 #include ../include/camera_uniform_declarations.glsl uniform sampler2D Texture; in vec3 point; in vec2 im_coords; in float opacity; out vec2 v_im_coords; out float v_opacity; // Analog of import for manim only #include ../include/get_gl_Position.glsl #include ../include/position_point_into_frame.glsl void main(){ v_im_coords = im_coords; v_opacity = opacity; gl_Position = get_gl_Position(position_point_into_frame(point)); } ================================================ FILE: manim/renderer/shaders/include/add_light.glsl ================================================ ///// INSERT COLOR_MAP FUNCTION HERE ///// vec4 add_light(vec4 color, vec3 point, vec3 unit_normal, vec3 light_coords, float gloss, float shadow){ ///// INSERT COLOR FUNCTION HERE ///// // The line above may be replaced by arbitrary code snippets, as per // the method Mobject.set_color_by_code if(gloss == 0.0 && shadow == 0.0) return color; // TODO, do we actually want this? It effectively treats surfaces as two-sided if(unit_normal.z < 0){ unit_normal *= -1; } // TODO, read this in as a uniform? float camera_distance = 6; // Assume everything has already been rotated such that camera is in the z-direction vec3 to_camera = vec3(0, 0, camera_distance) - point; vec3 to_light = light_coords - point; vec3 light_reflection = -to_light + 2 * unit_normal * dot(to_light, unit_normal); float dot_prod = dot(normalize(light_reflection), normalize(to_camera)); float shine = gloss * exp(-3 * pow(1 - dot_prod, 2)); float dp2 = dot(normalize(to_light), unit_normal); float darkening = mix(1, max(dp2, 0), shadow); return vec4( darkening * mix(color.rgb, vec3(1.0), shine), color.a ); } vec4 finalize_color(vec4 color, vec3 point, vec3 unit_normal, vec3 light_coords, float gloss, float shadow){ // Put insertion here instead return add_light(color, point, unit_normal, light_coords, gloss, shadow); } ================================================ FILE: manim/renderer/shaders/include/camera_uniform_declarations.glsl ================================================ uniform vec2 frame_shape; uniform float anti_alias_width; uniform vec3 camera_center; uniform mat3 camera_rotation; uniform float is_fixed_in_frame; uniform float is_fixed_orientation; uniform vec3 fixed_orientation_center; uniform float focal_distance; ================================================ FILE: manim/renderer/shaders/include/finalize_color.glsl ================================================ vec3 float_to_color(float value, float min_val, float max_val, vec3[9] colormap_data){ float alpha = clamp((value - min_val) / (max_val - min_val), 0.0, 1.0); int disc_alpha = min(int(alpha * 8), 7); return mix(
camera_center; uniform mat3 camera_rotation; uniform float is_fixed_in_frame; uniform float is_fixed_orientation; uniform vec3 fixed_orientation_center; uniform float focal_distance; ================================================ FILE: manim/renderer/shaders/include/finalize_color.glsl ================================================ vec3 float_to_color(float value, float min_val, float max_val, vec3[9] colormap_data){ float alpha = clamp((value - min_val) / (max_val - min_val), 0.0, 1.0); int disc_alpha = min(int(alpha * 8), 7); return mix( colormap_data[disc_alpha], colormap_data[disc_alpha + 1], 8.0 * alpha - disc_alpha ); } vec4 add_light(vec4 color, vec3 point, vec3 unit_normal, vec3 light_coords, float gloss, float shadow){ if(gloss == 0.0 && shadow == 0.0) return color; // TODO, do we actually want this? It effectively treats surfaces as two-sided if(unit_normal.z < 0){ unit_normal *= -1; } // TODO, read this in as a uniform? float camera_distance = 6; // Assume everything has already been rotated such that camera is in the z-direction vec3 to_camera = vec3(0, 0, camera_distance) - point; vec3 to_light = light_coords - point; vec3 light_reflection = -to_light + 2 * unit_normal * dot(to_light, unit_normal); float dot_prod = dot(normalize(light_reflection), normalize(to_camera)); float shine = gloss * exp(-3 * pow(1 - dot_prod, 2)); float dp2 = dot(normalize(to_light), unit_normal); float darkening = mix(1, max(dp2, 0), shadow); return vec4( darkening * mix(color.rgb, vec3(1.0), shine), color.a ); } vec4 finalize_color(vec4 color, vec3 point, vec3 unit_normal, vec3 light_coords, float gloss, float shadow){ ///// INSERT COLOR FUNCTION HERE ///// // The line above may be replaced by arbitrary code snippets, as per // the method Mobject.set_color_by_code return add_light(color, point, unit_normal, light_coords, gloss, shadow); } ================================================ FILE: manim/renderer/shaders/include/get_gl_Position.glsl ================================================ // Assumes the following uniforms exist in the surrounding context: // uniform vec2 frame_shape; // uniform float focal_distance; // uniform float is_fixed_in_frame; // uniform float is_fixed_orientation; // uniform vec3 fixed_orientation_center; const vec2 DEFAULT_FRAME_SHAPE = vec2(8.0 * 16.0 / 9.0, 8.0); float perspective_scale_factor(float z, float focal_distance){ return max(0.0, focal_distance / (focal_distance - z)); } vec4 get_gl_Position(vec3 point){ vec4 result = vec4(point, 1.0); if(!bool(is_fixed_in_frame)){ result.x *= 2.0 / frame_shape.x; result.y *= 2.0 / frame_shape.y; float psf = perspective_scale_factor(result.z, focal_distance); if (psf > 0){ result.xy *= psf; // TODO, what's the better way to do this? // This is to keep vertices too far out of frame from getting cut. result.z *= 0.01; } } else{ if (!bool(is_fixed_orientation)){ result.x *= 2.0 / DEFAULT_FRAME_SHAPE.x; result.y *= 2.0 / DEFAULT_FRAME_SHAPE.y; } else{ result.x *= 2.0 / frame_shape.x; result.y *= 2.0 / frame_shape.y; } } result.z *= -1; return result; } ================================================ FILE: manim/renderer/shaders/include/get_rotated_surface_unit_normal_vector.glsl ================================================ // Assumes the following uniforms exist in the surrounding context: // uniform vec3 camera_center; // uniform mat3 camera_rotation; vec3 get_rotated_surface_unit_normal_vector(vec3 point, vec3 du_point, vec3 dv_point){ vec3 cp = cross( (du_point - point), (dv_point - point) ); if(length(cp) == 0){ // Instead choose a normal to just dv_point - point in the direction of point vec3 v2 = dv_point - point; cp = cross(cross(v2, point), v2); } return normalize(rotate_point_into_frame(cp)); } ================================================ FILE: manim/renderer/shaders/include/get_unit_normal.glsl ================================================ vec3 get_unit_normal(in vec3[3] points){ float tol = 1e-6; vec3 v1 = normalize(points[1] - points[0]); vec3 v2 = normalize(points[2] - points[0]); vec3 cp = cross(v1, v2); float cp_norm = length(cp); if(cp_norm < tol){ // Three points form a line,
= cross(cross(v2, point), v2); } return normalize(rotate_point_into_frame(cp)); } ================================================ FILE: manim/renderer/shaders/include/get_unit_normal.glsl ================================================ vec3 get_unit_normal(in vec3[3] points){ float tol = 1e-6; vec3 v1 = normalize(points[1] - points[0]); vec3 v2 = normalize(points[2] - points[0]); vec3 cp = cross(v1, v2); float cp_norm = length(cp); if(cp_norm < tol){ // Three points form a line, so find a normal vector // to that line in the plane shared with the z-axis vec3 k_hat = vec3(0.0, 0.0, 1.0); vec3 new_cp = cross(cross(v2, k_hat), v2); float new_cp_norm = length(new_cp); if(new_cp_norm < tol){ // We only come here if all three points line up // on the z-axis. return vec3(0.0, -1.0, 0.0); // return k_hat; } return new_cp / new_cp_norm; } return cp / cp_norm; } ================================================ FILE: manim/renderer/shaders/include/NOTE.md ================================================ There seems to be no analog to #include in C++ for OpenGL shaders. While there are other options for sharing code between shaders, a lot of them aren't great, especially if the goal is to have all the logic for which specific bits of code to share handled in the shader file itself. So the way manim currently works is to replace any line which looks like #INSERT <file_name> with the code from one of the files in this folder. The functions in this file often include reference to uniforms which are assumed to be part of the surrounding context into which they are inserted. ================================================ FILE: manim/renderer/shaders/include/position_point_into_frame.glsl ================================================ // Assumes the following uniforms exist in the surrounding context: // uniform float is_fixed_in_frame; // uniform float is_fixed_orientation; // uniform vec3 fixed_orientation_center; // uniform vec3 camera_center; // uniform mat3 camera_rotation; vec3 rotate_point_into_frame(vec3 point){ if(bool(is_fixed_in_frame)){ return point; } return camera_rotation * point; } vec3 position_point_into_frame(vec3 point){ if(bool(is_fixed_in_frame)){ return point; } if(bool(is_fixed_orientation)){ vec3 new_center = rotate_point_into_frame(fixed_orientation_center); return point + (new_center - fixed_orientation_center); } return rotate_point_into_frame(point - camera_center); } ================================================ FILE: manim/renderer/shaders/include/quadratic_bezier_distance.glsl ================================================ // Must be inserted in a context with a definition for modify_distance_for_endpoints // All of this is with respect to a curve that's been rotated/scaled // so that b0 = (0, 0) and b1 = (1, 0). That is, b2 entirely // determines the shape of the curve vec2 bezier(float t, vec2 b2){ // Quick returns for the 0 and 1 cases if (t == 0) return vec2(0, 0); else if (t == 1) return b2; // Everything else return vec2( 2 * t * (1 - t) + b2.x * t*t, b2.y * t * t ); } float cube_root(float x){ return sign(x) * pow(abs(x), 1.0 / 3.0); } int cubic_solve(float a, float b, float c, float d, out float roots[3]){ // Normalize so a = 1 b = b / a; c = c / a; d = d / a; float p = c - b*b / 3.0; float q = b * (2.0*b*b - 9.0*c) / 27.0 + d; float p3 = p*p*p; float disc = q*q + 4.0*p3 / 27.0; float offset = -b / 3.0; if(disc >= 0.0){ float z = sqrt(disc); float u = (-q + z) / 2.0; float v =
/ 3.0; float q = b * (2.0*b*b - 9.0*c) / 27.0 + d; float p3 = p*p*p; float disc = q*q + 4.0*p3 / 27.0; float offset = -b / 3.0; if(disc >= 0.0){ float z = sqrt(disc); float u = (-q + z) / 2.0; float v = (-q - z) / 2.0; u = cube_root(u); v = cube_root(v); roots[0] = offset + u + v; return 1; } float u = sqrt(-p / 3.0); float v = acos(-sqrt( -27.0 / p3) * q / 2.0) / 3.0; float m = cos(v); float n = sin(v) * 1.732050808; float all_roots[3] = float[3]( offset + u * (n - m), offset - u * (n + m), offset + u * (m + m) ); // Only accept roots with a positive derivative int n_valid_roots = 0; for(int i = 0; i < 3; i++){ float r = all_roots[i]; if(3*r*r + 2*b*r + c > 0){ roots[n_valid_roots] = r; n_valid_roots++; } } return n_valid_roots; } float dist_to_line(vec2 p, vec2 b2){ float t = clamp(p.x / b2.x, 0, 1); float dist; if(t == 0) dist = length(p); else if(t == 1) dist = distance(p, b2); else dist = abs(p.y); return modify_distance_for_endpoints(p, dist, t); } float dist_to_point_on_curve(vec2 p, float t, vec2 b2){ t = clamp(t, 0, 1); return modify_distance_for_endpoints( p, length(p - bezier(t, b2)), t ); } float min_dist_to_curve(vec2 p, vec2 b2, float degree){ // Check if curve is really a a line if(degree == 1) return dist_to_line(p, b2); // Try finding the exact sdf by solving the equation // (d/dt) dist^2(t) = 0, which amount to the following // cubic. float xm2 = uv_b2.x - 2.0; float y = uv_b2.y; float a = xm2*xm2 + y*y; float b = 3 * xm2; float c = -(p.x*xm2 + p.y*y) + 2; float d = -p.x; float roots[3]; int n = cubic_solve(a, b, c, d, roots); // At most 2 roots will have been populated. float d0 = dist_to_point_on_curve(p, roots[0], b2); if(n == 1) return d0; float d1 = dist_to_point_on_curve(p, roots[1], b2); return min(d0, d1); } ================================================ FILE: manim/renderer/shaders/include/quadratic_bezier_geometry_functions.glsl ================================================ float cross2d(vec2 v, vec2 w){ return v.x * w.y - w.x * v.y; } mat3 get_xy_to_uv(vec2 b0, vec2 b1){ mat3 shift = mat3( 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, -b0.x, -b0.y, 1.0 ); float sf = length(b1 - b0); vec2 I = (b1 - b0) / sf; vec2 J = vec2(-I.y, I.x); mat3 rotate = mat3( I.x, J.x, 0.0, I.y, J.y, 0.0, 0.0, 0.0, 1.0 ); return (1 / sf) * rotate * shift; } // Orthogonal matrix to convert to a uv space defined so that // b0 goes to [0, 0] and b1 goes to [1, 0] mat4 get_xyz_to_uv(vec3 b0, vec3 b1, vec3 unit_normal){ mat4 shift = mat4( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, -b0.x, -b0.y, -b0.z, 1 ); float scale_factor = length(b1 - b0); vec3 I = (b1 - b0) / scale_factor; vec3 K = unit_normal; vec3 J = cross(K, I); // Transpose
vec3 b1, vec3 unit_normal){ mat4 shift = mat4( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, -b0.x, -b0.y, -b0.z, 1 ); float scale_factor = length(b1 - b0); vec3 I = (b1 - b0) / scale_factor; vec3 K = unit_normal; vec3 J = cross(K, I); // Transpose (hence inverse) of matrix taking // i-hat to I, k-hat to unit_normal, and j-hat to their cross mat4 rotate = mat4( I.x, J.x, K.x, 0.0, I.y, J.y, K.y, 0.0, I.z, J.z, K.z, 0.0, 0.0, 0.0, 0.0, 1.0 ); return (1 / scale_factor) * rotate * shift; } // Returns 0 for null curve, 1 for linear, 2 for quadratic. // Populates new_points with bezier control points for the curve, // which for quadratics will be the same, but for linear and null // might change. The idea is to inform the caller of the degree, // while also passing tangency information in the linear case. // float get_reduced_control_points(vec3 b0, vec3 b1, vec3 b2, out vec3 new_points[3]){ float get_reduced_control_points(in vec3 points[3], out vec3 new_points[3]){ float length_threshold = 1e-6; float angle_threshold = 5e-2; vec3 p0 = points[0]; vec3 p1 = points[1]; vec3 p2 = points[2]; vec3 v01 = (p1 - p0); vec3 v12 = (p2 - p1); float dot_prod = clamp(dot(normalize(v01), normalize(v12)), -1, 1); bool aligned = acos(dot_prod) < angle_threshold; bool distinct_01 = length(v01) > length_threshold; // v01 is considered nonzero bool distinct_12 = length(v12) > length_threshold; // v12 is considered nonzero int n_uniques = int(distinct_01) + int(distinct_12); bool quadratic = (n_uniques == 2) && !aligned; bool linear = (n_uniques == 1) || ((n_uniques == 2) && aligned); bool constant = (n_uniques == 0); if(quadratic){ new_points[0] = p0; new_points[1] = p1; new_points[2] = p2; return 2.0; }else if(linear){ new_points[0] = p0; new_points[1] = (p0 + p2) / 2.0; new_points[2] = p2; return 1.0; }else{ new_points[0] = p0; new_points[1] = p0; new_points[2] = p0; return 0.0; } } ================================================ FILE: manim/renderer/shaders/manim_coords/frag.glsl ================================================ #version 330 uniform vec4 u_color; out vec4 frag_color; void main() { frag_color = u_color; } ================================================ FILE: manim/renderer/shaders/manim_coords/vert.glsl ================================================ #version 330 in vec4 in_vert; uniform mat4 u_model_view_matrix; uniform mat4 u_projection_matrix; void main() { vec4 camera_space_vertex = u_model_view_matrix * in_vert; vec4 clip_space_vertex = u_projection_matrix * camera_space_vertex; gl_Position = clip_space_vertex; } ================================================ FILE: manim/renderer/shaders/quadratic_bezier_fill/frag.glsl ================================================ #version 330 #include ../include/camera_uniform_declarations.glsl in vec4 color; in float fill_all; // Either 0 or 1e in float uv_anti_alias_width; in vec3 xyz_coords; in float orientation; in vec2 uv_coords; in vec2 uv_b2; in float bezier_degree; out vec4 frag_color; // Needed for quadratic_bezier_distance insertion below float modify_distance_for_endpoints(vec2 p, float dist, float t){ return dist; } #include ../include/quadratic_bezier_distance.glsl float sdf(){ if(bezier_degree < 2){ return abs(uv_coords[1]); } float u2 = uv_b2.x; float v2 = uv_b2.y; // For really flat curves, just take the distance to x-axis if(abs(v2 / u2) < 0.1 * uv_anti_alias_width){ return abs(uv_coords[1]); } // For flat-ish curves, take the curve else if(abs(v2 / u2) < 0.5 * uv_anti_alias_width){ return min_dist_to_curve(uv_coords, uv_b2, bezier_degree); } // I know, I don't love this amount of arbitrary-seeming branching either, // but a number of
distance to x-axis if(abs(v2 / u2) < 0.1 * uv_anti_alias_width){ return abs(uv_coords[1]); } // For flat-ish curves, take the curve else if(abs(v2 / u2) < 0.5 * uv_anti_alias_width){ return min_dist_to_curve(uv_coords, uv_b2, bezier_degree); } // I know, I don't love this amount of arbitrary-seeming branching either, // but a number of strange dimples and bugs pop up otherwise. // This converts uv_coords to yet another space where the bezier points sit on // (0, 0), (1/2, 0) and (1, 1), so that the curve can be expressed implicityly // as y = x^2. mat2 to_simple_space = mat2( v2, 0, 2 - u2, 4 * v2 ); vec2 p = to_simple_space * uv_coords; // Sign takes care of whether we should be filling the inside or outside of curve. float sgn = orientation * sign(v2); float Fp = (p.x * p.x - p.y); if(sgn * Fp < 0){ return 0.0; }else{ return min_dist_to_curve(uv_coords, uv_b2, bezier_degree); } } void main() { if (color.a == 0) discard; frag_color = color; if (fill_all == 1.0) return; frag_color.a *= smoothstep(1, 0, sdf() / uv_anti_alias_width); } ================================================ FILE: manim/renderer/shaders/quadratic_bezier_fill/geom.glsl ================================================ #version 330 layout (triangles) in; layout (triangle_strip, max_vertices = 5) out; uniform float anti_alias_width; // Needed for get_gl_Position uniform vec2 frame_shape; uniform float focal_distance; uniform float is_fixed_in_frame; uniform float is_fixed_orientation; uniform vec3 fixed_orientation_center; // Needed for finalize_color uniform vec3 light_source_position; uniform float gloss; uniform float shadow; in vec3 bp[3]; in vec3 v_global_unit_normal[3]; in vec4 v_color[3]; in float v_vert_index[3]; out vec4 color; out float fill_all; out float uv_anti_alias_width; out vec3 xyz_coords; out float orientation; // uv space is where b0 = (0, 0), b1 = (1, 0), and transform is orthogonal out vec2 uv_coords; out vec2 uv_b2; out float bezier_degree; // Analog of import for manim only #include ../include/quadratic_bezier_geometry_functions.glsl #include ../include/get_gl_Position.glsl #include ../include/get_unit_normal.glsl #include ../include/finalize_color.glsl void emit_vertex_wrapper(vec3 point, int index){ color = finalize_color( v_color[index], point, v_global_unit_normal[index], light_source_position, gloss, shadow ); xyz_coords = point; gl_Position = get_gl_Position(xyz_coords); EmitVertex(); } void emit_simple_triangle(){ for(int i = 0; i < 3; i++){ emit_vertex_wrapper(bp[i], i); } EndPrimitive(); } void emit_pentagon(vec3[3] points, vec3 normal){ vec3 p0 = points[0]; vec3 p1 = points[1]; vec3 p2 = points[2]; // Tangent vectors vec3 t01 = normalize(p1 - p0); vec3 t12 = normalize(p2 - p1); // Vectors perpendicular to the curve in the plane of the curve pointing outside the curve vec3 p0_perp = cross(t01, normal); vec3 p2_perp = cross(t12, normal); bool fill_inside = orientation > 0; float aaw = anti_alias_width; vec3 corners[5]; if(fill_inside){ // Note, straight lines will also fall into this case, and since p0_perp and p2_perp // will point to the right of the curve, it's just what we want corners = vec3[5]( p0 + aaw * p0_perp, p0, p1 + 0.5 * aaw * (p0_perp + p2_perp), p2, p2 + aaw * p2_perp ); }else{ corners = vec3[5]( p0, p0 - aaw * p0_perp, p1, p2 - aaw * p2_perp, p2 ); } mat4 xyz_to_uv = get_xyz_to_uv(p0, p1, normal); uv_b2 = (xyz_to_uv * vec4(p2, 1)).xy; uv_anti_alias_width = anti_alias_width / length(p1 - p0); for(int i
(p0_perp + p2_perp), p2, p2 + aaw * p2_perp ); }else{ corners = vec3[5]( p0, p0 - aaw * p0_perp, p1, p2 - aaw * p2_perp, p2 ); } mat4 xyz_to_uv = get_xyz_to_uv(p0, p1, normal); uv_b2 = (xyz_to_uv * vec4(p2, 1)).xy; uv_anti_alias_width = anti_alias_width / length(p1 - p0); for(int i = 0; i < 5; i++){ vec3 corner = corners[i]; uv_coords = (xyz_to_uv * vec4(corner, 1)).xy; int j = int(sign(i - 1) + 1); // Maps i = [0, 1, 2, 3, 4] onto j = [0, 0, 1, 2, 2] emit_vertex_wrapper(corner, j); } EndPrimitive(); } void main(){ // If vert indices are sequential, don't fill all fill_all = float( (v_vert_index[1] - v_vert_index[0]) != 1.0 || (v_vert_index[2] - v_vert_index[1]) != 1.0 ); if(fill_all == 1.0){ emit_simple_triangle(); return; } vec3 new_bp[3]; bezier_degree = get_reduced_control_points(vec3[3](bp[0], bp[1], bp[2]), new_bp); vec3 local_unit_normal = get_unit_normal(new_bp); orientation = sign(dot(v_global_unit_normal[0], local_unit_normal)); if(bezier_degree >= 1){ emit_pentagon(new_bp, local_unit_normal); } // Don't emit any vertices for bezier_degree 0 } ================================================ FILE: manim/renderer/shaders/quadratic_bezier_fill/vert.glsl ================================================ #version 330 #include ../include/camera_uniform_declarations.glsl in vec3 point; in vec3 unit_normal; in vec4 color; in float vert_index; out vec3 bp; // Bezier control point out vec3 v_global_unit_normal; out vec4 v_color; out float v_vert_index; // Analog of import for manim only #include ../include/position_point_into_frame.glsl void main(){ bp = position_point_into_frame(point.xyz); v_global_unit_normal = rotate_point_into_frame(unit_normal.xyz); v_color = color; v_vert_index = vert_index; } ================================================ FILE: manim/renderer/shaders/quadratic_bezier_stroke/frag.glsl ================================================ #version 330 #include ../include/camera_uniform_declarations.glsl in vec2 uv_coords; in vec2 uv_b2; in float uv_stroke_width; in vec4 color; in float uv_anti_alias_width; in float has_prev; in float has_next; in float bevel_start; in float bevel_end; in float angle_from_prev; in float angle_to_next; in float bezier_degree; out vec4 frag_color; float cross2d(vec2 v, vec2 w){ return v.x * w.y - w.x * v.y; } float modify_distance_for_endpoints(vec2 p, float dist, float t){ float buff = 0.5 * uv_stroke_width - uv_anti_alias_width; // Check the beginning of the curve if(t == 0){ // Clip the start if(has_prev == 0) return max(dist, -p.x + buff); // Bevel start if(bevel_start == 1){ float a = angle_from_prev; mat2 rot = mat2( cos(a), sin(a), -sin(a), cos(a) ); // Dist for intersection of two lines float bevel_d = max(abs(p.y), abs((rot * p).y)); // Dist for union of this intersection with the real curve // intersected with radius 2 away from curve to smooth out // really sharp corners return max(min(dist, bevel_d), dist / 2); } // Otherwise, start will be rounded off }else if(t == 1){ // Check the end of the curve // TODO, too much code repetition vec2 v21 = (bezier_degree == 2) ? vec2(1, 0) - uv_b2 : vec2(-1, 0); float len_v21 = length(v21); if(len_v21 == 0){ v21 = -uv_b2; len_v21 = length(v21); } float perp_dist = dot(p - uv_b2, v21) / len_v21; if(has_next == 0) return max(dist, -perp_dist + buff); // Bevel end if(bevel_end == 1){ float a = -angle_to_next; mat2 rot = mat2( cos(a), sin(a), -sin(a), cos(a) ); vec2 v21_unit = v21 / length(v21); float bevel_d = max( abs(cross2d(p - uv_b2, v21_unit)), abs(cross2d((rot * (p - uv_b2)), v21_unit)) ); return max(min(dist, bevel_d), dist / 2); } //
+ buff); // Bevel end if(bevel_end == 1){ float a = -angle_to_next; mat2 rot = mat2( cos(a), sin(a), -sin(a), cos(a) ); vec2 v21_unit = v21 / length(v21); float bevel_d = max( abs(cross2d(p - uv_b2, v21_unit)), abs(cross2d((rot * (p - uv_b2)), v21_unit)) ); return max(min(dist, bevel_d), dist / 2); } // Otherwise, end will be rounded off } return dist; } #include ../include/quadratic_bezier_distance.glsl void main() { if (uv_stroke_width == 0) discard; float dist_to_curve = min_dist_to_curve(uv_coords, uv_b2, bezier_degree); // An sdf for the region around the curve we wish to color. float signed_dist = abs(dist_to_curve) - 0.5 * uv_stroke_width; frag_color = color; frag_color.a *= smoothstep(0.5, -0.5, signed_dist / uv_anti_alias_width); } ================================================ FILE: manim/renderer/shaders/quadratic_bezier_stroke/geom.glsl ================================================ #version 330 layout (triangles) in; layout (triangle_strip, max_vertices = 5) out; // Needed for get_gl_Position uniform vec2 frame_shape; uniform float focal_distance; uniform float is_fixed_in_frame; uniform float is_fixed_orientation; uniform vec3 fixed_orientation_center; uniform float anti_alias_width; uniform float flat_stroke; //Needed for lighting uniform vec3 light_source_position; uniform float joint_type; uniform float gloss; uniform float shadow; in vec3 bp[3]; in vec3 prev_bp[3]; in vec3 next_bp[3]; in vec3 v_global_unit_normal[3]; in vec4 v_color[3]; in float v_stroke_width[3]; out vec4 color; out float uv_stroke_width; out float uv_anti_alias_width; out float has_prev; out float has_next; out float bevel_start; out float bevel_end; out float angle_from_prev; out float angle_to_next; out float bezier_degree; out vec2 uv_coords; out vec2 uv_b2; // Codes for joint types const float AUTO_JOINT = 0; const float ROUND_JOINT = 1; const float BEVEL_JOINT = 2; const float MITER_JOINT = 3; const float PI = 3.141592653; #include ../include/quadratic_bezier_geometry_functions.glsl #include ../include/get_gl_Position.glsl #include ../include/get_unit_normal.glsl #include ../include/finalize_color.glsl void flatten_points(in vec3[3] points, out vec2[3] flat_points){ for(int i = 0; i < 3; i++){ float sf = perspective_scale_factor(points[i].z, focal_distance); flat_points[i] = sf * points[i].xy; } } float angle_between_vectors(vec2 v1, vec2 v2){ float v1_norm = length(v1); float v2_norm = length(v2); if(v1_norm == 0 || v2_norm == 0) return 0.0; float dp = dot(v1, v2) / (v1_norm * v2_norm); float angle = acos(clamp(dp, -1.0, 1.0)); float sn = sign(cross2d(v1, v2)); return sn * angle; } bool find_intersection(vec2 p0, vec2 v0, vec2 p1, vec2 v1, out vec2 intersection){ // Find the intersection of a line passing through // p0 in the direction v0 and one passing through p1 in // the direction p1. // That is, find a solutoin to p0 + v0 * t = p1 + v1 * s float det = -v0.x * v1.y + v1.x * v0.y; if(det == 0) return false; float t = cross2d(p0 - p1, v1) / det; intersection = p0 + v0 * t; return true; } void create_joint(float angle, vec2 unit_tan, float buff, vec2 static_c0, out vec2 changing_c0, vec2 static_c1, out vec2 changing_c1){ float shift; if(abs(angle) < 1e-3){ // No joint shift = 0; }else if(joint_type == MITER_JOINT){ shift = buff * (-1.0 - cos(angle)) / sin(angle); }else{ // For a Bevel joint shift = buff * (1.0 - cos(angle)) / sin(angle); } changing_c0 = static_c0 - shift * unit_tan; changing_c1 = static_c1 + shift * unit_tan; } // This function is responsible for finding the corners of
shift = buff * (-1.0 - cos(angle)) / sin(angle); }else{ // For a Bevel joint shift = buff * (1.0 - cos(angle)) / sin(angle); } changing_c0 = static_c0 - shift * unit_tan; changing_c1 = static_c1 + shift * unit_tan; } // This function is responsible for finding the corners of // a bounding region around the bezier curve, which can be // emitted as a triangle fan int get_corners(vec2 controls[3], int degree, float stroke_widths[3], out vec2 corners[5]){ vec2 p0 = controls[0]; vec2 p1 = controls[1]; vec2 p2 = controls[2]; // Unit vectors for directions between control points vec2 v10 = normalize(p0 - p1); vec2 v12 = normalize(p2 - p1); vec2 v01 = -v10; vec2 v21 = -v12; vec2 p0_perp = vec2(-v01.y, v01.x); // Pointing to the left of the curve from p0 vec2 p2_perp = vec2(-v12.y, v12.x); // Pointing to the left of the curve from p2 // aaw is the added width given around the polygon for antialiasing. // In case the normal is faced away from (0, 0, 1), the vector to the // camera, this is scaled up. float aaw = anti_alias_width; float buff0 = 0.5 * stroke_widths[0] + aaw; float buff2 = 0.5 * stroke_widths[2] + aaw; float aaw0 = (1 - has_prev) * aaw; float aaw2 = (1 - has_next) * aaw; vec2 c0 = p0 - buff0 * p0_perp + aaw0 * v10; vec2 c1 = p0 + buff0 * p0_perp + aaw0 * v10; vec2 c2 = p2 + buff2 * p2_perp + aaw2 * v12; vec2 c3 = p2 - buff2 * p2_perp + aaw2 * v12; // Account for previous and next control points if(has_prev > 0) create_joint(angle_from_prev, v01, buff0, c0, c0, c1, c1); if(has_next > 0) create_joint(angle_to_next, v21, buff2, c3, c3, c2, c2); // Linear case is the simplest if(degree == 1){ // The order of corners should be for a triangle_strip. Last entry is a dummy corners = vec2[5](c0, c1, c3, c2, vec2(0.0)); return 4; } // Otherwise, form a pentagon around the curve float orientation = sign(cross2d(v01, v12)); // Positive for ccw curves if(orientation > 0) corners = vec2[5](c0, c1, p1, c2, c3); else corners = vec2[5](c1, c0, p1, c3, c2); // Replace corner[2] with convex hull point accounting for stroke width find_intersection(corners[0], v01, corners[4], v21, corners[2]); return 5; } void set_adjascent_info(vec2 c0, vec2 tangent, int degree, vec2 adj[3], out float bevel, out float angle ){ bool linear_adj = (angle_between_vectors(adj[1] - adj[0], adj[2] - adj[1]) < 1e-3); angle = angle_between_vectors(c0 - adj[1], tangent); // Decide on joint type bool one_linear = (degree == 1 || linear_adj); bool should_bevel = ( (joint_type == AUTO_JOINT && one_linear) || joint_type == BEVEL_JOINT ); bevel = should_bevel ? 1.0 : 0.0; } void find_joint_info(vec2 controls[3], vec2 prev[3], vec2 next[3], int degree){ float tol = 1e-6; // Made as floats not bools so they can be passed to the frag shader has_prev = float(distance(prev[2], controls[0]) < tol); has_next = float(distance(next[0], controls[2]) < tol); if(bool(has_prev)){ vec2 tangent = controls[1] - controls[0]; set_adjascent_info( controls[0], tangent,
void find_joint_info(vec2 controls[3], vec2 prev[3], vec2 next[3], int degree){ float tol = 1e-6; // Made as floats not bools so they can be passed to the frag shader has_prev = float(distance(prev[2], controls[0]) < tol); has_next = float(distance(next[0], controls[2]) < tol); if(bool(has_prev)){ vec2 tangent = controls[1] - controls[0]; set_adjascent_info( controls[0], tangent, degree, prev, bevel_start, angle_from_prev ); } if(bool(has_next)){ vec2 tangent = controls[1] - controls[2]; set_adjascent_info( controls[2], tangent, degree, next, bevel_end, angle_to_next ); angle_to_next *= -1; } } void main() { // Convert control points to a standard form if they are linear or null vec3 controls[3]; vec3 prev[3]; vec3 next[3]; bezier_degree = get_reduced_control_points(vec3[3](bp[0], bp[1], bp[2]), controls); if(bezier_degree == 0.0) return; // Null curve int degree = int(bezier_degree); get_reduced_control_points(vec3[3](prev_bp[0], prev_bp[1], prev_bp[2]), prev); get_reduced_control_points(vec3[3](next_bp[0], next_bp[1], next_bp[2]), next); // Adjust stroke width based on distance from the camera float scaled_strokes[3]; for(int i = 0; i < 3; i++){ float sf = perspective_scale_factor(controls[i].z, focal_distance); if(bool(flat_stroke)){ vec3 to_cam = normalize(vec3(0.0, 0.0, focal_distance) - controls[i]); sf *= abs(dot(v_global_unit_normal[i], to_cam)); } scaled_strokes[i] = v_stroke_width[i] * sf; } // Control points are projected to the xy plane before drawing, which in turn // gets translated to a uv plane. The z-coordinate information will be remembered // by what's sent out to gl_Position, and by how it affects the lighting and stroke width vec2 flat_controls[3]; vec2 flat_prev[3]; vec2 flat_next[3]; flatten_points(controls, flat_controls); flatten_points(prev, flat_prev); flatten_points(next, flat_next); find_joint_info(flat_controls, flat_prev, flat_next, degree); // Corners of a bounding region around curve vec2 corners[5]; int n_corners = get_corners(flat_controls, degree, scaled_strokes, corners); int index_map[5] = int[5](0, 0, 1, 2, 2); if(n_corners == 4) index_map[2] = 2; // Find uv conversion matrix mat3 xy_to_uv = get_xy_to_uv(flat_controls[0], flat_controls[1]); float scale_factor = length(flat_controls[1] - flat_controls[0]); uv_anti_alias_width = anti_alias_width / scale_factor; uv_b2 = (xy_to_uv * vec3(flat_controls[2], 1.0)).xy; // Emit each corner for(int i = 0; i < n_corners; i++){ uv_coords = (xy_to_uv * vec3(corners[i], 1.0)).xy; uv_stroke_width = scaled_strokes[index_map[i]] / scale_factor; // Apply some lighting to the color before sending out. // vec3 xyz_coords = vec3(corners[i], controls[index_map[i]].z); vec3 xyz_coords = vec3(corners[i], controls[index_map[i]].z); color = finalize_color( v_color[index_map[i]], xyz_coords, v_global_unit_normal[index_map[i]], light_source_position, gloss, shadow ); gl_Position = vec4( get_gl_Position(vec3(corners[i], 0.0)).xy, get_gl_Position(controls[index_map[i]]).zw ); EmitVertex(); } EndPrimitive(); } ================================================ FILE: manim/renderer/shaders/quadratic_bezier_stroke/vert.glsl ================================================ #version 330 #include ../include/camera_uniform_declarations.glsl in vec3 point; in vec3 prev_point; in vec3 next_point; in vec3 unit_normal; in float stroke_width; in vec4 color; // Bezier control point out vec3 bp; out vec3 prev_bp; out vec3 next_bp; out vec3 v_global_unit_normal; out float v_stroke_width; out vec4 v_color; const float STROKE_WIDTH_CONVERSION = 0.01; #include ../include/position_point_into_frame.glsl void main(){ bp = position_point_into_frame(point); prev_bp = position_point_into_frame(prev_point); next_bp = position_point_into_frame(next_point); v_global_unit_normal = rotate_point_into_frame(unit_normal); v_stroke_width = STROKE_WIDTH_CONVERSION * stroke_width; v_color = color; } ================================================ FILE: manim/renderer/shaders/surface/frag.glsl ================================================ #version 330 uniform vec3 light_source_position; uniform float gloss; uniform float shadow; in vec3 xyz_coords; in vec3 v_normal; in vec4 v_color; out vec4 frag_color; #include ../include/finalize_color.glsl void main() { frag_color = finalize_color( v_color, xyz_coords, normalize(v_normal), light_source_position, gloss, shadow ); } ================================================ FILE: manim/renderer/shaders/surface/vert.glsl ================================================ #version 330 #include ../include/camera_uniform_declarations.glsl in vec3 point; in vec3 du_point; in vec3 dv_point; in vec4 color; out vec3 xyz_coords; out vec3 v_normal; out
v_normal; in vec4 v_color; out vec4 frag_color; #include ../include/finalize_color.glsl void main() { frag_color = finalize_color( v_color, xyz_coords, normalize(v_normal), light_source_position, gloss, shadow ); } ================================================ FILE: manim/renderer/shaders/surface/vert.glsl ================================================ #version 330 #include ../include/camera_uniform_declarations.glsl in vec3 point; in vec3 du_point; in vec3 dv_point; in vec4 color; out vec3 xyz_coords; out vec3 v_normal; out vec4 v_color; #include ../include/position_point_into_frame.glsl #include ../include/get_gl_Position.glsl #include ../include/get_rotated_surface_unit_normal_vector.glsl void main(){ xyz_coords = position_point_into_frame(point); v_normal = get_rotated_surface_unit_normal_vector(point, du_point, dv_point); v_color = color; gl_Position = get_gl_Position(xyz_coords); } ================================================ FILE: manim/renderer/shaders/test/frag.glsl ================================================ #version 330 in vec4 v_color; out vec4 frag_color; void main() { frag_color = v_color; } ================================================ FILE: manim/renderer/shaders/test/vert.glsl ================================================ #version 330 in vec2 in_vert; in vec4 in_color; out vec4 v_color; void main() { v_color = in_color; gl_Position = vec4(in_vert, 0.0, 1.0); } ================================================ FILE: manim/renderer/shaders/textured_surface/frag.glsl ================================================ #version 330 uniform sampler2D LightTexture; uniform sampler2D DarkTexture; uniform float num_textures; uniform vec3 light_source_position; uniform float gloss; uniform float shadow; in vec3 xyz_coords; in vec3 v_normal; in vec2 v_im_coords; in float v_opacity; out vec4 frag_color; #include ../include/finalize_color.glsl const float dark_shift = 0.2; void main() { vec4 color = texture(LightTexture, v_im_coords); if(num_textures == 2.0){ vec4 dark_color = texture(DarkTexture, v_im_coords); float dp = dot( normalize(light_source_position - xyz_coords), normalize(v_normal) ); float alpha = smoothstep(-dark_shift, dark_shift, dp); color = mix(dark_color, color, alpha); } frag_color = finalize_color( color, xyz_coords, normalize(v_normal), light_source_position, gloss, shadow ); frag_color.a = v_opacity; } ================================================ FILE: manim/renderer/shaders/textured_surface/vert.glsl ================================================ #version 330 #include ../include/camera_uniform_declarations.glsl in vec3 point; in vec3 du_point; in vec3 dv_point; in vec2 im_coords; in float opacity; out vec3 xyz_coords; out vec3 v_normal; out vec2 v_im_coords; out float v_opacity; #include ../include/position_point_into_frame.glsl #include ../include/get_gl_Position.glsl #include ../include/get_rotated_surface_unit_normal_vector.glsl void main(){ xyz_coords = position_point_into_frame(point); v_normal = get_rotated_surface_unit_normal_vector(point, du_point, dv_point); v_im_coords = im_coords; v_opacity = opacity; gl_Position = get_gl_Position(xyz_coords); } ================================================ FILE: manim/renderer/shaders/true_dot/frag.glsl ================================================ #version 330 uniform vec3 light_source_position; uniform float gloss; uniform float shadow; uniform float anti_alias_width; in vec4 color; in float point_radius; in vec2 center; in vec2 point; out vec4 frag_color; #include ../include/finalize_color.glsl void main() { vec2 diff = point - center; float dist = length(diff); float signed_dist = dist - point_radius; if (signed_dist > 0.5 * anti_alias_width){ discard; } vec3 normal = vec3(diff / point_radius, sqrt(1 - (dist * dist) / (point_radius * point_radius))); frag_color = finalize_color( color, vec3(point.xy, 0.0), normal, light_source_position, gloss, shadow ); frag_color.a *= smoothstep(0.5, -0.5, signed_dist / anti_alias_width); } ================================================ FILE: manim/renderer/shaders/true_dot/geom.glsl ================================================ #version 330 layout (points) in; layout (triangle_strip, max_vertices = 4) out; // Needed for get_gl_Position uniform vec2 frame_shape; uniform float focal_distance; uniform float is_fixed_in_frame; uniform float is_fixed_orientation; uniform vec3 fixed_orientation_center; uniform float anti_alias_width; in vec3 v_point[1]; in float v_point_radius[1]; in vec4 v_color[1]; out vec4 color; out float point_radius; out vec2 center; out vec2 point; #include ../include/get_gl_Position.glsl void main() { color = v_color[0]; point_radius = v_point_radius[0]; center = v_point[0].xy; point_radius = v_point_radius[0] / max(1.0 - v_point[0].z / focal_distance / frame_shape.y, 0.0); float rpa = point_radius + anti_alias_width; for(int i = 0; i < 4; i++){ // To account for perspective int x_index = 2 * (i % 2) - 1; int y_index = 2 * (i / 2) - 1; vec3 corner
/ max(1.0 - v_point[0].z / focal_distance / frame_shape.y, 0.0); float rpa = point_radius + anti_alias_width; for(int i = 0; i < 4; i++){ // To account for perspective int x_index = 2 * (i % 2) - 1; int y_index = 2 * (i / 2) - 1; vec3 corner = v_point[0] + vec3(x_index * rpa, y_index * rpa, 0.0); gl_Position = get_gl_Position(corner); point = corner.xy; EmitVertex(); } EndPrimitive(); } ================================================ FILE: manim/renderer/shaders/true_dot/vert.glsl ================================================ #version 330 #include ../include/camera_uniform_declarations.glsl in vec3 point; in vec4 color; uniform float point_radius; out vec3 v_point; out float v_point_radius; out vec4 v_color; #include ../include/position_point_into_frame.glsl void main(){ v_point = position_point_into_frame(point); v_point_radius = point_radius; v_color = color; } ================================================ FILE: manim/renderer/shaders/vectorized_mobject_fill/frag.glsl ================================================ #version 330 in vec4 v_color; in vec2 v_texture_coords; flat in int v_texture_mode; out vec4 frag_color; void main() { float curve_func = v_texture_coords[0] * v_texture_coords[0] - v_texture_coords[1]; if (v_texture_mode * curve_func >= 0.0) { frag_color = v_color; } else { discard; } } ================================================ FILE: manim/renderer/shaders/vectorized_mobject_fill/vert.glsl ================================================ #version 330 uniform mat4 u_model_view_matrix; uniform mat4 u_projection_matrix; in vec3 in_vert; in vec4 in_color; in vec2 texture_coords; in int texture_mode; out vec4 v_color; out vec2 v_texture_coords; flat out int v_texture_mode; void main() { v_color = in_color; v_texture_coords = texture_coords; v_texture_mode = texture_mode; gl_Position = u_projection_matrix * u_model_view_matrix * vec4(in_vert, 1.0); } ================================================ FILE: manim/renderer/shaders/vectorized_mobject_stroke/frag.glsl ================================================ #version 330 in float v_degree; in float v_thickness; in vec2 uv_point; in vec2[3] uv_curve; in vec4 v_color; out vec4 frag_color; // https://www.shadertoy.com/view/ltXSDB // Test if point p crosses line (a, b), returns sign of result float testCross(vec2 a, vec2 b, vec2 p) { return sign((b.y-a.y) * (p.x-a.x) - (b.x-a.x) * (p.y-a.y)); } // Determine which side we're on (using barycentric parameterization) float signBezier(vec2 A, vec2 B, vec2 C, vec2 p) { vec2 a = C - A, b = B - A, c = p - A; vec2 bary = vec2(c.x*b.y-b.x*c.y,a.x*c.y-c.x*a.y) / (a.x*b.y-b.x*a.y); vec2 d = vec2(bary.y * 0.5, 0.0) + 1.0 - bary.x - bary.y; return mix(sign(d.x * d.x - d.y), mix(-1.0, 1.0, step(testCross(A, B, p) * testCross(B, C, p), 0.0)), step((d.x - d.y), 0.0)) * testCross(A, C, B); } // Solve cubic equation for roots vec3 solveCubic(float a, float b, float c) { float p = b - a*a / 3.0, p3 = p*p*p; float q = a * (2.0*a*a - 9.0*b) / 27.0 + c; float d = q*q + 4.0*p3 / 27.0; float offset = -a / 3.0; if(d >= 0.0) { float z = sqrt(d); vec2 x = (vec2(z, -z) - q) / 2.0; vec2 uv = sign(x)*pow(abs(x), vec2(1.0/3.0)); return vec3(offset + uv.x + uv.y); } float v = acos(-sqrt(-27.0 / p3) * q / 2.0) / 3.0; float m = cos(v), n = sin(v)*1.732050808; return vec3(m + m, -n - m, n - m) * sqrt(-p / 3.0) + offset; } // Find the signed distance from a point to a bezier curve float sdBezier(vec2 A, vec2 B, vec2 C, vec2 p) { B = mix(B + vec2(1e-4), B, abs(sign(B * 2.0 - A - C))); vec2 a =
- m, n - m) * sqrt(-p / 3.0) + offset; } // Find the signed distance from a point to a bezier curve float sdBezier(vec2 A, vec2 B, vec2 C, vec2 p) { B = mix(B + vec2(1e-4), B, abs(sign(B * 2.0 - A - C))); vec2 a = B - A, b = A - B * 2.0 + C, c = a * 2.0, d = A - p; vec3 k = vec3(3.*dot(a,b),2.*dot(a,a)+dot(d,b),dot(d,a)) / dot(b,b); vec3 t = clamp(solveCubic(k.x, k.y, k.z), 0.0, 1.0); vec2 pos = A + (c + b*t.x)*t.x; float dis = length(pos - p); pos = A + (c + b*t.y)*t.y; dis = min(dis, length(pos - p)); pos = A + (c + b*t.z)*t.z; dis = min(dis, length(pos - p)); return dis * signBezier(A, B, C, p); } // https://www.shadertoy.com/view/llcfR7 float dLine(vec2 p1, vec2 p2, vec2 x) { vec4 colA = vec4(clamp (5.0 - length (x - p1), 0.0, 1.0)); vec4 colB = vec4(clamp (5.0 - length (x - p2), 0.0, 1.0)); vec2 a_p1 = x - p1; vec2 p2_p1 = p2 - p1; float h = clamp (dot (a_p1, p2_p1) / dot (p2_p1, p2_p1), 0.0, 1.0); return length (a_p1 - p2_p1 * h); } void main() { float distance; if (v_degree == 2.0) { distance = sdBezier(uv_curve[0], uv_curve[1], uv_curve[2], uv_point); } else { distance = dLine(uv_curve[0], uv_curve[2], uv_point); } if (abs(distance) < v_thickness) { frag_color = v_color; } else { discard; } } ================================================ FILE: manim/renderer/shaders/vectorized_mobject_stroke/vert.glsl ================================================ #version 330 uniform vec3 manim_unit_normal; uniform mat4 u_model_view_matrix; uniform mat4 u_projection_matrix; in vec3[3] current_curve; in vec2 tile_coordinate; in vec4 in_color; in float in_width; out float v_degree; out float v_thickness; out vec2 uv_point; out vec2[3] uv_curve; out vec4 v_color; int get_degree(in vec3 points[3], out vec3 normal) { float length_threshold = 1e-6; float angle_threshold = 5e-2; vec3 v01 = (points[1] - points[0]); vec3 v12 = (points[2] - points[1]); float dot_prod = clamp(dot(normalize(v01), normalize(v12)), -1, 1); bool aligned = acos(dot_prod) < angle_threshold; bool distinct_01 = length(v01) > length_threshold; // v01 is considered nonzero bool distinct_12 = length(v12) > length_threshold; // v12 is considered nonzero int num_distinct = int(distinct_01) + int(distinct_12); bool quadratic = (num_distinct == 2) && !aligned; bool linear = (num_distinct == 1) || ((num_distinct == 2) && aligned); bool constant = (num_distinct == 0); if (quadratic) { // If the curve is quadratic pass a normal vector to the caller. normal = normalize(cross(v01, v12)); return 2; } else if (linear) { return 1; } else { return 0; } } // https://iquilezles.org/www/articles/bezierbbox/bezierbbox.htm vec4 bboxBezier(in vec2 p0, in vec2 p1, in vec2 p2) { vec2 mi = min(p0, p2); vec2 ma = max(p0, p2); if (p1.x < mi.x || p1.x > ma.x || p1.y < mi.y || p1.y > ma.y) { vec2 t = clamp((p0 - p1) / (p0 - 2.0 * p1 + p2), 0.0, 1.0); vec2 s = 1.0 - t; vec2 q = s * s * p0 + 2.0 * s * t * p1 + t * t * p2; mi = min(mi,
> ma.y) { vec2 t = clamp((p0 - p1) / (p0 - 2.0 * p1 + p2), 0.0, 1.0); vec2 s = 1.0 - t; vec2 q = s * s * p0 + 2.0 * s * t * p1 + t * t * p2; mi = min(mi, q); ma = max(ma, q); } return vec4(mi, ma); } vec2 convert_to_uv(vec3 x_unit, vec3 y_unit, vec3 point) { return vec2(dot(point, x_unit), dot(point, y_unit)); } vec3 convert_from_uv(vec3 translation, vec3 x_unit, vec3 y_unit, vec2 point) { vec3 untranslated_point = point[0] * x_unit + point[1] * y_unit; return untranslated_point + translation; } void main() { float thickness_multiplier = 0.004; v_color = in_color; vec3 computed_normal; v_degree = get_degree(current_curve, computed_normal); vec3 tile_x_unit = normalize(current_curve[2] - current_curve[0]); vec3 unit_normal; vec3 tile_y_unit; if (v_degree == 0) { tile_y_unit = vec3(0.0, 0.0, 0.0); } else if (v_degree == 1) { // Since the curve forms a straight line there's no way to compute a normal. unit_normal = manim_unit_normal; tile_y_unit = cross(unit_normal, tile_x_unit); } else { // Prefer to use a computed normal vector rather than the one from manim. unit_normal = computed_normal; // Ensure tile_y_unit is pointing toward p1 from p0. tile_y_unit = cross(unit_normal, tile_x_unit); if (dot(tile_y_unit, current_curve[1] - current_curve[0]) < 0) { tile_y_unit *= -1; } } // Project the curve onto the tile. for(int i = 0; i < 3; i++) { uv_curve[i] = convert_to_uv(tile_x_unit, tile_y_unit, current_curve[i]); } // Compute the curve's bounding box. vec4 uv_bounding_box = bboxBezier(uv_curve[0], uv_curve[1], uv_curve[2]); vec3 tile_translation = unit_normal * dot(current_curve[0], unit_normal); vec3 bounding_box_min = convert_from_uv(tile_translation, tile_x_unit, tile_y_unit, uv_bounding_box.xy); vec3 bounding_box_max = convert_from_uv(tile_translation, tile_x_unit, tile_y_unit, uv_bounding_box.zw); vec3 bounding_box_vec = bounding_box_max - bounding_box_min; vec3 tile_origin = bounding_box_min; vec3 tile_x_vec = tile_x_unit * dot(tile_x_unit, bounding_box_vec); vec3 tile_y_vec = tile_y_unit * dot(tile_y_unit, bounding_box_vec); // Expand the tile according to the line's thickness. v_thickness = thickness_multiplier * in_width; tile_origin = current_curve[0] - v_thickness * (tile_x_unit + tile_y_unit); tile_x_vec += 2 * v_thickness * tile_x_unit; tile_y_vec += 2 * v_thickness * tile_y_unit; vec3 tile_point = tile_origin + \ tile_coordinate[0] * tile_x_vec + \ tile_coordinate[1] * tile_y_vec; gl_Position = u_projection_matrix * u_model_view_matrix * vec4(tile_point, 1.0); uv_point = convert_to_uv(tile_x_unit, tile_y_unit, tile_point); } ================================================ FILE: manim/renderer/shaders/vertex_colors/frag.glsl ================================================ #version 330 in vec4 v_color; out vec4 frag_color; void main() { frag_color = v_color; } ================================================ FILE: manim/renderer/shaders/vertex_colors/vert.glsl ================================================ #version 330 uniform mat4 u_model_matrix; uniform mat4 u_view_matrix; uniform mat4 u_projection_matrix; in vec4 in_vert; in vec4 in_color; out vec4 v_color; void main() { v_color = in_color; gl_Position = u_projection_matrix * u_view_matrix * u_model_matrix * in_vert; } ================================================ FILE: manim/scene/__init__.py ================================================ [Empty file] ================================================ FILE: manim/scene/moving_camera_scene.py ================================================ """A scene whose camera can be moved around. .. SEEALSO:: :mod:`.moving_camera` Examples -------- .. manim:: ChangingCameraWidthAndRestore class ChangingCameraWidthAndRestore(MovingCameraScene): def construct(self): text = Text("Hello World").set_color(BLUE) self.add(text) self.camera.frame.save_state() self.play(self.camera.frame.animate.set(width=text.width * 1.2)) self.wait(0.3) self.play(Restore(self.camera.frame)) .. manim:: MovingCameraCenter class MovingCameraCenter(MovingCameraScene): def construct(self): s = Square(color=RED, fill_opacity=0.5).move_to(2 * LEFT) t = Triangle(color=GREEN, fill_opacity=0.5).move_to(2 * RIGHT) self.wait(0.3) self.add(s, t) self.play(self.camera.frame.animate.move_to(s)) self.wait(0.3) self.play(self.camera.frame.animate.move_to(t)) .. manim:: MovingAndZoomingCamera class MovingAndZoomingCamera(MovingCameraScene): def construct(self): s = Square(color=BLUE, fill_opacity=0.5).move_to(2 * LEFT) t = Triangle(color=YELLOW, fill_opacity=0.5).move_to(2 * RIGHT) self.add(s, t)
* 1.2)) self.wait(0.3) self.play(Restore(self.camera.frame)) .. manim:: MovingCameraCenter class MovingCameraCenter(MovingCameraScene): def construct(self): s = Square(color=RED, fill_opacity=0.5).move_to(2 * LEFT) t = Triangle(color=GREEN, fill_opacity=0.5).move_to(2 * RIGHT) self.wait(0.3) self.add(s, t) self.play(self.camera.frame.animate.move_to(s)) self.wait(0.3) self.play(self.camera.frame.animate.move_to(t)) .. manim:: MovingAndZoomingCamera class MovingAndZoomingCamera(MovingCameraScene): def construct(self): s = Square(color=BLUE, fill_opacity=0.5).move_to(2 * LEFT) t = Triangle(color=YELLOW, fill_opacity=0.5).move_to(2 * RIGHT) self.add(s, t) self.play(self.camera.frame.animate.move_to(s).set(width=s.width*2)) self.wait(0.3) self.play(self.camera.frame.animate.move_to(t).set(width=t.width*2)) self.play(self.camera.frame.animate.move_to(ORIGIN).set(width=14)) .. manim:: MovingCameraOnGraph class MovingCameraOnGraph(MovingCameraScene): def construct(self): self.camera.frame.save_state() ax = Axes(x_range=[-1, 10], y_range=[-1, 10]) graph = ax.plot(lambda x: np.sin(x), color=WHITE, x_range=[0, 3 * PI]) dot_1 = Dot(ax.i2gp(graph.t_min, graph)) dot_2 = Dot(ax.i2gp(graph.t_max, graph)) self.add(ax, graph, dot_1, dot_2) self.play(self.camera.frame.animate.scale(0.5).move_to(dot_1)) self.play(self.camera.frame.animate.move_to(dot_2)) self.play(Restore(self.camera.frame)) self.wait() .. manim:: SlidingMultipleScenes class SlidingMultipleScenes(MovingCameraScene): def construct(self): def create_scene(number): frame = Rectangle(width=16,height=9) circ = Circle().shift(LEFT) text = Tex(f"This is Scene {str(number)}").next_to(circ, RIGHT) frame.add(circ,text) return frame group = VGroup(*(create_scene(i) for i in range(4))).arrange_in_grid(buff=4) self.add(group) self.camera.auto_zoom(group[0], animate=False) for scene in group: self.play(self.camera.auto_zoom(scene)) self.wait() self.play(self.camera.auto_zoom(group, margin=2)) """ from __future__ import annotations __all__ = ["MovingCameraScene"] from typing import Any from manim.animation.animation import Animation from manim.mobject.mobject import Mobject from ..camera.camera import Camera from ..camera.moving_camera import MovingCamera from ..scene.scene import Scene from ..utils.family import extract_mobject_family_members from ..utils.iterables import list_update class MovingCameraScene(Scene): """ This is a Scene, with special configurations and properties that make it suitable for cases where the camera must be moved around. Note: Examples are included in the moving_camera_scene module documentation, see below in the 'see also' section. .. SEEALSO:: :mod:`.moving_camera_scene` :class:`.MovingCamera` """ def __init__( self, camera_class: type[Camera] = MovingCamera, **kwargs: Any ) -> None: super().__init__(camera_class=camera_class, **kwargs) def get_moving_mobjects(self, *animations: Animation) -> list[Mobject]: """ This method returns a list of all of the Mobjects in the Scene that are moving, that are also in the animations passed. Parameters ---------- *animations The Animations whose mobjects will be checked. """ moving_mobjects = super().get_moving_mobjects(*animations) all_moving_mobjects = extract_mobject_family_members(moving_mobjects) movement_indicators = self.renderer.camera.get_mobjects_indicating_movement() # type: ignore[union-attr] for movement_indicator in movement_indicators: if movement_indicator in all_moving_mobjects: # When one of these is moving, the camera should # consider all mobjects to be moving return list_update(self.mobjects, moving_mobjects) return moving_mobjects ================================================ FILE: manim/scene/scene_file_writer.py ================================================ """The interface between scenes and ffmpeg.""" from __future__ import annotations __all__ = ["SceneFileWriter"] import json import shutil from fractions import Fraction from pathlib import Path from queue import Queue from tempfile import NamedTemporaryFile, _TemporaryFileWrapper from threading import Thread from typing import TYPE_CHECKING, Any import av import numpy as np import srt from PIL import Image from pydub import AudioSegment from manim import __version__ from .. import config, logger from .._config.logger_utils import set_file_logger from ..constants import RendererType from ..utils.file_ops import ( add_extension_if_not_present, add_version_before_extension, guarantee_existence, is_gif_format, is_png_format, modify_atime, write_to_movie, ) from ..utils.sounds import get_full_sound_file_path from .section import DefaultSectionType, Section if TYPE_CHECKING: from av.container.output import OutputContainer from av.stream import Stream from manim.renderer.cairo_renderer import CairoRenderer from manim.renderer.opengl_renderer import OpenGLRenderer from manim.typing import PixelArray, StrPath def to_av_frame_rate(fps: float) -> Fraction: epsilon1 = 1e-4 epsilon2 = 0.02 if isinstance(fps, int): (num, denom) = (fps, 1) elif abs(fps - round(fps)) < epsilon1: (num, denom) = (round(fps), 1) else: denom = 1001 num = round(fps * denom / 1000) * 1000 if abs(fps - num / denom) >= epsilon2: raise ValueError("invalid frame rate") return
= 1e-4 epsilon2 = 0.02 if isinstance(fps, int): (num, denom) = (fps, 1) elif abs(fps - round(fps)) < epsilon1: (num, denom) = (round(fps), 1) else: denom = 1001 num = round(fps * denom / 1000) * 1000 if abs(fps - num / denom) >= epsilon2: raise ValueError("invalid frame rate") return Fraction(num, denom) def convert_audio( input_path: Path, output_path: Path | _TemporaryFileWrapper[bytes], codec_name: str ) -> None: with ( av.open(input_path) as input_audio, av.open(output_path, "w") as output_audio, ): input_audio_stream = input_audio.streams.audio[0] output_audio_stream = output_audio.add_stream(codec_name) for frame in input_audio.decode(input_audio_stream): for packet in output_audio_stream.encode(frame): output_audio.mux(packet) for packet in output_audio_stream.encode(): output_audio.mux(packet) class SceneFileWriter: """SceneFileWriter is the object that actually writes the animations played, into video files, using FFMPEG. This is mostly for Manim's internal use. You will rarely, if ever, have to use the methods for this class, unless tinkering with the very fabric of Manim's reality. Attributes ---------- sections : list of :class:`.Section` used to segment scene sections_output_dir : :class:`pathlib.Path` where are section videos stored output_name : str name of movie without extension and basis for section video names Some useful attributes are: "write_to_movie" (bool=False) Whether or not to write the animations into a video file. "movie_file_extension" (str=".mp4") The file-type extension of the outputted video. "partial_movie_files" List of all the partial-movie files. """ force_output_as_scene_name = False def __init__( self, renderer: CairoRenderer | OpenGLRenderer, scene_name: str, **kwargs: Any, ) -> None: self.renderer = renderer self.init_output_directories(scene_name) self.init_audio() self.frame_count = 0 self.partial_movie_files: list[str | None] = [] self.subcaptions: list[srt.Subtitle] = [] self.sections: list[Section] = [] # first section gets automatically created for convenience # if you need the first section to be skipped, add a first section by hand, it will replace this one self.next_section( name="autocreated", type_=DefaultSectionType.NORMAL, skip_animations=False ) def init_output_directories(self, scene_name: str) -> None: """Initialise output directories. Notes ----- The directories are read from ``config``, for example ``config['media_dir']``. If the target directories don't already exist, they will be created. """ if config["dry_run"]: # in dry-run mode there is no output return module_name = config.get_dir("input_file").stem if config["input_file"] else "" if SceneFileWriter.force_output_as_scene_name: self.output_name = Path(scene_name) elif config["output_file"] and not config["write_all"]: self.output_name = config.get_dir("output_file") else: self.output_name = Path(scene_name) if config["media_dir"]: image_dir = guarantee_existence( config.get_dir( "images_dir", module_name=module_name, scene_name=scene_name ), ) self.image_file_path = image_dir / add_extension_if_not_present( self.output_name, ".png" ) if write_to_movie(): movie_dir = guarantee_existence( config.get_dir( "video_dir", module_name=module_name, scene_name=scene_name ), ) self.movie_file_path = movie_dir / add_extension_if_not_present( self.output_name, config["movie_file_extension"] ) # TODO: /dev/null would be good in case sections_output_dir is used without being set (doesn't work on Windows), everyone likes defensive programming, right? self.sections_output_dir = Path("") if config.save_sections: self.sections_output_dir = guarantee_existence( config.get_dir( "sections_dir", module_name=module_name, scene_name=scene_name ) ) if is_gif_format(): self.gif_file_path = add_extension_if_not_present( self.output_name, ".gif" ) if not config["output_file"]: self.gif_file_path = add_version_before_extension( self.gif_file_path ) self.gif_file_path = movie_dir / self.gif_file_path self.partial_movie_directory = guarantee_existence( config.get_dir( "partial_movie_dir", scene_name=scene_name, module_name=module_name, ), ) if config["log_to_file"]: log_dir = guarantee_existence(config.get_dir("log_dir")) set_file_logger( scene_name=scene_name, module_name=module_name, log_dir=log_dir ) def finish_last_section(self) -> None: """Delete current section if it is empty.""" if len(self.sections) and self.sections[-1].is_empty(): self.sections.pop() def next_section(self, name: str, type_: str, skip_animations: bool) -> None: """Create segmentation cut here.""" self.finish_last_section() # images don't support sections section_video:
module_name=module_name, ), ) if config["log_to_file"]: log_dir = guarantee_existence(config.get_dir("log_dir")) set_file_logger( scene_name=scene_name, module_name=module_name, log_dir=log_dir ) def finish_last_section(self) -> None: """Delete current section if it is empty.""" if len(self.sections) and self.sections[-1].is_empty(): self.sections.pop() def next_section(self, name: str, type_: str, skip_animations: bool) -> None: """Create segmentation cut here.""" self.finish_last_section() # images don't support sections section_video: str | None = None # don't save when None if ( not config.dry_run and write_to_movie() and config.save_sections and not skip_animations ): # relative to index file section_video = f"{self.output_name}_{len(self.sections):04}_{name}{config.movie_file_extension}" self.sections.append( Section( type_, section_video, name, skip_animations, ), ) def add_partial_movie_file(self, hash_animation: str | None) -> None: """Adds a new partial movie file path to ``scene.partial_movie_files`` and current section from a hash. This method will compute the path from the hash. In addition to that it adds the new animation to the current section. Parameters ---------- hash_animation Hash of the animation. """ if not hasattr(self, "partial_movie_directory") or not write_to_movie(): return # None has to be added to partial_movie_files to keep the right index with scene.num_plays. # i.e if an animation is skipped, scene.num_plays is still incremented and we add an element to partial_movie_file be even with num_plays. if hash_animation is None: self.partial_movie_files.append(None) self.sections[-1].partial_movie_files.append(None) else: new_partial_movie_file = str( self.partial_movie_directory / f"{hash_animation}{config['movie_file_extension']}" ) self.partial_movie_files.append(new_partial_movie_file) self.sections[-1].partial_movie_files.append(new_partial_movie_file) def get_resolution_directory(self) -> str: """Get the name of the resolution directory directly containing the video file. This method gets the name of the directory that immediately contains the video file. This name is ``<height_in_pixels_of_video>p<frame_rate>``. For example, if you are rendering an 854x480 px animation at 15fps, the name of the directory that immediately contains the video, file will be ``480p15``. The file structure should look something like:: MEDIA_DIR |--Tex |--texts |--videos |--<name_of_file_containing_scene> |--<height_in_pixels_of_video>p<frame_rate> |--partial_movie_files |--<scene_name>.mp4 |--<scene_name>.srt Returns ------- :class:`str` The name of the directory. """ pixel_height = config["pixel_height"] frame_rate = config["frame_rate"] return f"{pixel_height}p{frame_rate}" # Sound def init_audio(self) -> None: """Preps the writer for adding audio to the movie.""" self.includes_sound = False def create_audio_segment(self) -> None: """Creates an empty, silent, Audio Segment.""" self.audio_segment = AudioSegment.silent() def add_audio_segment( self, new_segment: AudioSegment, time: float | None = None, gain_to_background: float | None = None, ) -> None: """This method adds an audio segment from an AudioSegment type object and suitable parameters. Parameters ---------- new_segment The audio segment to add time the timestamp at which the sound should be added. gain_to_background The gain of the segment from the background. """ if not self.includes_sound: self.includes_sound = True self.create_audio_segment() segment = self.audio_segment curr_end = segment.duration_seconds if time is None: time = curr_end if time < 0: raise ValueError("Adding sound at timestamp < 0") new_end = time + new_segment.duration_seconds diff = new_end - curr_end if diff > 0: segment = segment.append( AudioSegment.silent(int(np.ceil(diff * 1000))), crossfade=0, ) self.audio_segment = segment.overlay( new_segment, position=int(1000 * time), gain_during_overlay=gain_to_background, ) def add_sound( self, sound_file: StrPath, time: float | None = None, gain: float | None = None, **kwargs: Any, ) -> None: """This method adds an audio segment from a sound file. Parameters ---------- sound_file The path to the sound file. time The timestamp at which the audio should be