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 GlowDissipate(Scene):
    def construct(self):
        self.add(head("轨迹消散：只保留最近若干帧", "dissipating_time"))
        a = Dot(RIGHT * 2.6 + UP * 1.0, color=WHITE, radius=0.13)
        b = GlowingTracedPath(a.get_center,
                              gradient_colors=[BLUE, RED, YELLOW],
                              dissipating_time=0.7)
        self.add(a, b)
        self.play(a.animate(path_arc=PI).shift(LEFT * 5.2), run_time=3.0)
        self.play(a.animate(path_arc=-PI).shift(RIGHT * 5.2), run_time=3.0)
        b.clear_updaters()
        self.play(FadeIn(foot("限制历史点数量，尾迹就不会无限拉长")), run_time=0.4)
        self.wait(1.0)
