# -*- coding: utf-8 -*-
# 示例：LaggedStart + UpdateFromAlphaFunc 驱动 48 个小球做径向正弦运动（视频 20240902063049000）
# 本地复现：manim -qh 20240902063049000.py RadialDotsAnimation
# 知识点：LaggedStart 让一组动画按 lag_ratio 依次起步；UpdateFromAlphaFunc 把 0→1 的
#         alpha 交给自己算位置，所以能写出「正弦往复 + 逐球相位差」的旋转滚动效果。
# 注意：不要改 config.pixel_width/height 或 frame_width/height，-qh 负责 1920x1080/60fps；
#       原文附的竖屏 1080x1440 设置会覆盖它，横屏下直线端点也要相应收进画面。
from manim import *
import numpy as np
class RadialDotsAnimation(Scene):
    def construct(self):
        num_dots = 48
        max_radius = 1.6
        colors = [RED, ORANGE, YELLOW, GREEN, BLUE, PURPLE,
                  PINK, TEAL, MAROON, GOLD, DARK_BLUE, LIGHT_GRAY]
        title = Text("Number of Dots: %d" % num_dots, font_size=28).to_corner(UL)
        self.play(Write(title), run_time=0.6)
        # 48 条过原点的直线，方向角均分半个圆周（PI），端点 ±3.2 收在 1080p 画幅内。
        dots, lines = [], []
        for i in range(num_dots):
            angle = i * PI / num_dots
            line = Line(max_radius * np.array([-2 * np.cos(angle), -2 * np.sin(angle), 0]),
                        max_radius * np.array([2 * np.cos(angle), 2 * np.sin(angle), 0]),
                        color=GRAY, stroke_opacity=0.35)
            lines.append(line)
            start = line.point_from_proportion(0.5 + 0.5 * np.sin(TAU - angle))
            dots.append(Dot(point=start, color=colors[i % len(colors)], radius=0.085))
        self.play(LaggedStart(*[Create(l) for l in lines], lag_ratio=0.01, run_time=1.5))
        self.play(LaggedStart(*[GrowFromCenter(d) for d in dots], lag_ratio=0.01, run_time=1.5))
        self.wait(0.4)
        total_cycles = 2
        animation_time = 6.0
        dot_anims = []
        for i, (dot, line) in enumerate(zip(dots, lines)):
            phase = i * PI / num_dots
            # 默认参数把 line / phase 绑进闭包，否则循环结束后所有小球共用最后一条直线。
            def update_dot(mob, alpha, line=line, phase=phase):
                pos_ratio = 0.5 + 0.5 * np.sin(alpha * total_cycles * TAU - phase)
                mob.move_to(line.point_from_proportion(pos_ratio))
            dot_anims.append(UpdateFromAlphaFunc(dot, update_dot,
                                                  run_time=animation_time, rate_func=linear))
        # lag_ratio=0：48 个球同时起步，旋转感来自 phase 相位差，而不是起步延迟。
        self.play(LaggedStart(*dot_anims, lag_ratio=0, run_time=animation_time))
        self.play(LaggedStart(*[FadeOut(d) for d in dots],
                              *[FadeOut(l) for l in lines],
                              lag_ratio=0.01, run_time=1.2))
        self.wait(0.6)
