# -*- coding: utf-8 -*-
"""
凸透镜成像规律 —— 交互式动画演示（深色霓虹主题）
================================================
操作说明：
  · 「暂停 / 播放」：自动扫描物距，连续展示成像规律
  · 「物距 u (×f)」  ：手动拖动，控制物体到透镜的距离
  · 「焦距 f」「物高 h」：调整透镜参数与物体大小
  · 勾选框：分别控制三条特殊光线显示 / 隐藏
  · 「重置」：恢复默认参数

三条特殊光线：
  ① 平行于主光轴 → 折射后过另一侧焦点 F   （霓虹绿）
  ② 过光心      → 方向不变               （霓虹粉）
  ③ 过（反向延长过）焦点 → 折射后平行主光轴（霓虹金）
================================================
"""

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.patches import Polygon, Rectangle
from matplotlib.widgets import Slider, Button, CheckButtons

# ==================== 全局样式 ====================
plt.rcParams.update({
    'font.sans-serif': ['SimHei', 'Microsoft YaHei',
                        'Arial Unicode MS', 'DejaVu Sans'],
    'axes.unicode_minus': False,
    'figure.facecolor': '#0a0e1a',
    'savefig.facecolor': '#0a0e1a',
    'axes.facecolor': '#0a0e1a',
    'axes.edgecolor': '#2d3a55',
    'text.color': '#e2e8f0',
    'axes.labelcolor': '#e2e8f0',
    'xtick.color': '#94a3b8',
    'ytick.color': '#94a3b8',
})

# ==================== 配色方案 ====================
BG            = '#0a0e1a'
COL_AXIS      = '#3a4a6a'

COL_LENS_FILL = '#1e3a8a'
COL_LENS_EDGE = '#60a5fa'
COL_LENS_GLOW = '#93c5fd'

COL_MARK      = '#64748b'
COL_MARK_TEXT = '#cbd5e1'

COL_OBJ       = '#fbbf24'
COL_OBJ_EDGE  = '#f59e0b'
COL_OBJ_TEXT  = '#fde68a'

COL_IMG_R     = '#f87171'
COL_IMG_R_EDGE= '#ef4444'
COL_IMG_R_TEXT= '#fca5a5'

COL_IMG_V     = '#c4b5fd'
COL_IMG_V_EDGE= '#a78bfa'
COL_IMG_V_TEXT= '#ddd6fe'

COL_RAY1 = '#00ffa3'   # 霓虹绿
COL_RAY2 = '#ff6ec7'   # 霓虹粉
COL_RAY3 = '#ffb800'   # 霓虹金

COL_TEXT      = '#e2e8f0'
COL_TEXT_DIM  = '#94a3b8'
COL_PANEL     = '#0f172a'
COL_PANEL_EDGE= '#1e293b'
COL_CTRL_BG   = '#0f172a'
COL_CTRL_TRACK= '#1e293b'

# ==================== 参数 ====================
RATIO_MIN, RATIO_MAX = 0.40, 4.50
FRAMES_PER_PASS = 400
FPS = 20


# ==================== 工具函数 ====================
def arrow_verts(x, y0, y1, s, shaft=0.055, head_w=0.20, head_l=0.28):
    """生成从 (x,y0) 指向 (x,y1) 的竖直箭头多边形顶点"""
    sgn = 1.0 if y1 >= y0 else -1.0
    L = max(abs(y1 - y0), 1e-9)
    hl = min(head_l * s, 0.65 * L)
    base = y1 - sgn * hl
    sw = shaft * s * 0.5
    hw = head_w * s * 0.5
    return np.array([
        [x - sw, y0], [x + sw, y0], [x + sw, base],
        [x + hw, base], [x, y1], [x - hw, base], [x - sw, base],
    ])


def glow_ray(ax, x, y, color, z=6, lw=2.0, **kw):
    """带光晕效果的光线（画两层）"""
    ax.plot(x, y, color=color, lw=lw * 5, alpha=0.10,
            zorder=z - 1, solid_capstyle='round', **kw)
    ax.plot(x, y, color=color, lw=lw, alpha=1.0,
            zorder=z, solid_capstyle='round', **kw)


def dashed_ray(ax, x, y, color, z=5):
    """虚线延长线"""
    ax.plot(x, y, color=color, lw=1.2, ls='--', alpha=0.55,
            zorder=z, dashes=(4, 3))


# ==================== 主程序 ====================
class LensDemo:
    def __init__(self):
        self.playing = True
        self.frame_count = 0
        self.show_rays = [True, True, True]
        self._from_anim = False

        self.fig = plt.figure(figsize=(15.2, 9.0))
        try:
            self.fig.canvas.manager.set_window_title(
                '凸透镜成像规律 —— 交互演示 (深色霓虹主题)')
        except Exception:
            pass

        # 主绘图区
        self.ax = self.fig.add_axes([0.025, 0.325, 0.95, 0.66])

        # ---------- 滑块 ----------
        ax_u = self.fig.add_axes([0.13, 0.215, 0.46, 0.026])
        ax_f = self.fig.add_axes([0.13, 0.150, 0.46, 0.026])
        ax_h = self.fig.add_axes([0.13, 0.085, 0.46, 0.026])

        for a in (ax_u, ax_f, ax_h):
            a.set_facecolor(COL_CTRL_BG)
            for sp in a.spines.values():
                sp.set_color(COL_PANEL_EDGE)

        def _make_slider(a, label, lo, hi, v0, step, color):
            try:
                return Slider(a, label, lo, hi, valinit=v0, valstep=step,
                              color=color, track_color=COL_CTRL_TRACK,
                              valfmt='%.2f')
            except TypeError:
                return Slider(a, label, lo, hi, valinit=v0, valstep=step,
                              color=color, valfmt='%.2f')

        self.sl_u = _make_slider(ax_u, '物距 u (×f)', RATIO_MIN, RATIO_MAX,
                                 1.80, 0.01, COL_OBJ)
        self.sl_f = _make_slider(ax_f, '焦距 f', 0.90, 2.40, 1.50, 0.02,
                                 COL_LENS_EDGE)
        self.sl_h = _make_slider(ax_h, '物高 h', 0.40, 2.00, 1.00, 0.02,
                                 '#2dd4bf')

        for sl in (self.sl_u, self.sl_f, self.sl_h):
            sl.label.set_color(COL_TEXT)
            sl.valtext.set_color(COL_TEXT)
            sl.valtext.set_fontweight('bold')

        self.sl_u.on_changed(self.on_u)
        self.sl_f.on_changed(self.redraw)
        self.sl_h.on_changed(self.redraw)

        # ---------- 按钮 ----------
        ax_play  = self.fig.add_axes([0.665, 0.195, 0.095, 0.048])
        ax_reset = self.fig.add_axes([0.665, 0.125, 0.095, 0.048])
        self.btn_play  = Button(ax_play,  '暂停', color='#1e293b',
                                hovercolor='#334155')
        self.btn_reset = Button(ax_reset, '重置', color='#1e293b',
                                hovercolor='#334155')
        for b in (self.btn_play, self.btn_reset):
            b.label.set_color(COL_TEXT)
            b.label.set_fontweight('bold')
        self.btn_play.on_clicked(self.toggle_play)
        self.btn_reset.on_clicked(self.reset)

        # ---------- 勾选框 ----------
        ax_chk = self.fig.add_axes([0.80, 0.115, 0.155, 0.135])
        ax_chk.set_facecolor(COL_CTRL_BG)
        self.chk = CheckButtons(ax_chk, ['光线 ①', '光线 ②', '光线 ③'],
                                [True, True, True])
        ray_cols = [COL_RAY1, COL_RAY2, COL_RAY3]
        try:
            for i, lbl in enumerate(self.chk.labels):
                lbl.set_color(ray_cols[i])
                lbl.set_fontweight('bold')
        except Exception:
            pass
        try:
            for i, r in enumerate(self.chk.rectangles):
                r.set_facecolor('none')
                r.set_edgecolor(ray_cols[i])
        except Exception:
            pass
        try:
            for i, lines in enumerate(self.chk.lines):
                for l in lines:
                    l.set_color(ray_cols[i])
        except Exception:
            pass
        self.chk.on_clicked(self.on_rays)

        # ---------- 底部提示 ----------
        self.fig.text(
            0.13, 0.035,
            '拖动滑块可手动控制；自动播放时物距沿主光轴来回扫描。  '
            'u = f 时不成像；u < f 时成正立放大虚像。',
            fontsize=10.5, color=COL_TEXT_DIM)

        # 首次绘制
        self._from_anim = True
        self.redraw()
        self._from_anim = False

    # ==================== 回调 ====================
    def on_u(self, val):
        if not self._from_anim and self.playing:
            self.playing = False
            self.btn_play.label.set_text('播放')
        self.redraw()

    def toggle_play(self, event):
        self.playing = not self.playing
        self.btn_play.label.set_text('暂停' if self.playing else '播放')

    def reset(self, event):
        self.frame_count = 0
        self.sl_f.set_val(1.50)
        self.sl_h.set_val(1.00)
        self.sl_u.set_val(1.80)
        self.playing = True
        self.btn_play.label.set_text('暂停')

    def on_rays(self, label):
        self.show_rays = self.chk.get_status()
        self.redraw()

    # ==================== 绘制 ====================
    def redraw(self, val=None):
        ax = self.ax
        ax.cla()
        ax.set_aspect('equal')
        ax.axis('off')
        ax.set_facecolor(BG)

        f = self.sl_f.val
        h = self.sl_h.val
        ratio = self.sl_u.val
        u = ratio * f

        R = max(1.15 * f, 1.00 * h)
        xmax = 5.60 * f
        xmin = -5.60 * f
        half_h = max(3.10 * f, 1.60 * h)

        ax.set_xlim(xmin, xmax)
        ax.set_ylim(-half_h, half_h)

        # ---------- 主光轴 ----------
        ax.plot([xmin, xmax], [0, 0], color=COL_AXIS, lw=1.2,
                dashes=(8, 6), zorder=1)

        # ---------- 透镜（带光晕）----------
        yv = np.linspace(-R, R, 180)
        th = 0.15 * f
        xr = th * (1.0 - (yv / R) ** 2)
        verts = np.vstack([
            np.column_stack([xr, yv]),
            np.column_stack([-xr[::-1], yv[::-1]])
        ])
        ax.add_patch(Polygon(verts, closed=True, facecolor='none',
                             edgecolor=COL_LENS_GLOW, lw=11, alpha=0.10,
                             zorder=2))
        ax.add_patch(Polygon(verts, closed=True, facecolor='none',
                             edgecolor=COL_LENS_GLOW, lw=5, alpha=0.25,
                             zorder=2.5))
        ax.add_patch(Polygon(verts, closed=True, facecolor=COL_LENS_FILL,
                             edgecolor=COL_LENS_EDGE, lw=2.2, alpha=0.45,
                             zorder=3))
        ax.text(0, R + 0.20 * f, '凸透镜', ha='center', va='bottom',
                fontsize=14, color=COL_LENS_GLOW, weight='bold', zorder=6)

        # ---------- F / 2F 标记 ----------
        for xp, lab in [(-2 * f, '-2F'), (-f, '-F'), (f, 'F'), (2 * f, '2F')]:
            ax.plot([xp, xp], [-0.10 * f, 0.10 * f], color=COL_MARK,
                    lw=1.6, zorder=5)
            ax.text(xp, -0.25 * f, lab, ha='center', va='top',
                    fontsize=13, color=COL_MARK_TEXT, weight='bold')
        ax.text(0, -0.50 * f, 'O', ha='center', va='top',
                fontsize=13, color=COL_MARK_TEXT, weight='bold')

        # ---------- 物体 ----------
        Px, Py = -u, h
        ax.add_patch(Polygon(arrow_verts(Px, 0, Py, f), closed=True,
                             facecolor=COL_OBJ, edgecolor=COL_OBJ_EDGE,
                             lw=1.5, zorder=7))
        ax.text(Px, Py + 0.16 * f, '物', ha='center', va='bottom',
                fontsize=13, color=COL_OBJ_TEXT, weight='bold', zorder=8)

        # ---------- 成像计算：1/f = 1/u + 1/v, m = -v/u ----------
        du = u - f
        if abs(du) < 1e-6:
            v, hp = np.inf, np.inf
        else:
            v = u * f / du
            hp = -h * v / u

        show_img = (np.isfinite(v)
                    and abs(v) < xmax * 1.5
                    and abs(hp) < half_h * 1.5)

        if show_img:
            if v > 0:
                fc, ec, ls, name = COL_IMG_R, COL_IMG_R_EDGE, '-', '实像'
            else:
                fc, ec, ls, name = COL_IMG_V, COL_IMG_V_EDGE, '--', '虚像'
            ax.add_patch(Polygon(arrow_verts(v, 0, hp, f), closed=True,
                                 facecolor=fc, edgecolor=ec,
                                 linestyle=ls, lw=1.5, zorder=7))
            ty = hp + (0.16 * f if hp > 0 else -0.16 * f)
            ax.text(v, ty, name, ha='center',
                    va='bottom' if hp > 0 else 'top',
                    fontsize=13, color=ec, weight='bold', zorder=8)

        # ---------- 三条特殊光线 ----------
        sr = self.show_rays
        y_clip = half_h * 1.2

        # ① 平行主光轴入射 → 折射后过右焦点 F
        if sr[0]:
            glow_ray(ax, [Px, 0], [Py, Py], COL_RAY1)
            ex = xmax
            ey = Py * (1.0 - ex / f)
            if abs(ey) > y_clip:
                ey = np.sign(ey) * y_clip
                ex = f * (1.0 - ey / Py)
            glow_ray(ax, [0, ex], [Py, ey], COL_RAY1)
            if show_img and v < 0:
                dashed_ray(ax, [v, 0], [hp, Py], COL_RAY1)

        # ② 过光心 → 不偏折
        if sr[1]:
            glow_ray(ax, [Px, 0], [Py, 0], COL_RAY2)
            ex = xmax
            ey = -ex * Py / u
            if abs(ey) > y_clip:
                ey = np.sign(ey) * y_clip
                ex = -ey * u / Py
            glow_ray(ax, [0, ex], [0, ey], COL_RAY2)
            if show_img and v < 0:
                dashed_ray(ax, [v, 0], [hp, 0], COL_RAY2)

        # ③ 过（反向延长过）左焦点 → 折射后平行射出
        if sr[2] and abs(f - u) > 1e-3:
            y3 = h * f / (f - u)
            if abs(y3) <= R:
                glow_ray(ax, [Px, 0], [Py, y3], COL_RAY3)
                glow_ray(ax, [0, xmax], [y3, y3], COL_RAY3)
                if show_img and v < 0:
                    dashed_ray(ax, [v, 0], [hp, y3], COL_RAY3)

        # ---------- 右上信息面板 ----------
        if abs(u - f) < 0.03:
            nature = 'u = f  →  折射光平行射出，不成像'
            vs, ms = '∞', '—'
        else:
            m = -v / u
            if abs(u - 2 * f) < 0.06:
                nature = 'u = 2f  →  倒立、等大的实像'
            elif u > 2 * f:
                nature = 'u > 2f  →  倒立、缩小的实像（照相机）'
            elif u > f:
                nature = 'f < u < 2f  →  倒立、放大的实像（投影仪）'
            else:
                nature = 'u < f  →  正立、放大的虚像（放大镜）'
            vs = f'{v / f:+.2f} f'
            ms = f'{m:+.2f}'

        info_text = (
            f'物距  u = {u / f:.2f} f\n'
            f'焦距  f = {f:.2f}\n'
            f'物高  h = {h:.2f}\n'
            f'像距  v = {vs}\n'
            f'放大率 m = {ms}\n'
            f'{nature}'
        )
        ax.text(0.985, 0.975, info_text,
                transform=ax.transAxes, ha='right', va='top',
                fontsize=11.5, linespacing=1.55, color=COL_TEXT,
                bbox=dict(boxstyle='round,pad=0.6', fc=COL_PANEL,
                          ec=COL_PANEL_EDGE, alpha=0.95, lw=1.0),
                zorder=16)

        # ---------- 左上图例 ----------
        ax.add_patch(Rectangle((0.010, 0.845), 0.260, 0.145,
                               transform=ax.transAxes, facecolor=COL_PANEL,
                               edgecolor=COL_PANEL_EDGE, lw=0.9,
                               alpha=0.92, zorder=15))
        lx0, lx1 = 0.022, 0.068
        legend = [
            (COL_RAY1, '① 平行光 → 过焦点'),
            (COL_RAY2, '② 过光心 → 不偏折'),
            (COL_RAY3, '③ 过焦点 → 平行射出'),
        ]
        ys = [0.945, 0.905, 0.865]
        for y, (col, lab) in zip(ys, legend):
            ax.plot([lx0, lx1], [y, y], color=col, lw=3.0,
                    transform=ax.transAxes, zorder=20,
                    solid_capstyle='round')
            ax.text(lx1 + 0.012, y, lab, transform=ax.transAxes,
                    ha='left', va='center', fontsize=10.5,
                    color=COL_TEXT_DIM, zorder=20)

        self.fig.canvas.draw_idle()

    # ==================== 动画 ====================
    def animate(self, frame):
        if not self.playing:
            return
        self.frame_count += 1
        s = (self.frame_count / FRAMES_PER_PASS) % 2.0
        frac = s if s <= 1.0 else 2.0 - s
        ratio = RATIO_MIN + (RATIO_MAX - RATIO_MIN) * frac
        self._from_anim = True
        self.sl_u.set_val(ratio)
        self._from_anim = False


# ==================== 启动 ====================
if __name__ == '__main__':
    demo = LensDemo()
    ani = animation.FuncAnimation(
        demo.fig, demo.animate,
        interval=1000 / FPS,
        blit=False,
        cache_frame_data=False,
    )

    # 保存（可选）：
    # ani.save('convex_lens.mp4', writer='ffmpeg', fps=FPS, dpi=120)
    # ani.save('convex_lens.gif', writer='pillow', fps=FPS, dpi=90)

    plt.show()