Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

Add missing mobject method chaining (#4913)

GniLudioc591dae154fd
diff --git a/manim/mobject/geometry/arc.py b/manim/mobject/geometry/arc.py
index 32b1133a6..e04d8d281 100644
--- a/manim/mobject/geometry/arc.py
+++ b/manim/mobject/geometry/arc.py
@@ -336,15 +336,16 @@ class Arc(TipableVMobject):
self._failed_to_get_center: bool = False
super().__init__(**kwargs)
- def generate_points(self) -> None:
+ def generate_points(self) -> Self:
self._set_pre_positioned_points()
self.scale(self.radius, about_point=ORIGIN)
self.shift(self.arc_center)
+ return self
# Points are set a bit differently when rendering via OpenGL.
# TODO: refactor Arc so that only one strategy for setting points
# has to be used.
- def init_points(self) -> None:
+ def init_points(self) -> Self:
self.set_points(
Arc._create_quadratic_bezier_points(
angle=self.angle,
@@ -354,6 +355,7 @@ class Arc(TipableVMobject):
)
self.scale(self.radius, about_point=ORIGIN)
self.shift(self.arc_center)
+ return self
@staticmethod
def _create_quadratic_bezier_points(
@@ -998,7 +1000,7 @@ class AnnularSector(Arc):
**kwargs,
)
- def generate_points(self) -> None:
+ def generate_points(self) -> Self:
inner_arc, outer_arc = (
Arc(
start_angle=self.start_angle,
@@ -1013,9 +1015,11 @@ class AnnularSector(Arc):
self.add_line_to(outer_arc.points[0])
self.append_points(outer_arc.points)
self.add_line_to(inner_arc.points[0])
+ return self
- def init_points(self) -> None:
+ def init_points(self) -> Self:
self.generate_points()
+ return self
class Sector(AnnularSector):
@@ -1080,7 +1084,7 @@ class Annulus(Circle):
fill_opacity=fill_opacity, stroke_width=stroke_width, color=color, **kwargs
)
- def generate_points(self) -> None:
+ def generate_points(self) -> Self:
self.radius = self.outer_radius
outer_circle = Circle(radius=self.outer_radius)
inner_circle = Circle(radius=self.inner_radius)
@@ -1088,9 +1092,11 @@ class Annulus(Circle):
self.append_points(outer_circle.points)
self.append_points(inner_circle.points)
self.shift(self.arc_center)
+ return self
- def init_points(self) -> None:
+ def init_points(self) -> Self:
self.generate_points()
+ return self
class CubicBezier(VMobject, metaclass=ConvertToOpenGL):
diff --git a/manim/mobject/geometry/line.py b/manim/mobject/geometry/line.py
index 516ef8f23..b085cdb5a 100644
--- a/manim/mobject/geometry/line.py
+++ b/manim/mobject/geometry/line.py
@@ -106,13 +106,14 @@ class Line(TipableVMobject):
self._set_start_and_end_attrs(start, end)
super().__init__(**kwargs)
- def generate_points(self) -> None:
+ def generate_points(self) -> Self:
self.set_points_by_ends(
start=self.start,
end=self.end,
buff=self.buff,
path_arc=self.path_arc,
)
+ return self
def set_points_by_ends(
self,
@@ -120,7 +121,7 @@ class Line(TipableVMobject):
end: Point3DLike | Mobject,
buff: float = 0,
path_arc: float = 0,
- ) -> None:
+ ) -> Self:
"""Sets the points of the line based on its start and end points.
Unlike :meth:`put_start_and_end_on`, this method respects `self.buff` and
Mobject bounding boxes.
@@ -144,9 +145,11 @@ class Line(TipableVMobject):
self.set_points_as_corners(np.asarray([self.start, self.end]))
self._account_for_buff(buff)
+ return self
- def init_points(self) -> None:
+ def init_points(self) -> Self:
self.generate_points()
+ return self
def _account_for_buff(self, buff: float) -> None:
if buff <= 0:
@@ -195,9 +198,10 @@ class Line(TipableVMobject):
return mob.get_boundary_point(direction)
return np.array(mob_or_point)
- def set_path_arc(self, new_value: float) -> None:
+ def set_path_arc(self, new_value: float) -> Self:
self.path_arc = new_value
self.init_points()
+ return self
def put_start_and_end_on(
self,
diff --git a/manim/mobject/graph.py b/manim/mobject/graph.py
index 96ce76172..9d064aaec 100644
--- a/manim/mobject/graph.py
+++ b/manim/mobject/graph.py
@@ -10,7 +10,7 @@ __all__ = [
import itertools as it
from collections.abc import Hashable, Iterable, Sequence
from copy import copy
-from typing import TYPE_CHECKING, Any, Literal, Protocol, cast
+from typing import TYPE_CHECKING, Any, Literal, Protocol, Self, cast
import networkx as nx
import numpy as np
@@ -31,7 +31,7 @@ from manim.mobject.mobject import Mobject, override_animate
from manim.mobject.opengl.opengl_compatibility import ConvertToOpenGL
from manim.mobject.opengl.opengl_mobject import OpenGLMobject
from manim.mobject.text.tex_mobject import MathTex
-from manim.mobject.types.vectorized_mobject import VMobject
+from manim.mobject.types.vectorized_mobject import VGroup, VMobject
from manim.utils.color import BLACK
@@ -1162,7 +1162,7 @@ class GenericGraph(VMobject, metaclass=ConvertToOpenGL):
self.remove(edge_mobject)
return edge_mobject
- def remove_edges(self, *edges: tuple[Hashable]):
+ def remove_edges(self, *edges: tuple[Hashable]) -> VGroup:
"""Remove several edges from the graph.
Parameters
@@ -1576,7 +1576,7 @@ class Graph(GenericGraph):
for (u, v) in edges
}
- def update_edges(self, graph):
+ def update_edges(self, graph) -> Self:
for (u, v), edge in graph.edges.items():
# Undirected graph has a Line edge
edge.set_points_by_ends(
@@ -1585,6 +1585,7 @@ class Graph(GenericGraph):
buff=self._edge_config.get("buff", 0),
path_arc=self._edge_config.get("path_arc", 0),
)
+ return self
def __repr__(self: Graph) -> str:
return f"Undirected graph on {len(self.vertices)} vertices and {len(self.edges)} edges"
@@ -1786,7 +1787,7 @@ class DiGraph(GenericGraph):
for (u, v), edge in self.edges.items():
edge.add_tip(**self._tip_config[(u, v)])
- def update_edges(self, graph):
+ def update_edges(self, graph) -> Self:
"""Updates the edges to stick at their corresponding vertices.
Arrow tips need to be repositioned since otherwise they can be
@@ -1803,6 +1804,7 @@ class DiGraph(GenericGraph):
path_arc=self._edge_config.get("path_arc", 0),
)
edge.add_tip(tip)
+ return self
def __repr__(self: DiGraph) -> str:
return f"Directed graph on {len(self.vertices)} vertices and {len(self.edges)} edges"
diff --git a/manim/mobject/graphing/functions.py b/manim/mobject/graphing/functions.py
index 6c27ef62d..5b2f91b1a 100644
--- a/manim/mobject/graphing/functions.py
+++ b/manim/mobject/graphing/functions.py
@@ -180,8 +180,9 @@ class ParametricFunction(VMobject, metaclass=ConvertToOpenGL):
self.make_smooth()
return self
- def init_points(self) -> None:
+ def init_points(self) -> Self:
self.generate_points()
+ return self
class FunctionGraph(ParametricFunction):
@@ -327,5 +328,6 @@ class ImplicitFunction(VMobject, metaclass=ConvertToOpenGL):
self.make_smooth()
return self
- def init_points(self) -> None:
+ def init_points(self) -> Self:
self.generate_points()
+ return self
diff --git a/manim/mobject/graphing/number_line.py b/manim/mobject/graphing/number_line.py
index 7b0a491d3..3274c71c1 100644
--- a/manim/mobject/graphing/number_line.py
+++ b/manim/mobject/graphing/number_line.py
@@ -284,7 +284,7 @@ class NumberLine(Line):
) -> Self:
return self.rotate(angle, axis, about_point=self.n2p(number), **kwargs)
- def add_ticks(self) -> None:
+ def add_ticks(self) -> Self:
"""Adds ticks to the number line. Ticks can be accessed after creation
via ``self.ticks``.
"""
@@ -300,6 +300,7 @@ class NumberLine(Line):
ticks.add(self.get_tick(x, size))
self.add(ticks)
self.ticks = ticks
+ return self
def get_tick(self, x: float, size: float | None = None) -> Line:
"""Generates a tick and positions it along the number line.
diff --git a/manim/mobject/graphing/probability.py b/manim/mobject/graphing/probability.py
index 31c8d9058..0801fda25 100644
--- a/manim/mobject/graphing/probability.py
+++ b/manim/mobject/graphing/probability.py
@@ -6,7 +6,7 @@ __all__ = ["SampleSpace", "BarChart"]
from collections.abc import Iterable, MutableSequence, Sequence
-from typing import Any, cast
+from typing import Any, Self, cast
import numpy as np
@@ -75,7 +75,7 @@ class SampleSpace(Rectangle):
def add_title(
self, title: str = "Sample space", buff: float = MED_SMALL_BUFF
- ) -> None:
+ ) -> Self:
# TODO, should this really exist in SampleSpaceScene
title_mob = Tex(title)
if title_mob.width > self.width:
@@ -83,9 +83,11 @@ class SampleSpace(Rectangle):
title_mob.next_to(self, UP, buff=buff)
self.title = title_mob
self.add(title_mob)
+ return self
- def add_label(self, label: str) -> None:
+ def add_label(self, label: str) -> Self:
self.label = label
+ return self
def complete_p_list(self, p_list: float | Iterable[float]) -> list[float]:
p_list_tuplified: tuple[float] = tuplify(p_list)
@@ -133,13 +135,15 @@ class SampleSpace(Rectangle):
) -> VGroup:
return self.get_division_along_dimension(p_list, 0, colors, vect)
- def divide_horizontally(self, *args: Any, **kwargs: Any) -> None:
+ def divide_horizontally(self, *args: Any, **kwargs: Any) -> Self:
self.horizontal_parts = self.get_horizontal_division(*args, **kwargs)
self.add(self.horizontal_parts)
+ return self
- def divide_vertically(self, *args: Any, **kwargs: Any) -> None:
+ def divide_vertically(self, *args: Any, **kwargs: Any) -> Self:
self.vertical_parts = self.get_vertical_division(*args, **kwargs)
self.add(self.vertical_parts)
+ return self
def get_subdivision_braces_and_labels(
self,
@@ -198,7 +202,7 @@ class SampleSpace(Rectangle):
parts = self.vertical_parts
return self.get_subdivision_braces_and_labels(parts, labels, DOWN, **kwargs)
- def add_braces_and_labels(self) -> None:
+ def add_braces_and_labels(self) -> Self:
for attr in "horizontal_parts", "vertical_parts":
if not hasattr(self, attr):
continue
@@ -206,6 +210,7 @@ class SampleSpace(Rectangle):
for subattr in "braces", "labels":
if hasattr(parts, subattr):
self.add(getattr(parts, subattr))
+ return self
def __getitem__(self, index: Any) -> VMobject:
if hasattr(self, "horizontal_parts"):
@@ -481,7 +486,7 @@ class BarChart(Axes):
def change_bar_values(
self, values: Iterable[float], update_colors: bool = True
- ) -> None:
+ ) -> Self:
"""Updates the height of the bars of the chart.
Parameters
@@ -548,3 +553,4 @@ class BarChart(Axes):
self._update_colors()
self.values[: len(list(values))] = values
+ return self
diff --git a/manim/mobject/logo.py b/manim/mobject/logo.py
index 3cdab467f..505ac5f4f 100644
--- a/manim/mobject/logo.py
+++ b/manim/mobject/logo.py
@@ -4,7 +4,7 @@ from __future__ import annotations
__all__ = ["ManimBanner"]
-from typing import Any
+from typing import Any, Self
import svgelements as se
@@ -184,7 +184,7 @@ class ManimBanner(VGroup):
# and thus not yet added to the submobjects of self.
self.anim = anim
- def scale(self, scale_factor: float, **kwargs: Any) -> ManimBanner:
+ def scale(self, scale_factor: float, **kwargs: Any) -> Self:
"""Scale the banner by the specified scale factor.
Parameters
diff --git a/manim/mobject/mobject.py b/manim/mobject/mobject.py
index 589711bc6..6b61aadf9 100644
--- a/manim/mobject/mobject.py
+++ b/manim/mobject/mobject.py
@@ -458,19 +458,21 @@ class Mobject:
self.points = np.zeros((0, self.dim))
return self
- def init_colors(self, propagate_colors: bool = True) -> object:
+ def init_colors(self, propagate_colors: bool = True) -> Self:
"""Initializes the colors.
Gets called upon creation. This is an empty method that can be implemented by
subclasses.
"""
+ return self
- def generate_points(self) -> object:
+ def generate_points(self) -> Self:
"""Initializes :attr:`points` and therefore the shape.
Gets called upon creation. This is an empty method that can be implemented by
subclasses.
"""
+ return self
def add(self, *mobjects: Mobject) -> Self:
"""Add mobjects as submobjects.
@@ -560,7 +562,7 @@ class Mobject:
self.submobjects = list_update(self.submobjects, unique_mobjects)
return self
- def insert(self, index: int, mobject: Mobject) -> None:
+ def insert(self, index: int, mobject: Mobject) -> Self:
"""Inserts a mobject at a specific position into self.submobjects
Effectively just calls ``self.submobjects.insert(index, mobject)``,
@@ -577,6 +579,7 @@ class Mobject:
"""
self._assert_valid_submobjects([mobject])
self.submobjects.insert(index, mobject)
+ return self
def __add__(self, mobject: Mobject) -> Self:
raise NotImplementedError
@@ -1232,7 +1235,7 @@ class Mobject:
# Transforming operations
- def apply_to_family(self, func: Callable[[Mobject], None]) -> None:
+ def apply_to_family(self, func: Callable[[Mobject], None]) -> Self:
"""Apply a function to ``self`` and every submobject with points recursively.
Parameters
@@ -1254,6 +1257,8 @@ class Mobject:
for mob in self.family_members_with_points():
func(mob)
+ return self
+
def shift(self, *vectors: Vector3DLike) -> Self:
"""Shift by the given vectors.
@@ -2889,14 +2894,15 @@ class Mobject:
self.submobjects.sort(key=submob_func)
return self
- def shuffle(self, recursive: bool = False) -> None:
+ def shuffle(self, recursive: bool = False) -> Self:
"""Shuffles the list of :attr:`submobjects`."""
if recursive:
for submob in self.submobjects:
submob.shuffle(recursive=True)
random.shuffle(self.submobjects)
+ return self
- def invert(self, recursive: bool = False) -> None:
+ def invert(self, recursive: bool = False) -> Self:
"""Inverts the list of :attr:`submobjects`.
Parameters
@@ -2921,6 +2927,7 @@ class Mobject:
for submob in self.submobjects:
submob.invert(recursive=True)
self.submobjects.reverse()
+ return self
# Just here to keep from breaking old scenes.
def arrange_submobjects(self, *args: Any, **kwargs: Any) -> Self:
@@ -2948,7 +2955,7 @@ class Mobject:
"""Sort the :attr:`submobjects`"""
return self.sort(*args, **kwargs)
- def shuffle_submobjects(self, *args: Any, **kwargs: Any) -> None:
+ def shuffle_submobjects(self, *args: Any, **kwargs: Any) -> Self:
"""Shuffles the order of :attr:`submobjects`
Examples
@@ -2967,7 +2974,7 @@ class Mobject:
return self.shuffle(*args, **kwargs)
# Alignment
- def align_data(self, mobject: Mobject, skip_point_alignment: bool = False) -> None:
+ def align_data(self, mobject: Mobject, skip_point_alignment: bool = False) -> Self:
"""Aligns the family structure and data of this mobject with another mobject.
Afterwards, the two mobjects will have the same number of submobjects
@@ -2998,6 +3005,7 @@ class Mobject:
>>> rect = Rectangle(width=4.0, height=2.0, grid_xstep=1.0, grid_ystep=0.5)
>>> line = Line(start=ORIGIN,end=RIGHT)
>>> line.align_data(rect)
+ Line
>>> len(line.get_family()) == len(rect.get_family())
True
>>> line.get_num_points() == rect.get_num_points()
@@ -3015,6 +3023,7 @@ class Mobject:
# Recurse
for m1, m2 in zip(self.submobjects, mobject.submobjects, strict=True):
m1.align_data(m2)
+ return self
def get_point_mobject(self, center: Point3DLike | None = None) -> Point:
"""The simplest :class:`~.Mobject` to be transformed to or from self.
@@ -3032,7 +3041,7 @@ class Mobject:
mobject.align_points_with_larger(self)
return self
- def align_points_with_larger(self, larger_mobject: Mobject) -> None:
+ def align_points_with_larger(self, larger_mobject: Mobject) -> Self:
raise NotImplementedError("Please override in a child class.")
def align_submobjects(self, mobject: Mobject) -> Self:
@@ -3167,7 +3176,7 @@ class Mobject:
def interpolate_color(
self, mobject1: Mobject, mobject2: Mobject, alpha: float
- ) -> None:
+ ) -> Self:
raise NotImplementedError("Please override in a child class.")
def become(
diff --git a/manim/mobject/opengl/dot_cloud.py b/manim/mobject/opengl/dot_cloud.py
index 3ba440ebe..76935588a 100644
--- a/manim/mobject/opengl/dot_cloud.py
+++ b/manim/mobject/opengl/dot_cloud.py
@@ -27,7 +27,7 @@ class DotCloud(OpenGLPMobject):
stroke_width=stroke_width, density=density, color=color, **kwargs
)
- def init_points(self) -> None:
+ def init_points(self) -> Self:
self.points = np.array(
[
r * (np.cos(theta) * RIGHT + np.sin(theta) * UP)
@@ -41,6 +41,7 @@ class DotCloud(OpenGLPMobject):
],
dtype=np.float32,
)
+ return self
def make_3d(self, gloss: float = 0.5, shadow: float = 0.2) -> Self:
self.set_gloss(gloss)
diff --git a/manim/mobject/opengl/opengl_geometry.py b/manim/mobject/opengl/opengl_geometry.py
index 6b09a82e2..6028de126 100644
--- a/manim/mobject/opengl/opengl_geometry.py
+++ b/manim/mobject/opengl/opengl_geometry.py
@@ -255,7 +255,7 @@ class OpenGLArc(OpenGLTipableVMobject):
super().__init__(**kwargs)
self.orientation = -1
- def init_points(self) -> None:
+ def init_points(self) -> Self:
self.set_points(
OpenGLArc.create_quadratic_bezier_points(
angle=self.angle,
@@ -266,6 +266,7 @@ class OpenGLArc(OpenGLTipableVMobject):
# To maintain proper orientation for fill shaders.
self.scale(self.radius, about_point=ORIGIN)
self.shift(self.arc_center)
+ return self
@staticmethod
def create_quadratic_bezier_points(
@@ -420,7 +421,7 @@ class OpenGLAnnularSector(OpenGLArc):
**kwargs,
)
- def init_points(self) -> None:
+ def init_points(self) -> Self:
inner_arc, outer_arc = (
OpenGLArc(
start_angle=self.start_angle,
@@ -435,6 +436,7 @@ class OpenGLAnnularSector(OpenGLArc):
self.add_line_to(outer_arc.points[0])
self.append_points(outer_arc.points)
self.add_line_to(inner_arc.points[0])
+ return self
class OpenGLSector(OpenGLAnnularSector):
@@ -460,7 +462,7 @@ class OpenGLAnnulus(OpenGLCircle):
fill_opacity=fill_opacity, stroke_width=stroke_width, color=color, **kwargs
)
- def init_points(self) -> None:
+ def init_points(self) -> Self:
self.radius = self.outer_radius
outer_circle = OpenGLCircle(radius=self.outer_radius)
inner_circle = OpenGLCircle(radius=self.inner_radius)
@@ -468,6 +470,7 @@ class OpenGLAnnulus(OpenGLCircle):
self.append_points(outer_circle.points)
self.append_points(inner_circle.points)
self.shift(self.arc_center)
+ return self
class OpenGLLine(OpenGLTipableVMobject):
@@ -485,22 +488,25 @@ class OpenGLLine(OpenGLTipableVMobject):
self.set_start_and_end_attrs(start, end)
super().__init__(**kwargs)
- def init_points(self) -> None:
+ def init_points(self) -> Self:
self.set_points_by_ends(self.start, self.end, self.buff, self.path_arc)
+ return self
def set_points_by_ends(
self, start: Point3DLike, end: Point3DLike, buff: float = 0, path_arc: float = 0
- ) -> None:
+ ) -> Self:
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)
+ return self
- def set_path_arc(self, new_value: float) -> None:
+ def set_path_arc(self, new_value: float) -> Self:
self.path_arc = new_value
self.init_points()
+ return self
def account_for_buff(self, buff: float) -> Self:
if buff == 0:
@@ -516,7 +522,7 @@ class OpenGLLine(OpenGLTipableVMobject):
def set_start_and_end_attrs(
self, start: Mobject | Point3DLike, end: Mobject | Point3DLike
- ) -> None:
+ ) -> Self:
# If either start or end are Mobjects, this
# gives their centers
rough_start = self.pointify(start)
@@ -527,6 +533,7 @@ class OpenGLLine(OpenGLTipableVMobject):
# 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
+ return self
def pointify(
self, mob_or_point: Mobject | Point3DLike, direction: Vector3DLike = None
@@ -581,8 +588,9 @@ class OpenGLLine(OpenGLTipableVMobject):
)
return self
- def set_length(self, length: float) -> None:
+ def set_length(self, length: float) -> Self:
self.scale(length / self.get_length())
+ return self
class OpenGLDashedLine(OpenGLLine):
@@ -693,7 +701,7 @@ class OpenGLArrow(OpenGLLine):
def set_points_by_ends(
self, start: Point3DLike, end: Point3DLike, buff: float = 0, path_arc: float = 0
- ) -> None:
+ ) -> Self:
# Find the right tip length and thickness
vect = np.asarray(end) - np.asarray(start)
length = max(np.linalg.norm(vect), 1e-8)
@@ -755,6 +763,7 @@ class OpenGLArrow(OpenGLLine):
)
self.shift(start - self.get_start())
self.refresh_triangulation()
+ return self
def reset_points_around_ends(self) -> Self:
self.set_points_by_ends(
@@ -786,10 +795,10 @@ class OpenGLArrow(OpenGLLine):
self.reset_points_around_ends()
return self
- def set_path_arc(self, path_arc: float) -> None:
+ def set_path_arc(self, path_arc: float) -> Self:
self.path_arc = path_arc
self.reset_points_around_ends()
- # return self
+ return self
class OpenGLVector(OpenGLArrow):
@@ -829,9 +838,10 @@ class OpenGLPolygon(OpenGLVMobject):
self.vertices: Point3D_Array = np.array(vertices)
super().__init__(**kwargs)
- def init_points(self) -> None:
+ def init_points(self) -> Self:
verts = self.vertices
self.set_points_as_corners([*verts, verts[0]])
+ return self
def get_vertices(self) -> Point3D_Array:
return self.get_start_anchors()
diff --git a/manim/mobject/opengl/opengl_mobject.py b/manim/mobject/opengl/opengl_mobject.py
index e624dc2e5..25fdf8b46 100644
--- a/manim/mobject/opengl/opengl_mobject.py
+++ b/manim/mobject/opengl/opengl_mobject.py
@@ -358,29 +358,31 @@ class OpenGLMobject:
else:
cls.__init__ = cls._original__init__
- def init_data(self) -> None:
+ def init_data(self) -> Self:
"""Initializes the ``points``, ``bounding_box`` and ``rgbas`` attributes and groups them into self.data.
Subclasses can inherit and overwrite this method to extend `self.data`.
"""
self.points = np.zeros((0, 3))
self.bounding_box = np.zeros((3, 3))
self.rgbas = np.zeros((1, 4))
+ return self
- def init_colors(self) -> None:
+ def init_colors(self) -> Self:
"""Initializes the colors.
Gets called upon creation
"""
self.set_color(self.color, self.opacity)
+ return self
- def init_points(self) -> None:
+ def init_points(self) -> Self:
"""Initializes :attr:`points` and therefore the shape.
Gets called upon creation. This is an empty method that can be implemented by
subclasses.
"""
# Typically implemented in subclass, unless purposefully left blank
- pass
+ return self
def set(self, **kwargs: object) -> Self:
"""Sets attributes.
@@ -1423,7 +1425,7 @@ class OpenGLMobject:
# Copying
- def copy(self, shallow: bool = False) -> OpenGLMobject:
+ def copy(self, shallow: bool = False) -> Self:
"""Create and return an identical copy of the :class:`OpenGLMobject` including all
:attr:`submobjects`.
@@ -1481,14 +1483,14 @@ class OpenGLMobject:
# setattr(copy_mobject, attr, value.copy())
return copy_mobject
- def deepcopy(self) -> OpenGLMobject:
+ def deepcopy(self) -> Self:
parents = self.parents
self.parents = []
result = copy.deepcopy(self)
self.parents = parents
return result
- def generate_target(self, use_deepcopy: bool = False) -> OpenGLMobject:
+ def generate_target(self, use_deepcopy: bool = False) -> Self:
self.target: OpenGLMobject | None = None # Prevent exponential explosion
if use_deepcopy:
self.target = self.deepcopy()
@@ -1516,11 +1518,12 @@ class OpenGLMobject:
# Updating
- def init_updaters(self) -> None:
+ def init_updaters(self) -> Self:
self.time_based_updaters: list["_TimeBasedUpdater"] = [] # noqa: UP037
self.non_time_updaters: list["_NonTimeBasedUpdater"] = [] # noqa: UP037
self.has_updaters: bool = False
self.updating_suspended: bool = False
+ return self
def update(self, dt: float = 0, recurse: bool = True) -> Self:
if self.has_updaters and not self.updating_suspended:
@@ -2796,7 +2799,7 @@ class OpenGLMobject:
# Locking data
- def lock_data(self, keys: Iterable[str]) -> None:
+ def lock_data(self, keys: Iterable[str]) -> Self:
"""
To speed up some animations, particularly transformations,
it can be handy to acknowledge which pieces of data
@@ -2805,10 +2808,11 @@ class OpenGLMobject:
read into the shader_wrapper objects needlessly
"""
if self.has_updaters:
- return
+ return self
# Be sure shader data has most up to date information
self.refresh_shader_data()
self.locked_data_keys = set(keys)
+ return self
def lock_matching_data(
self, mobject1: OpenGLMobject, mobject2: OpenGLMobject
@@ -2830,9 +2834,10 @@ class OpenGLMobject:
)
return self
- def unlock_data(self) -> None:
+ def unlock_data(self) -> Self:
for mob in self.get_family():
mob.locked_data_keys = set()
+ return self
# Operations touching shader uniforms
@@ -2977,19 +2982,21 @@ class OpenGLMobject:
shader_data: _ShaderData, # has structured data type, ex. ("point", np.float32, (3,))
shader_data_key: str,
data_key: str,
- ) -> None:
+ ) -> Self:
if data_key in self.locked_data_keys:
- return
+ return self
self.check_data_alignment(shader_data, data_key)
shader_data[shader_data_key] = self.data[data_key]
+ return self
def get_shader_data(self) -> _ShaderData:
shader_data = self.get_resized_shader_data_array(self.get_num_points())
self.read_data_to_shader(shader_data, "point", "points")
return shader_data
- def refresh_shader_data(self) -> None:
+ def refresh_shader_data(self) -> Self:
self.get_shader_data()
+ return self
def get_shader_uniforms(self) -> dict[str, Any]:
return self.uniforms
@@ -3051,8 +3058,9 @@ class OpenGLPoint(OpenGLMobject):
def get_bounding_box_point(self, *args: object, **kwargs: Any) -> Point3D:
return self.get_location()
- def set_location(self, new_loc: Point3DLike) -> None:
+ def set_location(self, new_loc: Point3DLike) -> Self:
self.set_points(np.array(new_loc, ndmin=2, dtype=float))
+ return self
class _AnimationBuilder:
diff --git a/manim/mobject/opengl/opengl_point_cloud_mobject.py b/manim/mobject/opengl/opengl_point_cloud_mobject.py
index 03e07b547..69a3d69a6 100644
--- a/manim/mobject/opengl/opengl_point_cloud_mobject.py
+++ b/manim/mobject/opengl/opengl_point_cloud_mobject.py
@@ -93,7 +93,7 @@ class OpenGLPMobject(OpenGLMobject):
self.rgbas = np.append(self.rgbas, new_rgbas, axis=0)
return self
- def thin_out(self, factor=5):
+ def thin_out(self, factor=5) -> Self:
"""Removes all but every nth point for n = factor"""
for mob in self.family_members_with_points():
num_points = mob.get_num_points()
@@ -107,7 +107,7 @@ class OpenGLPMobject(OpenGLMobject):
return self
- def set_color_by_gradient(self, *colors):
+ def set_color_by_gradient(self, *colors) -> Self:
self.rgbas = np.array(
list(map(color_to_rgba, color_gradient(*colors, self.get_num_points()))),
)
@@ -119,7 +119,7 @@ class OpenGLPMobject(OpenGLMobject):
radius=1,
inner_color=WHITE,
outer_color=BLACK,
- ):
+ ) -> Self:
start_rgba, end_rgba = list(map(color_to_rgba, [inner_color, outer_color]))
if center is None:
center = self.get_center()
@@ -134,25 +134,25 @@ class OpenGLPMobject(OpenGLMobject):
)
return self
- def match_colors(self, pmobject):
+ def match_colors(self, pmobject) -> Self:
self.rgbas[:] = resize_with_interpolation(pmobject.rgbas, self.get_num_points())
return self
- def fade_to(self, color, alpha, family=True):
+ def fade_to(self, color, alpha, family=True) -> Self:
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):
+ def filter_out(self, condition) -> Self:
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]):
+ def sort_points(self, function=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))
@@ -160,7 +160,7 @@ class OpenGLPMobject(OpenGLMobject):
mob.data[key] = mob.data[key][indices]
return self
- def ingest_submobjects(self):
+ def ingest_submobjects(self) -> Self:
for key in self.data:
self.data[key] = np.vstack([sm.data[key] for sm in self.get_family()])
return self
@@ -169,7 +169,7 @@ class OpenGLPMobject(OpenGLMobject):
index = alpha * (self.get_num_points() - 1)
return self.points[int(index)]
- def pointwise_become_partial(self, pmobject, a, b):
+ def pointwise_become_partial(self, pmobject, a, b) -> Self:
lower_index = int(a * pmobject.get_num_points())
upper_index = int(b * pmobject.get_num_points())
for key in self.data:
@@ -194,10 +194,11 @@ class OpenGLPGroup(OpenGLPMobject):
super().__init__(**kwargs)
self.add(*pmobs)
- def fade_to(self, color, alpha, family=True):
+ def fade_to(self, color, alpha, family=True) -> Self:
if family:
for mob in self.submobjects:
mob.fade_to(color, alpha, family)
+ return self
class OpenGLPMPoint(OpenGLPMobject):
@@ -205,5 +206,6 @@ class OpenGLPMPoint(OpenGLPMobject):
self.location = location
super().__init__(stroke_width=stroke_width, **kwargs)
- def init_points(self):
+ def init_points(self) -> Self:
self.points = np.array([self.location], dtype=np.float32)
+ return self
diff --git a/manim/mobject/opengl/opengl_surface.py b/manim/mobject/opengl/opengl_surface.py
index 27084635c..e7648398d 100644
--- a/manim/mobject/opengl/opengl_surface.py
+++ b/manim/mobject/opengl/opengl_surface.py
@@ -2,7 +2,7 @@ from __future__ import annotations
from collections.abc import Iterable
from pathlib import Path
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Self
import moderngl
import numpy as np
@@ -124,7 +124,7 @@ class OpenGLSurface(OpenGLMobject):
return self.passed_uv_func(u, v)
return (u, v, 0.0)
- def init_points(self):
+ def init_points(self) -> Self:
dim = self.dim
nu, nv = self.resolution
u_range = np.linspace(*self.u_range, nu)
@@ -144,15 +144,16 @@ class OpenGLSurface(OpenGLMobject):
# can perform all the manipulations they'd like to the surface, and normals
# are still easily recoverable.
self.set_points(np.vstack(point_lists))
+ return self
- def compute_triangle_indices(self):
+ def compute_triangle_indices(self) -> 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
+ return self
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
@@ -162,6 +163,7 @@ class OpenGLSurface(OpenGLMobject):
indices[4::6] = index_grid[+1:, :-1].flatten() # Bottom left
indices[5::6] = index_grid[+1:, +1:].flatten() # Bottom right
self.triangle_indices = indices
+ return self
def get_triangle_indices(self):
return self.triangle_indices
@@ -181,7 +183,7 @@ class OpenGLSurface(OpenGLMobject):
)
return normalize_along_axis(normals, 1)
- def pointwise_become_partial(self, smobject, a, b, axis=None):
+ def pointwise_become_partial(self, smobject, a, b, axis=None) -> Self:
assert isinstance(smobject, OpenGLSurface)
if axis is None:
axis = self.prefered_creation_axis
@@ -239,7 +241,7 @@ class OpenGLSurface(OpenGLMobject):
).reshape(shape)
return points.reshape((nu * nv, *resolution[2:]))
- def sort_faces_back_to_front(self, vect=OUT):
+ def sort_faces_back_to_front(self, vect=OUT) -> Self:
tri_is = self.triangle_indices
indices = list(range(len(tri_is) // 3))
points = self.points
@@ -359,8 +361,9 @@ class OpenGLSurfaceGroup(OpenGLSurface):
super().__init__(uv_func=None, **kwargs)
self.add(*parametric_surfaces)
- def init_points(self):
- pass # Needed?
+ def init_points(self) -> Self:
+ # Needed?
+ return self
class OpenGLTexturedSurface(OpenGLSurface):
@@ -425,12 +428,13 @@ class OpenGLTexturedSurface(OpenGLSurface):
image_file = get_full_raster_image_path(image_file)
return Image.open(image_file).convert(image_mode)
- def init_data(self):
+ def init_data(self) -> Self:
super().init_data()
self.im_coords = np.zeros((0, 2))
self.opacity = np.zeros((0, 1))
+ return self
- def init_points(self):
+ def init_points(self) -> Self:
nu, nv = self.uv_surface.resolution
self.set_points(self.uv_surface.points)
self.im_coords = np.array(
@@ -440,16 +444,18 @@ class OpenGLTexturedSurface(OpenGLSurface):
for v in np.linspace(1, 0, nv) # Reverse y-direction
],
)
+ return self
- def init_colors(self):
+ def init_colors(self) -> Self:
self.opacity = np.array([self.uv_surface.rgbas[:, 3]])
+ return self
- def set_opacity(self, opacity, recurse=True):
+ def set_opacity(self, opacity, recurse=True) -> Self:
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):
+ def pointwise_become_partial(self, tsmobject, a, b, axis=1) -> Self:
super().pointwise_become_partial(tsmobject, a, b, axis)
im_coords = self.im_coords
im_coords[:] = tsmobject.im_coords
diff --git a/manim/mobject/opengl/opengl_three_dimensions.py b/manim/mobject/opengl/opengl_three_dimensions.py
index 56ed68a41..896c9e4e7 100644
--- a/manim/mobject/opengl/opengl_three_dimensions.py
+++ b/manim/mobject/opengl/opengl_three_dimensions.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-from typing import Any
+from typing import Any, Self
import numpy as np
@@ -33,7 +33,7 @@ class OpenGLSurfaceMesh(OpenGLVGroup):
**kwargs,
)
- def init_points(self) -> None:
+ def init_points(self) -> Self:
uv_surface = self.uv_surface
full_nu, full_nv = uv_surface.resolution
@@ -54,3 +54,5 @@ class OpenGLSurfaceMesh(OpenGLVGroup):
path = OpenGLVMobject()
path.set_points_smoothly(nudged_points[vi::full_nv])
self.add(path)
+
+ return self
diff --git a/manim/mobject/opengl/opengl_vectorized_mobject.py b/manim/mobject/opengl/opengl_vectorized_mobject.py
index c805ebb37..5c3958616 100644
--- a/manim/mobject/opengl/opengl_vectorized_mobject.py
+++ b/manim/mobject/opengl/opengl_vectorized_mobject.py
@@ -184,16 +184,17 @@ class OpenGLVMobject(OpenGLMobject):
self.remove(*self.submobjects)
self.add(*submobject_list)
- def init_data(self):
+ def init_data(self) -> Self:
super().init_data()
self.data.pop("rgbas")
self.fill_rgba = np.zeros((1, 4))
self.stroke_rgba = np.zeros((1, 4))
self.unit_normal = np.zeros((1, 3))
# stroke_width belongs to self.data, but is defined through init_colors+set_stroke
+ return self
# Colors
- def init_colors(self):
+ def init_colors(self) -> Self:
self.set_fill(
color=self.fill_color or self.color,
opacity=self.fill_opacity,
@@ -213,7 +214,7 @@ class OpenGLVMobject(OpenGLMobject):
color: ParsableManimColor | None = None,
opacity: float | None = None,
recurse: bool = True,
- ) -> OpenGLVMobject:
+ ) -> Self:
"""Set the fill color and fill opacity of a :class:`OpenGLVMobject`.
Parameters
@@ -265,7 +266,7 @@ class OpenGLVMobject(OpenGLMobject):
opacity=None,
background=None,
recurse=True,
- ):
+ ) -> Self:
if opacity is not None:
self.stroke_opacity = opacity
if recurse:
@@ -304,7 +305,7 @@ class OpenGLVMobject(OpenGLMobject):
gloss=None,
shadow=None,
recurse=True,
- ):
+ ) -> Self:
if fill_rgba is not None:
self.fill_rgba = resize_with_interpolation(fill_rgba, len(fill_rgba))
else:
@@ -336,7 +337,7 @@ class OpenGLVMobject(OpenGLMobject):
"shadow": self.shadow,
}
- def match_style(self, vmobject, recurse=True):
+ def match_style(self, vmobject, recurse=True) -> Self:
vmobject_style = vmobject.get_style()
if config.renderer == RendererType.OPENGL:
vmobject_style["stroke_width"] = vmobject_style["stroke_width"][0][0]
@@ -354,7 +355,7 @@ class OpenGLVMobject(OpenGLMobject):
sm1.match_style(sm2)
return self
- def set_color(self, color, opacity=None, recurse=True):
+ def set_color(self, color, opacity=None, recurse=True) -> Self:
if opacity is not None:
self.opacity = opacity
@@ -362,12 +363,12 @@ class OpenGLVMobject(OpenGLMobject):
self.set_stroke(color, opacity=opacity, recurse=recurse)
return self
- def set_opacity(self, opacity, recurse=True):
+ def set_opacity(self, opacity, recurse=True) -> Self:
self.set_fill(opacity=opacity, recurse=recurse)
self.set_stroke(opacity=opacity, recurse=recurse)
return self
- def fade(self, darkness=0.5, recurse=True):
+ def fade(self, darkness=0.5, recurse=True) -> Self:
factor = 1.0 - darkness
self.set_fill(
opacity=factor * self.get_fill_opacity(),
@@ -454,7 +455,7 @@ class OpenGLVMobject(OpenGLMobject):
return self.get_fill_opacity()
return self.get_stroke_opacity()
- def set_flat_stroke(self, flat_stroke=True, recurse=True):
+ def set_flat_stroke(self, flat_stroke=True, recurse=True) -> Self:
for mob in self.get_family(recurse):
mob.flat_stroke = flat_stroke
return self
@@ -463,7 +464,7 @@ class OpenGLVMobject(OpenGLMobject):
return self.flat_stroke
# Points
- def set_anchors_and_handles(self, anchors1, handles, anchors2):
+ def set_anchors_and_handles(self, anchors1, handles, anchors2) -> Self:
assert len(anchors1) == len(handles) == len(anchors2)
nppc = self.n_points_per_curve
new_points = np.zeros((nppc * len(anchors1), self.dim))
@@ -473,7 +474,7 @@ class OpenGLVMobject(OpenGLMobject):
self.set_points(new_points)
return self
- def start_new_path(self, point):
+ def start_new_path(self, point) -> Self:
assert self.get_num_points() % self.n_points_per_curve == 0
self.append_points([point])
return self
@@ -484,7 +485,7 @@ class OpenGLVMobject(OpenGLMobject):
handle1: Point3DLike,
handle2: Point3DLike,
anchor2: Point3DLike,
- ):
+ ) -> Self:
new_points = get_quadratic_approximation_of_cubic(
anchor1,
handle1,
@@ -492,8 +493,9 @@ class OpenGLVMobject(OpenGLMobject):
anchor2,
)
self.append_points(new_points)
+ return self
- def add_cubic_bezier_curve_to(self, handle1, handle2, anchor):
+ def add_cubic_bezier_curve_to(self, handle1, handle2, anchor) -> Self:
"""Add cubic bezier curve to the path."""
self.throw_error_if_no_points()
quadratic_approx = get_quadratic_approximation_of_cubic(
@@ -506,15 +508,17 @@ class OpenGLVMobject(OpenGLMobject):
self.append_points(quadratic_approx[1:])
else:
self.append_points(quadratic_approx)
+ return self
- def add_quadratic_bezier_curve_to(self, handle, anchor):
+ def add_quadratic_bezier_curve_to(self, handle, anchor) -> Self:
self.throw_error_if_no_points()
if self.has_new_path_started():
self.append_points([handle, anchor])
else:
self.append_points([self.get_last_point(), handle, anchor])
+ return self
- def add_line_to(self, point: Sequence[float]) -> OpenGLVMobject:
+ def add_line_to(self, point: Sequence[float]) -> Self:
"""Add a straight line from the last point of OpenGLVMobject to the given point.
Parameters
@@ -537,7 +541,7 @@ class OpenGLVMobject(OpenGLMobject):
self.append_points(points)
return self
- def add_smooth_curve_to(self, point):
+ def add_smooth_curve_to(self, point) -> Self:
if self.has_new_path_started():
self.add_line_to(point)
else:
@@ -546,10 +550,11 @@ class OpenGLVMobject(OpenGLMobject):
self.add_quadratic_bezier_curve_to(new_handle, point)
return self
- def add_smooth_cubic_curve_to(self, handle, point):
+ def add_smooth_cubic_curve_to(self, handle, point) -> Self:
self.throw_error_if_no_points()
new_handle = self.get_reflection_of_last_handle()
self.add_cubic_bezier_curve_to(new_handle, handle, point)
+ return self
def has_new_path_started(self):
return self.get_num_points() % self.n_points_per_curve == 1
@@ -561,14 +566,17 @@ class OpenGLVMobject(OpenGLMobject):
points = self.points
return 2 * points[-1] - points[-2]
- def close_path(self):
+ def close_path(self) -> Self:
if not self.is_closed():
self.add_line_to(self.get_subpaths()[-1][0])
+ return self
def is_closed(self):
return self.consider_points_equals(self.points[0], self.points[-1])
- def subdivide_sharp_curves(self, angle_threshold=30 * DEGREES, recurse=True):
+ def subdivide_sharp_curves(
+ self, angle_threshold=30 * DEGREES, recurse=True
+ ) -> Self:
vmobs = [vm for vm in self.get_family(recurse) if vm.has_points()]
for vmob in vmobs:
new_points = []
@@ -588,12 +596,12 @@ class OpenGLVMobject(OpenGLMobject):
vmob.set_points(np.vstack(new_points))
return self
- def add_points_as_corners(self, points):
+ def add_points_as_corners(self, points) -> Self:
for point in points:
self.add_line_to(point)
- return points
+ return self
- def set_points_as_corners(self, points: Point3DLike_Array) -> OpenGLVMobject:
+ def set_points_as_corners(self, points: Point3DLike_Array) -> Self:
"""Given an array of points, set them as corner of the vmobject.
To achieve that, this algorithm sets handles aligned with the anchors such that the resultant bezier curve will be the segment
@@ -623,7 +631,7 @@ class OpenGLVMobject(OpenGLMobject):
self.make_smooth()
return self
- def change_anchor_mode(self, mode):
+ def change_anchor_mode(self, mode) -> Self:
"""Changes the anchor mode of the bezier curves. This will modify the handles.
There can be only three modes, "jagged", "approx_smooth" and "true_smooth".
@@ -660,7 +668,7 @@ class OpenGLVMobject(OpenGLMobject):
submob.refresh_triangulation()
return self
- def make_smooth(self):
+ def make_smooth(self) -> Self:
"""
This will double the number of points in the mobject,
so should not be called repeatedly. It also means
@@ -670,7 +678,7 @@ class OpenGLVMobject(OpenGLMobject):
self.change_anchor_mode("true_smooth")
return self
- def make_approximately_smooth(self):
+ def make_approximately_smooth(self) -> Self:
"""
Unlike make_smooth, this will not change the number of
points, but it also does not result in a perfectly smooth
@@ -681,16 +689,16 @@ class OpenGLVMobject(OpenGLMobject):
self.change_anchor_mode("approx_smooth")
return self
- def make_jagged(self):
+ def make_jagged(self) -> Self:
self.change_anchor_mode("jagged")
return self
- def add_subpath(self, points):
+ def add_subpath(self, points) -> Self:
assert len(points) % self.n_points_per_curve == 0
self.append_points(points)
return self
- def append_vectorized_mobject(self, vectorized_mobject):
+ def append_vectorized_mobject(self, vectorized_mobject) -> Self:
new_points = list(vectorized_mobject.points)
if self.has_new_path_started():
@@ -705,7 +713,7 @@ class OpenGLVMobject(OpenGLMobject):
return np.linalg.norm(p1 - p0) < self.tolerance_for_point_equality
# Information about the curve
- def force_direction(self, target_direction: str):
+ def force_direction(self, target_direction: str) -> Self:
"""Makes sure that points are either directed clockwise or
counterclockwise.
@@ -722,7 +730,7 @@ class OpenGLVMobject(OpenGLMobject):
return self
- def reverse_direction(self):
+ def reverse_direction(self) -> Self:
"""Reverts the point direction by inverting the point order.
Returns
@@ -1193,16 +1201,16 @@ class OpenGLVMobject(OpenGLMobject):
points[2] - points[1],
)
- def refresh_unit_normal(self):
+ def refresh_unit_normal(self) -> Self:
for mob in self.get_family():
mob.unit_normal[:] = mob.get_unit_normal(recompute=True)
return self
# Alignment
- def align_points(self, vmobject):
+ def align_points(self, vmobject) -> Self:
# TODO: This shortcut can be a bit over eager. What if they have the same length, but different subpath lengths?
if self.get_num_points() == len(vmobject.points):
- return
+ return self
for mob in self, vmobject:
# If there are no points, add one to
@@ -1254,7 +1262,7 @@ class OpenGLVMobject(OpenGLMobject):
vmobject.set_points(np.vstack(new_subpaths2))
return self
- def insert_n_curves(self, n: int, recurse=True) -> OpenGLVMobject:
+ def insert_n_curves(self, n: int, recurse=True) -> Self:
"""Inserts n curves to the bezier curves of the vmobject.
Parameters
@@ -1304,7 +1312,7 @@ class OpenGLVMobject(OpenGLMobject):
new_points = new_bezier_tuples.reshape(-1, 3)
return new_points
- def interpolate(self, mobject1, mobject2, alpha, *args, **kwargs):
+ def interpolate(self, mobject1, mobject2, alpha, *args, **kwargs) -> Self:
super().interpolate(mobject1, mobject2, alpha, *args, **kwargs)
if config["use_projection_fill_shaders"]:
self.refresh_triangulation()
@@ -1318,7 +1326,7 @@ class OpenGLVMobject(OpenGLMobject):
def pointwise_become_partial(
self, vmobject: OpenGLVMobject, a: float, b: float, remap: bool = True
- ) -> OpenGLVMobject:
+ ) -> Self:
"""Given two bounds a and b, transforms the points of the self vmobject into the points of the vmobject
passed as parameter with respect to the bounds. Points here stand for control points of the bezier curves (anchors and handles)
@@ -1467,35 +1475,35 @@ class OpenGLVMobject(OpenGLMobject):
return tri_indices
@triggers_refreshed_triangulation
- def set_points(self, points):
+ def set_points(self, points) -> Self:
super().set_points(points)
return self
@triggers_refreshed_triangulation
- def set_data(self, data):
+ def set_data(self, data) -> Self:
super().set_data(data)
return self
# TODO, how to be smart about tangents here?
@triggers_refreshed_triangulation
- def apply_function(self, function, make_smooth=False, **kwargs):
+ def apply_function(self, function, make_smooth=False, **kwargs) -> Self:
super().apply_function(function, **kwargs)
if self.make_smooth_after_applying_functions or make_smooth:
self.make_approximately_smooth()
return self
@triggers_refreshed_triangulation
- def apply_points_function(self, *args, **kwargs):
+ def apply_points_function(self, *args, **kwargs) -> Self:
super().apply_points_function(*args, **kwargs)
return self
@triggers_refreshed_triangulation
- def flip(self, *args, **kwargs):
+ def flip(self, *args, **kwargs) -> Self:
super().flip(*args, **kwargs)
return self
# For shaders
- def init_shader_data(self):
+ def init_shader_data(self) -> Self:
self.fill_data = np.zeros(0, dtype=self.fill_dtype)
self.stroke_data = np.zeros(0, dtype=self.stroke_dtype)
self.fill_shader_wrapper = ShaderWrapper(
@@ -1509,8 +1517,9 @@ class OpenGLVMobject(OpenGLMobject):
shader_folder=self.stroke_shader_folder,
render_primitive=self.render_primitive,
)
+ return self
- def refresh_shader_wrapper_id(self):
+ def refresh_shader_wrapper_id(self) -> Self:
for wrapper in [self.fill_shader_wrapper, self.stroke_shader_wrapper]:
wrapper.refresh_id()
return self
@@ -1519,20 +1528,22 @@ class OpenGLVMobject(OpenGLMobject):
self.update_fill_shader_wrapper()
return self.fill_shader_wrapper
- def update_fill_shader_wrapper(self):
+ def update_fill_shader_wrapper(self) -> Self:
self.fill_shader_wrapper.vert_data = self.get_fill_shader_data()
self.fill_shader_wrapper.vert_indices = self.get_triangulation()
self.fill_shader_wrapper.uniforms = self.get_fill_uniforms()
self.fill_shader_wrapper.depth_test = self.depth_test
+ return self
def get_stroke_shader_wrapper(self):
self.update_stroke_shader_wrapper()
return self.stroke_shader_wrapper
- def update_stroke_shader_wrapper(self):
+ def update_stroke_shader_wrapper(self) -> Self:
self.stroke_shader_wrapper.vert_data = self.get_stroke_shader_data()
self.stroke_shader_wrapper.uniforms = self.get_stroke_uniforms()
self.stroke_shader_wrapper.depth_test = self.depth_test
+ return self
def get_shader_wrapper_list(self):
# Build up data lists
@@ -1609,9 +1620,10 @@ class OpenGLVMobject(OpenGLMobject):
return self.fill_data
- def refresh_shader_data(self):
+ def refresh_shader_data(self) -> Self:
self.get_fill_shader_data()
self.get_stroke_shader_data()
+ return self
def get_fill_shader_vert_indices(self):
return self.get_triangulation()
@@ -1698,7 +1710,7 @@ class OpenGLVGroup(OpenGLVMobject):
f"submobject{'s' if len(self.submobjects) > 0 else ''}"
)
- def add(self, *vmobjects: OpenGLVMobject):
+ def add(self, *vmobjects: OpenGLVMobject) -> Self:
"""Checks if all passed elements are an instance of OpenGLVMobject and then add them to submobjects
Parameters
diff --git a/manim/mobject/svg/svg_mobject.py b/manim/mobject/svg/svg_mobject.py
index 5f67b8adc..e0079e35b 100644
--- a/manim/mobject/svg/svg_mobject.py
+++ b/manim/mobject/svg/svg_mobject.py
@@ -4,7 +4,7 @@ from __future__ import annotations
import os
from pathlib import Path
-from typing import Any
+from typing import Any, Self
from xml.etree import ElementTree as ET
import numpy as np
@@ -158,7 +158,7 @@ class SVGMobject(VMobject, metaclass=ConvertToOpenGL):
)
self.move_into_position()
- def init_svg_mobject(self, use_svg_cache: bool) -> None:
+ def init_svg_mobject(self, use_svg_cache: bool) -> Self:
"""Checks whether the SVG has already been imported and
generates it if not.
@@ -172,11 +172,12 @@ class SVGMobject(VMobject, metaclass=ConvertToOpenGL):
mob = SVG_HASH_TO_MOB_MAP[hash_val].copy()
self.add(*mob)
self.id_to_vgroup_dict = mob.id_to_vgroup_dict
- return
+ return self
self.generate_mobject()
if use_svg_cache:
SVG_HASH_TO_MOB_MAP[hash_val] = self.copy()
+ return self
@property
def hash_seed(self) -> tuple:
@@ -193,7 +194,7 @@ class SVGMobject(VMobject, metaclass=ConvertToOpenGL):
config.renderer,
)
- def generate_mobject(self) -> None:
+ def generate_mobject(self) -> Self:
"""Parse the SVG and translate its elements to submobjects."""
file_path = self.get_file_path()
element_tree = ET.parse(file_path)
@@ -209,6 +210,7 @@ class SVGMobject(VMobject, metaclass=ConvertToOpenGL):
self.add(*mobjects)
self.id_to_vgroup_dict = mobject_dict
self.flip(RIGHT) # Flip y
+ return self
def get_file_path(self) -> Path:
"""Search for an existing file based on the specified file name."""
@@ -487,7 +489,7 @@ class SVGMobject(VMobject, metaclass=ConvertToOpenGL):
logger.warning(f"Unsupported element type: {type(text)}")
return # type: ignore[return-value]
- def move_into_position(self) -> None:
+ def move_into_position(self) -> Self:
"""Scale and move the generated mobject into position."""
if self.should_center:
self.center()
@@ -495,6 +497,7 @@ class SVGMobject(VMobject, metaclass=ConvertToOpenGL):
self.set(height=self.svg_height)
if self.svg_width is not None:
self.set(width=self.svg_width)
+ return self
class VMobjectFromSVGPath(VMobject, metaclass=ConvertToOpenGL):
@@ -542,7 +545,7 @@ class VMobjectFromSVGPath(VMobject, metaclass=ConvertToOpenGL):
super().__init__(**kwargs)
- def generate_points(self) -> None:
+ def generate_points(self) -> Self:
# TODO: cache mobject in a re-importable way
self.handle_commands()
@@ -554,11 +557,13 @@ class VMobjectFromSVGPath(VMobject, metaclass=ConvertToOpenGL):
if self.should_remove_null_curves:
# Get rid of any null curves
self.set_points(self.get_points_without_null_curves())
+ return self
- def init_points(self) -> None:
+ def init_points(self) -> Self:
self.generate_points()
+ return self
- def handle_commands(self) -> None:
+ def handle_commands(self) -> Self:
all_points: list[np.ndarray] = []
last_move: np.ndarray = None
curve_start = None
@@ -654,3 +659,5 @@ class VMobjectFromSVGPath(VMobject, metaclass=ConvertToOpenGL):
# add or remove points correctly.
if len(all_points) == 0:
self.points = np.reshape(self.points, (0, 3))
+
+ return self
diff --git a/manim/mobject/table.py b/manim/mobject/table.py
index 270f851ab..ca4c96a7f 100644
--- a/manim/mobject/table.py
+++ b/manim/mobject/table.py
@@ -55,6 +55,8 @@ Examples
from __future__ import annotations
+from typing import Self
+
__all__ = [
"Table",
"MathTable",
@@ -66,7 +68,7 @@ __all__ = [
import itertools as it
from collections.abc import Callable, Iterable, Sequence
-from typing import Any, Self
+from typing import Any
from manim.mobject.geometry.line import Line
from manim.mobject.geometry.polygram import Polygon
@@ -527,7 +529,7 @@ class Table(VGroup):
"""
return VGroup(*(VGroup(*row) for row in self.mob_table))
- def set_column_colors(self, *colors: Iterable[ParsableManimColor]) -> Table:
+ def set_column_colors(self, *colors: Iterable[ParsableManimColor]) -> Self:
"""Set individual colors for each column of the table.
Parameters
@@ -556,7 +558,7 @@ class Table(VGroup):
column.set_color(color)
return self
- def set_row_colors(self, *colors: Iterable[ParsableManimColor]) -> Table:
+ def set_row_colors(self, *colors: Iterable[ParsableManimColor]) -> Self:
"""Set individual colors for each row of the table.
Parameters
@@ -777,7 +779,7 @@ class Table(VGroup):
label_group.add(*label)
return label_group
- def add_background_to_entries(self, color: ParsableManimColor = BLACK) -> Table:
+ def add_background_to_entries(self, color: ParsableManimColor = BLACK) -> Self:
"""Adds a black :class:`~.BackgroundRectangle` to each entry of the table."""
for mob in self.get_entries():
mob.add_background_rectangle(color=ManimColor(color))
@@ -884,7 +886,7 @@ class Table(VGroup):
pos: Sequence[int] = (1, 1),
color: ParsableManimColor = PURE_YELLOW,
**kwargs: Any,
- ) -> Table:
+ ) -> Self:
"""Highlights one cell at a specific position on the table by adding a :class:`~.BackgroundRectangle`.
Parameters
diff --git a/manim/mobject/text/numbers.py b/manim/mobject/text/numbers.py
index cd2372c54..41abd6868 100644
--- a/manim/mobject/text/numbers.py
+++ b/manim/mobject/text/numbers.py
@@ -311,8 +311,9 @@ class DecimalNumber(VMobject, metaclass=ConvertToOpenGL):
def get_value(self) -> float:
return self.number
- def increment_value(self, delta_t: float = 1) -> None:
+ def increment_value(self, delta_t: float = 1) -> Self:
self.set_value(self.get_value() + delta_t)
+ return self
class Integer(DecimalNumber):
diff --git a/manim/mobject/text/tex_mobject.py b/manim/mobject/text/tex_mobject.py
index 6784cfad0..a60ba9d5f 100644
--- a/manim/mobject/text/tex_mobject.py
+++ b/manim/mobject/text/tex_mobject.py
@@ -595,8 +595,9 @@ class MathTex(SingleStringMathTex):
raise ValueError("Trying to get index of part not in MathTex")
return index
- def sort_alphabetically(self) -> None:
+ def sort_alphabetically(self) -> Self:
self.submobjects.sort(key=lambda m: m.get_tex_string())
+ return self
class MathTexPart(VMobject, metaclass=ConvertToOpenGL):
@@ -693,7 +694,7 @@ class BulletedList(Tex):
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:
+ def fade_all_but(self, index_or_string: int | str, opacity: float = 0.5) -> Self:
arg = index_or_string
if isinstance(arg, str):
part: VGroup | VMobject | None = self.get_part_by_tex(arg)
@@ -711,6 +712,8 @@ class BulletedList(Tex):
else:
other_part.set_fill(opacity=opacity)
+ return self
+
class Title(Tex):
"""A mobject representing an underlined title.
diff --git a/manim/mobject/text/typst_mobject.py b/manim/mobject/text/typst_mobject.py
index c974506e1..e239bdf58 100644
--- a/manim/mobject/text/typst_mobject.py
+++ b/manim/mobject/text/typst_mobject.py
@@ -124,7 +124,7 @@ __all__ = [
import re
from pathlib import Path
-from typing import Any, cast
+from typing import Any, Self, cast
from xml.etree import ElementTree as ET
import numpy as np
@@ -297,7 +297,7 @@ class Typst(SVGMobject):
*,
about_point: np.ndarray | None = None,
about_edge: np.ndarray | None = None,
- ) -> Typst:
+ ) -> Self:
result = super().scale(
scale_factor,
scale_stroke=scale_stroke,
@@ -599,7 +599,7 @@ class Typst(SVGMobject):
# -- color handling ------------------------------------------------------
- def init_colors(self, propagate_colors: bool = True) -> Typst:
+ def init_colors(self, propagate_colors: bool = True) -> Self:
"""Recolor black submobjects to ``self.color``.
Typst renders text in black (``fill="#000000"``) by default.
diff --git a/manim/mobject/three_d/polyhedra.py b/manim/mobject/three_d/polyhedra.py
index 61292b030..a31d22e14 100644
--- a/manim/mobject/three_d/polyhedra.py
+++ b/manim/mobject/three_d/polyhedra.py
@@ -3,7 +3,7 @@
from __future__ import annotations
from collections.abc import Hashable
-from typing import TYPE_CHECKING, Any
+from typing import TYPE_CHECKING, Any, Self
import numpy as np
@@ -145,10 +145,11 @@ class Polyhedron(VGroup):
face_group.add(Polygon(*face, **self.faces_config))
return face_group
- def update_faces(self, m: Mobject) -> None:
+ def update_faces(self, m: Mobject) -> Self:
face_coords = self.extract_face_coords()
new_faces = self.create_faces(face_coords)
self.faces.match_points(new_faces)
+ return self
def extract_face_coords(self) -> Point3DLike_Array:
"""Extracts the coordinates of the vertices in the graph.
diff --git a/manim/mobject/three_d/three_dimensions.py b/manim/mobject/three_d/three_dimensions.py
index f2698de7e..4508cc0da 100644
--- a/manim/mobject/three_d/three_dimensions.py
+++ b/manim/mobject/three_d/three_dimensions.py
@@ -574,7 +574,7 @@ class Cube(VGroup):
**kwargs,
)
- def generate_points(self) -> None:
+ def generate_points(self) -> Self:
"""Creates the sides of the :class:`Cube`."""
for vect in IN, OUT, LEFT, RIGHT, UP, DOWN:
face = Square(
@@ -587,9 +587,11 @@ class Cube(VGroup):
face.apply_matrix(z_to_vector(vect))
self.add(face)
+ return self
- def init_points(self) -> None:
+ def init_points(self) -> Self:
self.generate_points()
+ return self
class Prism(Cube):
@@ -623,11 +625,12 @@ class Prism(Cube):
self.dimensions = dimensions
super().__init__(**kwargs)
- def generate_points(self) -> None:
+ def generate_points(self) -> Self:
"""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)
+ return self
class Cone(Surface):
@@ -767,7 +770,7 @@ class Cone(Surface):
self._current_theta = theta
self._current_phi = phi
- def set_direction(self, direction: Vector3DLike) -> None:
+ def set_direction(self, direction: Vector3DLike) -> Self:
"""Changes the direction of the apex of the :class:`Cone`.
Parameters
@@ -777,6 +780,7 @@ class Cone(Surface):
"""
self.direction = np.array(direction)
self._rotate_to_direction()
+ return self
def get_direction(self) -> Vector3D:
"""Returns the current direction of the apex of the :class:`Cone`.
@@ -875,7 +879,7 @@ class Cylinder(Surface):
r = self.radius
return np.array([r * np.cos(phi), r * np.sin(phi), height])
- def add_bases(self) -> None:
+ def add_bases(self) -> Self:
"""Adds the end caps of the cylinder."""
opacity: float
if config.renderer == RendererType.OPENGL:
@@ -903,6 +907,7 @@ class Cylinder(Surface):
)
self.base_bottom.shift(self.u_range[0] * IN)
self.add(self.base_top, self.base_bottom)
+ return self
def _rotate_to_direction(self) -> None:
x, y, z = self.direction
@@ -934,7 +939,7 @@ class Cylinder(Surface):
self._current_theta = theta
self._current_phi = phi
- def set_direction(self, direction: Vector3DLike) -> None:
+ def set_direction(self, direction: Vector3DLike) -> Self:
"""Sets the direction of the central axis of the :class:`Cylinder`.
Parameters
@@ -946,6 +951,7 @@ class Cylinder(Surface):
# pass
self.direction = direction
self._rotate_to_direction()
+ return self
def get_direction(self) -> np.ndarray:
"""Returns the direction of the central axis of the :class:`Cylinder`.
@@ -1014,7 +1020,7 @@ class Line3D(Cylinder):
def set_start_and_end_attrs(
self, start: Point3DLike, end: Point3DLike, **kwargs: Any
- ) -> None:
+ ) -> Self:
"""Sets the start and end points of the line.
If either ``start`` or ``end`` are :class:`Mobjects <.Mobject>`,
@@ -1045,6 +1051,7 @@ class Line3D(Cylinder):
**kwargs,
)
self.shift((self.start + self.end) / 2)
+ return self
def pointify(
self,
diff --git a/manim/mobject/types/image_mobject.py b/manim/mobject/types/image_mobject.py
index 1e35c9c60..0fc5a8f86 100644
--- a/manim/mobject/types/image_mobject.py
+++ b/manim/mobject/types/image_mobject.py
@@ -73,7 +73,7 @@ class AbstractImageMobject(Mobject):
color: ParsableManimColor = YELLOW_C,
alpha: Any = None,
family: bool = True,
- ) -> AbstractImageMobject:
+ ) -> Self:
# Likely to be implemented in subclasses, but no obligation
raise NotImplementedError()
@@ -262,7 +262,7 @@ class ImageMobject(AbstractImageMobject):
def interpolate_color(
self, mobject1: Mobject, mobject2: Mobject, alpha: float
- ) -> None:
+ ) -> Self:
"""Interpolates the array of pixel color values from one ImageMobject
into an array of equal size in the target ImageMobject.
@@ -299,6 +299,7 @@ class ImageMobject(AbstractImageMobject):
mobject2.pixel_array,
alpha,
).astype(self.pixel_array_dtype)
+ return self
def get_style(self) -> dict[str, Any]:
return {
@@ -344,7 +345,7 @@ class ImageMobjectFromCamera(AbstractImageMobject):
def interpolate_color(
self, mobject1: Mobject, mobject2: Mobject, alpha: float
- ) -> None:
+ ) -> Self:
assert isinstance(mobject1, ImageMobjectFromCamera)
assert isinstance(mobject2, ImageMobjectFromCamera)
assert mobject1.pixel_array.shape == mobject2.pixel_array.shape, (
@@ -357,3 +358,4 @@ class ImageMobjectFromCamera(AbstractImageMobject):
mobject2.pixel_array,
alpha,
).astype(self.pixel_array_dtype)
+ return self
diff --git a/manim/mobject/types/point_cloud_mobject.py b/manim/mobject/types/point_cloud_mobject.py
index 95c4bc2df..ef78fc56b 100644
--- a/manim/mobject/types/point_cloud_mobject.py
+++ b/manim/mobject/types/point_cloud_mobject.py
@@ -216,11 +216,12 @@ class PMobject(Mobject, metaclass=ConvertToOpenGL):
return PMobject
# Alignment
- def align_points_with_larger(self, larger_mobject: Mobject) -> None:
+ def align_points_with_larger(self, larger_mobject: Mobject) -> Self:
assert isinstance(larger_mobject, PMobject)
self.apply_over_attr_arrays(
lambda a: stretch_array_to_length(a, larger_mobject.get_num_points()),
)
+ return self
def get_point_mobject(self, center: Point3DLike | None = None) -> Point:
if center is None:
@@ -240,12 +241,13 @@ class PMobject(Mobject, metaclass=ConvertToOpenGL):
)
return self
- def pointwise_become_partial(self, mobject: Mobject, a: float, b: float) -> None:
+ def pointwise_become_partial(self, mobject: Mobject, a: float, b: float) -> Self:
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)
+ return self
# TODO, Make the two implementations below non-redundant
@@ -260,7 +262,7 @@ class Mobject1D(PMobject, metaclass=ConvertToOpenGL):
start: npt.NDArray,
end: npt.NDArray,
color: ParsableManimColor | None = None,
- ) -> None:
+ ) -> Self:
start, end = list(map(np.array, [start, end]))
length = np.linalg.norm(end - start)
if length == 0:
@@ -272,6 +274,8 @@ class Mobject1D(PMobject, metaclass=ConvertToOpenGL):
)
self.add_points(points, color=color)
+ return self
+
class Mobject2D(PMobject, metaclass=ConvertToOpenGL):
def __init__(self, density: int = DEFAULT_POINT_DENSITY_2D, **kwargs: Any) -> None:
@@ -369,11 +373,12 @@ class PointCloudDot(Mobject1D):
)
self.shift(center)
- def init_points(self) -> None:
+ def init_points(self) -> Self:
self.reset_points()
self.generate_points()
+ return self
- def generate_points(self) -> None:
+ def generate_points(self) -> Self:
self.add_points(
np.array(
[
@@ -388,6 +393,7 @@ class PointCloudDot(Mobject1D):
]
),
)
+ return self
class Point(PMobject):
@@ -417,10 +423,12 @@ class Point(PMobject):
self.location = location
super().__init__(color=color, **kwargs)
- def init_points(self) -> None:
+ def init_points(self) -> Self:
self.reset_points()
self.generate_points()
self.set_points([self.location])
+ return self
- def generate_points(self) -> None:
+ def generate_points(self) -> Self:
self.add_points(np.array([self.location]))
+ return self
diff --git a/manim/mobject/types/vectorized_mobject.py b/manim/mobject/types/vectorized_mobject.py
index b523028ff..da6a16dad 100644
--- a/manim/mobject/types/vectorized_mobject.py
+++ b/manim/mobject/types/vectorized_mobject.py
@@ -851,9 +851,9 @@ class VMobject(Mobject):
self.points[index::nppcc] = array
return self
- def clear_points(self) -> None:
- # TODO: shouldn't this return self instead of None?
+ def clear_points(self) -> Self:
self.points = np.zeros((0, self.dim))
+ return self
def append_points(self, new_points: Point3DLike_Array) -> Self:
"""Append the given ``new_points`` to the end of
@@ -915,13 +915,15 @@ class VMobject(Mobject):
handle1: Point3DLike,
handle2: Point3DLike,
anchor2: Point3DLike,
- ) -> None:
+ ) -> Self:
# TODO, check the len(self.points) % 4 == 0?
self.append_points([anchor1, handle1, handle2, anchor2])
+ return self
# what type is curves?
- def add_cubic_bezier_curves(self, curves) -> None:
+ def add_cubic_bezier_curves(self, curves) -> Self:
self.append_points(curves.flatten())
+ return self
def add_cubic_bezier_curve_to(
self,
@@ -1058,9 +1060,10 @@ class VMobject(Mobject):
# TODO use consider_points_equals_2d ?
return self.consider_points_equals(self.points[0], self.points[-1])
- def close_path(self) -> None:
+ def close_path(self) -> Self:
if not self.is_closed():
self.add_line_to(self.get_subpaths()[-1][0])
+ return self
def add_points_as_corners(self, points: Point3DLike_Array) -> Self:
"""Append multiple straight lines at the end of
@@ -1203,12 +1206,13 @@ class VMobject(Mobject):
self.append_points(points)
return self
- def append_vectorized_mobject(self, vectorized_mobject: VMobject) -> None:
+ def append_vectorized_mobject(self, vectorized_mobject: VMobject) -> Self:
if self.has_new_path_started():
# Remove last point, which is starting
# a new path
self.points = self.points[:-1]
self.append_points(vectorized_mobject.points)
+ return self
def apply_function(
self,
@@ -1767,7 +1771,7 @@ class VMobject(Mobject):
self.align_rgbas(vmobject)
# TODO: This shortcut can be a bit over eager. What if they have the same length, but different subpath lengths?
if self.get_num_points() == vmobject.get_num_points():
- return
+ return self
for mob in self, vmobject:
# If there are no points, add one to
@@ -1892,7 +1896,7 @@ class VMobject(Mobject):
def interpolate_color(
self, mobject1: VMobject, mobject2: VMobject, alpha: float
- ) -> None:
+ ) -> Self:
attrs = [
"fill_rgbas",
"stroke_rgbas",
@@ -1913,6 +1917,7 @@ class VMobject(Mobject):
if isinstance(val, np.ndarray):
val = val.copy()
setattr(self, attr, val)
+ return self
def pointwise_become_partial(
self,
@@ -2628,7 +2633,7 @@ class VDict(VMobject, metaclass=ConvertToOpenGL):
submobjects = self.submob_dict.values()
return submobjects
- def add_key_value_pair(self, key: Hashable, value: VMobject) -> None:
+ def add_key_value_pair(self, key: Hashable, value: VMobject) -> Self:
"""A utility function used by :meth:`add` to add the key-value pair
to :attr:`submob_dict`. Not really meant to be used externally.
@@ -2667,6 +2672,7 @@ class VDict(VMobject, metaclass=ConvertToOpenGL):
self.submob_dict[key] = mob
super().add(value)
+ return self
class VectorizedPoint(VMobject, metaclass=ConvertToOpenGL):
@@ -2703,8 +2709,9 @@ class VectorizedPoint(VMobject, metaclass=ConvertToOpenGL):
def get_location(self) -> Point3D:
return np.array(self.points[0])
- def set_location(self, new_loc: Point3D):
+ def set_location(self, new_loc: Point3D) -> Self:
self.set_points(np.array([new_loc]))
+ return self
class CurvesAsSubmobjects(VGroup):
diff --git a/manim/mobject/vector_field.py b/manim/mobject/vector_field.py
index ec3443360..540649e42 100644
--- a/manim/mobject/vector_field.py
+++ b/manim/mobject/vector_field.py
@@ -12,7 +12,7 @@ import itertools as it
import random
from collections.abc import Callable, Iterable, Sequence
from math import ceil, floor
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Self
import numpy as np
from PIL import Image
@@ -187,7 +187,7 @@ class VectorField(VGroup):
"""
return lambda p: func(p * scalar)
- def fit_to_coordinate_system(self, coordinate_system: CoordinateSystem):
+ def fit_to_coordinate_system(self, coordinate_system: CoordinateSystem) -> Self:
"""Scale the vector field to fit a coordinate system.
This method is useful when the vector field is defined in a coordinate system
@@ -202,6 +202,7 @@ class VectorField(VGroup):
"""
self.apply_function(lambda pos: coordinate_system.coords_to_point(*pos))
+ return self
def nudge(
self,
@@ -209,7 +210,7 @@ class VectorField(VGroup):
dt: float = 1,
substeps: int = 1,
pointwise: bool = False,
- ) -> VectorField:
+ ) -> Self:
"""Nudge a :class:`~.Mobject` along the vector field.
Parameters
@@ -293,7 +294,7 @@ class VectorField(VGroup):
dt: float = 1,
substeps: int = 1,
pointwise: bool = False,
- ) -> VectorField:
+ ) -> Self:
"""Apply a nudge along the vector field to all submobjects.
Parameters
@@ -344,7 +345,7 @@ class VectorField(VGroup):
self,
speed: float = 1,
pointwise: bool = False,
- ) -> VectorField:
+ ) -> Self:
"""Start continuously moving all submobjects along the vector field.
Calling this method multiple times will result in removing the previous updater created by this method.
@@ -370,7 +371,7 @@ class VectorField(VGroup):
self.add_updater(self.submob_movement_updater)
return self
- def stop_submobject_movement(self) -> VectorField:
+ def stop_submobject_movement(self) -> Self:
"""Stops the continuous movement started using :meth:`start_submobject_movement`.
Returns
@@ -929,7 +930,7 @@ class StreamLines(VectorField):
rate_func: Callable[[float], float] = linear,
line_animation_class: type[ShowPassingFlash] = ShowPassingFlash,
**kwargs,
- ) -> None:
+ ) -> Self:
"""Animates the stream lines using an updater.
The stream lines will continuously flow
@@ -987,6 +988,7 @@ class StreamLines(VectorField):
self.flow_animation = updater
self.flow_speed = flow_speed
self.time_width = time_width
+ return self
def end_animation(self) -> AnimationGroup:
"""End the stream line animation smoothly.
diff --git a/manim/renderer/opengl_renderer.py b/manim/renderer/opengl_renderer.py
index 9c1c577c5..80fc251f0 100644
--- a/manim/renderer/opengl_renderer.py
+++ b/manim/renderer/opengl_renderer.py
@@ -208,12 +208,13 @@ class OpenGLCamera(OpenGLMobject):
def unformatted_view_matrix(self) -> MatrixMN:
return typing.cast(MatrixMN, np.linalg.inv(self.model_matrix))
- def init_points(self) -> None:
+ def init_points(self) -> Self:
"""Initialize the camera's points based on frame shape and center point."""
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)
+ return self
def to_default_state(self) -> Self:
"""Reset the camera to its default state
@@ -226,7 +227,7 @@ class OpenGLCamera(OpenGLMobject):
self.model_matrix = self.default_model_matrix
return self
- def refresh_rotation_matrix(self) -> None:
+ def refresh_rotation_matrix(self) -> Self:
"""Refresh the camera's inverse rotation matrix based on its Euler angles."""
# Rotate based on camera orientation
theta, phi, gamma = self.euler_angles
@@ -238,6 +239,7 @@ class OpenGLCamera(OpenGLMobject):
self.inverse_rotation_matrix = rotation_matrix_transpose_from_quaternion(
np.asarray(quat, dtype=float)
)
+ return self
@override
def rotate(