Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

Increased opengl testing (#2146)

Ryan McCauley0ee32815848a
diff --git a/tests/opengl/test_composition_opengl.py b/tests/opengl/test_composition_opengl.py
new file mode 100644
index 000000000..aa6fcb607
--- /dev/null
+++ b/tests/opengl/test_composition_opengl.py
@@ -0,0 +1,99 @@
+from manim.animation.animation import Animation, Wait
+from manim.animation.composition import AnimationGroup, Succession
+from manim.animation.fading import FadeIn, FadeOut
+from manim.constants import DOWN, UP
+from manim.mobject.geometry import Circle, Line, Square
+
+
+def test_succession_timing(using_opengl_renderer):
+ """Test timing of animations in a succession."""
+ line = Line()
+ animation_1s = FadeIn(line, shift=UP, run_time=1.0)
+ animation_4s = FadeOut(line, shift=DOWN, run_time=4.0)
+ succession = Succession(animation_1s, animation_4s)
+ assert succession.get_run_time() == 5.0
+ succession.begin()
+ assert succession.active_index == 0
+ # The first animation takes 20% of the total run time.
+ succession.interpolate(0.199)
+ assert succession.active_index == 0
+ succession.interpolate(0.2)
+ assert succession.active_index == 1
+ succession.interpolate(0.8)
+ assert succession.active_index == 1
+ # At 100% and more, no animation must be active anymore.
+ succession.interpolate(1.0)
+ assert succession.active_index == 2
+ assert succession.active_animation is None
+ succession.interpolate(1.2)
+ assert succession.active_index == 2
+ assert succession.active_animation is None
+
+
+def test_succession_in_succession_timing(using_opengl_renderer):
+ """Test timing of nested successions."""
+ line = Line()
+ animation_1s = FadeIn(line, shift=UP, run_time=1.0)
+ animation_4s = FadeOut(line, shift=DOWN, run_time=4.0)
+ nested_succession = Succession(animation_1s, animation_4s)
+ succession = Succession(
+ FadeIn(line, shift=UP, run_time=4.0),
+ nested_succession,
+ FadeIn(line, shift=UP, run_time=1.0),
+ )
+ assert nested_succession.get_run_time() == 5.0
+ assert succession.get_run_time() == 10.0
+ succession.begin()
+ succession.interpolate(0.1)
+ assert succession.active_index == 0
+ # The nested succession must not be active yet, and as a result hasn't set active_animation yet.
+ assert not hasattr(nested_succession, "active_animation")
+ succession.interpolate(0.39)
+ assert succession.active_index == 0
+ assert not hasattr(nested_succession, "active_animation")
+ # The nested succession starts at 40% of total run time
+ succession.interpolate(0.4)
+ assert succession.active_index == 1
+ assert nested_succession.active_index == 0
+ # The nested succession second animation starts at 50% of total run time.
+ succession.interpolate(0.49)
+ assert succession.active_index == 1
+ assert nested_succession.active_index == 0
+ succession.interpolate(0.5)
+ assert succession.active_index == 1
+ assert nested_succession.active_index == 1
+ # The last animation starts at 90% of total run time. The nested succession must be finished at that time.
+ succession.interpolate(0.89)
+ assert succession.active_index == 1
+ assert nested_succession.active_index == 1
+ succession.interpolate(0.9)
+ assert succession.active_index == 2
+ assert nested_succession.active_index == 2
+ assert nested_succession.active_animation is None
+ # After 100%, nothing must be playing anymore.
+ succession.interpolate(1.0)
+ assert succession.active_index == 3
+ assert succession.active_animation is None
+ assert nested_succession.active_index == 2
+ assert nested_succession.active_animation is None
+
+
+def test_animationbuilder_in_group(using_opengl_renderer):
+ sqr = Square()
+ circ = Circle()
+ animation_group = AnimationGroup(sqr.animate.shift(DOWN).scale(2), FadeIn(circ))
+ assert all(isinstance(anim, Animation) for anim in animation_group.animations)
+ succession = Succession(sqr.animate.shift(DOWN).scale(2), FadeIn(circ))
+ assert all(isinstance(anim, Animation) for anim in succession.animations)
+
+
+def test_animationgroup_with_wait(using_opengl_renderer):
+ sqr = Square()
+ sqr_anim = FadeIn(sqr)
+ wait = Wait()
+ animation_group = AnimationGroup(wait, sqr_anim, lag_ratio=1)
+
+ animation_group.begin()
+ timings = animation_group.anims_with_timings
+
+ assert timings == [(wait, 0.0, 1.0), (sqr_anim, 1.0, 2.0)]
diff --git a/tests/opengl/test_config_opengl.py b/tests/opengl/test_config_opengl.py
new file mode 100644
index 000000000..b2a9a7b9b
--- /dev/null
+++ b/tests/opengl/test_config_opengl.py
@@ -0,0 +1,135 @@
+import tempfile
+from pathlib import Path
+
+import numpy as np
+
+from manim import WHITE, Scene, Square, config, tempconfig
+
+
+def test_tempconfig(using_opengl_renderer):
+ """Test the tempconfig context manager."""
+ original = config.copy()
+
+ with tempconfig({"frame_width": 100, "frame_height": 42}):
+ # check that config was modified correctly
+ assert config["frame_width"] == 100
+ assert config["frame_height"] == 42
+
+ # check that no keys are missing and no new keys were added
+ assert set(original.keys()) == set(config.keys())
+
+ # check that the keys are still untouched
+ assert set(original.keys()) == set(config.keys())
+
+ # check that config is correctly restored
+ for k, v in original.items():
+ if isinstance(v, np.ndarray):
+ assert np.allclose(config[k], v)
+ else:
+ assert config[k] == v
+
+
+class MyScene(Scene):
+ def construct(self):
+ self.add(Square())
+ self.wait(1)
+
+
+def test_background_color(using_opengl_renderer):
+ """Test the 'background_color' config option."""
+ with tempconfig({"background_color": WHITE, "verbosity": "ERROR", "dry_run": True}):
+ scene = MyScene()
+ scene.render()
+ frame = scene.renderer.get_frame()
+ assert np.allclose(frame[0, 0], [255, 255, 255, 255])
+
+
+def test_digest_file(using_opengl_renderer, tmp_path):
+ """Test that a config file can be digested programmatically."""
+ with tempconfig({}):
+ tmp_cfg = tempfile.NamedTemporaryFile("w", dir=tmp_path, delete=False)
+ tmp_cfg.write(
+ """
+ [CLI]
+ media_dir = this_is_my_favorite_path
+ video_dir = {media_dir}/videos
+ frame_height = 10
+ """,
+ )
+ tmp_cfg.close()
+ config.digest_file(tmp_cfg.name)
+
+ assert config.get_dir("media_dir") == Path("this_is_my_favorite_path")
+ assert config.get_dir("video_dir") == Path("this_is_my_favorite_path/videos")
+
+
+def test_frame_size(using_opengl_renderer, tmp_path):
+ """Test that the frame size can be set via config file."""
+ assert np.allclose(config.aspect_ratio, config.pixel_width / config.pixel_height)
+ assert np.allclose(config.frame_height, 8.0)
+
+ with tempconfig({}):
+ tmp_cfg = tempfile.NamedTemporaryFile("w", dir=tmp_path, delete=False)
+ tmp_cfg.write(
+ """
+ [CLI]
+ pixel_height = 10
+ pixel_width = 10
+ """,
+ )
+ tmp_cfg.close()
+ config.digest_file(tmp_cfg.name)
+
+ # aspect ratio is set using pixel measurements
+ assert np.allclose(config.aspect_ratio, 1.0)
+ # if not specified in the cfg file, frame_width is set using the aspect ratio
+ assert np.allclose(config.frame_height, 8.0)
+ assert np.allclose(config.frame_width, 8.0)
+
+ with tempconfig({}):
+ tmp_cfg = tempfile.NamedTemporaryFile("w", dir=tmp_path, delete=False)
+ tmp_cfg.write(
+ """
+ [CLI]
+ pixel_height = 10
+ pixel_width = 10
+ frame_height = 10
+ frame_width = 10
+ """,
+ )
+ tmp_cfg.close()
+ config.digest_file(tmp_cfg.name)
+
+ assert np.allclose(config.aspect_ratio, 1.0)
+ # if both are specified in the cfg file, the aspect ratio is ignored
+ assert np.allclose(config.frame_height, 10.0)
+ assert np.allclose(config.frame_width, 10.0)
+
+
+def test_temporary_dry_run(using_opengl_renderer):
+ """Test that tempconfig correctly restores after setting dry_run."""
+ assert config["write_to_movie"]
+ assert not config["save_last_frame"]
+
+ with tempconfig({"dry_run": True}):
+ assert not config["write_to_movie"]
+ assert not config["save_last_frame"]
+
+ assert config["write_to_movie"]
+ assert not config["save_last_frame"]
+
+
+def test_dry_run_with_png_format(using_opengl_renderer):
+ """Test that there are no exceptions when running a png without output"""
+ with tempconfig({"write_to_movie": False, "disable_caching": True}):
+ assert config["dry_run"] is True
+ scene = MyScene()
+ scene.render()
+
+
+def test_dry_run_with_png_format_skipped_animations(using_opengl_renderer):
+ """Test that there are no exceptions when running a png without output and skipped animations"""
+ with tempconfig({"write_to_movie": False, "disable_caching": True}):
+ assert config["dry_run"] is True
+ scene = MyScene(skip_animations=True)
+ scene.render()
diff --git a/tests/opengl/test_coordinate_system_opengl.py b/tests/opengl/test_coordinate_system_opengl.py
new file mode 100644
index 000000000..d3e81cade
--- /dev/null
+++ b/tests/opengl/test_coordinate_system_opengl.py
@@ -0,0 +1,127 @@
+import math
+
+import numpy as np
+import pytest
+
+from manim import LEFT, ORIGIN, PI, UR, Axes, Circle, ComplexPlane
+from manim import CoordinateSystem as CS
+from manim import NumberPlane, PolarPlane, ThreeDAxes, config, tempconfig
+
+
+def test_initial_config(using_opengl_renderer):
+ """Check that all attributes are defined properly from the config."""
+ cs = CS()
+ assert cs.x_range[0] == round(-config["frame_x_radius"])
+ assert cs.x_range[1] == round(config["frame_x_radius"])
+ assert cs.x_range[2] == 1.0
+ assert cs.y_range[0] == round(-config["frame_y_radius"])
+ assert cs.y_range[1] == round(config["frame_y_radius"])
+ assert cs.y_range[2] == 1.0
+
+ ax = Axes()
+ assert np.allclose(ax.get_center(), ORIGIN)
+ assert np.allclose(ax.y_axis_config["label_direction"], LEFT)
+
+ with tempconfig({"frame_x_radius": 100, "frame_y_radius": 200}):
+ cs = CS()
+ assert cs.x_range[0] == -100
+ assert cs.x_range[1] == 100
+ assert cs.y_range[0] == -200
+ assert cs.y_range[1] == 200
+
+
+def test_dimension(using_opengl_renderer):
+ """Check that objects have the correct dimension."""
+ assert Axes().dimension == 2
+ assert NumberPlane().dimension == 2
+ assert PolarPlane().dimension == 2
+ assert ComplexPlane().dimension == 2
+ assert ThreeDAxes().dimension == 3
+
+
+def test_abstract_base_class(using_opengl_renderer):
+ """Check that CoordinateSystem has some abstract methods."""
+ with pytest.raises(Exception):
+ CS().get_axes()
+
+
+ reason="Causes conflicts with other tests due to axis_config changing default config",
+)
+def test_NumberPlane(using_opengl_renderer):
+ """Test that NumberPlane generates the correct number of lines when its ranges do not cross 0."""
+ pos_x_range = (0, 7)
+ neg_x_range = (-7, 0)
+
+ pos_y_range = (2, 6)
+ neg_y_range = (-6, -2)
+
+ x_vals = [0, 1.5, 2, 2.8, 4, 6.25]
+ y_vals = [2, 5, 4.25, 6, 4.5, 2.75]
+
+ testing_data = [
+ (pos_x_range, pos_y_range, x_vals, y_vals),
+ (pos_x_range, neg_y_range, x_vals, [-v for v in y_vals]),
+ (neg_x_range, pos_y_range, [-v for v in x_vals], y_vals),
+ (neg_x_range, neg_y_range, [-v for v in x_vals], [-v for v in y_vals]),
+ ]
+
+ for test_data in testing_data:
+
+ x_range, y_range, x_vals, y_vals = test_data
+
+ x_start, x_end = x_range
+ y_start, y_end = y_range
+
+ plane = NumberPlane(
+ x_range=x_range,
+ y_range=y_range,
+ # x_length = 7,
+ axis_config={"include_numbers": True},
+ )
+
+ # normally these values would be need to be added by one to pass since there's an
+ # overlapping pair of lines at the origin, but since these planes do not cross 0,
+ # this is not needed.
+ num_y_lines = math.ceil(x_end - x_start)
+ num_x_lines = math.floor(y_end - y_start)
+
+ assert len(plane.y_lines) == num_y_lines
+ assert len(plane.x_lines) == num_x_lines
+
+ plane = NumberPlane((-5, 5, 0.5), (-8, 8, 2)) # <- test for different step values
+ assert len(plane.x_lines) == 8
+ assert len(plane.y_lines) == 20
+
+
+def test_point_to_coords(using_opengl_renderer):
+ ax = Axes(x_range=[0, 10, 2])
+ circ = Circle(radius=0.5).shift(UR * 2)
+
+ # get the coordinates of the circle with respect to the axes
+ coords = np.around(ax.point_to_coords(circ.get_right()), decimals=4)
+ assert np.array_equal(coords, (7.0833, 2.6667))
+
+
+def test_coords_to_point(using_opengl_renderer):
+ ax = Axes()
+
+ # a point with respect to the axes
+ c2p_coord = np.around(ax.coords_to_point(2, 2), decimals=4)
+ assert np.array_equal(c2p_coord, (1.7143, 1.5, 0))
+
+
+def test_input_to_graph_point(using_opengl_renderer):
+ ax = Axes()
+ curve = ax.get_graph(lambda x: np.cos(x))
+ line_graph = ax.get_line_graph([1, 3, 5], [-1, 2, -2], add_vertex_dots=False)[
+ "line_graph"
+ ]
+
+ # move a square to PI on the cosine curve.
+ position = np.around(ax.input_to_graph_point(x=PI, graph=curve), decimals=4)
+ assert np.array_equal(position, (2.6928, -0.75, 0))
+
+ # test the line_graph implementation
+ position = np.around(ax.input_to_graph_point(x=PI, graph=line_graph), decimals=4)
+ assert np.array_equal(position, (2.6928, 1.2876, 0))
diff --git a/tests/opengl/test_number_line_opengl.py b/tests/opengl/test_number_line_opengl.py
new file mode 100644
index 000000000..16cff0caf
--- /dev/null
+++ b/tests/opengl/test_number_line_opengl.py
@@ -0,0 +1,66 @@
+import numpy as np
+
+from manim import NumberLine
+from manim.mobject.numbers import Integer
+
+
+def test_unit_vector():
+ """Check if the magnitude of unit vector along
+ the NumberLine is equal to its unit_size."""
+ axis1 = NumberLine(unit_size=0.4)
+ axis2 = NumberLine(x_range=[-2, 5], length=12)
+ for axis in (axis1, axis2):
+ assert np.linalg.norm(axis.get_unit_vector()) == axis.unit_size
+
+
+def test_decimal_determined_by_step():
+ """Checks that step size is considered when determining the number of decimal
+ places."""
+ axis = NumberLine(x_range=[-2, 2, 0.5])
+ expected_decimal_places = 1
+ actual_decimal_places = axis.decimal_number_config["num_decimal_places"]
+ assert actual_decimal_places == expected_decimal_places, (
+ "Expected 1 decimal place but got " + actual_decimal_places
+ )
+
+ axis2 = NumberLine(x_range=[-1, 1, 0.25])
+ expected_decimal_places = 2
+ actual_decimal_places = axis2.decimal_number_config["num_decimal_places"]
+ assert actual_decimal_places == expected_decimal_places, (
+ "Expected 1 decimal place but got " + actual_decimal_places
+ )
+
+
+def test_decimal_config_overrides_defaults():
+ """Checks that ``num_decimal_places`` is determined by step size and gets overridden by ``decimal_number_config``."""
+ axis = NumberLine(
+ x_range=[-2, 2, 0.5],
+ decimal_number_config={"num_decimal_places": 0},
+ )
+ expected_decimal_places = 0
+ actual_decimal_places = axis.decimal_number_config["num_decimal_places"]
+ assert actual_decimal_places == expected_decimal_places, (
+ "Expected 1 decimal place but got " + actual_decimal_places
+ )
+
+
+def test_whole_numbers_step_size_default_to_0_decimal_places():
+ """Checks that ``num_decimal_places`` defaults to 0 when a whole number step size is passed."""
+ axis = NumberLine(x_range=[-2, 2, 1])
+ expected_decimal_places = 0
+ actual_decimal_places = axis.decimal_number_config["num_decimal_places"]
+ assert actual_decimal_places == expected_decimal_places, (
+ "Expected 1 decimal place but got " + actual_decimal_places
+ )
+
+
+def test_add_labels():
+ expected_label_length = 6
+ num_line = NumberLine(x_range=[-4, 4])
+ num_line.add_labels(
+ dict(zip(list(range(-3, 3)), [Integer(m) for m in range(-1, 5)])),
+ )
+ actual_label_length = len(num_line.labels)
+ assert (
+ actual_label_length == expected_label_length
+ ), f"Expected a VGroup with {expected_label_length} integers but got {actual_label_length}."
diff --git a/tests/opengl/test_numbers_opengl.py b/tests/opengl/test_numbers_opengl.py
new file mode 100644
index 000000000..01b9e76c5
--- /dev/null
+++ b/tests/opengl/test_numbers_opengl.py
@@ -0,0 +1,37 @@
+import pytest
+
+from manim.mobject.numbers import DecimalNumber
+
+
+def test_font_size():
+ """Test that DecimalNumber returns the correct font_size value
+ after being scaled."""
+ num = DecimalNumber(0).scale(0.3)
+
+ assert round(num.font_size, 5) == 14.4
+
+
+def test_font_size_vs_scale():
+ """Test that scale produces the same results as .scale()"""
+ num = DecimalNumber(0, font_size=12)
+ num_scale = DecimalNumber(0).scale(1 / 4)
+
+ assert num.height == num_scale.height
+
+
+def test_changing_font_size():
+ """Test that the font_size property properly scales DecimalNumber."""
+ num = DecimalNumber(0, font_size=12)
+ num.font_size = 48
+
+ assert num.height == DecimalNumber(0, font_size=48).height
+
+
+def test_set_value_size():
+ """Test that the size of DecimalNumber after set_value is correct."""
+ num = DecimalNumber(0).scale(0.3)
+ test_num = num.copy()
+ num.set_value(0)
+
+ # round because the height is off by 1e-17
+ assert round(num.height, 12) == round(test_num.height, 12)
diff --git a/tests/opengl/test_opengl_vectorized_mobject.py b/tests/opengl/test_opengl_vectorized_mobject.py
new file mode 100644
index 000000000..44f05c047
--- /dev/null
+++ b/tests/opengl/test_opengl_vectorized_mobject.py
@@ -0,0 +1,208 @@
+import numpy as np
+import pytest
+
+from manim import Circle, Line, Square, VDict, VGroup
+from manim.mobject.opengl_mobject import OpenGLMobject
+from manim.mobject.types.opengl_vectorized_mobject import OpenGLVMobject
+
+
+def test_opengl_vmobject_point_from_propotion(using_opengl_renderer):
+ obj = OpenGLVMobject()
+
+ # One long line, one short line
+ obj.set_points_as_corners(
+ [
+ np.array([0, 0, 0]),
+ np.array([4, 0, 0]),
+ np.array([4, 2, 0]),
+ ],
+ )
+
+ # Total length of 6, so halfway along the object
+ # would be at length 3, which lands in the first, long line.
+ assert np.all(obj.point_from_proportion(0.5) == np.array([3, 0, 0]))
+
+ with pytest.raises(ValueError, match="between 0 and 1"):
+ obj.point_from_proportion(2)
+
+ obj.clear_points()
+ with pytest.raises(Exception, match="with no points"):
+ obj.point_from_proportion(0)
+
+
+def test_vgroup_init(using_opengl_renderer):
+ """Test the VGroup instantiation."""
+ VGroup()
+ VGroup(OpenGLVMobject())
+ VGroup(OpenGLVMobject(), OpenGLVMobject())
+ with pytest.raises(TypeError):
+ VGroup(OpenGLMobject())
+ with pytest.raises(TypeError):
+ VGroup(OpenGLMobject(), OpenGLMobject())
+
+
+def test_vgroup_add(using_opengl_renderer):
+ """Test the VGroup add method."""
+ obj = VGroup()
+ assert len(obj.submobjects) == 0
+ obj.add(OpenGLVMobject())
+ assert len(obj.submobjects) == 1
+ with pytest.raises(TypeError):
+ obj.add(OpenGLMobject())
+ assert len(obj.submobjects) == 1
+ with pytest.raises(TypeError):
+ # If only one of the added object is not an instance of OpenGLVMobject, none of them should be added
+ obj.add(OpenGLVMobject(), OpenGLMobject())
+ assert len(obj.submobjects) == 1
+ with pytest.raises(Exception): # TODO change this to ValueError once #307 is merged
+ # a OpenGLMobject cannot contain itself
+ obj.add(obj)
+
+
+def test_vgroup_add_dunder(using_opengl_renderer):
+ """Test the VGroup __add__ magic method."""
+ obj = VGroup()
+ assert len(obj.submobjects) == 0
+ obj + OpenGLVMobject()
+ assert len(obj.submobjects) == 0
+ obj += OpenGLVMobject()
+ assert len(obj.submobjects) == 1
+ with pytest.raises(TypeError):
+ obj += OpenGLMobject()
+ assert len(obj.submobjects) == 1
+ with pytest.raises(TypeError):
+ # If only one of the added object is not an instance of OpenGLVMobject, none of them should be added
+ obj += (OpenGLVMobject(), OpenGLMobject())
+ assert len(obj.submobjects) == 1
+ with pytest.raises(Exception): # TODO change this to ValueError once #307 is merged
+ # a OpenGLMobject cannot contain itself
+ obj += obj
+
+
+def test_vgroup_remove(using_opengl_renderer):
+ """Test the VGroup remove method."""
+ a = OpenGLVMobject()
+ c = OpenGLVMobject()
+ b = VGroup(c)
+ obj = VGroup(a, b)
+ assert len(obj.submobjects) == 2
+ assert len(b.submobjects) == 1
+ obj.remove(a)
+ b.remove(c)
+ assert len(obj.submobjects) == 1
+ assert len(b.submobjects) == 0
+ obj.remove(b)
+ assert len(obj.submobjects) == 0
+
+
+def test_vgroup_remove_dunder(using_opengl_renderer):
+ """Test the VGroup __sub__ magic method."""
+ a = OpenGLVMobject()
+ c = OpenGLVMobject()
+ b = VGroup(c)
+ obj = VGroup(a, b)
+ assert len(obj.submobjects) == 2
+ assert len(b.submobjects) == 1
+ assert len(obj - a) == 1
+ assert len(obj.submobjects) == 2
+ obj -= a
+ b -= c
+ assert len(obj.submobjects) == 1
+ assert len(b.submobjects) == 0
+ obj -= b
+ assert len(obj.submobjects) == 0
+
+
+def test_vmob_add_to_back(using_opengl_renderer):
+ """Test the OpenGLMobject add_to_back method."""
+ a = OpenGLVMobject()
+ b = Line()
+ c = "text"
+ with pytest.raises(ValueError):
+ # OpenGLMobject cannot contain self
+ a.add_to_back(a)
+ with pytest.raises(TypeError):
+ # All submobjects must be of type OpenGLMobject
+ a.add_to_back(c)
+
+ # No submobject gets added twice
+ a.add_to_back(b)
+ a.add_to_back(b, b)
+ assert len(a.submobjects) == 1
+ a.submobjects.clear()
+ a.add_to_back(b, b, b)
+ a.add_to_back(b, b)
+ assert len(a.submobjects) == 1
+ a.submobjects.clear()
+
+ # Make sure the ordering has not changed
+ o1, o2, o3 = Square(), Line(), Circle()
+ a.add_to_back(o1, o2, o3)
+ assert a.submobjects.pop() == o3
+ assert a.submobjects.pop() == o2
+ assert a.submobjects.pop() == o1
+
+
+def test_vdict_init(using_opengl_renderer):
+ """Test the VDict instantiation."""
+ # Test empty VDict
+ VDict()
+ # Test VDict made from list of pairs
+ VDict([("a", OpenGLVMobject()), ("b", OpenGLVMobject()), ("c", OpenGLVMobject())])
+ # Test VDict made from a python dict
+ VDict({"a": OpenGLVMobject(), "b": OpenGLVMobject(), "c": OpenGLVMobject()})
+ # Test VDict made using zip
+ VDict(zip(["a", "b", "c"], [OpenGLVMobject(), OpenGLVMobject(), OpenGLVMobject()]))
+ # If the value is of type OpenGLMobject, must raise a TypeError
+ with pytest.raises(TypeError):
+ VDict({"a": OpenGLMobject()})
+
+
+def test_vdict_add(using_opengl_renderer):
+ """Test the VDict add method."""
+ obj = VDict()
+ assert len(obj.submob_dict) == 0
+ obj.add([("a", OpenGLVMobject())])
+ assert len(obj.submob_dict) == 1
+ with pytest.raises(TypeError):
+ obj.add([("b", OpenGLMobject())])
+
+
+def test_vdict_remove(using_opengl_renderer):
+ """Test the VDict remove method."""
+ obj = VDict([("a", OpenGLVMobject())])
+ assert len(obj.submob_dict) == 1
+ obj.remove("a")
+ assert len(obj.submob_dict) == 0
+ with pytest.raises(KeyError):
+ obj.remove("a")
+
+
+def test_vgroup_supports_item_assigment(using_opengl_renderer):
+ """Test VGroup supports array-like assignment for OpenGLVMObjects"""
+ a = OpenGLVMobject()
+ b = OpenGLVMobject()
+ vgroup = VGroup(a)
+ assert vgroup[0] == a
+ vgroup[0] = b
+ assert vgroup[0] == b
+ assert len(vgroup) == 1
+
+
+def test_vgroup_item_assignment_at_correct_position(using_opengl_renderer):
+ """Test VGroup item-assignment adds to correct position for OpenGLVMObjects"""
+ n_items = 10
+ vgroup = VGroup()
+ for _i in range(n_items):
+ vgroup.add(OpenGLVMobject())
+ new_obj = OpenGLVMobject()
+ vgroup[6] = new_obj
+ assert vgroup[6] == new_obj
+ assert len(vgroup) == n_items
+
+
+def test_vgroup_item_assignment_only_allows_vmobjects(using_opengl_renderer):
+ """Test VGroup item-assignment raises TypeError when invalid type is passed"""
+ vgroup = VGroup(OpenGLVMobject())
+ with pytest.raises(TypeError, match="All submobjects must be of type VMobject"):
+ vgroup[0] = "invalid object"
diff --git a/tests/opengl/test_override_animation_opengl.py b/tests/opengl/test_override_animation_opengl.py
new file mode 100644
index 000000000..f115e9577
--- /dev/null
+++ b/tests/opengl/test_override_animation_opengl.py
@@ -0,0 +1,98 @@
+import pytest
+
+from manim import Animation, override_animation
+from manim.mobject.opengl_mobject import OpenGLMobject
+from manim.utils.exceptions import MultiAnimationOverrideException
+
+
+class AnimationA1(Animation):
+ pass
+
+
+class AnimationA2(Animation):
+ pass
+
+
+class AnimationA3(Animation):
+ pass
+
+
+class AnimationB1(AnimationA1):
+ pass
+
+
+class AnimationC1(AnimationB1):
+ pass
+
+
+class AnimationX(Animation):
+ pass
+
+
+class OpenGLMobjectA(OpenGLMobject):
+ @override_animation(AnimationA1)
+ def anim_a1(self):
+ return AnimationA2(self)
+
+ @override_animation(AnimationX)
+ def anim_x(self, *args, **kwargs):
+ return args, kwargs
+
+
+class OpenGLMobjectB(OpenGLMobjectA):
+ pass
+
+
+class OpenGLMobjectC(OpenGLMobjectB):
+ @override_animation(AnimationA1)
+ def anim_a1(self):
+ return AnimationA3(self)
+
+
+class OpenGLMobjectX(OpenGLMobject):
+ @override_animation(AnimationB1)
+ def animation(self):
+ return "Overridden"
+
+
[email protected](reason="Needs investigating")
+def test_opengl_mobject_inheritance():
+ mob = OpenGLMobject()
+ a = OpenGLMobjectA()
+ b = OpenGLMobjectB()
+ c = OpenGLMobjectC()
+
+ assert type(AnimationA1(mob)) is AnimationA1
+ assert type(AnimationA1(a)) is AnimationA2
+ assert type(AnimationA1(b)) is AnimationA2
+ assert type(AnimationA1(c)) is AnimationA3
+
+
[email protected](reason="Needs investigating")
+def test_arguments():
+ a = OpenGLMobjectA()
+ args = (1, "two", {"three": 3}, ["f", "o", "u", "r"])
+ kwargs = {"test": "manim", "keyword": 42, "arguments": []}
+ animA = AnimationX(a, *args, **kwargs)
+
+ assert animA[0] == args
+ assert animA[1] == kwargs
+
+
[email protected](reason="Needs investigating")
+def test_multi_animation_override_exception():
+ with pytest.raises(MultiAnimationOverrideException):
+
+ class OpenGLMobjectB2(OpenGLMobjectA):
+ @override_animation(AnimationA1)
+ def anim_a1_different_name(self):
+ pass
+
+
[email protected](reason="Needs investigating")
+def test_animation_inheritance():
+ x = OpenGLMobjectX()
+
+ assert type(AnimationA1(x)) is AnimationA1
+ assert AnimationB1(x) == "Overridden"
+ assert type(AnimationC1(x)) is AnimationC1
diff --git a/tests/opengl/test_sound_opengl.py b/tests/opengl/test_sound_opengl.py
new file mode 100644
index 000000000..990f7fe1f
--- /dev/null
+++ b/tests/opengl/test_sound_opengl.py
@@ -0,0 +1,24 @@
+import struct
+import wave
+from pathlib import Path
+
+import pytest
+
+from manim import Scene
+
+
[email protected](reason="Not currently implemented for opengl")
+def test_add_sound(using_opengl_renderer, tmpdir):
+ # create sound file
+ sound_loc = Path(tmpdir, "noise.wav")
+ f = wave.open(str(sound_loc), "w")
+ f.setparams((2, 2, 44100, 0, "NONE", "not compressed"))
+ for _ in range(22050): # half a second of sound
+ packed_value = struct.pack("h", 14242)
+ f.writeframes(packed_value)
+ f.writeframes(packed_value)
+
+ f.close()
+
+ scene = Scene()
+ scene.add_sound(sound_loc)
diff --git a/tests/opengl/test_stroke_opengl.py b/tests/opengl/test_stroke_opengl.py
new file mode 100644
index 000000000..bebd24d44
--- /dev/null
+++ b/tests/opengl/test_stroke_opengl.py
@@ -0,0 +1,18 @@
+from colour import Color
+
+import manim.utils.color as C
+from manim.mobject.types.opengl_vectorized_mobject import OpenGLVMobject
+
+
+def test_stroke_props_in_ctor(using_opengl_renderer):
+ m = OpenGLVMobject(stroke_color=C.ORANGE, stroke_width=10)
+ assert m.stroke_color == Color(C.ORANGE)
+ assert m.stroke_width == 10
+
+
+def test_set_stroke(using_opengl_renderer):
+ m = OpenGLVMobject()
+ m.set_stroke(color=C.ORANGE, width=2, opacity=0.8)
+ assert m.stroke_width == 2
+ assert m.stroke_opacity == 0.8
+ assert m.stroke_color == Color(C.ORANGE)
diff --git a/tests/opengl/test_svg_mobject_opengl.py b/tests/opengl/test_svg_mobject_opengl.py
new file mode 100644
index 000000000..a1afabf5a
--- /dev/null
+++ b/tests/opengl/test_svg_mobject_opengl.py
@@ -0,0 +1,56 @@
+from colour import Color
+
+from manim import *
+from tests.helpers.path_utils import get_svg_resource
+
+
+def test_set_fill_color(using_opengl_renderer):
+ expected_color = "#FF862F"
+ svg = SVGMobject(get_svg_resource("heart.svg"), fill_color=expected_color)
+ assert svg.fill_color == Color(expected_color)
+
+
+def test_set_stroke_color(using_opengl_renderer):
+ expected_color = "#FFFDDD"
+ svg = SVGMobject(get_svg_resource("heart.svg"), stroke_color=expected_color)
+ assert svg.stroke_color == Color(expected_color)
+
+
+def test_set_color_sets_fill_and_stroke(using_opengl_renderer):
+ expected_color = "#EEE777"
+ svg = SVGMobject(get_svg_resource("heart.svg"), color=expected_color)
+ assert svg.color == Color(expected_color)
+ assert svg.fill_color == Color(expected_color)
+ assert svg.stroke_color == Color(expected_color)
+
+
+def test_set_fill_opacity(using_opengl_renderer):
+ expected_opacity = 0.5
+ svg = SVGMobject(get_svg_resource("heart.svg"), fill_opacity=expected_opacity)
+ assert svg.fill_opacity == expected_opacity
+
+
+def test_stroke_opacity(using_opengl_renderer):
+ expected_opacity = 0.4
+ svg = SVGMobject(get_svg_resource("heart.svg"), stroke_opacity=expected_opacity)
+ assert svg.stroke_opacity == expected_opacity
+
+
+def test_fill_overrides_color(using_opengl_renderer):
+ expected_color = "#343434"
+ svg = SVGMobject(
+ get_svg_resource("heart.svg"),
+ color="#123123",
+ fill_color=expected_color,
+ )
+ assert svg.fill_color == Color(expected_color)
+
+
+def test_stroke_overrides_color(using_opengl_renderer):
+ expected_color = "#767676"
+ svg = SVGMobject(
+ get_svg_resource("heart.svg"),
+ color="#334433",
+ stroke_color=expected_color,
+ )
+ assert svg.stroke_color == Color(expected_color)
diff --git a/tests/test_scene_rendering/opengl/test_caching_related_opengl.py b/tests/test_scene_rendering/opengl/test_caching_related_opengl.py
new file mode 100644
index 000000000..63e0b43dd
--- /dev/null
+++ b/tests/test_scene_rendering/opengl/test_caching_related_opengl.py
@@ -0,0 +1,57 @@
+import sys
+
+from ...utils.video_tester import *
+
+
+@video_comparison(
+ "SceneWithMultipleWaitCallsWithNFlag.json",
+ "videos/simple_scenes/480p15/SceneWithMultipleWaitCalls.mp4",
+)
+def test_wait_skip(tmp_path, manim_cfg_file, simple_scenes_path):
+ # Test for PR #468. Intended to test if wait calls are correctly skipped.
+ scene_name = "SceneWithMultipleWaitCalls"
+ command = [
+ sys.executable,
+ "-m",
+ "manim",
+ "--renderer",
+ "opengl",
+ "--write_to_movie",
+ "-ql",
+ "--media_dir",
+ str(tmp_path),
+ "-n",
+ "3",
+ simple_scenes_path,
+ scene_name,
+ ]
+ out, err, exit_code = capture(command)
+ assert exit_code == 0, err
+
+
+@video_comparison(
+ "SceneWithMultiplePlayCallsWithNFlag.json",
+ "videos/simple_scenes/480p15/SceneWithMultipleCalls.mp4",
+)
+def test_play_skip(tmp_path, manim_cfg_file, simple_scenes_path):
+ # Intended to test if play calls are correctly skipped.
+ scene_name = "SceneWithMultipleCalls"
+ command = [
+ sys.executable,
+ "-m",
+ "manim",
+ "--renderer",
+ "opengl",
+ "--write_to_movie",
+ "-ql",
+ "--media_dir",
+ str(tmp_path),
+ "-n",
+ "3",
+ simple_scenes_path,
+ scene_name,
+ ]
+ out, err, exit_code = capture(command)
+ assert exit_code == 0, err
diff --git a/tests/test_scene_rendering/opengl/test_opengl_renderer.py b/tests/test_scene_rendering/opengl/test_opengl_renderer.py
index 7a3b44ccc..f1394589d 100644
--- a/tests/test_scene_rendering/opengl/test_opengl_renderer.py
+++ b/tests/test_scene_rendering/opengl/test_opengl_renderer.py
@@ -2,6 +2,7 @@ from unittest.mock import Mock
import pytest
+from manim.renderer.opengl_renderer import OpenGLRenderer
from tests.assert_utils import assert_file_exists
from tests.test_scene_rendering.simple_scenes import *
@@ -44,3 +45,36 @@ def test_force_window_opengl_render_with_format(
scene.render()
assert renderer.window is not None
renderer.window.close()
+
+
[email protected]("enable_preview", [False])
+def test_get_frame_with_preview_disabled(use_opengl_renderer):
+ """Get frame is able to fetch frame with the correct dimensions when preview is disabled"""
+ scene = SquareToCircle()
+ assert isinstance(scene.renderer, OpenGLRenderer)
+ assert not config.preview
+
+ renderer = scene.renderer
+ renderer.update_frame(scene)
+ frame = renderer.get_frame()
+
+ # height and width are flipped
+ assert renderer.get_pixel_shape()[0] == frame.shape[1]
+ assert renderer.get_pixel_shape()[1] == frame.shape[0]
+
+
[email protected]("enable_preview", [True])
+def test_get_frame_with_preview_enabled(use_opengl_renderer):
+ """Get frame is able to fetch frame with the correct dimensions when preview is enabled"""
+ scene = SquareToCircle()
+ assert isinstance(scene.renderer, OpenGLRenderer)
+ assert config.preview is True
+
+ renderer = scene.renderer
+ renderer.update_frame(scene)
+ frame = renderer.get_frame()
+
+ # height and width are flipped
+ assert renderer.get_pixel_shape()[0] == frame.shape[1]
+ assert renderer.get_pixel_shape()[1] == frame.shape[0]
diff --git a/tests/test_scene_rendering/opengl/test_play_logic_opengl.py b/tests/test_scene_rendering/opengl/test_play_logic_opengl.py
new file mode 100644
index 000000000..73e637481
--- /dev/null
+++ b/tests/test_scene_rendering/opengl/test_play_logic_opengl.py
@@ -0,0 +1,89 @@
+from unittest.mock import Mock
+
+import pytest
+
+from manim import *
+from manim import config
+
+from ..simple_scenes import (
+ SceneWithMultipleCalls,
+ SceneWithNonStaticWait,
+ SceneWithStaticWait,
+ SquareToCircle,
+)
+
+
+ sys.version_info < (3, 8),
+ reason="Mock object has a different implementation in python 3.7, which makes it broken with this logic.",
+)
[email protected]("frame_rate", argvalues=[15, 30, 60])
+def test_t_values(using_temp_opengl_config, disabling_caching, frame_rate):
+ """Test that the framerate corresponds to the number of t values generated"""
+ config.frame_rate = frame_rate
+ scene = SquareToCircle()
+ scene.update_to_time = Mock()
+ scene.render()
+ assert scene.update_to_time.call_count == config["frame_rate"]
+ np.testing.assert_allclose(
+ ([call.args[0] for call in scene.update_to_time.call_args_list]),
+ np.arange(0, 1, 1 / config["frame_rate"]),
+ )
+
+
+ sys.version_info < (3, 8),
+ reason="Mock object has a different implementation in python 3.7, which makes it broken with this logic.",
+)
+def test_t_values_with_skip_animations(using_temp_opengl_config, disabling_caching):
+ """Test the behaviour of scene.skip_animations"""
+ scene = SquareToCircle()
+ scene.update_to_time = Mock()
+ scene.renderer._original_skipping_status = True
+ scene.render()
+ assert scene.update_to_time.call_count == 1
+ np.testing.assert_almost_equal(
+ scene.update_to_time.call_args.args[0],
+ 1.0,
+ )
+
+
[email protected](reason="Not currently implemented for opengl")
+def test_static_wait_detection(using_temp_opengl_config, disabling_caching):
+ """Test if a static wait (wait that freeze the frame) is correctly detected"""
+ scene = SceneWithStaticWait()
+ scene.render()
+ # Test is is_static_wait of the Wait animation has been set to True by compile_animation_ata
+ assert scene.animations[0].is_static_wait
+ assert scene.is_current_animation_frozen_frame()
+
+
+def test_non_static_wait_detection(using_temp_opengl_config, disabling_caching):
+ scene = SceneWithNonStaticWait()
+ scene.render()
+ assert not scene.animations[0].is_static_wait
+ assert not scene.is_current_animation_frozen_frame()
+
+
[email protected](reason="Should be fixed in #2133")
+def test_t_values_with_cached_data(using_temp_opengl_config):
+ """Test the proper generation and use of the t values when an animation is cached."""
+ scene = SceneWithMultipleCalls()
+ # Mocking the file_writer will skip all the writing process.
+ scene.renderer.file_writer = Mock(scene.renderer.file_writer)
+ # Simulate that all animations are cached.
+ scene.renderer.file_writer.is_already_cached.return_value = True
+ scene.update_to_time = Mock()
+
+ scene.render()
+ assert scene.update_to_time.call_count == 10
+
+
[email protected](reason="Not currently handled correctly for opengl")
+def test_t_values_save_last_frame(using_temp_opengl_config):
+ """Test that there is only one t value handled when only saving the last frame"""
+ config.save_last_frame = True
+ scene = SquareToCircle()
+ scene.update_to_time = Mock()
+ scene.render()
+ scene.update_to_time.assert_called_once_with(1)
diff --git a/tests/test_scene_rendering/test_opengl_renderer.py b/tests/test_scene_rendering/test_opengl_renderer.py
deleted file mode 100644
index 1e5bebdfa..000000000
--- a/tests/test_scene_rendering/test_opengl_renderer.py
+++ /dev/null
@@ -1,38 +0,0 @@
-import pytest
-
-from manim.renderer.opengl_renderer import OpenGLRenderer
-
-from .simple_scenes import *
-
-
[email protected]("enable_preview", [False])
-def testGetFrameWithPreviewDisabled(use_opengl_renderer):
- """Get frame is able to fetch frame with the correct dimensions when preview is disabled"""
- scene = SquareToCircle()
- assert isinstance(scene.renderer, OpenGLRenderer)
- assert not config.preview
-
- renderer = scene.renderer
- renderer.update_frame(scene)
- frame = renderer.get_frame()
-
- # height and width are flipped
- assert renderer.get_pixel_shape()[0] == frame.shape[1]
- assert renderer.get_pixel_shape()[1] == frame.shape[0]
-
-
[email protected]("enable_preview", [True])
-def testGetFrameWithPreviewEnabled(use_opengl_renderer):
- """Get frame is able to fetch frame with the correct dimensions when preview is enabled"""
- scene = SquareToCircle()
- assert isinstance(scene.renderer, OpenGLRenderer)
- assert config.preview is True
-
- renderer = scene.renderer
- renderer.update_frame(scene)
- frame = renderer.get_frame()
-
- # height and width are flipped
- assert renderer.get_pixel_shape()[0] == frame.shape[1]
- assert renderer.get_pixel_shape()[1] == frame.shape[0]