from manim import *
import numpy as np
def head(cn, en):
    t = Text(cn, font="STLiti", font_size=27).to_edge(UP)
    s = Text(en, font="Consolas", font_size=20, color=YELLOW).next_to(t, DOWN, buff=0.10)
    return VGroup(t, s)
def foot(cn):
    return Text(cn, font="STLiti", font_size=20, color=YELLOW).to_edge(DOWN)
class GlowingTracedPath(VMobject):
    """闪光轨迹：收集被追踪点的历史位置，按时间切换渐变色。"""
    def __init__(self, traced_point_func, stroke_width=7,
                 gradient_colors=None, dissipating_time=None,
                 glow_speed=2, **kwargs):
        super().__init__(**kwargs)
        self.traced_point_func = traced_point_func
        self.gradient_colors = gradient_colors or [BLUE, RED, YELLOW]
        self.dissipating_time = dissipating_time
        self.glow_speed = glow_speed
        self.stroke_width = stroke_width
        self.points_list = []
        self.elapsed = 0.0
        self.set_stroke(self.gradient_colors[0], width=stroke_width)
        self.add_updater(self.update_path)
    def update_path(self, mob, dt):
        mob.elapsed += dt
        mob.points_list.append(np.array(mob.traced_point_func(), dtype=float))
        if mob.dissipating_time:
            keep = max(2, int(mob.dissipating_time * 60))
            mob.points_list = mob.points_list[-keep:]
        if len(mob.points_list) >= 2:
            mob.set_points_as_corners(mob.points_list)
            idx = int(mob.elapsed * mob.glow_speed) % len(mob.gradient_colors)
            mob.set_stroke(mob.gradient_colors[idx], width=mob.stroke_width)
class GlowSpeedCompare(Scene):
    def construct(self):
        self.add(head("闪光频率对比", "glow_speed = 8 / 16"))
        a1 = Dot(LEFT * 3 + UP * 1.2, color=WHITE, radius=0.12)
        a2 = Dot(LEFT * 3 + DOWN * 1.2, color=WHITE, radius=0.12)
        b1 = GlowingTracedPath(a1.get_center, gradient_colors=[BLUE, RED, YELLOW], glow_speed=8)
        b2 = GlowingTracedPath(a2.get_center, gradient_colors=[BLUE, RED, YELLOW], glow_speed=16)
        lab1 = Text("glow_speed = 8", font="Consolas", font_size=20, color=GREY_A).to_edge(LEFT).shift(UP * 1.7)
        lab2 = Text("glow_speed = 16", font="Consolas", font_size=20, color=GREY_A).to_edge(LEFT).shift(DOWN * 1.7)
        self.add(lab1, lab2, a1, a2, b1, b2)
        self.play(a1.animate.shift(RIGHT * 5.6), a2.animate.shift(RIGHT * 5.6), run_time=3.2)
        self.play(a1.animate.shift(LEFT * 5.6), a2.animate.shift(LEFT * 5.6), run_time=2.2)
        b1.clear_updaters(); b2.clear_updaters()
        self.play(FadeIn(foot("glow_speed 越大，同一段轨迹里颜色切换越频繁")), run_time=0.4)
        self.wait(1.0)
