The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.
Python
Add fractal and packing examples
apoogdk294ecfb9dcbe
diff --git a/examples/menger_slice.py b/examples/menger_slice.pynew file mode 100644index 00000000..50b4ec3b--- /dev/null+++ b/examples/menger_slice.py@@ -0,0 +1,310 @@+"""The stars inside the Menger sponge: cut it through its center, perpendicular to a long+diagonal, and the cut face is a hexagon riddled with six-pointed stars.++The sponge keeps a cube of the 3 × 3 × 3 grid unless two of its three coordinates sit in the+middle third, and repeats that at every scale (level 3: 20³ = 8,000 cubes). Here it is cut by the+plane x + y + z = s. The cut is exact: every face of the sponge is clipped against the plane each+frame, and the cut face is painted from the same rule, so its holes are the sponge's tunnels. At+s = 3/2 the cut is a regular hexagon full of hexagrams; sweep s toward a corner and the pattern+morphs through Sierpinski-like triangles (a cut made famous by George Hart's 3D prints).+"""++import functools++import numpy as np++import manimgx as m++LEVEL = 3+SIZE = 4.3 # edge of the sponge on screen+NORMAL = np.ones(3) / np.sqrt(3)+E1 = np.array([1.0, -1.0, 0.0]) / np.sqrt(2)+E2 = np.array([1.0, 1.0, -2.0]) / np.sqrt(6)+CAP_PIXELS = 720+CAP_HALF = 0.74 # half the side of the cap's square, in unit-cube coordinates+BONE = "#e3dccb"+GOLD = np.array([1.0, 0.72, 0.18])+# the cap's pixel centers on the plane, a across the picture and b down it+CAP_A = ((np.arange(CAP_PIXELS) + 0.5) / CAP_PIXELS * 2 - 1) * CAP_HALF+CAP_B = -CAP_A # rows go down the picture++# the six outward faces of a unit voxel: (axis, side) → its corners, counter-clockwise outside+FACES = {+ (0, -1): [(0, 0, 0), (0, 0, 1), (0, 1, 1), (0, 1, 0)],+ (0, 1): [(1, 0, 0), (1, 1, 0), (1, 1, 1), (1, 0, 1)],+ (1, -1): [(0, 0, 0), (1, 0, 0), (1, 0, 1), (0, 0, 1)],+ (1, 1): [(0, 1, 0), (0, 1, 1), (1, 1, 1), (1, 1, 0)],+ (2, -1): [(0, 0, 0), (0, 1, 0), (1, 1, 0), (1, 0, 0)],+ (2, 1): [(0, 0, 1), (1, 0, 1), (1, 1, 1), (0, 1, 1)],+}+++def sponge(level: int) -> np.ndarray:+ """Occupancy of the level-`level` sponge on its 3^level grid."""+ n = 3**level+ x, y, z = np.meshgrid(*[np.arange(n)] * 3, indexing="ij")+ keep = np.ones((n, n, n), bool)+ for k in range(level):+ middles = sum(((c // 3**k) % 3 == 1).astype(int) for c in (x, y, z))+ keep &= middles < 2+ return keep+++def in_sponge(x: np.ndarray, y: np.ndarray, z: np.ndarray, level: int) -> np.ndarray:+ """Is each point inside the sponge (in [0, 1)³)? The same rule, digit by digit, on+ coordinate arrays that broadcast (one constant along an axis is worked once)."""+ inside = (x >= 0) & (x < 1) & (y >= 0) & (y < 1) & (z >= 0) & (z < 1)+ q = [x * 3, y * 3, z * 3] # at the next scale, worked in place (big arrays)+ digits = [np.empty_like(c) for c in q]+ for _ in range(level):+ for c, d in zip(q, digits, strict=True):+ np.floor(c, out=d)+ c -= d+ c *= 3+ mx, my, mz = (d == 1 for d in digits)+ inside &= ~((mx & my) | (mz & (mx | my))) # fewer than two middle digits+ return inside+++def boundary_quads(occupied: np.ndarray, all_faces: bool = False) -> np.ndarray:+ """(F, 4, 3) quads in unit coordinates: the faces between filled and empty voxels (or every+ face of every filled voxel)."""+ n = occupied.shape[0]+ padded = np.pad(occupied, 1)+ quads = []+ for (axis, side), corners in FACES.items():+ lo = [1, 1, 1]+ lo[axis] += side+ neighbor = padded[lo[0] : lo[0] + n, lo[1] : lo[1] + n, lo[2] : lo[2] + n]+ cells = np.argwhere(occupied if all_faces else occupied & ~neighbor)+ quads.append(cells[:, None, :] + np.array(corners)[None])+ return np.concatenate(quads).astype(float) / n+++def clip_below(quads: np.ndarray, s: float) -> tuple[np.ndarray, np.ndarray]:+ """The part of every quad with x + y + z ≤ s, fan-triangulated: vertices, triangles.+ Each polygon keeps its own vertices, so faces stay flat-shaded."""+ d = quads.sum(axis=2) - s+ whole = quads[(d <= 0).all(axis=1)]+ cut = ~(d <= 0).all(axis=1) & (d <= 0).any(axis=1)+ q, dq = quads[cut], d[cut]+ nxt = [1, 2, 3, 0]+ a, b, da, db = q, q[:, nxt], dq, dq[:, nxt]+ t = da / np.where(da == db, 1.0, da - db)+ crossing = a + t[..., None] * (b - a)+ slots = np.stack([a, crossing], axis=2).reshape(len(q), 8, 3)+ valid = np.stack([da <= 0, (da <= 0) != (db <= 0)], axis=2).reshape(len(q), 8)+ order = np.argsort(~valid, axis=1, kind="stable")+ polygon = np.take_along_axis(slots, order[..., None], axis=1)[:, :5]+ count = valid.sum(axis=1)+ # whole quads: two triangles each; cut polygons (3–5 corners): a fan of count − 2+ verts = [whole.reshape(-1, 3), polygon.reshape(-1, 3)]+ tris = [+ (+ np.arange(len(whole))[:, None, None] * 4 + np.array([[0, 1, 2], [0, 2, 3]])+ ).reshape(-1, 3)+ ]+ base = len(whole) * 4 + np.arange(len(q)) * 5+ for k in (1, 2, 3):+ rows = count >= k + 2+ tris.append(np.stack([base[rows], base[rows] + k, base[rows] + k + 1], axis=1))+ return np.concatenate(verts), np.concatenate(tris)+++def to_world(unit: np.ndarray) -> np.ndarray:+ return SIZE * (unit - 0.5)+++def cap_colors() -> np.ndarray:+ """The cap's picture before the cut, the same for every plane: gold, a little brighter in+ rings about its center, and transparent."""+ glow = 0.8 + 0.2 * np.cos(4 * np.hypot(CAP_A, CAP_B[:, None]))+ rgba = np.zeros((CAP_PIXELS, CAP_PIXELS, 4), np.uint8)+ rgba[..., :3] = GOLD * glow[..., None] * 255+ return rgba+++def cap_pixels(s: float) -> np.ndarray:+ """The cut face as a picture on a square of the plane: the sponge's material where the+ plane meets it, transparent elsewhere (outside the cube and in the tunnels)."""+ # p = s/3 + a E1 + b E2, a coordinate at a time (E1 has no z: z varies only down)+ x = s / 3 + CAP_A * E1[0] + (CAP_B * E2[0])[:, None]+ y = s / 3 + CAP_A * E1[1] + (CAP_B * E2[1])[:, None]+ z = (s / 3 + CAP_B * E2[2])[:, None]+ rgba = cap_colors().copy()+ rgba[..., 3] = 255 * in_sponge(x, y, z, LEVEL).astype(np.uint8)+ return rgba+++def cap_corners(s: float) -> np.ndarray:+ """Corners of the cap's square in the order of an ImageMobject: UL, UR, DL, DR."""+ center = np.full(3, s / 3)+ h = CAP_HALF+ unit = [+ center - h * E1 + h * E2,+ center + h * E1 + h * E2,+ center - h * E1 - h * E2,+ center + h * E1 - h * E2,+ ]+ return to_world(np.array(unit))+++class MengerSlice(m.ThreeDScene):+ def construct(self) -> None:+ self.set_camera_orientation(+ phi=64 * m.DEGREES, theta=-38 * m.DEGREES, zoom=0.95+ )+ cut = m.ValueTracker(3.0) # s: x + y + z ≤ s is kept (3: the whole sponge)++ # the sponge, clipped by the plane as it moves+ occupied = sponge(LEVEL)+ faces = boundary_quads(occupied)++ def solid_mesh() -> tuple[np.ndarray, np.ndarray]:+ verts, tris = clip_below(faces, cut.get_value())+ return to_world(verts), tris++ body = m.MeshMobject(*solid_mesh(), shade_in_3d=True, fill_color=BONE)+ # where each was last cut: while the plane stands still, body and cap stay+ cut_at: dict[str, float] = {}++ def reclip(mob: m.Mobject) -> None:+ assert isinstance(mob, m.MeshMobject)+ s = cut.get_value()+ if cut_at.get("body") != s:+ cut_at["body"] = s+ mob.points, mob.triangles = solid_mesh()++ # the build: at each level the cubes it removes shrink away into their centers+ levels = [sponge(k) for k in range(LEVEL + 1)]+ quad_order = np.array([[0, 1, 2], [0, 2, 3]])++ def quad_triangles(count: int) -> np.ndarray:+ return (np.arange(count)[:, None, None] * 4 + quad_order).reshape(-1, 3)++ title = m.Text("The stars inside the Menger sponge", font_size=36).to_corner(+ m.UL+ )+ subtitle = m.Text(+ "cut through its center, perpendicular to a long diagonal", font_size=22+ )+ subtitle.set_color(m.GREY_B).next_to(+ title, m.DOWN, aligned_edge=m.LEFT, buff=0.12+ )++ def count_text(level: int) -> m.Text:+ label = m.Text(f"level {level} · {20**level:,} cubes", font_size=26)+ return label.to_corner(m.UR)++ counter = count_text(0)+ plane_label = m.MathTex(r"x + y + z = s", font_size=34)+ s_value = m.DecimalNumber(1.5, num_decimal_places=2, font_size=34)+ s_row = m.VGroup(m.MathTex(r"s =", font_size=34), s_value).arrange(+ m.RIGHT, buff=0.15+ )+ plane_group = m.VGroup(plane_label, s_row).arrange(m.DOWN, aligned_edge=m.LEFT)+ plane_group.next_to(counter, m.DOWN, aligned_edge=m.RIGHT, buff=0.4)+ s_value.add_updater(lambda d: d.set_value(cut.get_value()))+ closing = m.Text("A hexagon full of six-pointed stars.", font_size=28)+ closing.to_edge(m.DOWN, buff=0.35)+ self.add_fixed_in_frame_mobjects(title, subtitle, counter, plane_group, closing)+ self.remove(plane_group, closing)++ # 0–5 s: cube → level 1 → 2 → 3, the removed cubes shrinking away+ cube = boundary_quads(levels[0])+ body.points, body.triangles = (+ to_world(cube.reshape(-1, 3)),+ quad_triangles(len(cube)),+ )+ self.add(body)+ self.begin_ambient_camera_rotation(rate=0.12)+ for k in range(LEVEL):+ n = 3 ** (k + 1)+ coarse = np.kron(levels[k], np.ones((3, 3, 3), bool))+ gone = np.argwhere(coarse & ~levels[k + 1]) # the cubes this level removes+ corners = np.array(list(FACES.values())) # (6, 4, 3)+ quads = ((gone[:, None, None, :] + corners[None]) / n).reshape(-1, 4, 3)+ centers = np.repeat((gone + 0.5) / n, 6, axis=0)[:, None, :]+ shrink = m.ValueTracker(1.0)+ ghost = m.MeshMobject(+ to_world(quads.reshape(-1, 3)),+ quad_triangles(len(quads)),+ shade_in_3d=True,+ fill_color=BONE,+ )++ def squeeze(+ mob: m.Mobject,+ quads: np.ndarray = quads,+ centers: np.ndarray = centers,+ shrink: m.ValueTracker = shrink,+ ) -> None:+ f = shrink.get_value()+ mob.points = to_world((centers + f * (quads - centers)).reshape(-1, 3))++ ghost.add_updater(squeeze)+ holed = boundary_quads(levels[k + 1])+ body.points, body.triangles = (+ to_world(holed.reshape(-1, 3)),+ quad_triangles(len(holed)),+ )+ self.add(ghost)+ counter.become(count_text(k + 1))+ shrink.set_value(+ 0.97+ ) # the cuts show as hairlines before the pieces fall in+ self.play(+ shrink.animate.set_value(0.0), run_time=1.5, rate_func=m.rush_into+ )+ self.remove(ghost)+ body.add_updater(reclip)++ # 5–9 s: the cutting plane arrives at the center; the top half slides away+ top_verts, top_tris = clip_below(+ faces * -1 + 1, 1.5+ ) # x+y+z ≥ 3/2, by symmetry+ top = m.MeshMobject(+ to_world(1 - top_verts), top_tris, shade_in_3d=True, fill_color=BONE+ )+ cap = m.ImageMobject(cap_pixels(1.5))+ cap.points = cap_corners(1.5)+ cut.set_value(1.5)+ self.add(top, cap)+ self.play(m.FadeIn(plane_group), run_time=1)+ self.play(top.animate.shift(13 * NORMAL), run_time=2.2, rate_func=m.rush_into)+ self.remove(top)+ self.stop_ambient_camera_rotation()++ def refresh_cap(mob: m.Mobject) -> None:+ s = cut.get_value()+ if cut_at.get("cap") != s:+ cut_at["cap"] = s+ mob.points = cap_corners(s)+ mob.paint = mob.paint.but(texture=cap_pixels(s))++ cap.add_updater(refresh_cap)+ # 9–14 s: look straight down the diagonal at the cut+ self.move_camera(+ phi=54.74 * m.DEGREES,+ theta=45 * m.DEGREES,+ gamma=0,+ zoom=0.95,+ frame_center=np.array([0.0, 0.0, 0.5]),+ run_time=3.5,+ )+ self.wait(1.5)+ # 14–26 s: sweep the plane toward a corner and back+ self.play(cut.animate.set_value(0.62), run_time=6)+ self.play(cut.animate.set_value(1.5), run_time=6)+ # 26–30 s: the stars, turning slowly about the diagonal+ self.play(+ m.FadeIn(closing),+ self.camera.gamma_tracker.animate.set_value(30 * m.DEGREES),+ run_time=5.3,+ rate_func=m.smooth,+ )+++if __name__ == "__main__":+ MengerSlice().render("menger_slice.mp4")diff --git a/examples/rupert_cube.py b/examples/rupert_cube.pynew file mode 100644index 00000000..a0f61aa2--- /dev/null+++ b/examples/rupert_cube.py@@ -0,0 +1,258 @@+"""A cube through a hole in an identical cube (Prince Rupert's problem, 1693).++Seen straight along its long diagonal, a unit cube's outline is a regular hexagon of side √(2/3),+and a square of side √(2/3)·(3 − √3) ≈ 1.035 fits inside it. Bore a square tunnel of side just+over 1 along that diagonal and the cube stays in one piece — and a second unit cube slides right+through it. (Nieuwland found the best tilt: side 3√2/4 ≈ 1.061. In 2025 Steininger and+Yurkevich found the first convex polyhedron that cannot pass through a copy of itself.)+"""++import itertools++import numpy as np++import manimgx as m++SIZE = 2.4 # screen units per unit of length+DIAGONAL = np.ones(3) / np.sqrt(3)+E1 = np.array([1.0, -1.0, 0.0]) / np.sqrt(2)+E2 = np.cross(DIAGONAL, E1)+TUNNEL = 1.02 # side of the tunnel's square cross-section (the cube's side is 1)+WIDEST = np.sqrt(2 / 3) * (3 - np.sqrt(3))+FACES = [(axis, side) for axis in range(3) for side in (-0.5, 0.5)]+++def box_faces(subdivide: int) -> tuple[np.ndarray, np.ndarray]:+ """A unit cube centered at the origin as one mesh, each face a subdivided grid (the light+ is reckoned at its vertices), each face with its own vertices (flat shading)."""+ verts, tris = [], []+ g = np.linspace(-0.5, 0.5, subdivide + 1)+ uu, vv = np.meshgrid(g, g, indexing="ij")+ for axis, side in FACES:+ others = [a for a in range(3) if a != axis]+ p = np.zeros((subdivide + 1, subdivide + 1, 3))+ p[..., axis] = side+ p[..., others[0]], p[..., others[1]] = uu, vv+ base = sum(len(v) for v in verts)+ verts.append(p.reshape(-1, 3))+ i, j = np.meshgrid(np.arange(subdivide), np.arange(subdivide), indexing="ij")+ a = (i * (subdivide + 1) + j).ravel() + base+ tris.append(+ np.concatenate(+ [+ np.stack([a, a + subdivide + 1, a + subdivide + 2], 1),+ np.stack([a, a + subdivide + 2, a + 1], 1),+ ]+ )+ )+ return np.concatenate(verts), np.concatenate(tris)+++def through_cube(starts: np.ndarray) -> tuple[np.ndarray, np.ndarray]:+ """Where lines p + t·DIAGONAL enter and leave the unit cube (slab method): two point sets."""+ with np.errstate(divide="ignore"):+ low = (-0.5 - starts) / DIAGONAL+ high = (0.5 - starts) / DIAGONAL+ enter = np.minimum(low, high).max(axis=1)+ leave = np.maximum(low, high).min(axis=1)+ return starts + enter[:, None] * DIAGONAL, starts + leave[:, None] * DIAGONAL+++class RupertCube(m.ThreeDScene):+ def construct(self) -> None:+ # cube A: glass, with a square tunnel along its diagonal+ verts, tris = box_faces(14)+ shell = m.MeshMobject(+ SIZE * verts,+ tris,+ shade_in_3d=True,+ fill_color="#6fb6ff",+ fill_opacity=0.22,+ )+ edges = m.VGroup(+ *[+ m.Line(+ SIZE * (a - 0.5),+ SIZE * (b - 0.5),+ stroke_width=2,+ color="#cfe6ff",+ shade_in_3d=True,+ )+ for a, b in itertools.combinations(+ np.array(list(itertools.product((0.0, 1.0), repeat=3))), 2+ )+ if np.abs(a - b).sum() == 1+ ]+ )+ # the tunnel: lines along the diagonal through the edge of a square of side TUNNEL+ t = np.linspace(0, 4, 401)[:-1]+ side = np.floor(t).astype(int)+ f = t - side+ square = np.array([[-1, -1], [1, -1], [1, 1], [-1, 1]]) * TUNNEL / 2+ rim = square[side] + f[:, None] * (square[(side + 1) % 4] - square[side])+ starts = rim[:, :1] * E1 + rim[:, 1:] * E2+ entry, exit_ = through_cube(starts)+ walls_v = SIZE * np.concatenate([entry, exit_])+ n = len(entry)+ k = np.arange(n)+ walls_t = np.concatenate(+ [+ np.stack([k, (k + 1) % n, n + (k + 1) % n], 1),+ np.stack([k, n + (k + 1) % n, n + k], 1),+ ]+ )+ walls = m.MeshMobject(+ walls_v, walls_t, shade_in_3d=True, fill_color="#9ec9ff", fill_opacity=0.35+ )+ holes = m.VGroup(+ *[+ m.VMobject(+ stroke_color=m.GOLD, stroke_width=4, shade_in_3d=True+ ).set_points_as_corners(SIZE * np.concatenate([ring, ring[:1]]))+ for ring in (entry, exit_)+ ]+ )++ # cube B: solid gold; it turns to line up with the tunnel, then slides through+ solid_v, solid_t = box_faces(1)+ turn = np.stack(+ [E1, E2, DIAGONAL], axis=1+ ) # columns: where B's x, y, z axes go+ rest = np.array([3.4, -1.2, 0.0])+ start = -2.6 * SIZE * DIAGONAL+ path = m.ValueTracker(+ 0.0+ ) # 0: resting beside A; 1: lined up behind A; 2: through and out+ solid = m.MeshMobject(+ SIZE * solid_v + rest, solid_t, shade_in_3d=True, fill_color="#ffb52e"+ )++ def place(mob: m.Mobject) -> None:+ u = path.get_value()+ if u <= 1:+ w = u * u * (3 - 2 * u)+ # rotate from identity toward `turn` along the shortest path (via its axis–angle)+ angle = np.arccos(np.clip((np.trace(turn) - 1) / 2, -1, 1))+ axis = np.array(+ [+ turn[2, 1] - turn[1, 2],+ turn[0, 2] - turn[2, 0],+ turn[1, 0] - turn[0, 1],+ ]+ )+ axis /= np.linalg.norm(axis)+ k_ = np.array(+ [+ [0, -axis[2], axis[1]],+ [axis[2], 0, -axis[0]],+ [-axis[1], axis[0], 0],+ ]+ )+ r = (+ np.eye(3)+ + np.sin(w * angle) * k_+ + (1 - np.cos(w * angle)) * k_ @ k_+ )+ mob.points = SIZE * solid_v @ r.T + (1 - w) * rest + w * start+ else:+ mob.points = (+ SIZE * solid_v @ turn.T + start + (u - 1) * 4.5 * SIZE * DIAGONAL+ )++ solid.add_updater(place)++ title = m.Text("A cube through a hole in itself", font_size=36).to_corner(m.UL)+ subtitle = m.Text("Prince Rupert's problem (1693)", font_size=24).set_color(+ m.GREY_B+ )+ subtitle.next_to(title, m.DOWN, aligned_edge=m.LEFT, buff=0.12)+ fit = m.MathTex(+ r"\text{widest square} = \sqrt{\tfrac{2}{3}}\,(3-\sqrt3) \approx 1.035 > 1",+ font_size=32,+ )+ fit.to_corner(m.UR)+ closing = (+ m.VGroup(+ m.Text(+ "Nieuwland's tilt fits a square of side 3√2/4 ≈ 1.061.",+ font_size=24,+ ),+ m.Text(+ "2025: the Noperthedron is the first convex solid that cannot do"+ " this.",+ font_size=24,+ ),+ )+ .arrange(m.DOWN, buff=0.12)+ .to_edge(m.DOWN, buff=0.3)+ )+ self.add_fixed_in_frame_mobjects(title, subtitle, fit, closing)+ self.remove(fit, closing)++ self.set_camera_orientation(+ phi=66 * m.DEGREES,+ theta=-62 * m.DEGREES,+ zoom=0.82,+ frame_center=np.array([1.6, -0.6, 0.0]),+ )+ self.add(solid, edges, shell)+ self.wait(1.5)++ # 1.5–8 s: B lines up behind A; looking down A's long diagonal (nearly orthographic),+ # B's square shows through the glass, inside A's hexagonal outline+ widest = m.VMobject(+ stroke_color=m.YELLOW, stroke_width=4, shade_in_3d=True+ ).set_points_as_corners(+ SIZE+ * np.array(+ [+ p[0] * E1 + p[1] * E2+ for p in (+ np.array([[-1, -1], [1, -1], [1, 1], [-1, 1], [-1, -1]])+ * WIDEST+ / 2+ )+ ]+ )+ )+ self.move_camera(+ phi=54.74 * m.DEGREES,+ theta=45 * m.DEGREES,+ zoom=1.2,+ focal_distance=90,+ frame_center=np.zeros(3),+ added_anims=[path.animate.set_value(1.0)],+ run_time=4,+ )+ self.play(m.Create(widest), m.FadeIn(fit), run_time=1.5)+ self.wait(1)+ # 8–12 s: bore the tunnel+ self.add(walls, holes)+ self.play(m.FadeOut(widest), m.FadeIn(holes), run_time=1)+ # watch from the side, square to the tunnel: in one side, out the other+ self.move_camera(+ phi=74 * m.DEGREES,+ theta=-45 * m.DEGREES,+ zoom=0.7,+ focal_distance=20,+ frame_center=np.array([0.3, 0.3, 0.1]),+ run_time=3,+ )+ # 12–24 s: the second cube slides through+ self.play(+ path.animate.set_value(2.0),+ self.camera.theta_tracker.animate.set_value(-38 * m.DEGREES),+ run_time=11,+ rate_func=m.linear,+ )+ # 24–30 s: records+ self.play(+ m.FadeIn(closing),+ self.camera.theta_tracker.animate.set_value(-30 * m.DEGREES),+ run_time=4,+ )+ self.wait(2.3)+++if __name__ == "__main__":+ RupertCube().render("rupert_cube.mp4")diff --git a/examples/sphere_packing.py b/examples/sphere_packing.pynew file mode 100644index 00000000..9fe6557a--- /dev/null+++ b/examples/sphere_packing.py@@ -0,0 +1,434 @@+"""Two ways to stack oranges: ABAB... and ABCABC..., and the second one is a cube.++A hexagonal layer of spheres leaves two sets of hollows, B and C; the second layer fills one+set. The third layer then has a choice: over the first (ABAB..., hexagonal close packing) or+into the C hollows (ABCABC..., face-centred cubic). The ABC pile is the face-centred cubic+lattice seen along a body diagonal: trim it and a cube stands on its corner. Both fill+π/(3√2) ≈ 74.05% of space, and nothing fills more (Kepler's conjecture, 1611; proved by+Hales, 1998; formal proof 2014). The fill is measured by Cavalieri's principle: a knife+slices both piles, and the filled share of the cut, averaged down whole periods of the+lattice, is the filled share of space.+"""++import numpy as np++import manimgx as m++D = 0.5 # sphere diameter (scene units)+R = D / 2+H = D * np.sqrt(2 / 3) # spacing of the layers+A1, A2 = np.array([1.0, 0.0]), np.array([0.5, np.sqrt(3) / 2])+HOLLOW = {"A": 0.0, "B": 1 / 3, "C": 2 / 3} # layer offsets along a1 + a2+COLOR = {"A": "#f28a1e", "B": "#f2cf3c", "C": "#86c440"} # orange, lemon, lime+STACKS = ("ABABABA", "ABCABCA")+BASE_Z = -1.2+APART = 2.3 # the towers' x offsets once they split+NT, NP = 10, 22 # a ball's mesh: rows from its cut to its bottom, columns around+UP = np.array([0.0, 0.0, 1.0])+++def hexagon_norm(p: np.ndarray) -> np.ndarray:+ """Circumradius of the hexagon through p with vertices at 30°, 90°, ... (a crate)."""+ normals = np.array([[1.0, 0.0], [0.5, np.sqrt(3) / 2], [-0.5, np.sqrt(3) / 2]])+ return np.abs(p @ normals.T).max(axis=1) / np.cos(np.pi / 6)+++def layer_sites(letter: str, radius: float) -> np.ndarray:+ """Centres (in diameters) of one hexagonal layer inside a crate of that radius."""+ i, j = np.meshgrid(np.arange(-8, 9), np.arange(-8, 9), indexing="ij")+ p = i.ravel()[:, None] * A1 + j.ravel()[:, None] * A2 + HOLLOW[letter] * (A1 + A2)+ return p[hexagon_norm(p) <= radius + 1e-9]+++def drop_height(tau: np.ndarray, h0: float, g: float = 30.0) -> np.ndarray:+ """Height above its rest of a ball let go from h0 at tau = 0, bouncing to a stop."""+ out = np.where(tau < 0, h0, h0 - 0.5 * g * np.maximum(tau, 0) ** 2)+ start = np.sqrt(2 * h0 / g)+ speed = 0.3 * g * start # restitution 0.3+ for _ in range(3):+ s = tau - start+ out = np.where((s >= 0) & (s < 2 * speed / g), speed * s - 0.5 * g * s**2, out)+ start, speed = start + 2 * speed / g, 0.3 * speed+ return np.where(tau >= start, 0.0, np.maximum(out, 0.0))+++def turn(axis: np.ndarray, angle: float) -> np.ndarray:+ """Rotation matrix about a unit axis (Rodrigues)."""+ x, y, z = axis+ k = np.array([[0, -z, y], [z, 0, -x], [-y, x, 0]])+ return np.eye(3) + np.sin(angle) * k + (1 - np.cos(angle)) * k @ k+++def ball_triangles(n: int) -> np.ndarray:+ """Triangles of n balls, each a polar grid (NT+1 x NP+1) and a cap disc (2 x NP+1)."""+ idx = np.arange((NT + 1) * (NP + 1)).reshape(NT + 1, NP + 1)+ a, b, c, d = idx[:-1, :-1], idx[1:, :-1], idx[1:, 1:], idx[:-1, 1:]+ shell = np.concatenate([np.stack([a, b, c], -1), np.stack([a, c, d], -1)])+ k, first = np.arange(NP), idx.size # the cap: a centre ring, then a rim ring+ cap = np.stack([first + k, first + NP + 1 + k, first + NP + 2 + k], -1)+ one = np.concatenate([shell.reshape(-1, 3), cap])+ stride = idx.size + 2 * (NP + 1)+ return (one[None] + stride * np.arange(n)[:, None, None]).reshape(-1, 3)+++def ball_points(c: np.ndarray, r: np.ndarray, knife: np.ndarray) -> np.ndarray:+ """Vertices of balls (centres c, radii r) cut by a horizontal knife at a height per+ ball: the part below the knife, and the flat cut face."""+ n = len(r)+ # the cut's polar angle: 0 keeps the whole ball, π keeps nothing+ cut = np.clip((knife - c[:, 2]) / r, -1, 1)+ top = np.arccos(cut)+ theta = top[:, None] + (np.pi - top)[:, None] * np.linspace(0, 1, NT + 1)+ theta = theta[..., None]+ phi = np.linspace(0, 2 * np.pi, NP + 1)+ unit = np.stack(+ [+ np.sin(theta) * np.cos(phi),+ np.sin(theta) * np.sin(phi),+ np.broadcast_to(np.cos(theta), (n, NT + 1, NP + 1)),+ ],+ -1,+ )+ shell = c[:, None, None] + r[:, None, None, None] * unit+ cap = np.zeros((n, 2, NP + 1, 3)) # a centre ring and a rim ring+ cap[:, 1, :, 0] = (r * np.sin(top))[:, None] * np.cos(phi)+ cap[:, 1, :, 1] = (r * np.sin(top))[:, None] * np.sin(phi)+ cap += np.column_stack([c[:, :2], c[:, 2] + r * cut])[:, None, None]+ out = np.concatenate([shell.reshape(n, -1, 3), cap.reshape(n, -1, 3)], 1)+ return out.reshape(-1, 3)+++def covered(samples: np.ndarray, centres: np.ndarray, z: float) -> float:+ """Share of the sample points (x, y) inside the discs the balls cut at height z."""+ dz = z - centres[:, 2]+ near = np.abs(dz) < R+ d2 = ((samples[:, None, :] - centres[near][None, :, :2]) ** 2).sum(-1)+ return float((d2 < R**2 - dz[near] ** 2).any(axis=1).mean())+++def grid_in(u: np.ndarray, v: np.ndarray, n: int) -> np.ndarray:+ """Midpoints of an n x n grid on the parallelogram spanned by u and v."""+ s = (np.arange(n) + 0.5) / n+ ss, tt = np.meshgrid(s, s)+ return ss.reshape(-1, 1) * u + tt.reshape(-1, 1) * v+++def rgba(hex_color: str, whiten: float = 0.0) -> np.ndarray:+ c = np.array(m.ManimColor(hex_color).to_rgb())+ return np.array([*(c + (1 - c) * whiten), 1.0])+++class SpherePacking(m.ThreeDScene):+ def construct(self) -> None:+ cam = self.camera+ self.set_camera_orientation(phi=58 * m.DEGREES, theta=-72 * m.DEGREES, zoom=1.7)+ cam.frame.move_to([0, 0, -0.75])++ # ── the two piles, ABABABA (left) and ABCABCA (right), in hexagonal crates ────────+ # each layer's start and how long its balls take to let go (roughly centre first)+ schedule = [(-1.0, 2.5), (2.1, 1.1)] + [(6.2 + 1.1 * k, 0.6) for k in range(5)]+ # one random order per layer: the two piles are one until they split+ jitter = np.random.default_rng(7).random((7, 64))+ side, home, letters, release = [], [], [], []+ for s, seq in enumerate(STACKS):+ for k, ch in enumerate(seq):+ sites = layer_sites(ch, 2.4)+ order = np.linalg.norm(sites, axis=1) + 2 * jitter[k, : len(sites)]+ side += [s] * len(sites)+ home += [np.column_stack([sites * D, np.full(len(sites), k * H)])]+ letters += [ch] * len(sites)+ release += list(schedule[k][0] + schedule[k][1] * order / order.max())+ tower, base, released = np.array(side), np.vstack(home), np.array(release)+ n_balls = len(base)++ # the FCC cube: 2 x 2 x 2 cells of side a = √2 D, standing on a corner in the ABC pile+ a = np.sqrt(2) * D+ g = np.arange(5) / 2+ grid = np.stack(np.meshgrid(g, g, g, indexing="ij"), -1).reshape(-1, 3)+ cube = grid[np.round(2 * grid).sum(axis=1) % 2 == 0] * a - a # about its centre+ diagonal = np.ones(3) / np.sqrt(3)+ across = np.array([-1.0, 1.0, 0.0]) / np.sqrt(2)+ # cube frame → pile frame: the body diagonal points up+ on_corner = np.vstack([across, np.cross(diagonal, across), diagonal])+ standing = cube @ on_corner.T + 3 * H * UP+ gap = np.linalg.norm(base[:, None] - standing[None], axis=2)+ in_cube = (tower == 1) & (gap.min(axis=1) < 1e-6)+ cube_index = np.flatnonzero(in_cube)+ cube_coord = cube[gap[cube_index].argmin(axis=1)]+ assert len(cube_index) == 63+ # it tips onto a face, and turns about the vertical to show three faces+ face = on_corner[:, 2]+ tilt_axis = np.cross(face, UP) / np.linalg.norm(np.cross(face, UP))+ tilt = float(np.arccos(face[2]))+ side_face = turn(tilt_axis, tilt) @ on_corner[:, 0]+ spin = -27 * m.DEGREES - float(np.arctan2(side_face[1], side_face[0]))++ def cube_pose(s: float) -> tuple[np.ndarray, np.ndarray]:+ """Rotation and centre as it tips (s: 0 → 1), to rest level with the towers."""+ rot = turn(UP, s * spin) @ turn(tilt_axis, s * tilt) @ on_corner+ return rot, np.array([APART, 0, BASE_Z + 3 * H + s * (a - 3 * H)])++ clock = m.ValueTracker(0.0) # the build's own clock, seconds+ split = m.ValueTracker(0.0) # 1: two towers, APART each side+ trim = m.ValueTracker(0.0) # 1: the FCC balls outside the cube are gone+ tip = m.ValueTracker(0.0) # 1: the cube lies on a face+ knife = m.ValueTracker(0.0) # 0: above everything, 1: region tops, 2: bottoms+ swept = m.ValueTracker(0.0) # how much of the regions the knife has measured++ # the measured regions, whole periods of each lattice: the cube (FCC), and a+ # hexagonal prism of circumradius √3 D from layer 1 to layer 5 (HCP)+ cube_top, prism_top = BASE_Z + 2 * a, BASE_Z + 5 * H++ def knife_heights() -> tuple[float, float]:+ lead = min(knife.get_value(), 1.0)+ sweep = float(np.clip(knife.get_value() - 1, 0, 1))+ above = BASE_Z + 6 * H + R + 0.05+ left = above + lead * (prism_top - above) - sweep * 4 * H+ return left, above + lead * (cube_top - above) - sweep * 2 * a++ def pile_points() -> np.ndarray:+ sway = np.where(tower == 0, -APART, APART) * split.get_value()+ c = base + np.column_stack([sway, 0 * sway, np.full(n_balls, BASE_Z)])+ falling = clock.get_value() - released+ c[:, 2] += drop_height(falling, 3.4)+ # a ball grows in as it starts to fall+ r = R * np.clip(falling / 0.15, 1e-4, 1)+ # the trimmed balls shrink away, top first+ gone = (tower == 1) & ~in_cube+ lag = 0.35 * (1 - base[gone, 2] / (6 * H))+ x = np.clip((trim.get_value() - lag) / 0.65, 0, 1)+ r[gone] = np.maximum(r[gone] * (1 - x * x * (3 - 2 * x)), 1e-4)+ if tip.get_value() > 0:+ rot, centre = cube_pose(tip.get_value())+ c[cube_index] = centre + cube_coord @ rot.T+ left, right = knife_heights()+ return ball_points(c, r, np.where(tower == 0, left, right))++ skin = np.array([rgba(COLOR[ch]) for ch in letters])+ flesh = np.array([rgba(COLOR[ch], 0.45) for ch in letters]) # the cut faces+ paint = [np.repeat(skin[:, None], (NT + 1) * (NP + 1), 1)]+ paint += [np.repeat(flesh[:, None], 2 * (NP + 1), 1)]+ pile = m.MeshMobject(pile_points(), ball_triangles(n_balls), shade_in_3d=True)+ pile.paint = pile.paint.but(fill=np.concatenate(paint, 1).reshape(-1, 4))+ pile.add_updater(lambda mob: mob.set_points(pile_points()))++ # the C hollows of the second layer: lime beads resting in them (they ride right)+ # (a bead of radius 0.3 R touches the three balls around it, D/√3 away sideways)+ c_sites = layer_sites("C", 1.9) * D+ bead_z = BASE_Z + H + np.sqrt((1.3 * R) ** 2 - D**2 / 3)+ bead_size = m.ValueTracker(0.0)++ def bead_points() -> np.ndarray:+ c = np.column_stack([c_sites, np.full(len(c_sites), bead_z)])+ c[:, 0] += split.get_value() * APART+ r = np.full(len(c), 0.3 * R * bead_size.get_value() + 1e-4)+ return ball_points(c, r, np.full(len(c), 99.0))++ bead_tris = ball_triangles(len(c_sites))+ beads = m.MeshMobject(bead_points(), bead_tris, shade_in_3d=True)+ beads.set_fill(COLOR["C"], 1.0)+ beads.add_updater(lambda mob: mob.set_points(bead_points()))++ # a wooden tray under each pile (flat faces: each face has its own vertices)+ turn6 = np.radians(30 + 60 * np.arange(6))+ rim = 3.05 * D * np.column_stack([np.cos(turn6), np.sin(turn6), np.zeros(6)])+ drop = np.array([0, 0, 0.1])+ walls = [+ [rim[k], rim[k - 1], rim[k - 1] - drop, rim[k] - drop] for k in range(6)+ ]+ slab = np.vstack([[0, 0, 0], rim, *walls]) + [0, 0, BASE_Z - R - 0.004]+ k = np.arange(6)+ fan = np.stack([0 * k, 1 + k, 1 + (k + 1) % 6], 1)+ quads = 7 + 4 * k[:, None] + np.array([[0, 1, 2], [0, 2, 3]])[:, None]+ slab_tris = np.concatenate([fan, *quads])+ trays = m.Group()+ for sign in (-1, 1):+ tray = m.MeshMobject(slab, slab_tris, shade_in_3d=True)+ tray.paint = tray.paint.but(+ fill=np.repeat([rgba("#4a3524"), rgba("#241a12")], [7, 24], 0)+ )+ tray.add_updater(+ lambda mob, s=sign: mob.set_points(+ slab + [s * APART * split.get_value(), 0, 0]+ )+ )+ trays.add(tray)++ # ── Cavalieri: the filled share of each cut, tabulated down each region ───────────+ square = grid_in(np.array([2 * a, 0]), np.array([0, 2 * a]), 150) - a+ corners = np.radians(30 + 60 * np.arange(7))+ rim = np.sqrt(3) * D * np.column_stack([np.cos(corners), np.sin(corners)])+ hexagon = np.vstack([grid_in(rim[k], rim[k + 2], 80) for k in (0, 2, 4)])+ depth = np.linspace(0, 1, 201) # down each region, from its top+ fcc_share = np.array([covered(square, cube, a - 2 * a * t) for t in depth])+ hcp = base[tower == 0]+ hcp_share = np.array([covered(hexagon, hcp, 5 * H - 4 * H * t) for t in depth])++ def measured() -> int:+ return max(1, int(round(swept.get_value() * (len(depth) - 1))))++ def running_mean(share: np.ndarray) -> float:+ """The filled share (in percent) averaged down the part measured so far."""+ k = measured()+ return 100 * float(np.trapezoid(share[: k + 1], depth[: k + 1]) / depth[k])++ final = cube_pose(1.0)[0]++ def outlines() -> m.VGroup:+ """The knife's outline on each measured region."""+ left, right = knife_heights()+ hexa = np.column_stack([rim - [APART, 0], np.full(7, min(left, prism_top))])+ sq = np.array([[-1, -1, 0], [1, -1, 0], [1, 1, 0], [-1, 1, 0], [-1, -1, 0]])+ sq = a * sq @ final.T + [APART, 0, min(right, cube_top)]+ lines = [m.VMobject().set_points_as_corners(p) for p in (hexa, sq)]+ return m.VGroup(*lines).set_stroke(m.WHITE, 3, 0.95).shift(0.01 * UP)++ knife_lines = m.always_redraw(outlines)++ # ── heads-up display ──────────────────────────────────────────────────────────────+ title = m.Text("Two ways to stack oranges", font_size=36).to_corner(m.UL)++ def caption(text: str, size: float = 22) -> m.Text:+ c = m.Text(text, font_size=size).set_color(m.GREY_B)+ return c.next_to(title, m.DOWN, aligned_edge=m.LEFT, buff=0.15)++ captions = [+ caption("each layer settles into the hollows of the one below"),+ caption("layer B fills half the hollows: the other half, C, stay open"),+ caption("the third layer can go back over A, or into the C hollows"),+ caption("trim the ABC pile: it is a cube, balanced on its corner"),+ caption("slice both: a cut's average filled share is the share of space"),+ caption("Both fill 74.05% of space, and no stack of spheres fills more"),+ ]+ credit = "Kepler, 1611 · proved by Hales, 1998; by computer, 2014"+ history = m.Text(credit, font_size=18).set_color(m.GREY_C)+ history.next_to(captions[5], m.DOWN, aligned_edge=m.LEFT, buff=0.1)++ def name_tag(seq: str, name: str, x: float) -> m.VGroup:+ row = m.VGroup(*[m.Text(ch, font_size=28, weight=m.BOLD) for ch in seq])+ for letter, ch in zip(row, seq):+ letter.set_color(COLOR[ch])+ tag = m.VGroup(row.arrange(m.RIGHT, buff=0.12), m.Text(name, font_size=22))+ return tag.arrange(m.DOWN, buff=0.1).move_to([x, -3.07, 0])++ tags = [+ name_tag(STACKS[0], "hexagonal close packing", -APART - 0.9),+ name_tag(STACKS[1], "face-centred cubic", APART + 0.9),+ ]++ # the filled share of each cut as the knife goes down, and the running averages+ plot = m.Axes(+ x_range=[0, 1, 0.25],+ y_range=[0.5, 1.0, 0.1],+ x_length=2.6,+ y_length=1.5,+ tips=False,+ axis_config={"include_ticks": False, "stroke_width": 1.5},+ ).move_to([4.55, 2.45, 0])+ plot.set_color(m.GREY_B)+ level = np.pi / (3 * np.sqrt(2))+ mean_line = m.DashedLine(plot.c2p(0, level), plot.c2p(1, level))+ mean_line.set_stroke(m.WHITE, 1.5)+ mean_label = m.MathTex(r"\tfrac{\pi}{3\sqrt{2}}", font_size=30)+ mean_label.next_to(mean_line, m.RIGHT, 0.1)+ plot_label = m.Text("filled share of the cut", font_size=18).set_color(m.GREY_B)+ plot_label.next_to(plot, m.UP, buff=0.08)++ def trace(share: np.ndarray, color: str) -> m.VMobject:+ def draw() -> m.VMobject:+ k = measured()+ upto = zip(depth[: k + 1], share[: k + 1])+ pts = [plot.c2p(float(t), float(v)) for t, v in upto]+ return m.VMobject().set_points_as_corners(pts).set_stroke(color, 2.5)++ return m.always_redraw(draw)++ def readout(share: np.ndarray, color: str, x: float) -> m.VGroup:+ label = m.Text("filled", font_size=24).set_color(m.GREY_B)+ number = m.DecimalNumber(running_mean(share), unit=r"\%", font_size=32)+ row = m.VGroup(label, number.set_color(color)).arrange(m.RIGHT, buff=0.15)+ row.move_to([x, -3.68, 0])++ def update(d: m.DecimalNumber) -> None:+ d.set_value(running_mean(share))+ d.next_to(label, m.RIGHT, buff=0.15)++ number.add_updater(update)+ return row++ live = [+ trace(hcp_share, COLOR["B"]),+ trace(fcc_share, COLOR["C"]),+ readout(hcp_share, COLOR["B"], -APART - 0.9),+ readout(fcc_share, COLOR["C"], APART + 0.9),+ ]+ chart = [plot, mean_line, mean_label, plot_label]+ hud = [*captions[1:], history, *tags, *chart, *live]+ self.add_fixed_in_frame_mobjects(title, captions[0], *hud)+ self.remove(*hud)+ self.add(trays, pile, beads)++ def swap(k: int, *more: m.Mobject) -> list[m.Animation]:+ """Caption k replaces caption k - 1 (one fades out, then the other in)."""+ early = m.squish_rate_func(m.smooth, 0, 0.35)+ late = m.squish_rate_func(m.smooth, 0.35, 0.85)+ ins = [m.FadeIn(mob, rate_func=late) for mob in (captions[k], *more)]+ return [m.FadeOut(captions[k - 1], rate_func=early), *ins]++ def build(until: float, *also: m.Animation, run_time: float) -> None:+ """Let the build's clock run on (steadily), with other animations alongside."""+ steady = clock.animate(rate_func=m.linear).set_value(until)+ self.play(steady, *also, run_time=run_time)++ # 0–5 s: layer A drops; layer B settles into half its hollows; the other half shows+ build(2.2, cam.zoom_tracker.animate.set_value(2.0), run_time=2.2)+ build(3.5, *swap(1), run_time=1.3)+ build(4.8, bead_size.animate.set_value(1.0), run_time=1.3)+ # 5–6 s: the choice: the pile splits in two+ build(+ 6.2,+ split.animate.set_value(1.0),+ cam.zoom_tracker.animate.set_value(1.07), # (the piles clear of the text)+ cam.phi_tracker.animate.set_value(64 * m.DEGREES),+ cam.frame.animate.move_to([0, 0, -0.3]),+ *swap(2),+ run_time=1.4,+ )+ # 6–12 s: five more layers each: ABABABA on the left, ABCABCA on the right+ build(12.2, *[m.FadeIn(t, shift=0.2 * m.UP) for t in tags], run_time=6.0)+ self.remove(beads)+ # 12–16.5 s: trim the ABC pile: a cube on its corner; tip it onto a face+ self.play(trim.animate.set_value(1.0), *swap(3), run_time=1.8)+ self.wait(0.6)+ self.play(tip.animate.set_value(1.0), run_time=2.0)+ # 16.5–24.5 s: the knife measures both, down whole periods of each lattice+ self.add(knife_lines)+ self.play(+ knife.animate.set_value(1.0),+ cam.phi_tracker.animate.set_value(54 * m.DEGREES),+ *swap(4, *chart, *live),+ run_time=1.2,+ )+ self.play(+ knife.animate.set_value(2.0),+ swept.animate.set_value(1.0),+ cam.theta_tracker.animate.set_value(-66 * m.DEGREES),+ run_time=6.5,+ rate_func=m.linear,+ )+ # 24.5–30 s: the oranges come back+ self.remove(knife_lines)+ self.begin_ambient_camera_rotation(rate=0.035)+ self.play(+ knife.animate.set_value(0.0),+ cam.phi_tracker.animate.set_value(63 * m.DEGREES),+ cam.zoom_tracker.animate.set_value(0.9),+ cam.frame.animate.move_to([0, 0, 0.15]),+ *swap(5, history),+ run_time=1.8,+ )+ self.wait(3.0)+++if __name__ == "__main__":+ SpherePacking().render("sphere_packing.mp4")