The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.
Python
Add integration scene stories
apoogdk8f48efe750ab
diff --git a/src/manimgx/rendering/window.py b/src/manimgx/rendering/window.pyindex 914f6d08..8d832509 100644--- a/src/manimgx/rendering/window.py+++ b/src/manimgx/rendering/window.py@@ -22,6 +22,7 @@ import threadingfrom collections.abc import Sequencefrom types import TracebackTypefrom typing import Self+from warnings import deprecatedfrom manimgx import _enginefrom manimgx.rendering.film import Cut@@ -34,8 +35,7 @@ class Window:[`Scene.render`][manimgx.Scene.render] as `take`, and it plays the film as it is recorded.Once it is closed, a film sent to it is cut (see [`Cut`][manimgx.rendering.film.Cut]).- Its viewer can ask for another of the file's scenes (N and P): see- [`scenes`][manimgx.Window.scenes] and [`asked`][manimgx.Window.asked].+ Its viewer can ask for another of the file's scenes (N and P).Args:title: The window's title.@@ -76,6 +76,7 @@ class Window:pipe.close()raise Cut from None+ @deprecated("manimgx's machinery: manimgx preview calls it", category=None)def scenes(self, names: Sequence[str], playing: str) -> None:"""Tell the window the file's scenes, and the one it plays: its viewer can ask forthe others (N, P; see [`asked`][manimgx.Window.asked]).@@ -86,6 +87,7 @@ class Window:"""self._say({"scenes": list(names), "scene": playing})+ @deprecated("manimgx's machinery: manimgx preview calls it", category=None)def failed(self, error: BaseException, trace: str, line: int | None = None) -> None:"""Show the scene's error over the last picture it made, until the next take.@@ -107,6 +109,7 @@ class Window:"""Whether the window is open: until its viewer closes it, or it is closed."""return self._process.poll() is None+ @deprecated("manimgx's machinery: manimgx preview calls it", category=None)def asked(self) -> str | None:"""The scene the viewer asked for last, if they asked since (N, P: the next or theprevious of the file's scenes)."""@@ -147,19 +150,20 @@ class Window:def _listen(self) -> None:"""What the window says, a line of JSON each, as it comes: a scene its viewer asks- for, or why it failed."""+ for, or why it failed; its end of the pipe closed once it has said all."""assert self._process.stdout is not None- for line in self._process.stdout:- try:- said = json.loads(line)- except ValueError:- continue- if not isinstance(said, dict):- continue- if isinstance(scene := said.get("scene"), str):- self._asked.put(scene)- if isinstance(failure := said.get("failure"), str):- self.failure = failure+ with self._process.stdout as lines:+ for line in lines:+ try:+ said = json.loads(line)+ except ValueError:+ continue+ if not isinstance(said, dict):+ continue+ if isinstance(scene := said.get("scene"), str):+ self._asked.put(scene)+ if isinstance(failure := said.get("failure"), str):+ self.failure = failuredef _main() -> None:diff --git a/tests/integration/test_banner.py b/tests/integration/test_banner.pynew file mode 100644index 00000000..627ed4c7--- /dev/null+++ b/tests/integration/test_banner.py@@ -0,0 +1,127 @@+"""ManimBanner.expand opens the logo into the banner as a function of its progress, from the+banner as it is when it begins.++- No part jumps: between two instants the scene computes, nothing moves further than the+ parting's top speed allows.+- It ends exactly on the banner: the expanded banner of a banner scaled by s and moved is the+ unit banner's, scaled by s and moved the same way; what `direction` holds still (the M for+ "right", the shapes for "left", the middle of the banner for "center") has not moved.+- A letter is never seen ahead of the square that uncovers it; the letters go in front of the+ shapes (as the M is) only where none of them overlaps a shape, and end in front.++Each story is told with every frame computed, at 10 and 60 fps.+"""++from fractions import Fraction+from itertools import pairwise+from typing import Literal++import pytest+from tests import scenes++import manimgx as m+from manimgx.config import config++type Direction = Literal["left", "right", "center"]+type Place = tuple[float, float, float] # scale, then shift x, y+# a part as seen: its x-range, its fill opacity, its place in the draw order+type Part = tuple[float, float, float, int]+type Seen = dict[Fraction, dict[str, Part]] # at every instant the scene computes++DIRECTIONS: tuple[Direction, ...] = ("right", "center", "left")+PLACES: list[Place] = [(1.0, 0.0, 0.0), (0.5, 1.0, 2.0), (0.25, -3.0, -1.0)]+RUN_TIME = 1.5+++def expanded(place: Place, direction: Direction, fps: int) -> Seen:+ """What a banner, scaled and moved, shows at every instant of its expanding, at `fps`."""+ config.frame_rate = fps+ scale, dx, dy = place+ b = m.ManimBanner().scale(scale).shift([dx, dy, 0])+ parts: dict[str, m.Mobject] = {"M": b.M, "circle": b.circle, "square": b.square}+ parts["triangle"] = b.triangle+ parts |= dict(zip("anim", b.anim, strict=True))++ def construct(scene: m.Scene) -> None:+ scene.add(b)+ scene.play(b.expand(RUN_TIME, direction))++ def seen(scene: m.Scene) -> dict[str, Part]:+ order = {id(leaf): i for i, leaf in enumerate(scene.display_list())}+ return {+ name: (+ float(part.points[:, 0].min()),+ float(part.points[:, 0].max()),+ float(part.paint.fill[:, 3].max()),+ order.get(id(part), -1),+ )+ for name, part in parts.items()+ }++ return scenes.instants(construct, seen)++[email protected]("fps", [10, 60])[email protected]("direction", DIRECTIONS)[email protected]("place", PLACES)+def test_the_banner_expands_without_a_jump(+ place: Place,+ direction: Direction,+ fps: int,+) -> None:+ seen = expanded(place, direction, fps)+ # the parting's top speed: (6.25 + 0.8)·s over the first two thirds of the run time,+ # eased in and out (ease_in_out_cubic is steepest, slope 3, halfway)+ top = 7.05 * place[0] * 3 / (RUN_TIME * 2 / 3)+ for a, b in pairwise(sorted(seen)):+ for name in ("M", "square"):+ moved = abs(seen[b][name][0] - seen[a][name][0])+ assert moved <= top * float(b - a) + 1e-9, f"{name} jumps at {b} s"++[email protected]("direction", DIRECTIONS)[email protected]("place", PLACES[1:])+def test_the_banner_ends_as_the_unit_banner_scaled_and_moved(+ place: Place,+ direction: Direction,+) -> None:+ scale, dx, _ = place+ unit = expanded(PLACES[0], direction, 10)+ seen = expanded(place, direction, 10)+ start, end, unit_end = seen[min(seen)], seen[max(seen)], unit[max(unit)]+ for name, (x0, x1, *_) in unit_end.items():+ assert end[name][:2] == pytest.approx(+ (scale * x0 + dx, scale * x1 + dx), abs=1e-9+ )++ def middle(parts: dict[str, Part]) -> float:+ return (parts["M"][0] + parts["triangle"][1]) / 2++ if direction == "right":+ assert end["M"][:2] == pytest.approx(start["M"][:2], abs=1e-9)+ elif direction == "left":+ assert end["square"][:2] == pytest.approx(start["square"][:2], abs=1e-9)+ else:+ assert middle(end) == pytest.approx(middle(start), abs=1e-9)+ for name in "anim":+ assert end[name][2] == 1, f"{name} is shown at the end"+ assert end[name][3] > end["circle"][3], f"{name} ends in front of the shapes"++[email protected]("direction", DIRECTIONS)+def test_the_letters_are_uncovered_by_the_shapes(+ direction: Direction,+) -> None:+ seen = expanded(PLACES[1], direction, 60)+ instants = sorted(seen)+ for t in instants:+ square = (seen[t]["square"][0] + seen[t]["square"][1]) / 2+ for name in "anim":+ x0, x1, opacity, _ = seen[t][name]+ assert opacity == 0 or (x0 + x1) / 2 < square, f"{name} ahead at {t} s"+ for a, b in pairwise(instants):+ for name in "anim":+ front = [seen[t][name][3] > seen[t]["circle"][3] for t in (a, b)]+ if front[0] != front[1]: # it changes places with the shapes: none overlaps+ for t in (a, b):+ assert all(seen[t][k][1] < seen[t]["circle"][0] for k in "anim")diff --git a/tests/integration/test_compositing.py b/tests/integration/test_compositing.pynew file mode 100644index 00000000..edf0cdbc--- /dev/null+++ b/tests/integration/test_compositing.py@@ -0,0 +1,216 @@+"""A 3D view composites what can be seen through in depth order, whatever order it is drawn+in: a pixel shows every surface, shape and point on its ray, the nearer over the farther — in a+picture and in a video alike, however many a ray meets. Where things meet edge to edge, each+covers its own part of a pixel."""++from pathlib import Path++import numpy as np+import pytest+from tests import scenes+from tests.integration.corpus.frames import decode++import manimgx as m++SIZE = (320, 180)+OPACITY = 0.4+COLORS = (m.RED, m.GREEN, m.BLUE, m.YELLOW, m.TEAL, m.PURPLE)+++pytestmark = pytest.mark.config(pixel_width=SIZE[0], pixel_height=SIZE[1])+++def stack(+ order: list[int],+ points: frozenset[int] = frozenset(),+ colors: tuple[m.ManimColor, ...] = COLORS,+ meshes: frozenset[int] = frozenset(),+) -> m.Scene:+ """Layers one behind another, layer k nearer than layer k - 1, in `colors[k]`, each+ see-through; added in `order`. Each is a plane filling the view (a shape, or, if in+ `meshes`, a surface), or, if in `points`, a point's disk over its center."""++ def layer(k: int, color: m.ManimColor) -> m.Mobject:+ if k in points:+ shape = m.PMobject(stroke_width=270).add_points(+ [m.ORIGIN], color=color, alpha=OPACITY+ )+ elif k in meshes:+ shape = m.Surface(+ lambda u, v: np.array([u, v, 0.0]),+ u_range=[-20, 20],+ v_range=[-20, 20],+ resolution=1,+ checkerboard_colors=False,+ stroke_width=0,+ shade_in_3d=False, # (its color as given, as a shape's)+ ).set_fill(color, OPACITY)+ else:+ shape = m.Square(side_length=40.0).set_fill(color, OPACITY)+ shape.set_stroke(width=0)+ return shape.shift(0.5 * k * m.OUT)++ def construct(scene: m.ThreeDScene) -> None:+ scene.set_camera_orientation(phi=0.0, theta=-90 * m.DEGREES)+ layers = [layer(k, color) for k, color in enumerate(colors)]+ scene.add(*(layers[k] for k in order))+ scene.wait(0.1)++ return scenes.scene_3d(construct)+++def picture(scene: m.Scene) -> np.ndarray:+ """The first frame the scene shows (RGB rows)."""+ return scenes.frames(scene)[0][..., :3]+++def composite(colors: tuple[m.ManimColor, ...] = COLORS) -> np.ndarray:+ """The layers over black, nearest first: each seen through all nearer ones."""+ rgb = np.zeros(3)+ seen = 1.0 # how much of what is behind the nearer layers shows+ for color in reversed(colors):+ rgb += seen * OPACITY * m.ManimColor(color).to_rgb()+ seen *= 1.0 - OPACITY+ return rgb * 255++[email protected]("colors", [COLORS, COLORS * 2], ids=["six", "twelve"])+def test_see_through_layers_composite_in_depth_order_in_any_order(+ colors: tuple[m.ManimColor, ...],+) -> None:+ # twelve: more than a pixel sorts at once (`FEW`), so it takes them a batch at a time+ n = len(colors)+ forward = picture(stack(list(range(n)), colors=colors))+ backward = picture(stack(list(reversed(range(n))), colors=colors))+ assert np.array_equal(forward, backward)+ center = forward[SIZE[1] // 2, SIZE[0] // 2].astype(float)+ assert np.abs(center - composite(colors)).max() <= 2.0+++ALL, ODD = frozenset(range(len(COLORS))), frozenset(range(1, len(COLORS), 2))+++ ("points", "colors", "meshes"),+ [+ (ALL, COLORS, frozenset()),+ (ODD, COLORS, frozenset()),+ (ALL, (m.TEAL,) * len(COLORS), frozenset()),+ (ODD, COLORS, frozenset({2, 4})),+ ],+ ids=[+ "points",+ "points-between-planes",+ "points-of-one-color",+ "points-between-surfaces",+ ],+)+def test_see_through_points_composite_in_depth_order_in_any_order(+ points: frozenset[int],+ colors: tuple[m.ManimColor, ...],+ meshes: frozenset[int],+) -> None:+ # points alone blend far to near (of one color, in any order); between planes, shapes or+ # surfaces, each blends among the points between the same two planes+ n = len(colors)+ forward = picture(stack(list(range(n)), points, colors, meshes))+ backward = picture(stack(list(reversed(range(n))), points, colors, meshes))+ assert np.array_equal(forward, backward)+ center = forward[SIZE[1] // 2, SIZE[0] // 2].astype(float)+ assert np.abs(center - composite(colors)).max() <= 2.0+++def test_a_title_fixed_in_the_frame_changes_no_pixel_but_its_own() -> None:+ # a deep pile of see-through points and a line beside it: a title fixed in the frame, over+ # everything, takes no place among the scene's depths, so the pile is drawn as without it+ def scene(title: bool) -> m.Scene:+ def construct(s: m.ThreeDScene) -> None:+ s.set_camera_orientation(phi=0.0, theta=-90 * m.DEGREES)+ rng = np.random.default_rng(5)+ pile = m.PMobject(stroke_width=20).add_points(+ rng.normal(scale=0.02, size=(400, 3)) + [-1.0, -1.5, 0.0],+ color=m.YELLOW,+ alpha=0.55,+ )+ s.add(pile, m.Line([4.0, -3.5, 0.0], [4.0, -0.5, 0.0], stroke_width=4))+ if title:+ s.add_fixed_in_frame_mobjects(m.Text("A title").to_corner(m.UL))+ s.wait(0.1)++ return scenes.scene_3d(construct)++ # the title is in the top left; the pile and the line below+ bottom = slice(SIZE[1] // 2, None)+ assert np.array_equal(picture(scene(True))[bottom], picture(scene(False))[bottom])+++def test_points_show_where_an_earlier_frame_had_see_through_surfaces() -> None:+ # a see-through surface over the whole view, then over its top only: the points below it+ # show in the last frame as if it had always been at the top+ def surface(v_range: list[float]) -> m.Surface:+ return m.Surface(+ lambda u, v: np.array([u, v, 1.0]),+ u_range=[-8, 8],+ v_range=v_range,+ resolution=1,+ checkerboard_colors=False,+ stroke_width=0,+ ).set_fill(m.BLUE, 0.5)++ def scene(first: list[float]) -> m.Scene:+ def construct(s: m.ThreeDScene) -> None:+ s.set_camera_orientation(phi=0.0, theta=-90 * m.DEGREES)+ grid = [[x, y, 0.0] for x in np.linspace(-6, 6, 13) for y in (-3, -2, -1)]+ s.add(+ m.PMobject(stroke_width=40).add_points(grid, color=m.YELLOW, alpha=0.6)+ )+ sheet = surface(first)+ s.add(sheet)+ s.wait(0.1)+ s.remove(sheet)+ s.add(surface([3.0, 5.0]))+ s.wait(0.1)++ return scenes.scene_3d(construct)++ bottom = slice(SIZE[1] // 2, None)+ moved = scenes.frames(scene([-5.0, 5.0]))[-1][..., :3]+ still = scenes.frames(scene([3.0, 5.0]))[-1][..., :3]+ assert np.array_equal(moved[bottom], still[bottom])+++def test_a_video_frame_that_outgrows_the_lists_is_drawn_whole(tmp_path: Path) -> None:+ # every pixel meets six planes, more than the lists first hold: the frame is drawn again+ stack(list(range(len(COLORS)))).render(tmp_path / "stack.mp4")+ frame = next(decode(tmp_path / "stack.mp4", SIZE)).astype(float)+ expected = picture(stack(list(range(len(COLORS))))).astype(float)+ assert np.abs(frame - expected).mean() <= 1.0++[email protected]("three_d", [False, True], ids=["2d", "3d"])+def test_a_mesh_and_a_shape_meeting_edge_to_edge_show_no_seam(three_d: bool) -> None:+ # a mesh and a shape side by side on black, their common edge through the middle of a pixel:+ # the pixel is half of each (were their coverages mixed as if independent, a quarter of the+ # black would show through it: a dark seam)+ boundary = 0.5 * 8 / SIZE[1] # half a pixel right of the view's centre, in units++ def seam(scene: m.Scene) -> None:+ if isinstance(scene, m.ThreeDScene):+ scene.set_camera_orientation(phi=0.0, theta=-90 * m.DEGREES)+ mesh = m.Surface(+ lambda u, v: np.array([u, v, 0]),+ u_range=[-5, boundary],+ v_range=[-3, 3],+ resolution=(1, 1),+ stroke_width=0,+ )+ corners = [[boundary, -3, 0], [5, -3, 0], [5, 3, 0], [boundary, 3, 0]]+ shape = m.Polygon(*corners, stroke_width=0, fill_opacity=1)+ scene.add(mesh.set_color(m.WHITE), shape.set_fill(m.WHITE))+ scene.wait(0.1)++ told = scenes.scene_3d(seam) if three_d else scenes.scene(seam)+ shown = picture(told).astype(float)+ row, middle = SIZE[1] // 2, SIZE[0] // 2+ left, here, right = (shown[row, middle + k] for k in (-3, 0, 3))+ assert np.abs(here - 0.5 * (left + right)).max() <= 2.0diff --git a/tests/integration/test_drawing.py b/tests/integration/test_drawing.pynew file mode 100644index 00000000..947d1426--- /dev/null+++ b/tests/integration/test_drawing.py@@ -0,0 +1,284 @@+"""What the engine draws is what the shapes say.++Strokes are drawn as SVG and PostScript define them (h: half the stroke's width).++- A cap ends a stroke where it shows: butt (AUTO) at its end, square h past it, round a+ half-disk of radius h; a partial reveal's moving end is capped like any other.+- Each dash is a stroke of its own: its ends are capped.+- A subpath that is one point is a dot with round caps, a square with square ones, nothing with+ butt ones. A point cloud's point is that dot: as wide as a stroke of its width.+- A joint fills the outside of a turn: a miter to its tip (AUTO), a bevel across the bodies'+ outer corners, round an arc of radius h. A closed subpath shown whole is joined at its seam.+- A stroke is painted once: however its pieces overlap, no pixel blends it twice.++A fill covers what its curves enclose (closed by a straight return to their start), however+far its control points bulge. An image enlarged is reconstructed from its pixels by its+`resampling_algorithm`: nearest holds each pixel, linear runs straight between pixel centres,+cubic follows Keys' kernel.+"""++from collections.abc import Callable++import numpy as np+import pytest+from tests import oracles, scenes++import manimgx as m+from manimgx.config import config+from manimgx.constants import Resampling++W, H = 640, 360+WIDTH = 40 # stroke width: h = 0.2 units+pytestmark = pytest.mark.config(pixel_width=W, pixel_height=H, frame_rate=10)+++def _frames(build: Callable[[m.Scene], None]) -> list[np.ndarray]:+ """The red channel of every frame of a scene whose construct is `build`, white on black."""+ return [rgba[..., 0] / 255 for rgba in scenes.frames(scenes.scene(build))]+++def _pixel(x: float, y: float) -> tuple[int, int]:+ """The pixel (row, column) holding scene point (x, y)."""+ unit = W / config.frame_width+ return int(np.floor(H / 2 - y * unit)), int(np.floor(W / 2 + x * unit))+++def _extent(row: np.ndarray) -> float:+ """How long a row's drawn run is, in scene units: its coverage summed."""+ return float(row.sum()) / (W / config.frame_width)+++# the rows 6 to 7 px below the axis (h = 9 px): a round cap reaches past the end by its mean+# half-chord there+BAND = np.linspace(6, 7, 1001)+ROUND_BAND = float(np.mean(np.sqrt(81 - BAND**2))) / 45+++ ("cap", "past", "past_off_axis"),+ [+ (m.CapStyleType.AUTO, 0.0, 0.0),+ (m.CapStyleType.BUTT, 0.0, 0.0),+ (m.CapStyleType.SQUARE, 0.2, 0.2),+ (m.CapStyleType.ROUND, 0.2, ROUND_BAND),+ ],+ ids=["auto", "butt", "square", "round"],+)+def test_a_cap_ends_the_stroke_where_it_shows(+ cap: m.CapStyleType,+ past: float,+ past_off_axis: float,+) -> None:+ def build(scene: m.Scene) -> None:+ line = m.Line(m.LEFT * 2, m.RIGHT * 2, stroke_width=WIDTH).set_cap_style(cap)+ scene.play(m.Create(line), run_time=1, rate_func=m.linear)++ frames = _frames(build)+ row = H // 2+ off = row + 6 # the band 6 to 7 px below the axis+ whole, half = frames[-1], frames[5] # at 10 fps: the whole line, and its first half+ assert _extent(whole[row]) == pytest.approx(4 + 2 * past, abs=0.03)+ assert _extent(whole[off]) == pytest.approx(4 + 2 * past_off_axis, abs=0.03)+ assert _extent(half[row]) == pytest.approx(2 + 2 * past, abs=0.03)+++def test_each_dash_is_capped() -> None:+ def build(scene: m.Scene) -> None:+ dashed = m.DashedLine(m.LEFT * 2, m.RIGHT * 2, dash_length=0.5, stroke_width=10)+ scene.add(dashed.set_cap_style(m.CapStyleType.ROUND))++ row = _frames(build)[-1][_pixel(0, 0)[0]]+ runs = np.split(row, np.flatnonzero(np.diff((row > 0).astype(int)) == 1) + 1)[1:]+ # ⌈4 / 0.5 · ½⌉ = 4 dashes, each ½ · 4 / 4 = 0.5 long, and h = 0.05 longer at both ends+ assert [_extent(r) for r in runs] == pytest.approx([0.6] * 4, abs=0.03)+++ ("cap", "centre", "diagonal", "far"),+ [+ (m.CapStyleType.ROUND, 1, 0, 0),+ (m.CapStyleType.SQUARE, 1, 1, 0),+ (m.CapStyleType.BUTT, 0, 0, 0),+ ],+ ids=["round", "square", "butt"],+)+def test_a_point_is_a_dot(+ cap: m.CapStyleType,+ centre: float,+ diagonal: float,+ far: float,+) -> None:+ def build(scene: m.Scene) -> None:+ point = m.VMobject(stroke_width=WIDTH).set_points(np.zeros((4, 3)))+ scene.add(point.set_cap_style(cap))++ frame = _frames(build)[-1]+ for (x, y), expected in (+ ((0.02, 0.02), centre),+ ((0.16, 0.16), diagonal),+ ((0.25, 0.0), far),+ ):+ assert frame[_pixel(x, y)] == pytest.approx(expected, abs=0.05)+++def test_a_cloud_point_is_the_dot_of_a_one_point_subpath() -> None:+ def drawn(mob: m.Mobject) -> np.ndarray:+ def build(scene: m.Scene) -> None:+ scene.add(mob)++ return _frames(build)[-1]++ cloud = m.PMobject(stroke_width=WIDTH).add_points([m.ORIGIN], color=m.WHITE)+ dot = m.VMobject(stroke_width=WIDTH).set_points(np.zeros((4, 3)))+ point, stroke = drawn(cloud), drawn(dot.set_cap_style(m.CapStyleType.ROUND))+ assert point.sum() == pytest.approx(stroke.sum(), rel=0.02)+ assert np.abs(point - stroke).max() <= 0.1+++ ("joint", "near", "middle", "tip"),+ [+ (m.LineJointType.AUTO, 1, 1, 1),+ (m.LineJointType.MITER, 1, 1, 1),+ (m.LineJointType.BEVEL, 1, 0, 0),+ (m.LineJointType.ROUND, 1, 1, 0),+ ],+ ids=["auto", "miter", "bevel", "round"],+)+def test_a_joint_fills_the_outside_of_the_turn(+ joint: m.LineJointType,+ near: float,+ middle: float,+ tip: float,+) -> None:+ def build(scene: m.Scene) -> None:+ corner = m.VMobject(stroke_width=WIDTH).set_points_as_corners(+ [m.LEFT * 2 + m.DOWN, m.RIGHT + m.DOWN, m.RIGHT + m.UP]+ )+ corner.joint_type = joint+ scene.add(corner)++ frame = _frames(build)[-1]+ # along the outer diagonal from the corner (1, -1), in h: the bevel's line crosses it at 0.5,+ # the round's arc at 0.71, the miter's tip at 1+ for s, expected in ((0.3, near), (0.6, middle), (0.9, tip)):+ assert frame[_pixel(1 + s * 0.2, -1 - s * 0.2)] == pytest.approx(+ expected, abs=0.05+ )+++def test_a_closed_subpath_is_joined_at_its_seam() -> None:+ def build(scene: m.Scene) -> None:+ scene.add(+ m.Square(side_length=2, stroke_width=WIDTH).set_cap_style(+ m.CapStyleType.ROUND+ )+ )++ frame = _frames(build)[-1]+ for x, y in (+ (1, 1),+ (-1, 1),+ (-1, -1),+ (1, -1),+ ): # every corner mitered, its seam's too+ assert frame[+ _pixel(x + 0.18 * np.sign(x), y + 0.18 * np.sign(y))+ ] == pytest.approx(1, abs=0.05)++[email protected]("joint", list(m.LineJointType), ids=lambda j: j.name.lower())[email protected]("cap", list(m.CapStyleType), ids=lambda c: c.name.lower())+def test_a_stroke_is_painted_once(joint: m.LineJointType, cap: m.CapStyleType) -> None:+ def build(scene: m.Scene) -> None:+ zig = [np.array([0.4 * i - 2, 0.8 if i % 2 else -0.8, 0]) for i in range(11)]+ path = m.VMobject(stroke_width=WIDTH, stroke_opacity=0.5).set_points_as_corners(+ zig+ )+ path.joint_type = joint+ scene.add(path.set_cap_style(cap))+ dashed = m.DashedLine(+ m.LEFT * 2 + m.UP * 2, m.RIGHT * 2 + m.UP * 2.5, stroke_width=WIDTH+ )+ scene.add(dashed.set_stroke(opacity=0.5).set_cap_style(cap))++ frame = _frames(build)[-1]+ assert frame.max() == pytest.approx(0.5, abs=1 / 255)+++class Enlarged(m.Scene):+ """A two-pixel image, black then white, stretched over the whole frame."""++ def __init__(self, algorithm: Resampling) -> None:+ super().__init__()+ self.algorithm = algorithm++ def construct(self) -> None:+ pixels = np.array([[0, 255]], dtype=np.uint8)+ image = m.ImageMobject(pixels, resampling_algorithm=self.algorithm)+ image.stretch_to_fit_width(config.frame_width)+ self.add(image.stretch_to_fit_height(config.frame_height))++[email protected](pixel_width=320, pixel_height=180)+ ("algorithm", "kernel"),+ [+ (0, lambda t: np.round(t)),+ (2, lambda t: t),+ (3, lambda t: -(t**3) + 1.5 * t**2 + 0.5 * t), # Keys, a = -1/2, edges held+ ],+ ids=["nearest", "linear", "cubic"],+)+def test_an_image_is_reconstructed_by_its_resampling_algorithm(+ algorithm: Resampling,+ kernel: Callable[[np.ndarray], np.ndarray],+) -> None:+ row = scenes.frames(Enlarged(algorithm))[-1][90, :, 0]+ columns = np.arange(90, 231, 10) # between the pixels' centres, at 80 and 240+ t = (columns + 0.5 - 80) / 160+ assert row[columns] == pytest.approx(255 * kernel(t), abs=1.5)+++def _filled(mob: m.VMobject) -> float:+ """The area a white fill shows alone on black, in square units: its pixels' coverage+ summed."""++ def alone(scene: m.Scene) -> None:+ scene.add(mob)+ scene.wait(0.1)++ shown = scenes.frames(scenes.scene(alone))[0][..., 0].astype(float) / 255+ return float(shown.sum()) / (H / config.frame_height) ** 2+++def _enclosed(points: np.ndarray) -> float:+ """The area cubic curves (four points each) enclose, closed by a straight return to+ their start."""+ return abs(oracles.polygon_area(oracles.sample(points, 4001)))++[email protected]("kind", ["open", "bulging"])+def test_a_fill_covers_what_its_curves_enclose(kind: str) -> None:+ # large enough that the composite visits only the tiles its curves cross and those inside them: a fill closed by+ # the straight return to its start (an open path: no curve runs there), and one whose control points bulge far+ # past its curve (inside its control polygon, outside it), each cover what their curves enclose+ if kind == "open":+ corners = [[-3, -2, 0], [0, 2, 0], [3, -2, 0]]+ points = np.concatenate(+ [+ [p, p + (q - p) / 3, p + 2 * (q - p) / 3, q]+ for p, q in zip(+ np.array(corners[:-1], float),+ np.array(corners[1:], float),+ strict=True,+ )+ ]+ )+ else:+ points = np.array(+ [[-3, -1.5, 0], [-3, 3.5, 0], [3, 3.5, 0], [3, -1.5, 0]], float+ )+ mob = m.VMobject(fill_opacity=1, stroke_width=0).set_points(points)+ mob.set_fill(m.WHITE, 1)+ assert abs(_filled(mob) - _enclosed(points)) <= 0.005 * _enclosed(points)diff --git a/tests/integration/test_engine.py b/tests/integration/test_engine.pynew file mode 100644index 00000000..e3d37a5b--- /dev/null+++ b/tests/integration/test_engine.py@@ -0,0 +1,111 @@+"""The engine in a process: the GPU comes up only in a process that will draw, on a thread of+its own, started as early as the process knows it will (a film that draws, the command line's+drawing commands), so that the first frame need not wait for it; a process that never draws+never brings it up. One that exits before the GPU is up waits for it, rather than unload a+driver while it starts (lavapipe crashed a process that did)."""++import subprocess+import sys+from pathlib import Path++from manimgx import _engine++SCENE = """+import manimgx as m+++class Square(m.Scene):+ def construct(self):+ self.play(m.Create(m.Square()))+"""+++def run(code: str, cwd: Path | None = None) -> subprocess.CompletedProcess[bytes]:+ """`code` run by a fresh Python."""+ return subprocess.run(+ [sys.executable, "-c", code], capture_output=True, check=False, cwd=cwd+ )+++def assert_ran(done: subprocess.CompletedProcess[bytes]) -> None:+ assert done.returncode == 0, done.stderr.decode(errors="replace")+++def test_importing_manimgx_does_not_start_the_gpu() -> None:+ # start_gpu says whether it began the GPU: nothing had+ assert_ran(+ run("import manimgx\nfrom manimgx import _engine\nassert _engine.start_gpu()")+ )+++def test_a_film_that_only_counts_or_records_its_frames_does_not_start_the_gpu() -> None:+ code = f"""{SCENE}+from manimgx import _engine++Square().render() # its frames counted+Square().render(take=lambda data: None) # recorded, for the player to draw+assert _engine.start_gpu()+"""+ assert_ran(run(code))+++def test_a_film_that_draws_starts_the_gpu_as_it_begins() -> None:+ code = """+from manimgx import _engine+from manimgx.rendering.film import Film++Film(frames=lambda frame: None)+assert not _engine.start_gpu()+"""+ assert_ran(run(code))+++def test_the_command_line_starts_the_gpu_for_a_command_that_draws(+ tmp_path: Path,+) -> None:+ # the scene's file checks, as the command loads it, that the GPU has been started+ (tmp_path / "scene.py").write_text(+ "from manimgx import _engine\n\nassert not _engine.start_gpu()\n" + SCENE,+ encoding="utf-8",+ )+ command = (+ "from manimgx.cli import main\ntry:\n main()\nexcept SystemExit as e:\n"+ )+ drawn = run(+ "import sys\nsys.argv = ['manimgx', 'check', 'scene.py']\n"+ + command+ + " assert not e.code, e.code",+ cwd=tmp_path,+ )+ assert_ran(drawn)+ shown = run(+ "import sys\nsys.argv = ['manimgx', '--version']\n"+ + command+ + " pass\nfrom manimgx import _engine\nassert _engine.start_gpu()"+ )+ assert_ran(shown)+++def test_the_commands_that_draw_are_every_command_but_preview() -> None:+ from manimgx.cli import DRAWING, app++ commands = {+ c.name or getattr(c.callback, "__name__", "") for c in app.registered_commands+ }+ assert set(DRAWING) == commands - {"preview"} # its window draws its takes+++def test_a_process_that_starts_the_gpu_and_exits_at_once_exits_cleanly() -> None:+ # the engine alone, loaded from its file (the package's imports would give the GPU a head+ # start), the GPU started, and the process ended at once: Python waits for it as it exits+ code = f"""+import atexit, importlib.util+waiting = atexit._ncallbacks()+spec = importlib.util.spec_from_file_location("manimgx._engine", {_engine.__file__!r})+engine = importlib.util.module_from_spec(spec)+spec.loader.exec_module(engine)+assert atexit._ncallbacks() == waiting + 1, "nothing waits for the GPU at exit"+assert engine.start_gpu()+"""+ for _ in range(5):+ assert_ran(run(code))diff --git a/tests/integration/test_film.py b/tests/integration/test_film.pynew file mode 100644index 00000000..dccd294a--- /dev/null+++ b/tests/integration/test_film.py@@ -0,0 +1,68 @@+"""A film's hooks: each frame handed over as it is sent, and `Cut`, which ends the film wherever+a hook raises it — at its last frame too, which is sent only when the film closes."""++from collections.abc import Callable+from pathlib import Path+from typing import cast++import pytest++import manimgx as m+from manimgx.config import config+from manimgx.rendering.film import Cut, Frame, X264Preset+++class Held(m.Scene):+ def construct(self) -> None:+ self.play(m.Create(m.Square()))+ self.wait() # the last frames: one held frame, sent when the film closes+++pytestmark = pytest.mark.config(pixel_width=320, pixel_height=180)+++def at_the_last(error: Exception) -> tuple[list[Frame], Callable[[Frame], None]]:+ """A frame sink that raises `error` at the held frame that ends the film."""+ sent: list[Frame] = []++ def sink(frame: Frame) -> None:+ sent.append(frame)+ if frame.repeat > 1:+ raise error++ return sent, sink+++def test_a_cut_at_the_last_frame_keeps_the_film(tmp_path: Path) -> None:+ sent, sink = at_the_last(Cut())+ film = Held().render(tmp_path / "held.mp4", preset="medium", crf=23, frames=sink)+ assert sent[-1].index + sent[-1].repeat == film.frame_count+ assert (tmp_path / "held.mp4").stat().st_size > 0+++def test_an_error_at_the_last_frame_abandons_the_video(tmp_path: Path) -> None:+ _, sink = at_the_last(ValueError("the sink failed"))+ with pytest.raises(ValueError, match="the sink failed"):+ Held().render(tmp_path / "held.mp4", frames=sink)+ assert list(tmp_path.iterdir()) == [] # not the video, nor a part of it+++def test_a_video_needs_even_sides(tmp_path: Path) -> None:+ config.pixel_width = 321 # H.264's 4:2:0 halves both sides+ with pytest.raises(ValueError, match="an even width and height, not 321x180"):+ Held().render(tmp_path / "odd.mp4")+++def test_an_unknown_encoder_preset_fails_before_writing(tmp_path: Path) -> None:+ with pytest.raises(ValueError, match="unknown x264 preset"):+ Held().render(tmp_path / "bad.mp4", preset=cast(X264Preset, "unknown"))+ assert list(tmp_path.iterdir()) == []++[email protected]("crf", [-0.1, 51.1, float("nan"), float("inf")])+def test_an_invalid_crf_fails_before_writing(tmp_path: Path, crf: float) -> None:+ with pytest.raises(+ ValueError, match="x264 CRF must be a finite number from 0 to 51"+ ):+ Held().render(tmp_path / "bad.mp4", crf=crf)+ assert list(tmp_path.iterdir()) == []diff --git a/tests/integration/test_light.py b/tests/integration/test_light.pynew file mode 100644index 00000000..69252404--- /dev/null+++ b/tests/integration/test_light.py@@ -0,0 +1,915 @@+"""A mobject with a material is lit by the scene's lights, as a physical surface is: a white+matte surface facing a light of intensity 1 shows white, a point light falls off with the+square of the distance, an ambient light lights every side alike, what is brighter than white+is clipped or rolled off as the camera says, and a highlight narrower than a pixel shows its+light over the pixel, steady as the camera turns. An environment lights with a picture of the+surroundings: a uniform one as an ambient light of its light does, its picture turning with+it, a mirror showing each direction's light where it reflects that direction, and a sun in it+as a sun of its light does, casting shadows. A path (a filled+shape) with a material is lit as a mesh with it is (its material alone: not Manim's shading+too), and shadows fall on it; what a path shows casts a shadow, as a mesh does. With ambient+occlusion, the light from all around is shut out where the surfaces near a point block it — a+floor inside a ring, beside a wall — by paths and meshes alike, but not by or from what can be+seen through, and a sun's light is left as it was. With bloom, a light brighter than white glows+into the dark around it, more with more strength and less farther off; what the glow spreads,+the light leaves; it is spread from the light the view shows (what hides a light hides its+glow) and lies over everything the view shows, paint and what is fixed in the frame too, and+alone where it shows nothing; paint never glows; and a moving light's glow moves with it+unchanged. A mobject without a material is shaded as it always was, whatever the lights.+"""++import itertools+from collections.abc import Callable+from pathlib import Path++import numpy as np+import pytest+from tests import scenes++import manimgx as m++SIZE = (160, 90)+MATTE = m.Material(roughness=1.0)+pytestmark = pytest.mark.config(pixel_width=SIZE[0], pixel_height=SIZE[1])+++def frames(build: Callable[[m.ThreeDScene], None]) -> list[np.ndarray]:+ """Every frame a 3D scene shows, looking straight down the z axis (RGB rows)."""++ def construct(scene: m.ThreeDScene) -> None:+ scene.set_camera_orientation(phi=0.0, theta=-90 * m.DEGREES)+ build(scene)++ shown = scenes.frames(scenes.scene_3d(construct))+ return [rgba[..., :3] for rgba in shown]+++def plane(material: m.Material | None = MATTE, z: float = 0.0) -> m.Mobject:+ """A white plane filling the view, facing the camera (and the z axis)."""+ surface = m.Surface(+ lambda u, v: np.array([u, v, z]),+ u_range=[-9, 9],+ v_range=[-5, 5],+ resolution=(2, 2),+ stroke_width=0,+ )+ surface.set_color(m.WHITE)+ return surface if material is None else surface.set_material(material)+++def center(picture: np.ndarray) -> np.ndarray:+ return picture[SIZE[1] // 2, SIZE[0] // 2].astype(float)+++def linear(value: float) -> float:+ """An sRGB-encoded level (0-255) in linear light."""+ c = value / 255+ return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4+++def test_a_white_matte_surface_facing_a_light_of_intensity_one_shows_white() -> None:+ def build(scene: m.ThreeDScene) -> None:+ scene.add(plane(), m.SunLight(5 * m.OUT, intensity=1.0))+ scene.wait(0.1)++ assert (center(frames(build)[0]) >= 254).all()+++def test_half_the_exposure_shows_half_the_light() -> None:+ def build(scene: m.ThreeDScene) -> None:+ scene.camera.exposure = 0.5+ scene.add(plane(), m.SunLight(5 * m.OUT, intensity=1.0))+ scene.wait(0.1)++ level = center(frames(build)[0])+ assert abs(linear(level[0]) - 0.5) < 0.02+++def test_a_point_light_falls_off_with_the_square_of_the_distance() -> None:+ def at(distance: float) -> float:+ def build(scene: m.ThreeDScene) -> None:+ scene.camera.exposure = 0.25 # nothing clips+ scene.add(+ plane(), m.PointLight(distance * m.OUT, intensity=1.0, radius=100.0)+ )+ scene.wait(0.1)++ return linear(center(frames(build)[0])[0])++ near, far = at(1.0), at(2.0)+ assert abs(near / far - 4.0) < 0.25+++def test_an_ambient_light_lights_every_side_alike() -> None:+ def build(scene: m.ThreeDScene) -> None:+ sphere = m.Sphere(radius=2.0, resolution=(48, 48), stroke_width=0).set_color(+ m.WHITE+ )+ scene.add(+ sphere.set_material(m.Material(roughness=1.0)),+ m.AmbientLight(intensity=0.5),+ )+ scene.wait(0.1)++ picture = frames(build)[0]+ y, x = np.mgrid[: SIZE[1], : SIZE[0]]+ radius = 2.0 / 8.0 * SIZE[1] # (the frame is 8 units tall)+ inside = (x + 0.5 - SIZE[0] / 2) ** 2 + (y + 0.5 - SIZE[1] / 2) ** 2 < (+ 0.8 * radius+ ) ** 2+ seen = picture[inside]+ assert seen.max() - seen.min() <= 3+++def test_a_surface_is_brightest_where_it_faces_the_sun() -> None:+ def build(scene: m.ThreeDScene) -> None:+ sphere = m.Sphere(radius=2.0, resolution=(48, 48), stroke_width=0).set_color(+ m.WHITE+ )+ scene.add(+ sphere.set_material(m.Material(roughness=1.0)),+ m.SunLight(5 * m.RIGHT + m.OUT),+ )+ scene.wait(0.1)++ picture = frames(build)[0]+ row = picture[SIZE[1] // 2, :, 0].astype(float)+ lit, unlit = row[SIZE[0] // 2 + 10], row[SIZE[0] // 2 - 10]+ assert lit > unlit + 40+++def test_a_white_rough_metal_in_a_uniform_light_shows_that_light_at_any_roughness() -> (+ None+):+ # a white furnace: a surface that loses no energy shows its surroundings' light and no+ # more, rough metal as smooth (the light single scattering loses on a rough surface is+ # given back, as Filament does)+ def level(roughness: float) -> float:+ def build(scene: m.ThreeDScene) -> None:+ sphere = m.Sphere(radius=2.0, resolution=(48, 48), stroke_width=0)+ sphere.set_color(m.WHITE).set_material(+ m.Material(metallic=1.0, roughness=roughness)+ )+ scene.add(sphere, m.AmbientLight(intensity=0.5))+ scene.wait(0.1)++ return linear(center(frames(build)[0])[0])++ for roughness in (0.25, 0.5, 0.75, 1.0):+ assert abs(level(roughness) - 0.5) < 0.01+++def radiance_file(path: Path, light: np.ndarray) -> Path:+ """A Radiance (.hdr) file of a grey picture's light (rows from the top), its pixels flat."""+ height, width = light.shape+ mantissa, exponent = np.frexp(light)+ rgbe = np.zeros((height, width, 4), np.uint8)+ rgbe[..., :3] = np.where(light > 0, mantissa * 256, 0).astype(np.uint8)[..., None]+ rgbe[..., 3] = np.where(light > 0, exponent + 128, 0)+ head = b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\n\n-Y %d +X %d\n" % (height, width)+ path.write_bytes(head + rgbe.tobytes())+ return path+++def ball(material: m.Material, light: m.Light) -> np.ndarray:+ """A white ball with a material, seen from above, lit by one light."""++ def build(scene: m.ThreeDScene) -> None:+ sphere = m.Sphere(radius=2.0, resolution=(48, 48), stroke_width=0)+ scene.add(sphere.set_color(m.WHITE).set_material(material), light)+ scene.wait(0.1)++ return frames(build)[0].astype(int)+++ ("metallic", "roughness"), [(0.0, 1.0), (0.0, 0.3), (1.0, 0.2), (1.0, 0.8)]+)+def test_a_uniform_environment_lights_as_an_ambient_light_of_its_light_does(+ tmp_path: Path, metallic: float, roughness: float+) -> None:+ grey = radiance_file(tmp_path / "grey.hdr", np.full((64, 128), 0.5))+ material = m.Material(metallic=metallic, roughness=roughness)+ around = ball(material, m.EnvironmentLight(grey))+ ambient = ball(material, m.AmbientLight(intensity=0.5))+ assert np.abs(around - ambient).max() <= 1+++def bright_spot(u: float, v: float = 0.5) -> np.ndarray:+ """A dark picture with a soft bright spot at (u, v) (fractions of its width and height)."""+ height, width = 64, 128+ y, x = np.mgrid[:height, :width] + 0.5+ across = (+ x - u * width + width / 2+ ) % width - width / 2 # (around the picture's seam)+ return 0.02 + 8.0 * np.exp(-(across**2 + (y - v * height) ** 2) / (2 * 4.0**2))+++def test_an_environment_turns_with_its_light(tmp_path: Path) -> None:+ # a quarter turn about the scene's up moves the picture's centre (seen along RIGHT) to UP:+ # as the same picture with its spot a quarter of its width to the left+ ahead = radiance_file(tmp_path / "ahead.hdr", bright_spot(0.5))+ left = radiance_file(tmp_path / "left.hdr", bright_spot(0.25))+ shiny = m.Material(metallic=1.0, roughness=0.3)+ turned = ball(shiny, m.EnvironmentLight(ahead).rotate(m.PI / 2, axis=m.OUT))+ assert np.abs(turned - ball(shiny, m.EnvironmentLight(left))).max() <= 3+ assert np.abs(turned - ball(shiny, m.EnvironmentLight(ahead))).max() > 60+++def test_a_mirror_shows_each_direction_where_it_reflects_it(tmp_path: Path) -> None:+ # a spot on the horizon to the right of the picture's centre (seen along RIGHT) is DOWN+ # in the scene, turning right as one looks across it: a mirror ball seen from above+ # shows it on its DOWN side, halfway out (where its surface faces between up and DOWN)+ spot = radiance_file(tmp_path / "spot.hdr", bright_spot(0.75))+ shown = ball(m.Material(metallic=1.0, roughness=0.1), m.EnvironmentLight(spot))+ # where the spot shows: the middle of what is brighter than most of the ball+ level = shown.sum(axis=2).astype(float)+ weight = np.clip(level - np.median(level[level > 0]) - 60, 0, None)+ y, x = np.mgrid[: SIZE[1], : SIZE[0]] + 0.5+ radius = 2.0 / 8.0 * SIZE[1] # (the frame is 8 units tall)+ below = ((y * weight).sum() / weight.sum() - SIZE[1] / 2) / radius # rows run down+ across = ((x * weight).sum() / weight.sum() - SIZE[0] / 2) / radius+ assert abs(below - np.sqrt(0.5)) < 0.1+ assert abs(across) < 0.1+++def sun_picture(+ path: Path, toward: tuple[float, float], glow: float+) -> tuple[Path, float]:+ """A Radiance file of a dark sky with a sun toward (azimuth, elevation) in degrees, a disc+ as wide as the Sun (0.53 degrees) of light `glow`, each pixel's share of it found by 8 x 8+ points; and what the sun shows on a white matte surface facing it."""+ height, width = 256, 512+ az, el = np.radians(toward)+ sun = np.array([np.cos(el) * np.cos(az), np.cos(el) * np.sin(az), np.sin(el)])+ inside = np.zeros((height, width))+ for k in range(64):+ u = (np.arange(width) + (k % 8 + 0.5) / 8) / width+ v = (np.arange(height) + (k // 8 + 0.5) / 8) / height+ phi, theta = np.meshgrid((0.5 - u) * 2 * np.pi, v * np.pi)+ d = np.stack(+ [np.sin(theta) * np.cos(phi), np.sin(theta) * np.sin(phi), np.cos(theta)],+ -1,+ )+ inside += (d @ sun > np.cos(np.radians(0.265))) / 64+ solid = (+ np.sin((np.arange(height) + 0.5) / height * np.pi)[:, None]+ * (2 * np.pi / width)+ * (np.pi / height)+ )+ shown = float((inside * glow * solid).sum() / np.pi)+ return radiance_file(path, 0.001 + inside * glow), shown+++def test_an_environments_sun_lights_as_a_sun_of_its_light_does(tmp_path: Path) -> None:+ # its light comes from its direction alone, all of it: as a sun's of the light it sends+ picture, shown = sun_picture(tmp_path / "sun.hdr", (30.0, 60.0), 22_000.0)+ toward = np.array(+ [+ np.cos(np.radians(60)) * np.cos(np.radians(30)),+ np.cos(np.radians(60)) * np.sin(np.radians(30)),+ np.sin(np.radians(60)),+ ]+ )++ def view(light: m.Light) -> np.ndarray:+ def build(scene: m.ThreeDScene) -> None:+ scene.add(plane(), light)+ scene.wait(0.1)++ return center(frames(build)[0])++ around = view(m.EnvironmentLight(picture, shadows=False))+ sun = view(m.SunLight(toward, intensity=shown, shadows=False))+ assert sun.min() > 100+ assert np.abs(around - sun).max() <= 1+++def test_an_environments_sun_casts_a_shadow(tmp_path: Path) -> None:+ # a sun 45 degrees up over LEFT: a ball 2 above the floor shadows the floor 2 to the right+ picture, _ = sun_picture(tmp_path / "sun.hdr", (180.0, 45.0), 30_000.0)++ def view(shadows: bool) -> np.ndarray:+ def build(scene: m.ThreeDScene) -> None:+ ball = m.Sphere(radius=0.6, resolution=(24, 24), stroke_width=0).shift(+ 2 * m.OUT+ )+ scene.add(+ plane(),+ ball.set_material(m.Material()),+ m.EnvironmentLight(picture, shadows=shadows),+ )+ scene.wait(0.1)++ return frames(build)[0]++ lit, shadowed = view(False), view(True)+ assert shadowed[floor_at(2.0)].max() < lit[floor_at(2.0)].max() - 100+ assert (shadowed[floor_at(-2.0)] == lit[floor_at(-2.0)]).all()+++def test_agx_rolls_off_what_clipping_saturates() -> None:+ def shown(tone: str) -> np.ndarray:+ def build(scene: m.ThreeDScene) -> None:+ scene.camera.tone_mapping = tone # type: ignore+ scene.add(plane(), m.SunLight(5 * m.OUT, intensity=4.0))+ scene.wait(0.1)++ return center(frames(build)[0])++ clipped, rolled = shown("linear"), shown("agx")+ assert (clipped >= 254).all()+ assert (rolled < 250).all()+ assert (rolled > 200).all()+++def test_a_material_tweens() -> None:+ def sphere(roughness: float) -> m.Mobject:+ mob = m.Sphere(radius=2.0, resolution=(48, 48), stroke_width=0).set_color(m.RED)+ return mob.set_material(m.Material(roughness=roughness))++ def still(roughness: float) -> np.ndarray:+ def build(scene: m.ThreeDScene) -> None:+ scene.add(sphere(roughness), m.SunLight(5 * m.OUT + m.RIGHT))+ scene.wait(0.1)++ return frames(build)[0]++ def build(scene: m.ThreeDScene) -> None:+ mob = sphere(0.1)+ scene.add(mob, m.SunLight(5 * m.OUT + m.RIGHT))+ scene.play(mob.animate.set_material(m.Material(roughness=0.9)), run_time=0.5)++ tween = frames(build)+ assert np.array_equal(tween[0], still(0.1))+ assert np.array_equal(tween[-1], still(0.9))+ assert (+ len({picture.tobytes() for picture in tween}) > 10+ ) # through every roughness between+++def test_a_scene_without_lights_lights_its_materials_by_its_camera() -> None:+ def build(scene: m.ThreeDScene) -> None:+ sphere = m.Sphere(radius=2.0, resolution=(48, 48), stroke_width=0).set_color(+ m.WHITE+ )+ scene.add(sphere.set_material(m.Material()))+ scene.wait(0.1)++ assert center(frames(build)[0]).max() > 60+++def test_a_path_with_a_material_is_lit_as_a_mesh_with_it() -> None:+ def view(kind: str) -> np.ndarray:+ def build(scene: m.ThreeDScene) -> None:+ if kind == "path":+ mob: m.Mobject = m.Square(side_length=6, stroke_width=0, fill_opacity=1)+ else:+ mob = m.Surface(+ lambda u, v: np.array([u, v, 0]),+ u_range=[-3, 3],+ v_range=[-3, 3],+ resolution=(2, 2),+ stroke_width=0,+ )+ mob.set_color(m.BLUE_D).rotate(40 * m.DEGREES, axis=m.RIGHT)+ scene.add(+ mob.set_material(m.Material(roughness=0.4)),+ m.PointLight(2 * m.OUT + m.LEFT, intensity=3.0),+ m.AmbientLight(intensity=0.1),+ )+ scene.wait(0.1)++ return frames(build)[0].astype(int)++ path, mesh = view("path"), view("mesh")+ # where both cover their pixels whole: away from their edges+ inside = (path.sum(axis=2) > 0) & (mesh.sum(axis=2) > 0)+ for _ in range(2):+ inside &= np.roll(inside, 1, 0) & np.roll(inside, -1, 0)+ inside &= np.roll(inside, 1, 1) & np.roll(inside, -1, 1)+ assert inside.sum() > 1000+ assert np.abs(path - mesh).max(axis=2)[inside].max() <= 2+++def encoded(light: float) -> float:+ """A linear light (0-1) as an sRGB-encoded level (0-255)."""+ c = 12.92 * light if light <= 0.0031308 else 1.055 * light ** (1 / 2.4) - 0.055+ return 255 * c+++def lit_rectangle(+ kind: str, x: tuple[float, float], y: tuple[float, float], color: str+) -> m.Mobject:+ """A matte rectangle in the xy plane, `x` and `y` its sides' ranges: a mesh or a path."""+ (x0, x1), (y0, y1) = x, y+ if kind == "mesh":+ mob: m.Mobject = m.Surface(+ lambda u, v: np.array([u, v, 0]),+ u_range=[x0, x1],+ v_range=[y0, y1],+ resolution=(1, 1),+ stroke_width=0,+ )+ else:+ corners = [[x0, y0, 0], [x1, y0, 0], [x1, y1, 0], [x0, y1, 0]]+ mob = m.Polygon(*corners, stroke_width=0, fill_opacity=1)+ return mob.set_color(color).set_material(MATTE)+++def mixes_light(left: int, middle: int, right: int) -> bool:+ """Whether a pixel half one level, half another shows the mean of their light (as a camera+ does), not the mean of the levels."""+ light = 0.5 * (linear(left) + linear(right))+ return abs(middle - encoded(light)) <= 2 and abs(middle - 0.5 * (left + right)) > 20+++ "kinds", [("mesh", "mesh"), ("path", "path"), ("mesh", "path"), ("path", "mesh")]+)+def test_lit_surfaces_meeting_in_a_pixel_mix_their_light_before_it_is_shown(+ kinds: tuple[str, str],+) -> None:+ # a white and a black matte surface meeting in the middle of a pixel, lit straight down: as a+ # camera integrates light, the pixel shows the mean of their light; mixing what each shows+ # would show the mean of their levels (here 141, 48 levels darker)+ # (the boundary: half a pixel right of the view's centre, in scene units)+ boundary = 0.5 * 8 / SIZE[1]++ def build(scene: m.ThreeDScene) -> None:+ white = lit_rectangle(kinds[0], (-9, boundary), (-5, 5), m.WHITE)+ black = lit_rectangle(kinds[1], (boundary, 9), (-5, 5), m.BLACK)+ scene.add(white, black, m.SunLight(m.OUT, intensity=1.0))+ scene.wait(0.1)++ shown = frames(build)[0].astype(int)+ row = SIZE[1] // 2+ assert mixes_light(*(shown[row, SIZE[0] // 2 + k, 0] for k in (-3, 0, 3)))++[email protected](pixel_width=1920, pixel_height=1080)+def test_a_lit_shape_mixes_light_with_one_drawn_long_before_it() -> None:+ # a white matte plane, many large shapes (more than the composite lays in one pass: they reach+ # far past the 64 million pixels of coverage a pass holds), then a black matte rectangle over+ # half of a pixel of the plane: the pixel still mixes their light+ boundary = 0.5 * 8 / 1080++ def build(scene: m.ThreeDScene) -> None:+ scene.add(lit_rectangle("path", (-7, 7), (-4, -1), m.WHITE))+ for k in range(150):+ filler = m.Rectangle(width=14, height=4.4, stroke_width=0, fill_opacity=1)+ scene.add(filler.set_fill(m.GREY).shift(1.7 * m.UP + 0.001 * k * m.RIGHT))+ scene.add(lit_rectangle("path", (boundary, 7), (-4, -1), m.BLACK))+ scene.add(m.SunLight(m.OUT, intensity=1.0))+ scene.wait(1 / 60)++ shown = frames(build)[0].astype(int)+ row = 540 + int(2.5 / (8 / 1080))+ assert mixes_light(*(shown[row, 960 + k, 0] for k in (-3, 0, 3)))+++def test_a_shape_shaded_in_3d_is_lit_by_its_material_alone() -> None:+ # a cube's faces are shaded in 3D (Manim's light, by which way each faces); with a material,+ # the scene's lights alone light them: under a light from all around, every face shows alike+ # (but for the specular lobe's share, which grows toward grazing angles: a few levels)+ def build(scene: m.ThreeDScene) -> None:+ scene.set_camera_orientation(phi=60 * m.DEGREES, theta=-50 * m.DEGREES)+ cube = m.Cube(side_length=3, fill_opacity=1, stroke_width=0).set_fill(m.GREY_B)+ scene.add(cube.set_material(MATTE), m.AmbientLight(intensity=1.0))+ scene.wait(0.1)++ shown = frames(build)[0].astype(int)+ cube = shown.sum(axis=2) > 0+ for _ in range(2): # (away from its edges)+ cube &= np.roll(cube, 1, 0) & np.roll(cube, -1, 0)+ cube &= np.roll(cube, 1, 1) & np.roll(cube, -1, 1)+ assert cube.sum() > 1000+ levels = shown[..., 0][cube]+ assert levels.max() - levels.min() <= 6+++def test_lights_leave_a_mobject_without_a_material_as_it_was() -> None:+ def build(lights: bool) -> Callable[[m.ThreeDScene], None]:+ def inner(scene: m.ThreeDScene) -> None:+ scene.add(m.Sphere(radius=2.0, resolution=(24, 24)).set_color(m.BLUE))+ scene.add(m.Square(side_length=2).shift(4 * m.RIGHT).set_fill(m.GREEN, 1))+ if lights:+ scene.add(+ m.SunLight(),+ m.PointLight(m.OUT, m.RED),+ m.AmbientLight(intensity=0.5),+ m.EnvironmentLight(),+ )+ scene.wait(0.1)++ return inner++ assert np.array_equal(frames(build(False))[0], frames(build(True))[0])+++def test_a_mobject_fixed_in_the_frame_is_not_lit() -> None:+ def view(material: m.Material | None) -> np.ndarray:+ def build(scene: m.ThreeDScene) -> None:+ badge = m.Square(side_length=2, stroke_width=0, fill_opacity=1)+ ball = m.Sphere(radius=0.6, resolution=(24, 24), stroke_width=0)+ badge.set_fill(m.BLUE).shift(3 * m.LEFT)+ ball.set_color(m.RED).shift(3 * m.RIGHT)+ if material is not None:+ badge.set_material(material)+ ball.set_material(material)+ scene.add_fixed_in_frame_mobjects(badge, ball)+ scene.add(m.SunLight(m.LEFT + 5 * m.OUT, intensity=3.0))+ scene.wait(0.1)++ return frames(build)[0]++ assert np.array_equal(view(m.Material()), view(None))+++def floor_at(x: float) -> tuple[int, int]:+ """The pixel showing the floor (z = 0) at (x, 0), looking straight down."""+ return SIZE[1] // 2, int(SIZE[0] / 2 + x * SIZE[1] / 8)+++def test_a_sun_casts_a_shadow_where_its_light_is_blocked() -> None:+ def view(shadows: bool) -> np.ndarray:+ def build(scene: m.ThreeDScene) -> None:+ ball = m.Sphere(radius=0.6, resolution=(24, 24), stroke_width=0).shift(+ 2 * m.OUT+ )+ sun = m.SunLight(+ m.LEFT + m.OUT, shadows=shadows+ ) # 45 degrees: a height of 2 casts 2 to the right+ scene.add(plane(), ball.set_material(m.Material()), sun)+ scene.wait(0.1)++ return frames(build)[0]++ lit, shadowed = view(False), view(True)+ assert shadowed[floor_at(2.0)].max() < lit[floor_at(2.0)].max() - 100+ assert (shadowed[floor_at(-2.0)] == lit[floor_at(-2.0)]).all()+++def test_a_still_shadow_stays_still_while_other_things_move() -> None:+ # a ball's shadow on a floor while another ball flies off past the floor's edge (the+ # map's fit to what casts grows with it): the still shadow keeps every pixel+ def build(scene: m.ThreeDScene) -> None:+ scene.set_camera_orientation(phi=60 * m.DEGREES, theta=-70 * m.DEGREES)+ scene.add(plane(), m.SunLight(2 * m.LEFT + 3 * m.UP + 5 * m.OUT))+ still = m.Sphere(radius=0.6, resolution=(24, 24), stroke_width=0)+ moving = m.Sphere(radius=0.4, resolution=(24, 24), stroke_width=0)+ still.shift(2.5 * m.LEFT + 0.8 * m.OUT).set_material(m.Material())+ moving.shift(1.5 * m.RIGHT + 2 * m.DOWN + 0.6 * m.OUT).set_material(+ m.Material()+ )+ scene.add(still, moving)+ scene.play(moving.animate.shift(9 * m.RIGHT + 3 * m.OUT), run_time=1.0)++ shown = [rgb.astype(int)[:, : int(0.45 * SIZE[0])] for rgb in frames(build)]+ assert len(shown) > 20+ assert max(np.abs(b - a).max() for a, b in itertools.pairwise(shown)) <= 2+++def test_a_spot_casts_a_shadow_within_its_cone() -> None:+ def view(shadows: bool) -> np.ndarray:+ def build(scene: m.ThreeDScene) -> None:+ ball = m.Sphere(radius=0.4, resolution=(24, 24), stroke_width=0).shift(+ m.OUT+ )+ # from (-3, 0, 3) through the ball at (0, 0, 1) to the floor at (1.5, 0, 0)+ spot = m.SpotLight(+ 3 * m.LEFT + 3 * m.OUT,+ toward=m.ORIGIN,+ intensity=20.0,+ angle=0.9,+ shadows=shadows,+ )+ scene.add(plane(), ball.set_material(m.Material()), spot)+ scene.wait(0.1)++ return frames(build)[0]++ lit, shadowed = view(False), view(True)+ assert shadowed[floor_at(1.5)].max() < lit[floor_at(1.5)].max() - 60+ assert (shadowed[floor_at(-1.5)] == lit[floor_at(-1.5)]).all()+++def test_a_shadow_falls_on_a_path_with_a_material() -> None:+ def view(shadows: bool) -> np.ndarray:+ def build(scene: m.ThreeDScene) -> None:+ floor = m.Square(side_length=12, stroke_width=0, fill_opacity=1)+ ball = m.Sphere(radius=0.6, resolution=(24, 24), stroke_width=0).shift(+ 2 * m.OUT+ )+ scene.add(+ floor.set_fill(m.WHITE).set_material(MATTE),+ ball.set_material(m.Material()),+ m.SunLight(m.LEFT + m.OUT, shadows=shadows),+ )+ scene.wait(0.1)++ return frames(build)[0]++ lit, shadowed = view(False), view(True)+ assert shadowed[floor_at(2.0)].max() < lit[floor_at(2.0)].max() - 100+ assert (shadowed[floor_at(-2.0)] == lit[floor_at(-2.0)]).all()+++def shadow_of(caster: Callable[[], m.Mobject]) -> tuple[np.ndarray, np.ndarray]:+ """A white matte floor under `caster`, lit by a sun at 45 degrees from the left (a height of 2+ casts 2 to the right), without and with shadows."""++ def view(shadows: bool) -> np.ndarray:+ def build(scene: m.ThreeDScene) -> None:+ scene.add(plane(), caster(), m.SunLight(m.LEFT + m.OUT, shadows=shadows))+ scene.wait(0.1)++ return frames(build)[0]++ return view(False), view(True)+++def test_a_path_casts_a_shadow() -> None:+ lit, shadowed = shadow_of(+ lambda: m.Square(side_length=1.2, stroke_width=0, fill_opacity=1).shift(+ 2 * m.OUT+ )+ )+ assert shadowed[floor_at(2.0)].max() < lit[floor_at(2.0)].max() - 100+ assert (shadowed[floor_at(-2.0)] == lit[floor_at(-2.0)]).all()+++def test_a_stroke_casts_a_shadow_and_an_unfilled_shape_none_inside() -> None:+ # a ring of radius 0.8 at a height of 2: its shadow is a ring around the floor's (2, 0)+ lit, shadowed = shadow_of(+ lambda: (+ m.Circle(radius=0.8, stroke_width=24).set_stroke(m.WHITE).shift(2 * m.OUT)+ )+ )+ assert shadowed[floor_at(2.8)].max() < lit[floor_at(2.8)].max() - 100+ assert (shadowed[floor_at(2.0)] == lit[floor_at(2.0)]).all()+++def grey(mob: m.Mobject) -> m.Mobject:+ """A matte grey surface (a quarter of the light it gets: lighter ones bounce more of it back+ into their creases, white ones nearly all)."""+ return mob.set_color(m.GREY).set_material(MATTE)+++def ring(opacity: float = 1.0) -> m.Mobject:+ """A ring lying on the floor around the origin: its hole half a unit across."""+ torus = m.Torus(major_radius=1.0, minor_radius=0.5, resolution=(32, 16))+ return grey(torus.set_stroke(width=0).shift(0.5 * m.OUT)).set_opacity(opacity)+++def resting(+ floor: m.Mobject, thing: m.Mobject, *lights: m.Light, phi: float = 0.0+) -> tuple[np.ndarray, np.ndarray]:+ """A floor with a thing resting on it, seen from above (or tilted `phi` toward the front),+ lit by `lights` (an ambient light of intensity 1 unless given): without and with ambient+ occlusion reaching a unit around."""++ def view(amount: float) -> np.ndarray:+ def build(scene: m.ThreeDScene) -> None:+ scene.set_camera_orientation(phi=phi, theta=-90 * m.DEGREES)+ scene.camera.ambient_occlusion = amount+ scene.camera.ambient_occlusion_radius = 1.0+ scene.add(floor.copy(), thing.copy())+ scene.add(+ *[light.copy() for light in lights or [m.AmbientLight(intensity=1.0)]]+ )+ scene.wait(0.1)++ return frames(build)[0].astype(int)++ return view(0.0), view(1.0)+++HOLE = (SIZE[1] // 2, SIZE[0] // 2) # the floor in the ring's hole (the view's centre)+TILT = (+ 30 * m.DEGREES+) # (from above, the ring's underside, which shuts light out of its hole, is hidden)++[email protected]("kind", ["mesh", "path"])+def test_ambient_occlusion_shuts_light_out_of_the_floor_inside_a_ring(+ kind: str,+) -> None:+ floor = plane(None) if kind == "mesh" else m.Square(side_length=12, fill_opacity=1)+ off, on = resting(grey(floor.set_stroke(width=0)), ring(), phi=TILT)+ assert linear(on[HOLE].max()) < 0.9 * linear(off[HOLE].max())+ # in the open, the floor is as it was+ assert (on[floor_at(6.0)] == off[floor_at(6.0)]).all()+++def test_a_shape_shuts_out_light_as_a_mesh_does() -> None:+ # a blue cube of six squares, seen from the front (screen-space occlusion knows what the view+ # shows: from above, its walls are edge-on): the floor just before its front wall+ cube = grey(m.Cube(side_length=2, fill_opacity=1, stroke_width=0).shift(m.OUT))+ off, on = resting(grey(plane(None)), cube.set_color(m.BLUE_E), phi=60 * m.DEGREES)+ column = off[:, SIZE[0] // 2]+ base = int(np.nonzero(column[:, 2] > column[:, 0] + 20)[0].max())+ before = (base + 2, SIZE[0] // 2)+ assert linear(on[before].max()) < 0.8 * linear(off[before].max())+ # far from it, the floor is as it was+ assert (on[SIZE[1] - 3, SIZE[0] - 3] == off[SIZE[1] - 3, SIZE[0] - 3]).all()+++def test_what_can_be_seen_through_neither_shuts_out_light_nor_is_darkened() -> None:+ off, on = resting(grey(plane(None)), ring(opacity=0.5))+ assert np.array_equal(off, on)+++def test_ambient_occlusion_takes_light_from_all_around_and_leaves_a_suns() -> None:+ # the hole's floor, lit from straight above by a sun too, loses what it loses without it+ def lost(*lights: m.Light) -> float:+ off, on = resting(grey(plane(None)), ring(), *lights, phi=TILT)+ return linear(off[HOLE].max()) - linear(on[HOLE].max())++ ambient = m.AmbientLight(intensity=0.6)+ alone = lost(ambient)+ assert alone > 0.01+ assert abs(lost(ambient, m.SunLight(m.OUT, intensity=0.6)) - alone) < 0.01+++def light_of(picture: np.ndarray) -> float:+ """The light a picture shows: its levels in linear light, summed."""+ c = picture.astype(float) / 255+ return float(np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4).sum())+++def test_a_polished_balls_glint_keeps_its_light_as_the_camera_turns() -> None:+ # a sun's glint on a polished ball is narrower than a pixel: the pixel shows its light over+ # the pixel (the ball's roughness widened by how far its normal turns across the pixel), not+ # its light at the pixel's centre, which the glint misses or hits as the camera turns (it+ # showed under a hundredth of its light, more on some frames); unclipped, the light it sends+ # into the view stays as it is+ def build(scene: m.ThreeDScene) -> None:+ scene.set_camera_orientation(phi=60 * m.DEGREES, theta=-90 * m.DEGREES)+ scene.camera.exposure = 0.002+ ball = m.Sphere(radius=1.0, resolution=(48, 48), stroke_width=0)+ polished = m.Material(metallic=1.0, roughness=0.05)+ scene.add(ball.set_color(m.WHITE).set_material(polished))+ scene.add(m.SunLight(m.OUT + m.LEFT))+ scene.begin_ambient_camera_rotation(rate=0.1)+ scene.wait(0.5)++ shown = frames(build)+ assert max(picture.max() for picture in shown) < 250 # (nothing clipped)+ lights = [light_of(picture) for picture in shown]+ assert min(lights) > 0.3+ assert max(lights) < 1.08 * min(lights)+++def bright_disk(+ strength: float, *beside: m.Mobject, fixed: m.Mobject | None = None+) -> np.ndarray:+ """A small white disk lit straight on by a sun, twenty times as bright as white, at the view's+ centre on black, with bloom at `strength`; `beside` it, and `fixed` in the frame."""++ def build(scene: m.ThreeDScene) -> None:+ scene.camera.exposure = 20.0+ scene.camera.bloom = strength+ disk = m.Circle(radius=0.4, stroke_width=0, fill_opacity=1).set_fill(m.WHITE)+ scene.add(disk.set_material(MATTE), m.SunLight(m.OUT, intensity=1.0), *beside)+ if fixed is not None:+ scene.add_fixed_in_frame_mobjects(fixed)+ scene.add(fixed)+ scene.wait(0.1)++ return frames(build)[0].astype(int)+++def off_centre(picture: np.ndarray, x: float) -> np.ndarray:+ """The pixel `x` scene units right of the view's centre."""+ return picture[SIZE[1] // 2, SIZE[0] // 2 + int(x * SIZE[1] / 8)]+++def dark_square(x: float, z: float = 0.0) -> m.Mobject:+ """A dark blue square a unit across, without a material, at (x, 0, z)."""+ square = m.Square(side_length=1.0, stroke_width=0, fill_opacity=1)+ return square.set_fill(m.BLUE_E).move_to([x, 0.0, z])+++def test_bloom_spreads_a_bright_lights_glow_into_the_dark_around_it() -> None:+ near, far = 1.0, 2.0 # (the disk's edge is 0.4 from its centre)+ none, faint, strong = (bright_disk(strength) for strength in (0.0, 0.05, 0.2))+ assert (off_centre(none, near) == 0).all()+ assert (off_centre(none, far) == 0).all()+ # the glow falls off with the distance from the light, and grows with the strength+ assert off_centre(faint, near)[0] > off_centre(faint, far)[0] > 0+ assert off_centre(strong, near)[0] > off_centre(faint, near)[0] + 20+ assert off_centre(strong, far)[0] > off_centre(faint, far)[0]++[email protected]("kind", ["path", "mesh"])+def test_bloom_keeps_the_light_it_spreads(kind: str) -> None:+ # what the glow spreads, the light leaves: a white disk on a lit black floor (every pixel's+ # light is lit content's, shown as light: no display paint mixed into it), unclipped, shows+ # as much light with half of it spread as without+ def view(strength: float) -> np.ndarray:+ def build(scene: m.ThreeDScene) -> None:+ scene.camera.exposure = 0.9+ scene.camera.bloom = strength+ disk = (+ m.Circle(radius=0.6, stroke_width=0, fill_opacity=1)+ if kind == "path"+ else m.Sphere(radius=0.6, resolution=(32, 32), stroke_width=0)+ )+ floor = m.Square(side_length=20, stroke_width=0, fill_opacity=1)+ scene.add(floor.set_fill(m.BLACK).shift(0.01 * m.IN).set_material(MATTE))+ scene.add(disk.set_color(m.WHITE).set_material(MATTE))+ scene.add(m.SunLight(m.OUT, intensity=1.0))+ scene.wait(0.1)++ return frames(build)[0].astype(int)++ kept, spread = view(0.0), view(0.5)+ # the disk's light left it, and lies around it+ assert (off_centre(spread, 0.0) < off_centre(kept, 0.0) - 10).all()+ assert (off_centre(spread, 1.0) > off_centre(kept, 1.0) + 5).all()+ assert abs(light_of(spread) / light_of(kept) - 1) < 0.005+++def test_bloom_spreads_light_not_paint() -> None:+ # display paint is not light: a view without materials shows as it did, and beside a bright+ # light, a white shape without a material has no glow of its own+ def unlit(strength: float) -> np.ndarray:+ def build(scene: m.ThreeDScene) -> None:+ scene.camera.bloom = strength+ scene.add(m.Sphere(radius=1.5, resolution=(24, 24)).set_color(m.BLUE))+ scene.add(m.Square(side_length=2).shift(4 * m.RIGHT).set_fill(m.WHITE, 1))+ scene.wait(0.1)++ return frames(build)[0]++ assert np.array_equal(unlit(0.0), unlit(0.5))+ white = dark_square(-4.5).set_fill(m.WHITE)+ glowing = bright_disk(0.2, white)+ assert (off_centre(glowing, -5.6) == 0).all() # (0.6 past its edge)+ assert (off_centre(glowing, 1.0) > 40).all() # (the disk's glow)+++def test_the_glow_lies_over_paint_and_what_is_fixed_in_the_frame() -> None:+ # the glow is light over everything the view shows: beside the bright disk, a dark shape+ # without a material and a dark one fixed in the frame show it over their paint+ without, glowing = (+ bright_disk(strength, dark_square(1.2), fixed=dark_square(-1.2))+ for strength in (0.0, 0.2)+ )+ for x in (1.0, -1.0):+ assert (off_centre(glowing, x) > off_centre(without, x) + 40).all()+++def test_where_the_view_shows_nothing_the_glow_shows_alone() -> None:+ # over a transparent background the glow is all a pixel shows, as opaque as it is bright (so+ # that laid over black it shows just the glow)+ def view(strength: float) -> np.ndarray:+ def construct(scene: m.ThreeDScene) -> None:+ scene.set_camera_orientation(phi=0.0, theta=-90 * m.DEGREES)+ scene.camera.background_opacity = 0.0+ scene.camera.exposure = 20.0+ scene.camera.bloom = strength+ disk = m.Circle(radius=0.4, stroke_width=0, fill_opacity=1)+ scene.add(disk.set_fill(m.WHITE).set_material(MATTE), m.SunLight(m.OUT))+ scene.wait(0.1)++ return scenes.frames(scenes.scene_3d(construct))[0].astype(int)++ without, glowing = view(0.0), view(0.2)+ assert (off_centre(without, 1.0) == 0).all()+ pixel = off_centre(glowing, 1.0)+ assert pixel[3] > 40+ assert (pixel[:3] <= pixel[3]).all()+ assert pixel[:3].max() == pixel[3]+++def test_what_hides_a_light_hides_its_glow() -> None:+ # the glow is spread from the light the view shows: a shape nearer the camera, over the+ # bright disk, leaves no glow around it; beside the disk, it leaves the disk's+ over = dark_square(0.0, z=1.0).scale(1.2)+ assert np.array_equal(bright_disk(0.2, over), bright_disk(0.0, over))+ beside = dark_square(3.0, z=1.0).scale(1.2)+ assert (off_centre(bright_disk(0.2, beside), -1.0) > 40).all()+++def test_a_moving_lights_glow_moves_with_it_unchanged() -> None:+ # the glow does not flicker as its light moves across the pixels: the light it spreads+ # around a small bright disk moving a third of a pixel a frame stays as it is+ def build(scene: m.ThreeDScene) -> None:+ scene.camera.exposure = 20.0+ scene.camera.bloom = 0.1+ disk = m.Circle(radius=0.15, stroke_width=0, fill_opacity=1).set_fill(m.WHITE)+ scene.add(disk.set_material(MATTE), m.SunLight(m.OUT, intensity=1.0))+ scene.play(disk.animate.shift(0.5 * m.RIGHT), run_time=0.5, rate_func=m.linear)++ shown = frames(build)+ y, x = np.mgrid[: SIZE[1], : SIZE[0]]+ glow = []+ for k, picture in enumerate(shown):+ # around the disk, from 0.6 to 1.6 units from its centre+ centre = (SIZE[0] / 2 + 0.5 * k / (len(shown) - 1) * SIZE[1] / 8, SIZE[1] / 2)+ r = np.hypot(x + 0.5 - centre[0], y + 0.5 - centre[1]) / (SIZE[1] / 8)+ glow.append(light_of(picture[..., 0][(r > 0.6) & (r < 1.6)]))+ assert min(glow) > 2.0+ assert max(glow) < 1.08 * min(glow)diff --git a/tests/integration/test_motion.py b/tests/integration/test_motion.pynew file mode 100644index 00000000..1847afad--- /dev/null+++ b/tests/integration/test_motion.py@@ -0,0 +1,202 @@+"""An animation carries out what it says, from the world as it finds it — alone or together.++- `.animate` records calls and carries them out when it begins: a Succession of `.animate`+ calls on one object goes on from where the last one left it.+- A call's arguments are as it is written: `.animate.move_to(dot)` goes where the dot was, so a+ Succession of such moves cycles its dots, computed frame by frame or at once. A mobject the+ call makes part of the object, or takes out, is that very mobject.+- A turn is a motion, not an endpoint: `.animate.rotate(a)` keeps the object rigid all the way+ and turns it through the whole angle (a full turn turns).+- Tweens that begin together on one object compose: its motion is all of their steps (a turn+ about the object's moving center, moves added up), its shape and paint change as each says.+ One that begins while another moves the object takes it over from there.++Each story is told with every frame computed, and probed at every instant the scene computes.+"""++import math+from collections.abc import Callable+from fractions import Fraction++import numpy as np+import pytest+from tests import scenes++import manimgx as m++type Probe = Callable[[m.Square], tuple[float, ...]]+pytestmark = pytest.mark.config(frame_rate=10)+++def pose(square: m.Square) -> tuple[float, ...]:+ """The square's center, side and first edge's direction (degrees, mod 360)."""+ points = square.points+ edge = points[3] - points[0]+ center = square.get_center()+ angle = math.degrees(math.atan2(edge[1], edge[0])) % 360+ return float(center[0]), float(center[1]), float(np.linalg.norm(edge)), angle+++def area(square: m.Square) -> tuple[float, ...]:+ anchors = square.points[::4, :2]+ x, y = anchors[:, 0], anchors[:, 1]+ shoelace = float(np.dot(x, np.roll(y, -1)) - np.dot(y, np.roll(x, -1)))+ return (abs(shoelace) / 2, float(np.linalg.norm(square.points[0, :2] - 1)))+++def told(+ tell: Callable[[m.Square], list[m.Animation]], probe: Probe+) -> dict[Fraction, tuple[float, ...]]:+ """What `probe` sees of a 2×2 square at every instant, as `tell` plays with it for a+ second."""+ square = m.Square(2)++ def construct(scene: m.Scene) -> None:+ scene.add(square)+ scene.play(*tell(square), run_time=1, rate_func=m.linear)++ return scenes.instants(construct, lambda _: probe(square))++[email protected]("angle", [math.pi / 2, math.pi, 2 * math.pi, -math.pi / 3])+def test_animate_rotate_is_rigid_and_turns_through_its_angle(angle: float) -> None:+ seen = told(lambda s: [s.animate.rotate(angle)], area)+ areas = [a for a, _ in seen.values()]+ assert min(areas) == pytest.approx(4, abs=1e-9), "the square keeps its shape"+ turned = max(travel for _, travel in seen.values())+ chord = 2 * math.sqrt(2) * abs(math.sin(min(abs(angle), math.pi) / 2))+ assert turned == pytest.approx(chord, abs=1e-9), "its corner goes round"+++def test_animate_binds_when_it_begins() -> None:+ seen = told(+ lambda s: [+ m.Succession(s.animate.shift(2 * m.RIGHT), s.animate.rotate(m.PI / 2))+ ],+ pose,+ )+ second = [pose for t, pose in seen.items() if t >= Fraction(1, 2)]+ assert all(x == pytest.approx(2, abs=1e-9) for x, *_ in second), "turning in place"+ assert second[-1][3] == pytest.approx(270, abs=1e-6)+++def test_animate_chain_turns_about_its_moving_center() -> None:+ seen = told(lambda s: [s.animate.shift(2 * m.RIGHT + m.UP).rotate(m.PI / 2)], pose)+ for t, (x, y, side, _) in seen.items():+ assert (x, y) == pytest.approx((2 * float(t), float(t)), abs=1e-9)+ assert side == pytest.approx(2, abs=1e-9)+++CORNERS = (m.UL, m.UR, m.DR, m.DL)++[email protected]("fast", [False, True])+def test_animate_takes_its_arguments_as_written(fast: bool) -> None:+ """Four dots on the corners, each moved to the next one's corner in turn."""+ dots = [m.Dot(corner) for corner in CORNERS]++ def cycle(scene: m.Scene) -> None:+ scene.add(*dots)+ after = dots[1:] + dots[:1]+ moves = (dot.animate.move_to(to) for dot, to in zip(dots, after, strict=True))+ scene.play(m.Succession(*moves), run_time=1)++ scenes.record(cycle, fast=fast)+ for dot, corner in zip(dots, CORNERS[1:] + CORNERS[:1], strict=True):+ assert dot.get_center() == pytest.approx(corner, abs=1e-9)+++def test_animate_adds_and_removes_the_mobjects_it_is_given() -> None:+ square, kept, added = m.Square(), m.Dot(), m.Dot(m.RIGHT)+ square.add(kept)++ def edit(scene: m.Scene) -> None:+ scene.add(square)+ scene.play(square.animate.add(added).remove(kept))++ scenes.scene(edit).render()+ assert any(s is added for s in square.submobjects)+ assert all(s is not kept for s in square.submobjects)+++STORIES: dict[+ str, tuple[Callable[[m.Square], list[m.Animation]], tuple[float, ...]]+] = {+ # the corpus's three: a move (and a scale) with a turn+ "shift and scale with a turn": (+ lambda s: [s.animate.shift(m.RIGHT).scale(2), m.Rotate(s, m.PI / 2)],+ (1, 0, 4, 270),+ ),+ "a turn with a shift and scale": (+ lambda s: [m.Rotate(s, m.PI / 2), s.animate.shift(m.RIGHT).scale(2)],+ (1, 0, 4, 270),+ ),+ "two turns": (+ lambda s: [m.Rotate(s, m.PI / 2), m.Rotate(s, m.PI / 3)],+ (0, 0, 2, 330),+ ),+}++[email protected]("name", STORIES)+def test_tweens_at_once_compose(name: str) -> None:+ tell, end = STORIES[name]+ seen = told(tell, pose)+ assert seen[max(seen)] == pytest.approx(end, abs=1e-6)+ for _x, y, side, _ in seen.values(): # the center never leaves its straight path+ assert y == pytest.approx(0, abs=1e-9) or name == "two turns"+ assert side >= 2 - 1e-9+++def test_a_fade_and_a_move_compose() -> None:+ seen = told(+ lambda s: [m.FadeIn(s), s.animate.shift(m.RIGHT)],+ lambda square: (float(square.get_x()), float(square.paint.stroke[0, 3])),+ )+ for t, (x, opacity) in seen.items():+ assert (x, opacity) == pytest.approx((float(t), float(t)), abs=1e-9)+++def test_a_tween_that_begins_later_takes_the_object_over() -> None:+ """The turn begins halfway through the shift: from then on the square turns where it is."""+ seen = told(+ lambda s: [+ m.LaggedStart(+ s.animate.shift(2 * m.RIGHT), m.Rotate(s, m.PI / 2), lag_ratio=0.5+ )+ ],+ pose,+ )+ poses = [seen[t] for t in sorted(seen)]+ turning = [p for p in poses if abs(p[3] - 180) > 1e-6]+ assert turning, "the square turns"+ for x, y, side, _ in turning:+ assert (x, y, side) == pytest.approx((turning[0][0], 0, 2), abs=1e-9)+ assert poses[-1][3] == pytest.approx(270, abs=1e-6)+++def stroke(square: m.Square) -> tuple[float, ...]:+ """The square's stroke (its first row) and its width."""+ paint = square.paint+ return (*map(float, paint.stroke[0]), float(paint.stroke_width))++[email protected]("composed", [False, True])+def test_write_draws_each_border_in_the_paint_it_is_seen_in(composed: bool) -> None:+ """A blue square that draws no stroke (its unseen stroke red) is traced in blue, thins+ away in blue and ends as it was: alone, or with a move that outlasts the Write."""++ def tell(s: m.Square) -> list[m.Animation]:+ write = m.Write(s.set_fill(m.BLUE, 1).set_stroke(m.RED, width=0))+ if not composed:+ return [write]+ return [m.AnimationGroup(write, m.Wait(2)), s.animate.shift(m.RIGHT)]++ seen = told(tell, stroke)+ blue, red = (tuple(m.ManimColor(c).to_rgba()) for c in (m.BLUE, m.RED))+ *end, width = seen[max(seen)]+ assert (*end, width) == pytest.approx((*red, 0))+ drawn = [color for *color, width in seen.values() if width > 0]+ assert drawn, "a border is drawn"+ for color in drawn:+ assert color == pytest.approx(blue, abs=1e-6)diff --git a/tests/integration/test_perspective.py b/tests/integration/test_perspective.pynew file mode 100644index 00000000..d525f869--- /dev/null+++ b/tests/integration/test_perspective.py@@ -0,0 +1,254 @@+"""A 3D view shows what lies in front of its camera: a shape that reaches behind the camera+shows the part in front of it, exactly where a surface in its place would, at any angle; what+lies wholly behind the camera shows nothing. Where shapes meet, the one drawn later shows if+they lie in one plane, the nearer if they do not, however near or far the camera; surfaces+too. Manim's light shades the side of a shape or surface the eye sees, however far off the+view's axis it lies."""++import numpy as np+import pytest+from tests import scenes++import manimgx as m+from manimgx.config import config++SIZE = (320, 180)+pytestmark = pytest.mark.config(pixel_width=SIZE[0], pixel_height=SIZE[1])+++def view(+ *mobs: m.Mobject, phi: float, theta: float, distance: float | None = None+) -> np.ndarray:+ """What a 3D view of the mobjects shows (RGB rows), the camera at `phi` and `theta`+ (degrees), `distance` from its focus."""++ def construct(scene: m.ThreeDScene) -> None:+ scene.set_camera_orientation(+ phi=phi * m.DEGREES, theta=theta * m.DEGREES, focal_distance=distance+ )+ scene.add(*mobs)+ scene.wait(0.05)++ shown = scenes.frames(scenes.scene_3d(construct))+ return shown[0][..., :3].astype(int)+++def coverage(mob: m.Mobject, phi: float, theta: float) -> np.ndarray:+ """How much of each pixel a white mobject covers over black, the camera at (phi, theta)."""+ return view(mob, phi=phi, theta=theta).sum(axis=2) / 765.0+++def shape(side: float) -> m.Mobject:+ return m.Square(side_length=side, fill_opacity=1, stroke_width=0).set_fill(m.WHITE)+++def surface(side: float) -> m.Mobject:+ half = side / 2+ mesh = m.Surface(+ lambda u, v: np.array([u, v, 0]),+ u_range=[-half, half],+ v_range=[-half, half],+ resolution=(32, 32),+ stroke_width=0,+ fill_opacity=1,+ ).set_color(m.WHITE)+ mesh.shade_in_3d = False+ return mesh++[email protected](("phi", "theta"), [(78, -60), (85, -90), (89, -45)])+def test_a_floor_reaching_behind_the_camera_shows_what_a_surface_does(+ phi: float, theta: float+) -> None:+ # a floor 40 units wide around the origin, the camera 20 units away and low over it+ path, mesh = coverage(shape(40), phi, theta), coverage(surface(40), phi, theta)+ assert path.sum() > 0.25 * path.size+ assert (+ np.abs(path - mesh) <= 0.5+ ).all() # they differ at their edges' anti-aliasing alone++[email protected]("tilt", [30, 80, 89.5])[email protected]("height", [19.9, 19.95, 20.3])+def test_a_tilted_square_crossing_the_near_plane_shows_what_a_surface_does(+ tilt: float, height: float+) -> None:+ # looking straight down from 20 units up: the near plane is at 19.95+ def placed(mob: m.Mobject) -> m.Mobject:+ return mob.rotate(tilt * m.DEGREES, axis=m.RIGHT).shift(+ height * m.OUT + 0.3 * m.RIGHT+ )++ path = coverage(placed(shape(2)), 0, -90)+ mesh = coverage(placed(surface(2)), 0, -90)+ assert (np.abs(path - mesh) <= 0.5).all()+ # in all, by no more than the surface's sampled edges miss an exact edge's area by+ edge_pixels = ((path > 0) & (path < 1)).sum()+ assert abs(path.sum() - mesh.sum()) <= 0.15 * edge_pixels + 1.0+++def test_a_shape_wholly_behind_the_camera_shows_nothing() -> None:+ behind = shape(2).shift(25 * m.OUT) # the camera is 20 units up+ assert coverage(behind, 0, -90).max() == 0+++BLUE = (m.ManimColor(m.BLUE).to_rgb() * 255).round()+++def centre_colour(mobs: list[m.Mobject], distance: float) -> np.ndarray:+ """The view's centre pixel, looking down at the mobjects from `distance` away."""+ shown = view(*mobs, phi=30, theta=-60, distance=distance)+ return shown[SIZE[1] // 2, SIZE[0] // 2]++[email protected]("distance", [5.0, 20.0, 60.0])+def test_shapes_in_one_plane_meet_by_draw_order_at_any_distance(+ distance: float,+) -> None:+ below = m.Square(side_length=2, fill_opacity=1, stroke_width=0).set_fill(m.RED)+ above = m.Square(side_length=1, fill_opacity=1, stroke_width=0).set_fill(m.BLUE)+ tilt = lambda mob: mob.rotate(20 * m.DEGREES, axis=m.RIGHT)+ shown = centre_colour([tilt(below), tilt(above)], distance)+ assert np.abs(shown.astype(int) - BLUE).max() <= 2 # the one drawn later++[email protected]("distance", [5.0, 20.0, 60.0])+def test_shapes_a_hair_apart_meet_by_depth_at_any_distance(distance: float) -> None:+ # the nearer square, 0.001 above, drawn first: the nearer shows, wherever the camera is+ near = m.Square(side_length=1, fill_opacity=1, stroke_width=0).set_fill(m.BLUE)+ far = m.Square(side_length=2, fill_opacity=1, stroke_width=0).set_fill(m.RED)+ shown = centre_colour([near.shift(0.001 * m.OUT), far], distance)+ assert np.abs(shown.astype(int) - BLUE).max() <= 2++[email protected]("distance", [5.0, 20.0, 60.0])+def test_meshes_a_hair_apart_meet_by_depth_at_any_distance(distance: float) -> None:+ # the nearer surface, 0.001 above, drawn first: the nearer shows, wherever the camera is+ def sheet(side: float, color: m.ManimColor, z: float) -> m.Mobject:+ mesh = surface(side).set_color(color).shift(z * m.OUT)+ return mesh++ shown = centre_colour([sheet(1, m.BLUE, 0.001), sheet(2, m.RED, 0.0)], distance)+ assert np.abs(shown.astype(int) - BLUE).max() <= 2+++def floor_mesh(grid: float = 0.0) -> m.Mobject:+ """A blue surface floor, 6 units wide, its grid lines `grid` wide (white)."""+ mesh = m.Surface(+ lambda u, v: np.array([u, v, 0]),+ u_range=[-3, 3],+ v_range=[-3, 3],+ resolution=(8, 8),+ stroke_width=grid,+ stroke_color=m.WHITE,+ fill_opacity=1,+ ).set_fill(m.BLUE)+ mesh.shade_in_3d = False+ return mesh+++ ("phi", "distance"), [(40, 5.0), (75, 20.0), (85, 20.0), (80, 60.0)]+)+def test_a_shape_on_a_surface_shows_however_steep_and_far(+ phi: float, distance: float+) -> None:+ # a red square lying on a surface floor (with its grid lines) shows wherever it covers, as+ # on a shape floor; one a hair below it does not show at all+ def on(offset: float | None) -> np.ndarray:+ floor = [] if offset is None else [floor_mesh(grid=1.0)]+ square = shape(2).set_fill(m.RED).shift((offset or 0.0) * m.OUT)+ return view(*floor, square, phi=phi, theta=-90, distance=distance)++ covered = on(None)[..., 0] > 250 # its pixels, whole+ red = lambda rgb: (rgb[..., 0] > 150) & (rgb[..., 2] < 120)+ assert covered.sum() > 20+ assert red(on(0.0))[covered].all()+ assert not red(on(-0.001)).any()++[email protected]("phi", [60, 85])+def test_a_surfaces_grid_shows_over_its_faces(phi: float) -> None:+ def grid(fill: float) -> np.ndarray:+ floor = floor_mesh(grid=6.0).set_fill(m.BLUE, opacity=fill)+ return view(floor, phi=phi, theta=-60)++ # where the grid alone (over black) covers most of a pixel, it shows over its faces at+ # least as bright (white over blue, not blue: the faces hide none of it)+ alone, over = grid(0.0).min(axis=2), grid(1.0).min(axis=2)+ lines = alone > 150+ assert lines.sum() > 100+ assert (over[lines] >= alone[lines] - 5).all()++[email protected]("opacity", [1.0, 0.5])+def test_where_shapes_cross_their_crossing_is_as_smooth_as_their_edges(+ opacity: float,+) -> None:+ # a floor and a tilted square through it: along the line where they cross, each pixel+ # shows each in the share of it where it is nearer, as an image drawn 4 x 4 times finer+ # and averaged does (within its own sampling: a sixteenth of the colours' difference; a+ # pixel's centre's order alone misses by half of it)+ def crossing(scale: int) -> np.ndarray:+ config.pixel_width, config.pixel_height = SIZE[0] * scale, SIZE[1] * scale+ floor = shape(4).set_fill(m.BLUE, opacity=opacity)+ tilted = shape(4).set_fill(m.RED, opacity=opacity)+ tilted.rotate(0.7, axis=m.UP).rotate(0.4, axis=m.RIGHT)+ rgb = view(floor, tilted, phi=60, theta=-50)+ return rgb.reshape(SIZE[1], scale, SIZE[0], scale, 3).mean(axis=(1, 3))++ drawn, finer = crossing(1), crossing(4)+ assert np.abs(drawn - finer).max() <= 0.06 * 255+++def test_a_line_just_above_a_floor_shows_its_whole_width_at_a_grazing_view() -> None:+ def line() -> m.Mobject:+ return (+ m.Line(4 * m.LEFT, 4 * m.RIGHT, stroke_width=8)+ .set_color(m.WHITE)+ .shift(0.001 * m.OUT + 2 * m.UP)+ )++ floor = m.Square(side_length=12, fill_opacity=1, stroke_width=0).set_fill(m.BLUE_E)+ over = coverage(m.VGroup(floor, line()), 82, -90)+ alone = coverage(line(), 82, -90)+ lit = alone > 0.9+ assert lit.sum() > 50+ assert (+ over[lit].min() > 0.9+ ) # every pixel the line covers alone, it covers over the floor++[email protected]("kind", ["shape", "surface"])+def test_manims_light_shades_the_side_the_eye_sees_off_the_axis(kind: str) -> None:+ # off the axis, turned 20° past edge-on to it but toward the eye, lit on the eye's side+ normal = np.array([-np.cos(20 * m.DEGREES), 0.0, -np.sin(20 * m.DEGREES)])+ if kind == "shape":+ mob: m.Mobject = m.Square(+ side_length=2, fill_opacity=1, stroke_width=0, shade_in_3d=True+ ).set_fill(m.GRAY)+ else:+ mob = m.Surface(+ lambda u, v: np.array([u, v, 0]),+ u_range=[-1, 1],+ v_range=[-1, 1],+ resolution=(4, 4),+ stroke_width=0,+ fill_opacity=1,+ ).set_color(m.GRAY)+ mob.rotate(-110 * m.DEGREES, axis=m.UP).shift(+ 4 * m.RIGHT+ ) # its plane faces `normal`++ def construct(scene: m.ThreeDScene) -> None:+ scene.set_camera_orientation(phi=0, theta=-90 * m.DEGREES, focal_distance=6)+ scene.camera.light_source.move_to(4 * m.RIGHT + 3 * normal)+ scene.add(mob)+ scene.wait(0.05)++ rgb = scenes.frames(scenes.scene_3d(construct))[0][..., :3].astype(int)+ shown = rgb[rgb.max(axis=2) > 10]+ assert len(shown) > 50+ base = round(m.ManimColor(m.GRAY).to_rgb()[0] * 255)+ # lit: the side the eye sees faces the light+ assert np.median(shown[:, 0]) > base + 60diff --git a/tests/integration/test_present.py b/tests/integration/test_present.pynew file mode 100644index 00000000..e36ec4e7--- /dev/null+++ b/tests/integration/test_present.py@@ -0,0 +1,86 @@+"""A film presented: each section begins on a keyframe of its video, so a player stops and starts+there exactly; the page holds the film's sections and captions; `manimgx present` writes the+video, the page and a handout of the pictures the slides end on.+"""++import json+from pathlib import Path++import av+import pytest+from typer.testing import CliRunner++import manimgx as m+from manimgx.cli import app+from manimgx.cli.export import page++TALK = """+import manimgx as m+++class Talk(m.Scene):+ def construct(self) -> None:+ self.play(m.Write(m.Text("Title")))+ self.next_section("points", notes="Say hello")+ self.play(m.FadeIn(m.Dot()), run_time=0.55)+ self.next_section("gear", "presentation.loop")+ self.play(m.Rotate(m.Square(), m.PI / 2))+"""+++pytestmark = pytest.mark.config(pixel_width=320, pixel_height=180, frame_rate=10)+++def keyframes(path: Path) -> list[int]:+ """The frames of an MP4 a player can start at: its keyframes' times, in frames."""+ with av.open(str(path)) as container:+ video = container.streams.video[0]+ base = video.time_base+ assert base is not None+ return [+ int(packet.pts * base * 10)+ for packet in container.demux(video)+ if packet.is_keyframe and packet.pts is not None+ ]+++def test_each_section_begins_on_a_keyframe(tmp_path: Path) -> None:+ namespace: dict[str, object] = {}+ exec(TALK, namespace)+ talk = namespace["Talk"]+ assert isinstance(talk, type)+ assert issubclass(talk, m.Scene)+ film = talk().render(tmp_path / "talk.mp4")+ assert [s.frame for s in film.sections] == keyframes(tmp_path / "talk.mp4")+ html = page(film, "talk.mp4", "Talk")+ deck = json.loads(html.split("const deck = ", 1)[1].split(";", 1)[0])+ assert [s["name"] for s in deck["sections"]] == ["unnamed", "points", "gear"]+ assert deck["sections"][2]["type"] == "presentation.loop"+ assert deck["frames"] == film.frame_count+ assert deck["fps"] == 10+++def test_the_pages_help_names_the_key_that_opens_the_presenter_view() -> None:+ # p goes back a slide, as a clicker's back key does: the presenter view is Shift+P+ html = (Path(m.__file__).parent / "cli" / "present.html").read_text(+ encoding="utf-8"+ )+ start = html.index('<div id="help">')+ shown = html[start : html.index("</div>", start)]+ assert 'case "P": openPresenter()' in html+ assert 'case "p": back()' in html+ assert "Shift+P: presenter view" in shown+++def test_present_writes_the_video_the_page_and_a_handout(tmp_path: Path) -> None:+ scene = tmp_path / "talk.py"+ scene.write_text(TALK, encoding="utf-8")+ result = CliRunner().invoke(+ app,+ ["present", str(scene), "--pdf", "--no-open", "-r", "320x180", "--fps", "10"],+ )+ assert result.exit_code == 0, result.output+ for suffix in (".mp4", ".html", ".pdf"):+ assert (tmp_path / f"Talk{suffix}").stat().st_size > 0+ # a page for each slide's end: the two sections' starts after the first, and the last frame+ assert b"/Count 3" in (tmp_path / "Talk.pdf").read_bytes()diff --git a/tests/integration/test_preview.py b/tests/integration/test_preview.pynew file mode 100644index 00000000..df6b71e6--- /dev/null+++ b/tests/integration/test_preview.py@@ -0,0 +1,202 @@+"""`manimgx preview`: the scene recorded as a take and sent to a window, which plays it; made+again when its file is saved, the new take after the old; an error, as a note between takes; a+scene the viewer asks for, run next; closing the window ends it. Driven as its user does — the+command, then the file edited — with the window a stand-in that keeps what it is sent.+"""++import importlib+import json+import queue+import struct+import threading+import time+from collections.abc import Iterator+from pathlib import Path+from types import TracebackType+from typing import Self++import pytest++from manimgx import _engine+from manimgx.rendering.film import Cut++# the module: `manimgx.cli.preview` is also the command's name in its package+command = importlib.import_module("manimgx.cli.preview")+START, NOTE, END = 0, 9, 12++SCENE = """+import manimgx as m+++class Dot(m.Scene):+ def construct(self):+ self.play(m.Create(m.Circle(){extra}))+++class Other(m.Scene):+ def construct(self):+ self.wait(0.5)+"""+++class Viewer:+ """A window as `manimgx preview` uses one: what it is sent, read as messages (op, fields);+ a scene its viewer asks for; its viewer closing it."""++ def __init__(self, title: str, *, time: float = 0.0) -> None:+ self.buffer = b""+ self.seen: list[tuple[int, bytes]] = []+ self.wants: queue.Queue[str] = queue.Queue()+ self.closed = threading.Event()+ self.failure: str | None = None+ self.lock = threading.Lock()++ def __call__(self, data: bytes) -> None:+ if self.closed.is_set():+ raise Cut+ with self.lock:+ self.buffer += data+ while len(self.buffer) >= 4:+ (n,) = struct.unpack_from("<I", self.buffer)+ if len(self.buffer) < 4 + n:+ break+ self.seen.append((self.buffer[4], self.buffer[5 : 4 + n]))+ self.buffer = self.buffer[4 + n :]++ def scenes(self, names: list[str], playing: str) -> None:+ self(_engine.note(json.dumps({"scenes": names, "scene": playing})))++ def failed(self, error: BaseException, trace: str, line: int | None = None) -> None:+ fault = {"type": type(error).__name__, "trace": trace, "line": line}+ self(_engine.note(json.dumps({"error": fault})))++ @property+ def open(self) -> bool:+ return not self.closed.is_set()++ def asked(self) -> str | None:+ return None if self.wants.empty() else self.wants.get()++ def __enter__(self) -> Self:+ return self++ def __exit__(+ self,+ kind: type[BaseException] | None,+ error: BaseException | None,+ trace: TracebackType | None,+ ) -> None:+ self.closed.set()++ def notes(self) -> list[dict[str, object]]:+ with self.lock:+ return [json.loads(fields[4:]) for op, fields in self.seen if op == NOTE]++ def until(+ self, wanted: str, count: int = 1, timeout: float = 60.0+ ) -> dict[str, object]:+ """Wait until the `count`th note with key `wanted`; return it."""+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ found = [n for n in self.notes() if wanted in n]+ if len(found) >= count:+ return found[count - 1]+ time.sleep(0.01)+ raise TimeoutError(f"no {wanted!r} note #{count}")++ def ended(self, count: int = 1, timeout: float = 60.0) -> None:+ """Wait until the `count`th take ends (its END message)."""+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ with self.lock:+ if sum(op == END for op, _ in self.seen) >= count:+ return+ time.sleep(0.01)+ raise TimeoutError(f"take #{count} never ended")++ def starts(self) -> int:+ with self.lock:+ return sum(op == START for op, _ in self.seen)+++SLOW = """+import time++import manimgx as m+++class Slow(m.Scene):+ def construct(self):+ for _ in range(40):+ time.sleep(0.1) # a scene that takes its time: four seconds+ self.play(m.Create(m.Circle(){extra}), run_time=0.1)+"""++[email protected](params=[SCENE])+def previewed(+ request: pytest.FixtureRequest, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> Iterator[tuple[Viewer, Path]]:+ """`manimgx preview scene.py` running, its window the stand-in: the window, the file."""+ scene = tmp_path / "scene.py"+ scene.write_text(request.param.format(extra=""), encoding="utf-8")+ windows: list[Viewer] = []++ def window(title: str, *, time: float = 0.0) -> Viewer:+ windows.append(Viewer(title, time=time))+ return windows[-1]++ monkeypatch.setattr(command, "Window", window)+ running = threading.Thread(+ target=command.preview, args=(scene, None, 0.0, None, None), daemon=True+ )+ running.start()+ while not windows:+ time.sleep(0.01)+ yield windows[0], scene+ windows[0].closed.set()+ running.join(10)+ assert not running.is_alive(), "closing the window ends the preview"+++def test_a_saved_edit_sends_a_new_take_and_a_mistake_a_note(+ previewed: tuple[Viewer, Path],+) -> None:+ window, scene = previewed+ assert window.until("scenes") == {"scenes": ["Dot", "Other"], "scene": "Dot"}+ window.ended()+ assert window.starts() == 1+ scene.write_text(SCENE.format(extra=", run_time=2"), encoding="utf-8")+ window.ended(2)+ assert window.starts() == 2+ scene.write_text(SCENE.format(extra=".no_such_method()"), encoding="utf-8")+ error = window.until("error")["error"]+ assert isinstance(error, dict)+ assert error["type"] == "AttributeError"+ assert error["line"] == 7+++def test_a_scene_the_viewer_asks_for_runs_next(previewed: tuple[Viewer, Path]) -> None:+ window, _ = previewed+ window.ended()+ window.wants.put("Other")+ assert window.until("scenes", 2) == {"scenes": ["Dot", "Other"], "scene": "Other"}+ window.ended(2)++[email protected]("previewed", [SLOW], indirect=True)+def test_a_save_cuts_the_run_it_makes_out_of_date(+ previewed: tuple[Viewer, Path],+) -> None:+ window, scene = previewed+ window.until("scenes")+ time.sleep(0.5) # well into the run's four seconds+ saved = time.monotonic()+ scene.write_text(SLOW.format(extra=".set_color(m.RED)"), encoding="utf-8")+ while window.starts() < 2 and time.monotonic() - saved < 10:+ time.sleep(0.01)+ assert time.monotonic() - saved < 1.5 # at once, not once the old run was done+ with window.lock:+ ops = [op for op, _ in window.seen]+ first = ops[: ops.index(START, 1)]+ assert END not in first # the old take was cut short, not endeddiff --git a/tests/integration/test_reveal.py b/tests/integration/test_reveal.pynew file mode 100644index 00000000..7a013e45--- /dev/null+++ b/tests/integration/test_reveal.py@@ -0,0 +1,122 @@+"""A reveal moves through every shape by the same steps, each shown whole with all it draws.++- u counts a shape's steps: a path's curves, a cloud's points, a mesh's triangles, a surface's+ faces. A reveal (`Create`, `Uncreate`, `ShowPassingFlash`) shows every step its window+ reaches into.+- A surface's face shows with its edges, and its edges only with it: none before the reveal+ reaches the face, whatever colors it (its fill, or a colorscale by value).+- A point shows once the reveal reaches into it.+- A part (`pointwise_become_partial`) draws what a reveal over its stretch shows: a surface's+ part is a surface, its faces as smooth and with the edges they have in the whole.+"""++from collections.abc import Callable++import numpy as np+import pytest++import manimgx as m+from manimgx.config import config+from manimgx.rendering.film import Frame++W, H = 640, 360+++def _frames(+ build: Callable[[m.Scene], None], monkeypatch: pytest.MonkeyPatch+) -> list[np.ndarray]:+ """Every frame of a scene whose construct is `build`: red, green and blue, from 0 to 1."""+ monkeypatch.setattr(config, "pixel_width", W)+ monkeypatch.setattr(config, "pixel_height", H)+ monkeypatch.setattr(config, "frame_rate", 10)+ shown: list[np.ndarray] = []++ def sink(frame: Frame) -> None:+ pixels = np.frombuffer(frame.pixels(), np.uint8).reshape(H, W, 4)[..., :3]+ shown.extend([pixels.astype(float) / 255] * frame.repeat)++ class Scene(m.Scene):+ def construct(self) -> None:+ build(self)++ Scene().render(frames=sink)+ return shown+++def _column(x: float) -> int:+ """The pixel column holding scene x."""+ return int(np.floor(W / 2 + x * W / config.frame_width))+++def _sheet(by_value: bool) -> m.Surface:+ """A flat sheet over [-2, 2] by [-1, 1], 8 faces along x (u: the reveal's order) by 4:+ blue, with white edges, so a frame's red is its edges alone."""+ sheet = m.Surface(+ lambda u, v: np.array([u, v, 0.0]),+ u_range=(-2, 2),+ v_range=(-1, 1),+ resolution=(8, 4),+ checkerboard_colors=False,+ fill_color=m.PURE_BLUE,+ )+ if by_value: # its colors a colorscale's: a picture, at v = 0.5 on every vertex+ sheet.set_fill_by_value(+ m.ThreeDAxes(), colorscale=[(m.PURE_BLUE, -1), (m.PURE_BLUE, 1)]+ )+ return sheet.set_stroke(m.WHITE, width=4, opacity=1)++[email protected]("by_value", [False, True], ids=["filled", "by-value"])+def test_a_surface_shows_each_face_with_its_edges_as_the_reveal_reaches_it(+ by_value: bool, monkeypatch: pytest.MonkeyPatch+) -> None:+ def build(scene: m.Scene) -> None:+ scene.play(m.Create(_sheet(by_value)), run_time=1, rate_func=m.linear)++ frames = _frames(build, monkeypatch)+ edges, faces = [f[..., 0] for f in frames], [f[..., 2] for f in frames]+ assert edges[0].max() == 0+ assert faces[0].max() == 0+ # at 10 fps, 3/10 of the 32 faces reach into the 10th (to x = -0.5), 5/10 to the 16th (0)+ for k, front in ((3, -0.5), (5, 0.0)):+ past, before = _column(front) + 4, _column(front) - 4+ assert edges[k][:, past:].max() == 0, "an edge shows past the faces drawn"+ assert faces[k][:, past:].max() == 0+ assert edges[k][:, :before].max() > 0.5, "the faces drawn show no edges"+ assert edges[-1][:, _column(1.5)].max() > 0.5++[email protected](("a", "b"), [(0.0, 0.5), (0.3, 0.8)])+def test_a_surface_part_draws_what_a_reveal_over_its_stretch_shows(+ a: float, b: float, monkeypatch: pytest.MonkeyPatch+) -> None:+ def part(scene: m.Scene) -> None:+ sheet = _sheet(by_value=False)+ scene.add(sheet.copy().pointwise_become_partial(sheet, a, b))++ def revealed(scene: m.Scene) -> None:+ sheet = _sheet(by_value=False)+ sheet.paint = sheet.paint.but(trim=np.array([a, b]))+ scene.add(sheet)++ shown = _frames(part, monkeypatch)[-1]+ assert shown[..., 0].max() > 0.5 # its edges+ np.testing.assert_array_equal(shown, _frames(revealed, monkeypatch)[-1])+++def test_a_point_shows_once_the_reveal_reaches_into_it(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ xs = (-3.0, -1.0, 1.0, 3.0)++ def build(scene: m.Scene) -> None:+ cloud = m.PMobject(stroke_width=20)+ cloud.add_points([[x, 0, 0] for x in xs], color=m.WHITE)+ scene.play(m.Create(cloud), run_time=1, rate_func=m.linear)++ frames = _frames(build, monkeypatch)+ shown = [[bool(f[H // 2, _column(x), 0] > 0.5) for x in xs] for f in frames]+ assert shown[0] == [False] * 4+ assert shown[1] == [True, False, False, False] # 1/10 of 4 points reaches into one+ assert shown[3] == [True, True, False, False] # 3/10 of 4: into the second+ assert shown[-1] == [True] * 4diff --git a/tests/integration/test_sound.py b/tests/integration/test_sound.pynew file mode 100644index 00000000..9d2b8bd8--- /dev/null+++ b/tests/integration/test_sound.py@@ -0,0 +1,195 @@+"""A film's sound, heard through a player: in its MP4, to the sample, as long as the film.++- The MP4 carries the film's sound as AAC; a decoder (FFmpeg's) finds each sound at its sample,+ the encoder's priming skipped, at any frame rate; the sound lasts exactly as long as the film.+- A film with no sound has no sound track.+- The engine reads audio files (WAV, FLAC, MP3…) as they are, and resamples band-limited: a+ tone keeps its level, and its images are gone.+"""++import wave+from fractions import Fraction+from pathlib import Path++import av+import numpy as np+import pytest++import manimgx as m+from manimgx._engine import decode_audio, resample_audio+from manimgx.audio.sound import RATE+from manimgx.config import config+++def impulse() -> m.Sound:+ x = np.zeros(4800, np.float32)+ x[0] = 0.9+ return m.Sound(x, rate=RATE)+++class Beats(m.Scene):+ def construct(self) -> None:+ square = m.Square()+ self.play(m.Create(square))+ self.play(m.FadeOut(square), impulse()) # at 1 s+ self.add_sound(impulse(), time_offset=1.5) # at 3.5 s+ self.wait(2)+++def decoded(path: Path) -> np.ndarray:+ """The MP4's sound as a player hears it (FFmpeg's decoder, through PyAV): from the+ encoder's priming, which the decoder skips, to the end of the edit list, which the stream's+ duration says; the first channel."""+ with av.open(str(path)) as container:+ stream = container.streams.audio[0]+ resampler = av.AudioResampler(format="flt", layout="mono", rate=RATE)+ frames = [+ out.to_ndarray().reshape(-1)+ for frame in container.decode(stream)+ for out in resampler.resample(frame)+ ]+ heard = stream.duration+ assert heard is not None+ return np.concatenate(frames)[:heard]+++def streams(path: Path) -> list[str]:+ with av.open(str(path)) as container:+ return [stream.codec_context.name for stream in container.streams]+++pytestmark = pytest.mark.config(pixel_width=320, pixel_height=180)++[email protected]("fps", [10, 24, 60])+def test_each_sound_is_at_its_sample_and_lasts_the_film(+ tmp_path: Path, fps: int+) -> None:+ config.frame_rate = fps+ film = Beats().render(tmp_path / "beats.mp4")+ assert streams(tmp_path / "beats.mp4") == ["h264", "aac"]+ x = decoded(tmp_path / "beats.mp4")+ assert len(x) == film.frame_count * RATE // fps+ for want in (RATE, 7 * RATE // 2):+ window = np.abs(x[want - 4000 : want + 4000])+ assert int(np.argmax(window)) + want - 4000 == want+++def test_a_film_without_sound_has_no_sound_track(tmp_path: Path) -> None:+ class Silent(m.Scene):+ def construct(self) -> None:+ self.play(m.Create(m.Square()))++ Silent().render(tmp_path / "silent.mp4")+ assert streams(tmp_path / "silent.mp4") == ["h264"]+++def test_audio_files_are_read_as_they_are(tmp_path: Path) -> None:+ rate, t = 44_100, np.arange(44_100) / 44_100+ tone = (0.5 * np.sin(2 * np.pi * 440 * t) * 32767).astype("<i2")+ with wave.open(str(tmp_path / "tone.wav"), "wb") as w:+ w.setnchannels(1)+ w.setsampwidth(2)+ w.setframerate(rate)+ w.writeframes(tone.tobytes())+ with (+ av.open(str(tmp_path / "tone.wav")) as wav,+ av.open(str(tmp_path / "tone.flac"), "w") as flac,+ ):+ out = flac.add_stream("flac", rate=rate, layout="mono")+ for frame in wav.decode(audio=0):+ for packet in out.encode(frame):+ flac.mux(packet)+ for packet in out.encode(None):+ flac.mux(packet)+ for name in ("tone.wav", "tone.flac"):+ samples, channels = decode_audio((tmp_path / name).read_bytes(), RATE)+ x = np.frombuffer(samples, np.float32)+ assert channels == 1+ assert len(x) == RATE+ assert np.abs(x[1000:-1000]).max() == pytest.approx(0.5, abs=2e-3)+ with pytest.raises(ValueError, match="not an audio file"):+ decode_audio(b"not audio at all", RATE)+++CLICKS = (12_000, 36_000) # where the clicks are, in a second of sound at RATE+++def clicks(channels: int) -> np.ndarray:+ """A second of near-silence with a short burst at each of CLICKS, in every channel."""+ x = np.zeros((RATE, channels), np.float32)+ burst = (0.4 * np.hanning(64) * np.sin(np.arange(64) * 0.7)).astype(np.float32)+ for at in CLICKS:+ x[at - 32 : at + 32] = burst[:, None]+ return x+++def encoded(path: Path, codec: str, layout: str, x: np.ndarray) -> bytes:+ """`x` (RATE, as `layout`) encoded by FFmpeg (PyAV's), in the container `path` names."""+ with av.open(str(path), "w") as file:+ stream = file.add_stream(codec, rate=RATE, layout=layout)+ assert isinstance(stream, av.AudioStream)+ frame = av.AudioFrame.from_ndarray(+ np.ascontiguousarray(x.T), format="fltp", layout=layout+ )+ # from time 0: the encoder's priming before it, which the file then declares+ frame.rate, frame.pts, frame.time_base = RATE, 0, Fraction(1, RATE)+ for packet in (*stream.encode(frame), *stream.encode(None)):+ file.mux(packet)+ return path.read_bytes()+++ ("name", "codec", "layout"),+ [+ ("aac.m4a", "aac", "stereo"),+ ("lame.mp3", "libmp3lame", "stereo"),+ ("opus.ogg", "libopus", "stereo"),+ ("opus.webm", "libopus", "mono"),+ ("flac.flac", "flac", "stereo"),+ ("alac.m4a", "alac", "mono"),+ ("surround.wav", "pcm_s16le", "5.1"),+ ],+)+def test_audio_files_start_and_end_where_they_declare(+ tmp_path: Path, name: str, codec: str, layout: str+) -> None:+ """Each container and codec: the sound exactly as long as it was, each click on its+ sample (the encoder's delay and padding trimmed as the file declares them), and surround+ mixed down to stereo without clipping."""+ channels = av.AudioLayout(layout).nb_channels+ x = clicks(channels) * 1.5+ samples, got = decode_audio(encoded(tmp_path / name, codec, layout, x), RATE)+ y = np.frombuffer(samples, np.float32).reshape(-1, got)+ assert got == min(channels, 2)+ assert len(y) == RATE+ assert np.abs(y).max() <= 1+ for at in CLICKS:+ peak = [int(np.argmax(np.abs(s[at - 2000 : at + 2000, 0]))) for s in (x, y)]+ assert abs(peak[0] - peak[1]) <= 2+++def test_a_sound_manimgx_does_not_decode_is_named(tmp_path: Path) -> None:+ data = encoded(tmp_path / "dolby.mkv", "ac3", "stereo", clicks(2))+ with pytest.raises(+ ValueError, match="its sound is ac3, which manimgx doesn't decode"+ ):+ decode_audio(data, RATE)+++def level(y: np.ndarray, hz: float) -> float:+ """A tone's level in `y` (at RATE), in decibels of a 0.5 sine."""+ w = np.hanning(len(y))+ spectrum = np.abs(np.fft.rfft(y * w)) / (w.sum() / 2)+ at = round(hz * len(y) / RATE)+ return float(20 * np.log10(spectrum[at - 2 : at + 3].max() / 0.5 + 1e-12))+++def test_resampling_keeps_the_band_and_drops_its_images() -> None:+ t = np.arange(24_000) / 24_000+ for f in (100, 1_000, 5_000, 10_000):+ x = (0.5 * np.sin(2 * np.pi * f * t)).astype(np.float32)+ y = np.frombuffer(resample_audio(x.tobytes(), 1, 24_000, RATE), np.float32)+ y = y[2400:-2400]+ assert level(y, f) == pytest.approx(0, abs=0.1)+ assert level(y, 24_000 - f) < -80diff --git a/tests/integration/test_take.py b/tests/integration/test_take.pynew file mode 100644index 00000000..22ac93a9--- /dev/null+++ b/tests/integration/test_take.py@@ -0,0 +1,260 @@+"""A film recorded as a take: the engine's work written down — each array of its shapes once,+then what changes of them, and each frame's view and records — for manimgx's player to draw (in+its window, or in the browser). A take holds the frames a video would, and tells the player+what else it shows: the plays, each with the line that played it, its sections, its sound and+captions, and the end — or that its scene failed. Its taker may cut the film, as a frame sink+may. Where the engine has no GPU (Pyodide), every film is a take.+"""++import io+import json+import struct+import wave+from pathlib import Path++import numpy as np+import pytest++import manimgx as m+from manimgx import _engine+from manimgx.rendering import feed+from manimgx.rendering.film import Cut, Frame++START, FRAME, NOTE, SOUND, END = 0, 8, 9, 10, 12+++class Held(m.Scene):+ def construct(self) -> None:+ square = m.Square()+ self.play(m.Create(square))+ self.play(square.animate.shift(m.RIGHT))+ self.wait()+++pytestmark = pytest.mark.config(pixel_width=320, pixel_height=180, frame_rate=30)+++def messages(take: bytes) -> list[tuple[int, bytes]]:+ """The take's messages, in order: (op, fields). Each is its length (u32), op (u8), fields."""+ out, at = [], 0+ while at < len(take):+ (n,) = struct.unpack_from("<I", take, at)+ out.append((take[at + 4], take[at + 5 : at + 4 + n]))+ at += 4 + n+ assert at == len(take), "the take ends in the middle of a message"+ return out+++def notes(take: bytes) -> list[str]:+ return [fields[4:].decode() for op, fields in messages(take) if op == NOTE]+++def record(scene: m.Scene) -> tuple[bytes, int]:+ chunks: list[bytes] = []+ film = scene.render(take=chunks.append)+ return b"".join(chunks), film.frame_count+++def test_a_take_holds_the_frames_a_video_would() -> None:+ sent: list[Frame] = []+ Held().render(frames=sent.append)+ take, count = record(Held())+ (op, start), *rest = messages(take)+ assert op == START+ assert struct.unpack("<IId", start) == (320, 180, 30.0)+ repeats = [+ struct.unpack_from("<I", fields)[0] for op, fields in rest if op == FRAME+ ]+ assert repeats == [frame.repeat for frame in sent] # a hold is one frame, lasting+ assert sum(repeats) == count+++def test_a_take_notes_each_play_with_its_line_and_its_end() -> None:+ take, _ = record(Held())+ plays = [json.loads(note) for note in notes(take)]+ source = Path(__file__).read_text(encoding="utf-8").splitlines()+ called = ["self.play(m.Create(square))", "self.play(square.animate.shift(m.RIGHT))"]+ lines = [source.index(f" {call}") + 1 for call in [*called, "self.wait()"]]+ assert [p["play"]["where"] for p in plays] == [[__file__, line] for line in lines]+ assert messages(take)[-1] == (END, b"\x00") # it ends, its scene ended+++class Slides(m.Scene):+ def construct(self) -> None:+ self.next_section("Intro")+ self.play(m.Create(m.Square()))+ self.next_section("Proof", "presentation.loop", notes="Slowly.")+ self.wait(0.5)+++def test_a_take_notes_each_section_where_the_film_begins_it() -> None:+ take, _ = record(Slides())+ sections = [+ json.loads(note)["section"] for note in notes(take) if '"section"' in note+ ]+ film = Slides().render()+ assert [+ (s["name"], s["start"], s["frame"], s["type"], s["notes"]) for s in sections+ ] == [(s.name, float(s.start), s.frame, s.type, s.notes) for s in film.sections]+++class Said(m.Scene):+ def construct(self) -> None:+ self.add_subcaption("A tone.", duration=0.5)+ self.play(m.Sound.of(lambda t: 0.5 * np.sin(2 * np.pi * 440 * t), 0.5))+ self.wait(0.5)+++def test_a_take_ends_with_the_film_s_sound_and_captions() -> None:+ take, count = record(Said())+ ((sound,),) = [(fields[4:],) for op, fields in messages(take) if op == SOUND]+ with wave.open(io.BytesIO(sound)) as wav:+ assert (wav.getsampwidth(), wav.getframerate()) == (2, 48_000)+ assert wav.getnframes() == count * 48_000 // 30 # as long as the film+ samples = np.frombuffer(wav.readframes(wav.getnframes()), "<i2")+ assert samples[:24_000].std() > 0.3 * 32767 # the tone+ assert not samples[24_000:].any() # then nothing+ said = [json.loads(note) for note in notes(take)]+ assert {"captions": [{"start": 0.0, "end": 0.5, "text": "A tone."}]} in said+ assert messages(take)[-1][0] == END # after them+++class Rippling(m.Scene):+ """A 50x50 mesh whose points move a little every frame, its triangles never."""++ def construct(self) -> None:+ u, v = np.meshgrid(np.linspace(-3, 3, 50), np.linspace(-2, 2, 50))+ cells = np.arange(50 * 50).reshape(50, 50)[:-1, :-1].ravel()+ triangles = np.concatenate(+ [+ np.stack([cells, cells + 1, cells + 51], 1),+ np.stack([cells, cells + 51, cells + 50], 1),+ ]+ )+ grid = m.MeshMobject(+ np.stack([u.ravel(), v.ravel(), 0 * u.ravel()], 1), triangles+ )+ time = m.ValueTracker(0)++ def ripple(mesh: m.MeshMobject) -> None:+ t = time.get_value()+ mesh.points = np.stack(+ [u.ravel(), v.ravel(), 0.2 * np.sin(2 * u.ravel() + t)], 1+ )++ grid.add_updater(ripple)+ self.add(grid)+ self.play(time.animate.set_value(3), run_time=2)+++def test_a_shape_that_changes_a_little_is_sent_as_its_changes() -> None:+ take, count = record(Rippling())+ points_and_uvs = count * 50 * 50 * (3 + 2) * 8 # float64s, every frame+ triangles = count * 49 * 49 * 2 * 3 * 4+ assert count >= 60+ assert (+ len(take) * 10 < points_and_uvs + triangles+ ) # its triangles once, its changes+++def test_without_a_gpu_every_film_is_a_take(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(feed, "Player", None) # the engine as Pyodide has it+ take, count = record(Held())+ assert count+ assert messages(take)[0][0] == START+ assert Held().render().frame_count == count # recorded all the same, to nowhere+ with pytest.raises(ValueError, match="no GPU"):+ Held().render(frames=lambda _: None)+++def test_a_take_is_not_also_a_video(tmp_path: Path) -> None:+ with pytest.raises(ValueError, match="drawn by manimgx's player"):+ Held().render(tmp_path / "held.mp4", take=lambda _: None)+++def test_a_note_between_takes_is_a_message_of_its_own() -> None:+ ((op, fields),) = messages(_engine.note('{"scenes": ["Held"]}'))+ assert (op, fields[4:]) == (NOTE, b'{"scenes": ["Held"]}')+++def test_a_take_that_cuts_the_film_is_sent_nothing_more() -> None:+ _, whole = record(Held())+ sent: list[bytes] = []++ def take(data: bytes) -> None:+ sent.append(data)+ if len(sent) == 3:+ raise Cut++ film = Held().render(take=take)+ assert len(sent) == 3 # not even how the film ends+ assert 0 < film.frame_count < whole+++class Failing(m.Scene):+ def construct(self) -> None:+ self.play(m.Create(m.Square()))+ raise RuntimeError("the scene's own mistake")+++def test_a_take_whose_scene_fails_ends_saying_so() -> None:+ chunks: list[bytes] = []+ scene = Failing()+ with pytest.raises(RuntimeError, match="own mistake"):+ scene.render(take=chunks.append)+ sent = messages(b"".join(chunks))+ assert sent[-1] == (END, b"\x01") # it ends, its scene failed+ frames = sum(+ struct.unpack_from("<I", fields)[0] for op, fields in sent if op == FRAME+ )+ assert frames == scene.film.frame_count # with every frame made, the last one too++[email protected]("points_first", [False, True])+def test_a_take_keeps_same_form_path_and_cloud_as_distinct_uploads(+ points_first: bool,+) -> None:+ points = np.array(+ [[-0.5, -0.5, 0.0], [-0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, -0.5, 0.0]]+ )+ path = m.VMobject(color=m.BLUE, stroke_width=8).set_points(points).shift(2 * m.LEFT)+ cloud = (+ m.PMobject(stroke_width=20).add_points(points, color=m.RED).shift(2 * m.RIGHT)+ )+ assert path._geometry.terms[0][1].affine[0] == cloud._geometry.terms[0][1].affine[0]++ class Both(m.Scene):+ def construct(self) -> None:+ self.add(*(cloud, path) if points_first else (path, cloud))++ scene = Both()+ take, count = record(scene)+ sent = messages(take)+ # Upload opcodes carry the interpretation; identifiers themselves are opaque.+ uploads = [+ (op, struct.unpack_from("<Q", fields)[0]) for op, fields in sent if op in (1, 2)+ ]+ assert [op for op, _ in uploads] == ([2, 1] if points_first else [1, 2])+ assert len({key for _, key in uploads}) == 2++ # A single closing frame draws both resources, in scene order. Its record array+ # is exactly the content the feeder handed to the recorder, independently of+ # whichever numeric identifiers the native uploads received.+ assert count == 1+ (raw_records,) = scene.film.feeder.latest+ records = np.frombuffer(raw_records, feed.RECORD)+ assert list(records["key1"]) == [key for _, key in uploads]+ assert not records["key2"].any()+ (frame,) = [fields for op, fields in sent if op == FRAME]+ repeat, view_bytes = struct.unpack_from("<II", frame)+ record_key, cameras = struct.unpack_from("<QI", frame, 8 + view_bytes)+ assert repeat == 1+ assert cameras == 0+ # Packed array kind 9 is Records. Compare content identity, never a fixed hash.+ assert record_key == _engine.digest(b"\x09", raw_records)+ arrays = {+ struct.unpack_from("<Q", fields)[0]: fields[16]+ for op, fields in sent+ if op == 11+ }+ assert arrays[record_key] == 9diff --git a/tests/integration/test_time.py b/tests/integration/test_time.pynew file mode 100644index 00000000..f06d3817--- /dev/null+++ b/tests/integration/test_time.py@@ -0,0 +1,356 @@+"""Scene time is one clock: a frame shows the world at its own instant, at any frame rate.++A time-based updater is handed exactly the time it has been live since it was last brought+forward, attached, added to the scene or resumed, measured on its own clock (`ChangeSpeed`'s+speed clock for `ChangeSpeed.add_updater`); the world is brought to every frame, every play's+end and the closing frame. So in each story below, a dot pushed by such an updater is where its+exact trajectory puts it at every instant the scene computes, at 10, 30 and 60 fps: what a+frame shows does not depend on the frame rate. The corpus cannot see this, since it compares a+scene's closing frame only when CE happens to draw that instant.+"""++from collections.abc import Callable+from fractions import Fraction+from itertools import pairwise++import numpy as np+import pytest++import manimgx as m+from manimgx.animation import clock+from manimgx.config import config+from manimgx.mobject import flow+from manimgx.scene import Act++type Story = Callable[[Probe], None]+type Trajectory = Callable[[Fraction], Fraction]+type Profile = dict[Fraction, Fraction]++SPEED = 4 # units per second of the updater's clock+# ChangeSpeed speed profiles, {node: speed}, with their implicit ends+SLOWING: Profile = {+ Fraction(0): Fraction(1),+ Fraction(2, 5): Fraction(1),+ Fraction(1, 2): Fraction(1, 5),+ Fraction(4, 5): Fraction(1, 5),+ Fraction(1): Fraction(1),+}+TO_A_STOP: Profile = {Fraction(0): Fraction(1), Fraction(1): Fraction(0)}+++def push(mob: m.Mobject, dt: float) -> None:+ mob.shift(m.RIGHT * SPEED * dt)+++def pull(mob: m.Mobject, dt: float) -> None:+ mob.shift(m.LEFT * SPEED * dt)+++class Probe(m.Scene):+ """A dot at x = -4 and a story told with it; at every instant the scene computes, the time,+ the time its own updater has been handed, and where the dot is."""++ def __init__(self, story: Story) -> None:+ super().__init__()+ self.story = story+ self.dot = m.Dot().shift(m.LEFT * 4)+ self.elapsed = 0.0+ self.seen: list[tuple[Fraction, float, float]] = []++ def construct(self) -> None:+ self.add_updater(self.look)+ self.story(self)++ def look(self, dt: float) -> None:+ self.elapsed += dt+ self.seen.append((clock.now, self.elapsed, float(self.dot.get_x())))+++def covered(speeds: Profile, length: Fraction, s: Fraction) -> Fraction:+ """How far a ChangeSpeed's wrapped animation, `length` seconds long, has run `s` seconds+ into its play (none before it): between two nodes its speed goes linearly, in real time,+ from one node's to the next's; after the last node, it is scene time again."""+ if s <= 0:+ return Fraction(0)+ done = Fraction(0)+ for (a, v), (b, w) in pairwise(speeds.items()):+ span = length * (b - a) * 2 / (v + w) # the real time this stretch takes+ if s <= span:+ return done + v * s + (w - v) * s * s / (2 * span)+ s -= span+ done += length * (b - a)+ return done + s+++def one_wait(s: Probe) -> None:+ s.add(s.dot)+ s.dot.add_updater(push)+ s.wait(2)+++def two_waits(s: Probe) -> None:+ s.add(s.dot)+ s.dot.add_updater(push)+ s.wait(1)+ s.wait(1)+++def attached_between_plays(s: Probe) -> None:+ s.add(s.dot)+ s.wait(1)+ s.dot.add_updater(push)+ s.wait(1)+++def added_between_plays(s: Probe) -> None:+ s.dot.add_updater(push)+ s.wait(1)+ s.add(s.dot)+ s.wait(1)+++def swapped_between_plays(s: Probe) -> None:+ s.add(s.dot)+ s.dot.add_updater(push)+ s.wait(1)+ s.dot.clear_updaters()+ s.dot.add_updater(pull)+ s.wait(1)+++def suspended_between_plays(s: Probe) -> None:+ s.add(s.dot)+ s.dot.add_updater(push)+ s.wait(1)+ s.dot.suspend_updating()+ s.wait(1)+ s.dot.resume_updating()+ s.wait(1)+++def ending_between_frames(s: Probe) -> None:+ s.add(s.dot)+ s.dot.add_updater(push)+ s.wait(0.25)+ s.wait(1)+++def sped(s: Probe) -> None:+ s.add(s.dot)+ m.ChangeSpeed.add_updater(s.dot, push)+ s.play(m.ChangeSpeed(m.Wait(2), speedinfo={0.4: 1, 0.5: 0.2, 0.8: 0.2, 1: 1}))+ s.wait(0.5)+++def slowed_to_a_stop(s: Probe) -> None:+ s.add(s.dot)+ m.ChangeSpeed.add_updater(s.dot, push)+ s.wait(1)+ s.play(m.ChangeSpeed(m.Wait(1), speedinfo={1: 0}))+++def stopping(t: Fraction) -> Fraction:+ """Where slowed_to_a_stop's dot is: a second at speed 1, then its play's."""+ return -4 + SPEED * (min(t, Fraction(1)) + covered(TO_A_STOP, Fraction(1), t - 1))+++STORIES: dict[str, tuple[Story, Trajectory]] = {+ "one_wait": (one_wait, lambda t: -4 + SPEED * t),+ "two_waits": (two_waits, lambda t: -4 + SPEED * t),+ "attached_between_plays": (+ attached_between_plays,+ lambda t: -4 + SPEED * max(t - 1, Fraction(0)),+ ),+ "added_between_plays": (+ added_between_plays,+ lambda t: -4 + SPEED * max(t - 1, Fraction(0)),+ ),+ "swapped_between_plays": (+ swapped_between_plays,+ lambda t: -4 + SPEED * (min(t, Fraction(1)) - max(t - 1, Fraction(0))),+ ),+ "suspended_between_plays": (+ suspended_between_plays,+ lambda t: -4 + SPEED * (min(t, Fraction(1)) + max(t - 2, Fraction(0))),+ ),+ # the closing frame is the first frame time after the end, and shows the world there+ "ending_between_frames": (ending_between_frames, lambda t: -4 + SPEED * t),+ "sped": (sped, lambda t: -4 + SPEED * covered(SLOWING, Fraction(2), t)),+ "slowed_to_a_stop": (slowed_to_a_stop, stopping),+}++[email protected]("fps", [10, 30, 60])[email protected]("name", STORIES)+def test_the_world_at_every_instant(+ name: str, fps: int, monkeypatch: pytest.MonkeyPatch+) -> None:+ story, trajectory = STORIES[name]+ monkeypatch.setattr(config, "frame_rate", fps)+ scene = Probe(story)+ scene.render()+ instants = {t for t, _, _ in scene.seen}+ unseen = [k for k in range(scene.frame) if Fraction(k, fps) not in instants]+ assert not unseen, f"frames {unseen} were not brought to their instants"+ for t, elapsed, x in scene.seen:+ assert elapsed == pytest.approx(float(t), abs=1e-9), f"scene updater at {t} s"+ assert x == pytest.approx(float(trajectory(t)), abs=1e-9), f"the dot at {t} s"+++def spring(mob: m.Mobject, dt: float) -> None:+ """x' = −x, one Euler step: an integrator (two steps of dt/2 are not one of dt)."""+ mob.shift(-mob.get_center() * dt)+++class Integrating(m.Scene):+ """A dot a spring pulls to the origin, and the path it traces; where the dot is at every+ instant the scene computes."""++ def construct(self) -> None:+ self.at: dict[Fraction, float] = {}+ self.dot = m.Dot(m.RIGHT * 2).add_updater(spring)+ self.trace = m.TracedPath(self.dot.get_center)+ self.add(self.dot, self.trace)+ self.wait(1.5)++ def _instant(+ self,+ t: Fraction,+ act: Act | None = None,+ stepping: bool = True,+ framing: bool = True,+ ) -> None:+ super()._instant(t, act, stepping, framing)+ self.at[t] = float(self.dot.get_x())++[email protected]("fps", [10, 24, 25, 30, 60])+def test_a_simulation_does_not_depend_on_the_frame_rate(+ fps: int, monkeypatch: pytest.MonkeyPatch+) -> None:+ """An updater that integrates steps on the simulation clock — every tick, and at the+ scene's events — never on frames: at every instant, at any frame rate, the dot is where+ that many Euler steps take it (a frame between two ticks shows the last), and the path it+ traces is the same, a point per tick."""+ monkeypatch.setattr(config, "frame_rate", fps)+ scene = Integrating()+ scene.render()+ h = Fraction(1, config.simulation_rate)+ for t, x in scene.at.items():+ assert x == pytest.approx(2 * (1 - float(h)) ** int(t // h), rel=1e-12), t+ shown = max(+ scene.at+ ) # the closing frame: the end, or the first frame time after it+ ticks = [2 * (1 - float(h)) ** k for k in range(int(shown // h) + 1)]+ assert scene.trace.points[3::4, 0] == pytest.approx(ticks, rel=1e-12)+++class Tracing(m.Scene):+ """A dot a tween carries round an arc, and the path it traces; at every instant, how far+ the path's end is from the dot."""++ def construct(self) -> None:+ self.gaps: list[float] = []+ self.dot = m.Dot(m.RIGHT * 2)+ self.trace = m.TracedPath(self.dot.get_center)+ self.add(self.dot, self.trace)+ self.play(m.Rotate(self.dot, m.PI, about_point=m.ORIGIN), rate_func=m.linear)++ def _instant(+ self,+ t: Fraction,+ act: Act | None = None,+ stepping: bool = True,+ framing: bool = True,+ ) -> None:+ super()._instant(t, act, stepping, framing)+ gap = self.trace.points[-1] - self.dot.get_center()+ self.gaps.append(float(abs(gap).max()))++[email protected]("fps", [10, 24, 25, 30, 60])+def test_a_traced_path_is_the_same_at_any_frame_rate(+ fps: int, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The path a point traces holds where it was at every tick — the same points at any frame+ rate — and at a frame between two ticks runs on to where it is: never behind it."""+ monkeypatch.setattr(config, "frame_rate", fps)+ scene = Tracing()+ scene.render()+ assert max(scene.gaps) < 1e-12+ h = 1 / config.simulation_rate+ angles = np.pi * np.arange(config.simulation_rate + 1) * h+ ticks = np.stack([2 * np.cos(angles), 2 * np.sin(angles)], axis=1)+ assert scene.trace.points[3::4, :2] == pytest.approx(ticks, abs=1e-12)+++class Lifting(m.Scene):+ """A dot a flow carries right, which a per-frame updater lifts a step every frame, and the+ path it traces; where the dot is at every frame."""++ def construct(self) -> None:+ self.dot = m.Dot()+ self.dot.add_updater(flow(lambda d, dt: d.shift(m.RIGHT * dt)))+ self.dot.add_updater(lambda d: d.shift(m.UP / 100))+ self.trace = m.TracedPath(self.dot.get_center)+ self.shown: list[np.ndarray] = []+ self.add(self.trace, self.dot)+ self.wait(1)++ def _emit(self, repeat: int = 1) -> None:+ self.shown.append(self.dot.get_center()[:2].copy())+ super()._emit(repeat)++[email protected]("fps", [10, 24, 25, 30, 60])+def test_a_per_frame_move_is_traced_over_its_frame(+ fps: int, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A per-frame updater moves a point at frames only: the change it makes at a frame is the+ change over that frame, so the path spreads it over the frame, in proportion to time. Here+ both motions are uniform, so between two frames the path runs straight from where the one+ showed the dot to where the next shows it: no stairs at the ticks between them."""+ monkeypatch.setattr(config, "frame_rate", fps)+ scene = Lifting()+ scene.render()+ shown = np.array(scene.shown)+ for point in scene.trace.points[3::4, :2]:+ k = min(int(point[0] * fps + 1e-9), len(shown) - 2)+ a, b = shown[k], shown[k + 1]+ u, v = b - a, point - a+ assert abs(u[0] * v[1] - u[1] * v[0]) / np.hypot(*u) < 1e-12+++class Counting(m.Scene):+ """How often a per-frame updater is called over a play — with a traced path in the scene,+ which is simulated, or without one."""++ def __init__(self, traced: bool) -> None:+ super().__init__()+ self.traced, self.calls = traced, 0++ def construct(self) -> None:+ def count(mob: m.Mobject) -> None:+ self.calls += 1++ dot = m.Dot().add_updater(count)+ self.add(dot)+ if self.traced:+ self.add(m.TracedPath(dot.get_center))+ self.play(dot.animate.shift(m.RIGHT), run_time=2)++[email protected]("fps", [10, 25, 60])+def test_a_per_frame_updater_runs_once_a_frame(+ fps: int, monkeypatch: pytest.MonkeyPatch+) -> None:+ """An updater that takes no time is called at every frame and event, and at no tick of the+ simulation clock between them: as often whether or not the scene simulates anything.+ """+ monkeypatch.setattr(config, "frame_rate", fps)+ counts = []+ for traced in (False, True):+ scene = Counting(traced)+ scene.render()+ counts.append(scene.calls)+ assert counts[0] == counts[1]diff --git a/tests/integration/test_video.py b/tests/integration/test_video.pynew file mode 100644index 00000000..7cb0713b--- /dev/null+++ b/tests/integration/test_video.py@@ -0,0 +1,59 @@+"""A film's video: decoded, it shows the frames the film drew, in their colors — the engine's+conversion to NV12, x264 (built into the engine), and what the MP4 says of its colors agree.+"""++from pathlib import Path++import av+import numpy as np+import pytest+from tests.integration.corpus.frames import decode++import manimgx as m+from manimgx.rendering.film import Frame, X264Preset++SIZE = (320, 180)+pytestmark = pytest.mark.config(pixel_width=SIZE[0], pixel_height=SIZE[1])+++class Filled(m.Scene):+ def construct(self) -> None:+ self.add(m.Rectangle(width=10, height=6, color=m.ORANGE, fill_opacity=1))+ self.play(m.Create(m.Circle(color=m.TEAL)))+ self.wait(0.5)+++def test_the_video_shows_the_frames_drawn(tmp_path: Path) -> None:+ drawn: list[np.ndarray] = []++ def sink(frame: Frame) -> None:+ pixels = np.frombuffer(frame.pixels(), np.uint8).reshape(SIZE[1], SIZE[0], 4)+ drawn.append(pixels[:, :, :3].astype(int))++ Filled().render(tmp_path / "filled.mp4", frames=sink)+ shown = [frame.astype(int) for frame in decode(tmp_path / "filled.mp4", SIZE)]+ assert len(shown) == len(drawn) # a held frame is one picture that lasts+ for picture, frame in zip(shown, drawn, strict=True):+ assert np.abs(picture - frame).mean() < 1.0+ # inside the rectangle, away from the circle's stroke: its orange, within a level or two+ assert np.abs(shown[-1][90, 60] - drawn[-1][90, 60]).max() <= 2++[email protected]("preset", ["ultrafast", "slow"])+def test_each_picture_shows_at_its_frame(tmp_path: Path, preset: X264Preset) -> None:+ # a slow preset encodes B-frames: pictures decoded after the picture they are shown+ # before, so the MP4 says when each is shown apart from when it is decoded+ starts: list[int] = []+ video = tmp_path / "filled.mp4"+ Filled().render(+ video, frames=lambda frame: starts.append(frame.index), preset=preset+ )+ with av.open(str(video)) as container:+ stream = container.streams.video[0]+ assert stream.time_base is not None+ shown = [+ frame.pts * stream.time_base * int(m.config.frame_rate)+ for frame in container.decode(stream)+ if frame.pts is not None+ ]+ assert shown == startsdiff --git a/tests/integration/test_window.py b/tests/integration/test_window.pynew file mode 100644index 00000000..a18cdd2e--- /dev/null+++ b/tests/integration/test_window.py@@ -0,0 +1,55 @@+"""manimgx's window: a process of its own, which plays the takes it is sent and closes when its+director closes it; a film sent to a closed window is cut. It needs a screen: on a Linux+without a display these are skipped; anywhere else, a window that cannot open is a failure.+"""++import os+import sys+from collections.abc import Iterator++import pytest++import manimgx as m+from manimgx.rendering.window import Window+++class Held(m.Scene):+ def construct(self) -> None:+ square = m.Square()+ self.play(m.Create(square))+ self.play(square.animate.shift(m.RIGHT))+ self.wait()+++pytestmark = pytest.mark.config(pixel_width=320, pixel_height=180, frame_rate=30)+++def window() -> Iterator[Window]:+ """A window, open (or the test skipped: there is no screen here)."""+ linux = sys.platform.startswith("linux")+ if linux and not (os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY")):+ pytest.skip("no display to open a window on")+ with Window("test_window.py") as opened:+ assert not opened.wait(timeout=1.0), (+ f"the window did not open: {opened.failure}"+ )+ yield opened+++def test_a_window_plays_what_it_is_sent_and_closes_with_its_director(+ window: Window,+) -> None:+ film = Held().render(take=window)+ assert film.frame_count+ assert window.open+ window.close()+ assert not window.open+ assert window.failure is None+++def test_a_film_sent_to_a_closed_window_is_cut(window: Window) -> None:+ whole = Held().render().frame_count+ window.close()+ film = Held().render(take=window)+ assert film.frame_count < whole