import tkinter as tk
import math

# ---------- 画布与光学参数 ----------
W, H = 1320, 720
AY, LX = 340, 560          # 主光轴 y、透镜 x
F_PX = 80.0                # 焦距（像素）
OBJ_H = 110.0              # 蜡烛总高度（像素）
LENS_HH = 150              # 透镜半高

BG = "#0a1220"
RAY1 = "#ffd166"           # 平行主轴光线
RAY2 = "#4cc9f0"           # 过光心光线
RAY3 = "#f72585"           # 过焦点光线


def clamp(v, lo, hi):
    return lo if v < lo else (hi if v > hi else v)


class LensApp:
    def __init__(self, root):
        self.root = root
        root.title("凸透镜成像规律 · 可拖动演示")
        root.configure(bg=BG)

        self.cv = tk.Canvas(root, width=W, height=H, bg=BG, highlightthickness=0)
        self.cv.pack()

        self.u = 240.0          # 物距
        self.sx = 820.0         # 光屏 x
        self.drag = None

        self.xo = LX - self.u
        self.Py = AY - OBJ_H
        self.v = 0.0
        self.m = 0.0
        self.xi = 0.0
        self.hi = 0.0
        self.real = False
        self.parallel = False

        self.cv.bind("<Button-1>", self.on_press)
        self.cv.bind("<B1-Motion>", self.on_motion)
        self.cv.bind("<ButtonRelease-1>", self.on_release)

        self.redraw()

    # ---------- 交互 ----------
    def on_press(self, e):
        x, y = e.x, e.y
        # 光屏
        if abs(x - self.sx) < 34 and AY - 190 < y < AY + 190:
            self.drag = "screen"
            return
        # 蜡烛
        if abs(x - self.xo) < 70 and AY - OBJ_H - 45 < y < AY + 45:
            self.drag = "candle"
            return
        self.drag = None

    def on_motion(self, e):
        if self.drag == "candle":
            self.u = clamp(LX - e.x, 50.0, 500.0)
            self.redraw()
        elif self.drag == "screen":
            self.sx = clamp(e.x, LX + 40, W - 70)
            self.redraw()

    def on_release(self, e):
        self.drag = None

    # ---------- 计算 ----------
    def compute(self):
        u, f = self.u, F_PX
        self.xo = LX - u
        self.Py = AY - OBJ_H

        if abs(u - f) < 0.8:
            self.parallel = True
            self.v = None
            self.m = None
            self.xi = None
            self.hi = 0.0
            self.real = False
        else:
            self.parallel = False
            self.v = u * f / (u - f)
            self.m = -self.v / u
            self.xi = LX + self.v
            self.hi = OBJ_H * abs(self.m)
            self.real = self.v > 0

    # ---------- 主绘制 ----------
    def redraw(self):
        cv = self.cv
        cv.delete("all")
        self.draw_bg()
        self.compute()
        self.draw_rays()
        self.draw_image()
        self.draw_screen()
        self.draw_lens()
        self.draw_object()
        self.draw_hud()

    # ---------- 背景 / 主光轴 ----------
    def draw_bg(self):
        cv = self.cv
        for x in range(0, W, 60):
            cv.create_line(x, 0, x, H, fill="#101b2e")
        for y in range(0, H, 60):
            cv.create_line(0, y, W, y, fill="#101b2e")

        # 主光轴
        cv.create_line(0, AY, W, AY, fill="#54688c", width=2)
        cv.create_line(W - 34, AY - 7, W - 8, AY, W - 34, AY + 7, fill="#54688c", width=2)
        cv.create_text(W - 78, AY - 18, text="主光轴", fill="#6b80a4",
                       font=("Microsoft YaHei", 11))

        # 焦点刻度
        for k, name in ((-2, "2F"), (-1, "F"), (1, "F'"), (2, "2F'")):
            x = LX + k * F_PX
            cv.create_line(x, AY - 9, x, AY + 9, fill="#8fa3c8", width=2)
            cv.create_text(x, AY + 24, text=name, fill="#8fa3c8",
                           font=("Consolas", 11, "bold"))

    # ---------- 光线 ----------
    def draw_rays(self):
        cv = self.cv
        f, u = F_PX, self.u
        xo, Py = self.xo, self.Py
        R = W + 500
        y3 = None

        # 光线1：平行于主光轴 → 过焦点 F'
        cv.create_line(xo, Py, LX, Py, fill=RAY1, width=2)
        dx, dy = f, AY - Py
        t = (R - LX) / dx
        cv.create_line(LX, Py, LX + dx * t, Py + dy * t, fill=RAY1, width=2)

        # 光线2：过光心，方向不变
        dx2, dy2 = u, AY - Py
        t2 = (R - LX) / dx2
        cv.create_line(xo, Py, LX, AY, fill=RAY2, width=2)
        cv.create_line(LX, AY, LX + dx2 * t2, AY + dy2 * t2, fill=RAY2, width=2)

        # 光线3：过前焦点 F → 出射平行主光轴
        den = f - u
        if abs(den) > 1.0:
            s = f / den
            y3 = AY + s * (Py - AY)
            if abs(y3) < 12000:
                cv.create_line(xo, Py, LX, y3, fill=RAY3, width=2)
                cv.create_line(LX, y3, R, y3, fill=RAY3, width=2)
            else:
                y3 = None

        # 虚像：反向延长线（虚线）
        if self.v is not None and self.v < 0 and abs(self.xi) < 4000:
            yi = AY - OBJ_H * self.m
            pts = [((LX, Py), RAY1), ((LX, AY), RAY2)]
            if y3 is not None:
                pts.append(((LX, y3), RAY3))
            for (px, py), col in pts:
                cv.create_line(px, py, self.xi, yi, fill=col,
                               width=1, dash=(8, 6))

    # ---------- 蜡烛（可用于物 / 像） ----------
    def candle(self, cx, base_y, h, up=True, ghost=False):
        if h < 5:
            return
        cv = self.cv
        s = -1 if up else 1
        body_h = h * 0.70
        flame_h = h - body_h
        w = min(84.0, max(6.0, h * 0.24))
        top = base_y + s * body_h
        tip = base_y + s * h

        # 蜡烛体（竖向明暗渐变 → 伪 3D 柱面）
        N = 12
        for i in range(N):
            t0, t1 = i / N, (i + 1) / N
            x0 = cx - w / 2 + w * t0
            x1 = cx - w / 2 + w * t1
            sh = math.sin((t0 + t1) / 2 * math.pi) ** 0.7
            if ghost:
                r = int(26 + 55 * sh)
                g = int(58 + 95 * sh)
                b = int(92 + 125 * sh)
            else:
                r = int(140 + 115 * sh)
                g = int(96 + 96 * sh)
                b = int(42 + 62 * sh)
            col = "#%02x%02x%02x" % (min(r, 255), min(g, 255), min(b, 255))
            cv.create_polygon(x0, base_y, x1, base_y, x1, top, x0, top,
                              fill=col, outline="")

        # 火焰 —— 用 (x, y) 元组列表，避免解包错误
        fw = w * 0.62
        pts = [
            (cx - fw,           top),
            (cx - fw * 0.85,    top + s * flame_h * 0.35),
            (cx - fw * 0.35,    top + s * flame_h * 0.78),
            (cx,                tip),
            (cx + fw * 0.35,    top + s * flame_h * 0.78),
            (cx + fw * 0.85,    top + s * flame_h * 0.35),
            (cx + fw,           top),
        ]
        flat = [c for p in pts for c in p]

        if ghost:
            cv.create_polygon(*flat, fill="#3f6b9a", outline="#6fa0d0",
                              width=1, smooth=True)
        else:
            cv.create_polygon(*flat, fill="#ff9f1c", outline="#ffd166",
                              width=1, smooth=True)
            inner = []
            for i, (px, py) in enumerate(pts):
                if i in (0, 6):
                    continue
                inner.append((cx + (px - cx) * 0.5,
                              top + (py - top) * 0.6))
            if inner:
                inner_flat = [c for p in inner for c in p]
                cv.create_polygon(*inner_flat,
                                  fill="#ffe066", outline="", smooth=True)

    def draw_object(self):
        # 地面阴影
        self.cv.create_oval(self.xo - 34, AY - 6, self.xo + 34, AY + 12,
                            fill="#0e1a2c", outline="")
        self.candle(self.xo, AY, OBJ_H, up=True, ghost=False)
        self.cv.create_text(self.xo, AY + 40, text="物（拖动）",
                            fill="#ffb703", font=("Microsoft YaHei", 10))

    def draw_image(self):
        if self.parallel or self.v is None:
            return
        if abs(self.xi) > W + 700 or self.hi > 1400:
            return
        self.candle(self.xi, AY, self.hi, up=(self.m > 0), ghost=True)

    # ---------- 光屏 ----------
    def draw_screen(self):
        cv = self.cv
        x = self.sx
        top, bot = AY - 168, AY + 168

        # 支架
        cv.create_line(x, bot, x, bot + 42, fill="#3d5878", width=6)
        cv.create_oval(x - 38, bot + 34, x + 38, bot + 52,
                       fill="#1b2a3d", outline="#2e4460")

        # 屏面（带侧边 → 伪 3D）
        cv.create_polygon(x - 7, top, x + 7, top + 8,
                          x + 7, bot - 8, x - 7, bot,
                          fill="#2e4460", outline="#6b90b8", width=2)
        cv.create_polygon(x - 7, top, x - 1, top + 4,
                          x - 1, bot - 4, x - 7, bot,
                          fill="#3c5a7d", outline="")

        # 是否正好承接住实像
        if self.real and self.v is not None and abs(x - self.xi) < 22:
            cv.create_text(x, top - 20, text="✔ 成像清晰",
                           fill="#4cc9f0", font=("Microsoft YaHei", 11, "bold"))

        cv.create_text(x, bot + 66, text="光屏（拖动）",
                       fill="#8fb3d9", font=("Microsoft YaHei", 10))

    # ---------- 凸透镜 ----------
    def draw_lens(self):
        cv = self.cv
        N = 48
        left, right = [], []
        for i in range(N + 1):
            t = i / N
            y = AY - LENS_HH + 2 * LENS_HH * t
            b = math.sin(math.pi * t)
            left.append((LX - 40 * b, y))
            right.append((LX + 40 * b, y))

        poly = left + right[::-1]
        flat = [c for p in poly for c in p]

        # 外发光
        glow = []
        for p in poly:
            glow.append((LX + (p[0] - LX) * 1.06, AY + (p[1] - AY) * 1.03))
        cv.create_polygon(*[c for p in glow for c in p],
                          fill="#0d2a3d", outline="")

        # 玻璃体
        cv.create_polygon(*flat, fill="#17475f", outline="#5fd6ff", width=2)

        # 高光条
        hl = []
        for i in range(N + 1):
            t = i / N
            y = AY - LENS_HH * 0.9 + 2 * LENS_HH * 0.9 * t
            b = math.sin(math.pi * t)
            hl.append((LX - 40 * b * 0.62, y))
        cv.create_line(*[c for p in hl for c in p],
                       fill="#a8ecff", width=2, smooth=True)

        # 中心标记
        cv.create_oval(LX - 4, AY - 4, LX + 4, AY + 4,
                       fill="#a8ecff", outline="")
        cv.create_text(LX, AY - LENS_HH - 20, text="凸透镜",
                       fill="#7fd4ff", font=("Microsoft YaHei", 12, "bold"))

    # ---------- 信息面板 ----------
    def draw_hud(self):
        cv = self.cv
        u, f = self.u, F_PX
        u_over_f = u / f

        if u_over_f > 2.02:
            state, col = "u > 2f  →  倒立、缩小的实像（照相机）", "#4cc9f0"
        elif abs(u_over_f - 2) <= 0.02:
            state, col = "u = 2f  →  倒立、等大的实像", "#ffd166"
        elif u_over_f > 1.02:
            state, col = "f < u < 2f  →  倒立、放大的实像（投影仪）", "#06d6a0"
        elif abs(u_over_f - 1) <= 0.02:
            state, col = "u = f  →  折射光平行射出，不成像", "#f72585"
        else:
            state, col = "u < f  →  正立、放大的虚像（放大镜）", "#f72585"

        if self.parallel or self.v is None:
            vtxt, mtxt = "像距 v = 无限远", "放大率 |m| = ∞"
        else:
            vtxt = "像距 v = %+.1f px" % self.v
            mtxt = "放大率 m = %+.2f" % self.m

        cv.create_rectangle(18, 16, 486, 176, fill="#0e1a2c",
                            outline="#1f3350", width=1)
        cv.create_text(34, 40, anchor="w", text="物距 u = %.0f px     焦距 f = %.0f px" % (u, f),
                       fill="#cfe3ff", font=("Consolas", 13, "bold"))
        cv.create_text(34, 72, anchor="w", text=vtxt, fill="#9fc3e8",
                       font=("Consolas", 12))
        cv.create_text(34, 100, anchor="w", text=mtxt, fill="#9fc3e8",
                       font=("Consolas", 12))
        cv.create_text(34, 142, anchor="w", text=state, fill=col,
                       font=("Microsoft YaHei", 13, "bold"))

        cv.create_text(W - 24, H - 24, anchor="e",
                       text="拖动蜡烛改变物距　·　拖动光屏承接实像",
                       fill="#54708f", font=("Microsoft YaHei", 11))


if __name__ == "__main__":
    root = tk.Tk()
    root.resizable(False, False)
    LensApp(root)
    root.mainloop()