diff --git a/README.md b/README.md index 16d0572bbb7886614a5f839e3480131c7da44e06..2921003d971c4ea657e1bdca02fac3bd02d41202 100644 --- a/README.md +++ b/README.md @@ -83,16 +83,21 @@ quanxue-src/ ## 四、实施步骤(每完成一步推送一次到本 Space) - [x] **Step 1** 编写计划(本文件)→ 推送 -- [ ] **Step 2** 文案定稿 + 旁白 TTS 生成 + 字体子集化 → 推送 -- [ ] **Step 3** 渲染引擎与全部场景(横竖屏)→ 推送 -- [ ] **Step 4** 音乐、音效合成与播放器(播放/暂停/拖动/章节/全屏)→ 推送 -- [ ] **Step 5** 浏览器本地 MP4 导出(2K/1080P/720P、24/30/60fps、音乐可选、横竖屏)→ 推送 -- [ ] **Step 6** 封面生成(4:3 / 3:4 / 16:9 多选多张)+ 四平台发布文案 → 推送 +- [x] **Step 2** 文案定稿 + 旁白 TTS 生成 + 字体子集化 → 推送 +- [x] **Step 3** 渲染引擎与全部场景(横竖屏)→ 推送 +- [x] **Step 4** 音乐、音效合成与播放器(播放/暂停/拖动/章节/全屏)→ 推送 +- [x] **Step 5** 浏览器本地 MP4 导出(2K/1080P/720P、24/30/60fps、音乐可选、横竖屏)→ 推送 +- [x] **Step 6** 封面生成(4:3 / 3:4 / 16:9 多选多张)+ 四平台发布文案 → 推送 - [ ] **Step 7** 手机竖屏适配、生产构建、整体验收 → 最终推送 ## 五、进度日志 - Step 1:计划已写入 README。 +- Step 2:完成 40 句原创解说文案(6 章,约 5 分 46 秒旁白);神经网络 TTS 生成旁白,古文引文放慢语速,并对“輮、槁暴、参省、中绳、知明、跂、没”等多音/生僻字做读音校正;字体(霞鹜文楷、马善政毛笔楷书、思源宋体、刘建毛草)按实际用字子集化,共约 0.9 MB,自托管。 +- Step 3:渲染引擎与 37 个镜头全部完成,横屏 / 竖屏两套构图;墨晕遮罩转场、竖排引文 + 乌丝栏 + 朱笔圈点、逐字随旁白显现、电影字幕、胶片颗粒、暗角、缓推运镜。 +- Step 4:配乐(古琴拨弦模型 + 泛音 + 箫 + 低音铺底 + 卷积混响,旁白处自动闪避)与 16 种程序化音效;为加快加载,构建时把同一份合成配乐预渲染为 mp3(浏览器内实时合成作为后备)。播放器:音频时钟同步、拖动、章节跳转、键盘控制、全屏(含手机伪全屏)。 +- Step 5:浏览器本地导出 MP4:WebCodecs H.264(不支持时依次回退 HEVC / VP9 / AV1)+ AAC(无原生 AAC 时自动加载 WASM AAC 编码器),2K / 1080P / 720P × 24 / 30 / 60fps × 横 / 竖屏 × 背景音乐可选;大文件可边渲染边写盘。已在无头浏览器实测 1080×1920@60fps 导出并解码校验通过。 +- Step 6:5 套原创封面 × 4:3 / 3:4 / 16:9 多选批量下载;小红书 / 抖音 / 视频号 / B站 各 3 个标题(实时字数校验)+ 描述 + 话题,一键复制;B站描述自动附章节时间戳。 --- diff --git a/quanxue-src/package.json b/quanxue-src/package.json new file mode 100644 index 0000000000000000000000000000000000000000..dbf82eaa1d785e98e10d262b93373da8b62310fb --- /dev/null +++ b/quanxue-src/package.json @@ -0,0 +1,85 @@ +{ + "name": "frontend", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "dev": "node scripts/check-env.cjs vite", + "build": "node scripts/check-env.cjs npm run build:client && npm run build:server", + "build:client": "vite build --outDir dist/client", + "build:server": "vite build --ssr src/entry-server.tsx --outDir dist/server", + "lint": "eslint .", + "preview": "vite preview", + "type-check": "tsc --noEmit --incremental" + }, + "dependencies": { + "@hookform/resolvers": "5.2.2", + "@mediabunny/aac-encoder": "1.62.1", + "@radix-ui/react-accordion": "1.2.12", + "@radix-ui/react-aspect-ratio": "1.1.8", + "@radix-ui/react-avatar": "1.1.11", + "@radix-ui/react-checkbox": "1.3.3", + "@radix-ui/react-collapsible": "1.1.12", + "@radix-ui/react-context-menu": "2.2.16", + "@radix-ui/react-dialog": "1.1.15", + "@radix-ui/react-dropdown-menu": "2.1.16", + "@radix-ui/react-hover-card": "1.1.15", + "@radix-ui/react-label": "2.1.8", + "@radix-ui/react-menubar": "1.1.16", + "@radix-ui/react-navigation-menu": "1.2.14", + "@radix-ui/react-popover": "1.1.15", + "@radix-ui/react-progress": "1.1.8", + "@radix-ui/react-radio-group": "1.3.8", + "@radix-ui/react-scroll-area": "1.2.10", + "@radix-ui/react-select": "2.2.6", + "@radix-ui/react-separator": "1.1.8", + "@radix-ui/react-slider": "1.3.6", + "@radix-ui/react-slot": "1.2.4", + "@radix-ui/react-switch": "1.2.6", + "@radix-ui/react-tabs": "1.1.13", + "@radix-ui/react-toast": "1.2.15", + "@radix-ui/react-toggle": "1.1.10", + "@radix-ui/react-toggle-group": "1.1.11", + "@radix-ui/react-tooltip": "1.2.8", + "@surf-ai/theme": "latest", + "@tanstack/query-core": "5.94.5", + "@tanstack/react-query": "5.94.5", + "class-variance-authority": "0.7.1", + "clsx": "2.1.1", + "cmdk": "1.1.1", + "date-fns": "4.1.0", + "echarts": "5.6.0", + "echarts-for-react": "3.0.6", + "embla-carousel-react": "8.6.0", + "lucide-react": "0.454.0", + "mediabunny": "^1.62.1", + "next-themes": "0.4.6", + "react": "19.2.4", + "react-day-picker": "9.14.0", + "react-dom": "19.2.4", + "react-hook-form": "7.72.0", + "react-resizable-panels": "4.7.6", + "scheduler": "0.27.0", + "sonner": "1.7.4", + "tailwind-merge": "2.6.1", + "vaul": "1.1.2", + "zod": "3.25.76" + }, + "devDependencies": { + "@types/react": "19.2.14", + "@types/react-dom": "19.2.3", + "@types/node": "22.19.15", + "@eslint/js": "9.39.4", + "@vitejs/plugin-react": "4.7.0", + "@tailwindcss/vite": "4.2.2", + "eslint": "9.39.4", + "eslint-plugin-react-hooks": "5.2.0", + "eslint-plugin-react-refresh": "0.4.26", + "globals": "16.5.0", + "tailwindcss": "4.2.2", + "tw-animate-css": "1.4.0", + "typescript-eslint": "8.57.1", + "typescript": "5.9.3", + "vite": "6.4.2" + } +} diff --git a/quanxue-src/public/README.md b/quanxue-src/public/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8be297716de23edf0b96b699c53001af0379cc3f --- /dev/null +++ b/quanxue-src/public/README.md @@ -0,0 +1,2 @@ +运行时资源(旁白 mp3、配乐 mp3、字体子集 woff2)与构建产物一起放在 `../quanxue/quanxue/` 目录下,这里不重复存放。 +重新生成:`python3 -I scripts/quanxue/gen_tts.py`、`python3 -I scripts/quanxue/gen_fonts.py <字体源目录>`、`python3 -I scripts/quanxue/render_music.py`。 diff --git a/quanxue-src/quanxue.html b/quanxue-src/quanxue.html new file mode 100644 index 0000000000000000000000000000000000000000..d3c9d5b63456d2c19c449cc4ab36a948bbdce7bc --- /dev/null +++ b/quanxue-src/quanxue.html @@ -0,0 +1,16 @@ + + + + + + + + 劝学 · 荀子 | 课文精讲(网页实时渲染视频) + + + + +
+ + + diff --git a/quanxue-src/scripts/quanxue/export_test.py b/quanxue-src/scripts/quanxue/export_test.py new file mode 100644 index 0000000000000000000000000000000000000000..d4e1e6ba0a34b0ed50cc042a4a4c1eaa325a139c --- /dev/null +++ b/quanxue-src/scripts/quanxue/export_test.py @@ -0,0 +1,20 @@ +"""导出冒烟测试:python3 -I scripts/quanxue/export_test.py 720P,30,0,6,0,1 /tmp/out.mp4""" +import asyncio, base64, sys +from playwright.async_api import async_playwright +arg, out = sys.argv[1], sys.argv[2] +async def main(): + async with async_playwright() as p: + b = await p.chromium.launch(channel=sys.argv[3] if len(sys.argv) > 3 else None) + pg = await b.new_page() + pg.on("pageerror", lambda e: print("PAGEERR", e)) + await pg.goto(f"http://localhost:5173/?exporttest={arg}") + await pg.wait_for_function("window.__done === true", timeout=590000) + st = (await pg.evaluate("window.__stats"))[0] + print(st) + if "bytes" in st: + size = 4 * 1024 * 1024; data = bytearray() + for i in range((st["bytes"] + size - 1) // size): + data += base64.b64decode(await pg.evaluate(f"window.__chunk({i}, {size})")) + open(out, "wb").write(data) + await b.close() +asyncio.run(main()) diff --git a/quanxue-src/scripts/quanxue/gen_fonts.py b/quanxue-src/scripts/quanxue/gen_fonts.py new file mode 100644 index 0000000000000000000000000000000000000000..b63955da509cb13232dc7f67b8ad3cfb21aa9b61 --- /dev/null +++ b/quanxue-src/scripts/quanxue/gen_fonts.py @@ -0,0 +1,44 @@ +"""字体子集化:扫描 src/quanxue 与 App.tsx 中出现的所有字符,裁剪出极小的 woff2 字体,自托管。 +用法: python3 -I scripts/quanxue/gen_fonts.py /tmp/fontsrc +""" +import os, re, sys, glob +from fontTools import subset +from fontTools.ttLib import TTFont + +ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +SRC_DIR = sys.argv[1] if len(sys.argv) > 1 else "/tmp/fontsrc" +OUT = os.path.join(ROOT, "public/quanxue/fonts") +FONTS = { + "qx-kai": "LXGWWenKai-Regular.ttf", # 霞鹜文楷(引文、字幕,覆盖生僻字) + "qx-brush": "MaShanZheng-Regular.ttf", # 毛笔楷书(大标题) + "qx-cao": "LiuJianMaoCao-Regular.ttf", # 草书(大背景字) + "qx-song": "NotoSerifSC[wght].ttf", # 思源宋体(正文、字幕,可变字重) +} + +chars = set(chr(c) for c in range(0x20, 0x7F)) +chars |= set("·—–…“”‘’《》〈〉「」『』【】、,。;:?!()〇") +files = glob.glob(os.path.join(ROOT, "src/quanxue/**/*.*"), recursive=True) + [os.path.join(ROOT, "src/App.tsx")] +for f in files: + if f.endswith((".ts", ".tsx", ".json", ".css")): + if f.endswith("voice.json"): + continue + txt = open(f, encoding="utf-8").read() + chars |= set(ch for ch in txt if ord(ch) > 0x2000) +text = "".join(sorted(chars)) +os.makedirs(OUT, exist_ok=True) +for name, fn in FONTS.items(): + font = TTFont(os.path.join(SRC_DIR, fn)) + cmap = font.getBestCmap() + opts = subset.Options() + opts.flavor = "woff2" + opts.layout_features = ["*"] + opts.name_IDs = ["*"] + sub = subset.Subsetter(opts) + sub.populate(text="荀性学假积止" if name == "qx-cao" else text) + sub.subset(font) + out = os.path.join(OUT, f"{name}.woff2") + font.flavor = "woff2" + font.save(out) + missing = [c for c in text if ord(c) not in cmap and ord(c) > 0x2E80] + print(name, os.path.getsize(out) // 1024, "KB", "missing:", "".join(missing[:40])) +print("chars:", len(text)) diff --git a/quanxue-src/scripts/quanxue/gen_tts.py b/quanxue-src/scripts/quanxue/gen_tts.py new file mode 100644 index 0000000000000000000000000000000000000000..08cf6f9d34dacc8186b9cc1be2a2d9b621703ffa --- /dev/null +++ b/quanxue-src/scripts/quanxue/gen_tts.py @@ -0,0 +1,61 @@ +"""旁白生成:读取 src/quanxue/script.json,逐句合成 mp3,并记录时长与逐词时间戳。 +用法: python3 -I scripts/quanxue/gen_tts.py [--force] +""" +import asyncio, json, os, sys +import edge_tts +from mutagen.mp3 import MP3 + +ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +SCRIPT = os.path.join(ROOT, "src/quanxue/script.json") +OUT_DIR = os.path.join(ROOT, "public/quanxue/voice") +META = os.path.join(ROOT, "src/quanxue/voice.json") +VOICE = "zh-CN-YunjianNeural" +RATE = {"say": "-6%", "quote": "-20%"} +PITCH = {"say": "-2Hz", "quote": "-4Hz"} +FORCE = "--force" in sys.argv + + +async def synth(line): + path = os.path.join(OUT_DIR, f"{line['id']}.mp3") + text = line.get("tts") or line["text"] + words = [] + if FORCE or not os.path.exists(path) or not os.path.exists(path + ".json"): + for attempt in range(4): + try: + com = edge_tts.Communicate(text, VOICE, rate=RATE[line["kind"]], pitch=PITCH[line["kind"]], boundary="WordBoundary") + audio = bytearray() + words = [] + async for chunk in com.stream(): + if chunk["type"] == "audio": + audio.extend(chunk["data"]) + elif chunk["type"] == "WordBoundary": + words.append({"o": round(chunk["offset"] / 1e7, 3), "d": round(chunk["duration"] / 1e7, 3), "t": chunk["text"]}) + open(path, "wb").write(audio) + json.dump(words, open(path + ".json", "w"), ensure_ascii=False) + break + except Exception as e: # network hiccup → retry + print("retry", line["id"], e) + await asyncio.sleep(2) + words = json.load(open(path + ".json")) + dur = MP3(path).info.length + return line["id"], {"dur": round(dur, 3), "words": words} + + +async def main(): + os.makedirs(OUT_DIR, exist_ok=True) + data = json.load(open(SCRIPT, encoding="utf-8")) + lines = [l for c in data["chapters"] for l in c["lines"]] + sem = asyncio.Semaphore(4) + + async def run(l): + async with sem: + return await synth(l) + + res = await asyncio.gather(*[run(l) for l in lines]) + meta = {k: v for k, v in res} + json.dump(meta, open(META, "w", encoding="utf-8"), ensure_ascii=False, indent=0) + total = sum(v["dur"] for v in meta.values()) + print(f"{len(meta)} lines, narration total {total:.1f}s") + + +asyncio.run(main()) diff --git a/quanxue-src/scripts/quanxue/page_test.py b/quanxue-src/scripts/quanxue/page_test.py new file mode 100644 index 0000000000000000000000000000000000000000..3b21ca1e22a2d79e1e5b8d6a62d567dba85dd960 --- /dev/null +++ b/quanxue-src/scripts/quanxue/page_test.py @@ -0,0 +1,29 @@ +"""页面冒烟测试:加载、播放、切换竖屏、检查控制台错误""" +import asyncio, sys +from playwright.async_api import async_playwright + +async def main(): + async with async_playwright() as p: + b = await p.chromium.launch(args=["--autoplay-policy=no-user-gesture-required"]) + for vp in [{"width": 1440, "height": 900}, {"width": 390, "height": 844}]: + pg = await b.new_page(viewport=vp) + logs = [] + pg.on("console", lambda m: logs.append(f"{m.type}: {m.text}") if m.type in ("error", "warning") else None) + pg.on("pageerror", lambda e: logs.append("PAGEERR " + str(e))) + await pg.goto("http://localhost:5173/") + await pg.wait_for_timeout(6000) + txt = await pg.evaluate("document.body.innerText.slice(0, 300)") + print(vp, "TEXT:", txt.replace("\n", " | ")[:300]) + await pg.click("button[aria-label=播放]") + await pg.wait_for_timeout(3000) + t = await pg.evaluate("document.querySelector('.tabular-nums')?.innerText") + print("time after play:", t) + box = await pg.evaluate("(()=>{const c=document.querySelector('canvas');const r=c.getBoundingClientRect();return [r.width,r.height,c.width,c.height]})()") + print("canvas css/px:", box) + imgs = await pg.evaluate("document.querySelectorAll('#cover img').length") + print("cover previews:", imgs) + await pg.screenshot(path=f"/tmp/page_{vp['width']}.png", full_page=True) + for l in logs[:15]: print(" ", l) + await pg.close() + await b.close() +asyncio.run(main()) diff --git a/quanxue-src/scripts/quanxue/render_music.py b/quanxue-src/scripts/quanxue/render_music.py new file mode 100644 index 0000000000000000000000000000000000000000..825a30319fb80ecdfb693605ea22b1624e684266 --- /dev/null +++ b/quanxue-src/scripts/quanxue/render_music.py @@ -0,0 +1,29 @@ +"""把程序化合成的配乐预渲染为 mp3(加快网页加载):python3 -I scripts/quanxue/render_music.py""" +import asyncio, base64, os +import lameenc +from playwright.async_api import async_playwright + +ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +OUT = os.path.join(ROOT, "public/quanxue/music.mp3") + + +async def main(): + async with async_playwright() as p: + b = await p.chromium.launch() + pg = await b.new_page() + await pg.goto("http://localhost:5173/?musicdump=1") + await pg.wait_for_function("window.__done === true", timeout=600000) + st = (await pg.evaluate("window.__stats"))[0] + n, sr = st["bytes"], st["sr"] + size = 4 * 1024 * 1024 + enc = lameenc.Encoder() + enc.set_bit_rate(128); enc.set_in_sample_rate(sr); enc.set_channels(2); enc.set_quality(2) + out = bytearray() + for i in range((n + size - 1) // size): + out += enc.encode(base64.b64decode(await pg.evaluate(f"window.__chunk({i}, {size})"))) + out += enc.flush() + open(OUT, "wb").write(out) + print("music.mp3", len(out) // 1024, "KB", sr, "Hz") + await b.close() + +asyncio.run(main()) diff --git a/quanxue-src/scripts/quanxue/shot.py b/quanxue-src/scripts/quanxue/shot.py new file mode 100644 index 0000000000000000000000000000000000000000..f44dfbaf77a9c0a04db8f837697063be377f4d52 --- /dev/null +++ b/quanxue-src/scripts/quanxue/shot.py @@ -0,0 +1,32 @@ +"""QA 截图:python3 -I scripts/quanxue/shot.py [l|p]""" +import sys, asyncio +from playwright.async_api import async_playwright + +out, ts = sys.argv[1], sys.argv[2] +o = sys.argv[3] if len(sys.argv) > 3 else 'l' + + +async def main(): + async with async_playwright() as p: + b = await p.chromium.launch(args=["--use-gl=swiftshader", "--enable-unsafe-swiftshader"]) + pg = await b.new_page(viewport={"width": 960 if o == 'l' else 540, "height": 540}) + logs = [] + pg.on("console", lambda m: logs.append(m.text) if m.type in ("error", "warning") else None) + pg.on("pageerror", lambda e: logs.append("PAGEERR " + str(e))) + await pg.goto(f"http://localhost:5173/?still={ts}&o={o}" if ts != "audio" else "http://localhost:5173/?audiotest=1") + try: + await pg.wait_for_function("window.__done === true", timeout=300000) + except Exception as e: + print("timeout", e) + st = await pg.evaluate("window.__stats") + for r in (st or []): + print(r) + if out != '-': + el = await pg.query_selector("canvas") + if el: + await el.screenshot(path=out) + for l in logs[:20]: + print(l) + await b.close() + +asyncio.run(main()) diff --git a/quanxue-src/src/App.tsx b/quanxue-src/src/App.tsx new file mode 100644 index 0000000000000000000000000000000000000000..07c8bbfcad186e561f8332c9594c11ed5c396b7c --- /dev/null +++ b/quanxue-src/src/App.tsx @@ -0,0 +1,103 @@ +import { useEffect, useState } from 'react' +import { BookOpen, Clapperboard, Image as ImageIcon, Send } from 'lucide-react' +import './quanxue/quanxue.css' +import { Player, type Orient } from './quanxue/ui/Player' +import { ExportPanel } from './quanxue/ui/ExportPanel' +import { CoverPanel } from './quanxue/ui/CoverPanel' +import { PublishPanel } from './quanxue/ui/PublishPanel' +import { Transcript } from './quanxue/ui/Transcript' +import { DURATION, TL } from './quanxue/timeline' +import { fmtTime } from './quanxue/ui/store' +import { ExportTest, MusicDump, Still } from './quanxue/dev' + +const isPhonePortrait = () => typeof window !== 'undefined' && window.matchMedia('(max-width: 820px) and (orientation: portrait)').matches + +function Section({ id, icon, title, sub, children }: { id: string; icon: React.ReactNode; title: string; sub: string; children: React.ReactNode }) { + return ( +
+
+ {icon} +

{title}

+ {sub} +
+ {children} +
+ ) +} + +function Main() { + const [orient, setOrientState] = useState(() => (isPhonePortrait() ? 'portrait' : 'landscape')) + const [manual, setManual] = useState(false) + const [seekReq, setSeekReq] = useState({ t: 0, n: 0 }) + const setOrient = (o: Orient) => { setManual(true); setOrientState(o) } + // 手机旋转时自动切换横竖屏(除非用户手动选择过) + useEffect(() => { + const mq = window.matchMedia('(max-width: 820px) and (orientation: portrait)') + const mq2 = window.matchMedia('(max-height: 520px) and (orientation: landscape)') + const f = () => { if (manual) return; if (mq.matches) setOrientState('portrait'); else if (mq2.matches) setOrientState('landscape') } + mq.addEventListener('change', f); mq2.addEventListener('change', f) + return () => { mq.removeEventListener('change', f); mq2.removeEventListener('change', f) } + }, [manual]) + const seek = (t: number) => { setSeekReq((s) => ({ t, n: s.n + 1 })); window.scrollTo({ top: 0, behavior: 'smooth' }) } + + const nav = [['watch', '观看'], ['script', '文稿'], ['export', '导出'], ['cover', '封面'], ['publish', '发布']] + return ( +
+ + +
+
+
+

劝学· 荀子

+

从“性恶论”到“化性起伪”,读懂学习的本质 · 时长 {fmtTime(DURATION)}

+
+ +
+ {TL.chapters.map((c) => ( + + ))} +
+
+ +
+
} title="解说文稿" sub="点击任意一句跳转播放"> + +
+
} title="导出 MP4" sub="浏览器本地渲染 · 不上传任何数据"> + +
+
} title="封面生成" sub="4:3 · 3:4 · 16:9 多选 · 每个比例多套设计"> + +
+
} title="发布文案" sub="小红书 · 抖音 · 视频号 · 哔哩哔哩"> + +
+
+
+ 原文据《荀子·劝学》(统编版高中语文必修上册)
解说文案原创 · AI 配音 · 画面 / 古琴配乐 / 音效 均为程序化实时生成 +
+
+
+ ) +} + +export default function App() { + if (typeof location !== 'undefined') { + if (location.search.includes('still=')) return + if (location.search.includes('musicdump')) return + if (location.search.includes('exporttest')) return + } + return
+} diff --git a/quanxue-src/src/entry-client.tsx b/quanxue-src/src/entry-client.tsx new file mode 100644 index 0000000000000000000000000000000000000000..8f7d4065f7285727bd1ccd55f604ab76809946f2 --- /dev/null +++ b/quanxue-src/src/entry-client.tsx @@ -0,0 +1,112 @@ +import './index.css' + +// --------------------------------------------------------------------------- +// Cold-start guard: verify React is real BEFORE rendering. +// +// During Vite dep-optimization (cold start or after `npm install `), +// Vite may serve placeholder "stub" modules where all React exports are +// undefined. Rendering with stub hooks causes "Cannot read properties of +// null (reading 'useState')". +// +// Strategy: +// 1. Dynamic-import React and check if useState is a function. +// 2. If stub → show a loading banner, schedule a reload with increasing +// delay, and do NOT mount any React tree (avoids the error entirely). +// 3. If real → dynamic-import App/ErrorBoundary and render normally. +// 4. Use createElement (not JSX) in this file so Vite doesn't inject a +// static `import { jsx } from 'react/jsx-dev-runtime'` which would +// itself be a stub and crash before our guard runs. +// --------------------------------------------------------------------------- + +const RELOAD_KEY = '__dep_reload' +const MAX_RELOADS = 6 +const RELOAD_WINDOW = 60_000 // 1 minute + +function getReloads(): { c: number; t: number } { + try { + return JSON.parse(sessionStorage.getItem(RELOAD_KEY) || '{}') as { c: number; t: number } + } catch { return { c: 0, t: 0 } } +} + +async function boot() { + const root = document.getElementById('root')! + + try { + const React = await import('react') + + // If useState is not a function, React is a dep-optimization stub + if (typeof React.useState !== 'function') throw new Error('dep-stub') + + const { createElement } = React + const { createRoot, hydrateRoot } = await import('react-dom/client') + const { QueryClient, QueryClientProvider } = await import('@tanstack/react-query') + const { default: App } = await import('./App') + const { default: ErrorBoundary } = await import('./ErrorBoundary') + + const queryClient = new QueryClient({ + defaultOptions: { queries: { + refetchOnWindowFocus: false, + retry: 3, + retryDelay: (attempt) => Math.min(1000 * 2 ** attempt, 10000), + staleTime: 30_000, + } }, + }) + + const children = createElement(ErrorBoundary, null, + createElement(QueryClientProvider, { client: queryClient }, + createElement(App) + ) + ) + + // Use hydrateRoot only when SSR rendered real app content. The scaffold's + // server entry intentionally returns a lightweight placeholder shell so + // SSR-incompatible libraries (for example echarts-for-react) cannot crash + // deploy-time render. Placeholder markup must be client-rendered, not hydrated. + const hasPlaceholder = !!root.querySelector('[data-surf-placeholder]') + if (root.childNodes.length > 0 && root.innerHTML !== '' && !hasPlaceholder) { + hydrateRoot(root, children) + } else { + root.innerHTML = '' + createRoot(root).render(children) + } + + // React rendered successfully — signal to index.html fallback & reset counter + ;(window as any).__reactOk = true + sessionStorage.removeItem(RELOAD_KEY) + + // Notify parent frame when real app content renders (not the placeholder). + // DO NOT REMOVE — the hosting app uses this to dismiss the loading overlay. + function notifyParentReady() { + if (!document.querySelector('[data-surf-placeholder]')) { + try { window.parent.postMessage({ type: 'surf-app-ready' }, '*') } catch { /* cross-origin — ignore */ } + } + } + notifyParentReady() + new MutationObserver(notifyParentReady).observe(root, { childList: true, subtree: true }) + } catch { + // React is not ready — show loading banner and schedule reload + const prev = getReloads() + const count = (Date.now() - prev.t > RELOAD_WINDOW) ? 0 : prev.c + + if (count < MAX_RELOADS) { + root.innerHTML = [ + '
', + '

Loading dependencies...

', + '

Reloading automatically

', + '
', + ].join('') + sessionStorage.setItem(RELOAD_KEY, JSON.stringify({ c: count + 1, t: Date.now() })) + // Increasing delay: 3s, 4s, 5s, ... gives Vite more time to finish + setTimeout(() => location.reload(), 3000 + count * 1000) + } else { + root.innerHTML = [ + '
', + '

Failed to load dependencies

', + '

Please refresh the page

', + '
', + ].join('') + } + } +} + +boot() diff --git a/quanxue-src/src/index.css b/quanxue-src/src/index.css new file mode 100644 index 0000000000000000000000000000000000000000..65196c048d7deee001b2e21a61363ad44536a92b --- /dev/null +++ b/quanxue-src/src/index.css @@ -0,0 +1,314 @@ +@import url('https://fonts.googleapis.com/css2?family=Lato:wght@400;600;700;900&family=Roboto+Mono:wght@400;500&display=swap'); + +@import "tailwindcss"; +@import "tw-animate-css"; + +/* ===== Tailwind CSS 4 Theme — maps CSS vars to Tailwind tokens ===== */ +@theme inline { + --color-background: var(--background); + --color-foreground: var(--foreground); + --color-card: var(--card); + --color-card-foreground: var(--card-foreground); + --color-popover: var(--popover); + --color-popover-foreground: var(--popover-foreground); + --color-primary: var(--primary); + --color-primary-foreground: var(--primary-foreground); + --color-secondary: var(--secondary); + --color-secondary-foreground: var(--secondary-foreground); + --color-muted: var(--muted); + --color-muted-foreground: var(--muted-foreground); + --color-accent: var(--accent); + --color-accent-foreground: var(--accent-foreground); + --color-destructive: var(--destructive); + --color-destructive-foreground: var(--destructive-foreground); + --color-border: var(--border); + --color-input: var(--input); + --color-ring: var(--ring); + --radius-sm: calc(var(--radius) - 4px); + --radius-md: calc(var(--radius) - 2px); + --radius-lg: var(--radius); + --radius-xl: calc(var(--radius) + 4px); + --animate-accordion-down: accordion-down 0.2s ease-out; + --animate-accordion-up: accordion-up 0.2s ease-out; + + /* Surf Semantic — Background */ + --color-bg-subtle: var(--bg-subtle); + --color-bg-subtle-hover: var(--bg-subtle-hover); + --color-bg-base: var(--bg-base); + --color-bg-base-opaque: var(--bg-base-opaque); + --color-bg-menu: var(--bg-menu); + --color-bg-chat: var(--bg-chat); + --color-bg-chat-nav: var(--bg-chat-nav); + + /* Surf Semantic — Foreground */ + --color-fg-base: var(--fg-base); + --color-fg-subtle: var(--fg-subtle); + --color-fg-muted: var(--fg-muted); + --color-fg-disabled: var(--fg-disabled); + + /* Surf Semantic — Border */ + --color-border-base: var(--border-base); + --color-border-strong: var(--border-strong); + --color-border-contrast: var(--border-contrast); + --color-border-focus: var(--border-focus); + + /* Surf Brand */ + --color-brand-100: var(--brand-100); + --color-brand-60: var(--brand-60); + --color-brand-30: var(--brand-30); + --color-brand-10: var(--brand-10); + + /* Surf Visualizer (Chart/Status) */ + --color-visualizer-rose-pop: var(--visualizer-rose-pop); + --color-visualizer-indigo-breeze: var(--visualizer-indigo-breeze); + --color-visualizer-emerald-mint: var(--visualizer-emerald-mint); + --color-visualizer-golden-amber: var(--visualizer-golden-amber); + --color-visualizer-royal-blue: var(--visualizer-royal-blue); + --color-visualizer-crimson-spark: var(--visualizer-crimson-spark); + --color-visualizer-aqua-glow: var(--visualizer-aqua-glow); + --color-visualizer-sunbeam-yellow: var(--visualizer-sunbeam-yellow); + + /* Surf Tags */ + --color-tag-blue-10: var(--tag-blue-10); + --color-tag-blue-100: var(--tag-blue-100); + --color-tag-yellow-10: var(--tag-yellow-10); + --color-tag-yellow-100: var(--tag-yellow-100); + --color-tag-purple-10: var(--tag-purple-10); + --color-tag-purple-100: var(--tag-purple-100); + --color-tag-cyan-10: var(--tag-cyan-10); + --color-tag-cyan-100: var(--tag-cyan-100); + --color-tag-pink-10: var(--tag-pink-10); + --color-tag-pink-100: var(--tag-pink-100); + --color-tag-orange-10: var(--tag-orange-10); + --color-tag-orange-100: var(--tag-orange-100); + + /* Neutral */ + --color-neutral-0: var(--neutral-0); +} + +@keyframes accordion-down { + from { height: 0; } + to { height: var(--radix-accordion-content-height); } +} + +@keyframes accordion-up { + from { height: var(--radix-accordion-content-height); } + to { height: 0; } +} + +/* ===== Light Mode (default) ===== */ +:root { + /* shadcn semantic tokens (Surf Light) */ + --background: hsl(0 0% 100%); + --foreground: hsl(0 0% 13%); + --card: hsl(0 0% 100%); + --card-foreground: hsl(0 0% 13%); + --popover: hsl(0 0% 100%); + --popover-foreground: hsl(0 0% 13%); + --primary: hsl(339 100% 58%); + --primary-foreground: hsl(0 0% 100%); + --secondary: hsl(0 3% 95%); + --secondary-foreground: hsl(0 0% 13%); + --muted: hsl(0 3% 95%); + --muted-foreground: hsl(0 0% 48%); + --accent: hsl(0 3% 95%); + --accent-foreground: hsl(0 0% 13%); + --destructive: hsl(357 91% 55%); + --destructive-foreground: hsl(0 0% 100%); + --border: hsl(0 0% 91%); + --input: hsl(0 0% 91%); + --ring: #212121; + --radius: 0.5rem; + + /* Surf Neutral Palette */ + --neutral-0: #ffffff; + --neutral-50: #fafafa; + --neutral-100: #f5f4f4; + --neutral-200: #e7e7e7; + --neutral-300: #d8d8d8; + --neutral-400: #aaaaaa; + --neutral-500: #7a7a7a; + --neutral-600: #5b5b5b; + --neutral-700: #464646; + --neutral-800: #2a2a2a; + --neutral-900: #212121; + --neutral-950: #1b1b1b; + --neutral-1000: #101010; + + /* Surf Brand */ + --brand-100: #ff2882; + --brand-60: rgba(255, 40, 130, 0.6); + --brand-30: rgba(255, 40, 130, 0.3); + --brand-10: rgba(255, 40, 130, 0.1); + + /* Surf Brand Extended */ + --brand-seafoam: #b6cfd0; + --brand-dusty-teal: #6ba4b8; + --brand-black-aqua: #002f38; + --brand-deep-teal-blue: #07272d; + + /* Surf Visualizer (Chart) Colors */ + --visualizer-rose-pop: #fd4b96; + --visualizer-indigo-breeze: #6366f1; + --visualizer-emerald-mint: #10b981; + --visualizer-golden-amber: #f59e0b; + --visualizer-royal-blue: #1d4ed8; + --visualizer-crimson-spark: #ef4444; + --visualizer-aqua-glow: #06b6d4; + --visualizer-sunbeam-yellow: #facc15; + + /* Surf Semantic Tokens (Light) */ + --bg-subtle: rgba(42, 42, 42, 0.04); + --bg-subtle-hover: rgba(42, 42, 42, 0.06); + --bg-base: rgba(255, 255, 255, 0.88); + --bg-base-opaque: #ffffff; + --bg-menu: #ffffff; + --bg-chat: #fcfcfc; + --bg-chat-nav: #f4f4f4; + --fg-base: #212121; + --fg-subtle: #7a7a7a; + --fg-muted: #aaaaaa; + --fg-disabled: #d8d8d8; + --border-base: rgba(42, 42, 42, 0.04); + --border-strong: rgba(42, 42, 42, 0.08); + --border-contrast: rgba(42, 42, 42, 0.12); + --border-focus: rgba(42, 42, 42, 0.4); + + /* Tag Colors */ + --tag-blue-10: rgba(91, 181, 255, 0.1); + --tag-blue-100: #5bb5ff; + --tag-yellow-10: rgba(222, 195, 120, 0.1); + --tag-yellow-100: #dec378; + --tag-purple-10: rgba(144, 142, 184, 0.1); + --tag-purple-100: #908eb8; + --tag-cyan-10: rgba(116, 173, 164, 0.1); + --tag-cyan-100: #74ada4; + --tag-pink-10: rgba(184, 142, 167, 0.1); + --tag-pink-100: #b88ea7; + --tag-orange-10: rgba(184, 160, 142, 0.1); + --tag-orange-100: #b8a08e; + + /* Surf Gradient Definitions (raw, mode-independent) */ + --gradient-max-dark: linear-gradient(213deg, #8c421d 2%, #fbe67b 31%, #fcfbe7 53%, #f7d14e 77%, #d4a041 100%); + --gradient-max-light: linear-gradient(125deg, #8c421d 22%, #d2af00 47%, #cd9124 67%, #d4a041 88%); + --gradient-pro-dark: linear-gradient(213deg, #7a96ac 1%, #c5d6e2 27%, #eaeff3 47%, #c5d6e2 65%, #a3bccf 89%); + --gradient-pro-light: linear-gradient(129deg, #7a96ac 4%, #6d7f8d 27%, #9fb9ce 55%, #6d7f8d 90%); + --gradient-plus-dark: linear-gradient(214deg, #986732 0%, #a7825b 23%, #f6d0ab 45%, #a07043 66%, #9d774e 100%); + --gradient-plus-light: linear-gradient(129deg, #9e8976 5%, #7a5e50 19%, #f6d0ab 35%, #9d774e 49%, #c99b70 65%, #795f52 78%); + --gradient-upgrade-dark: linear-gradient(214deg, #ffedf3 0%, #ff9fbf 30%, #fd5d92 59%, #ffdab2 100%); + --gradient-upgrade-light: linear-gradient(32deg, #fc3bb2 6%, #f7906e 79%); + --gradient-new-function: linear-gradient(33deg, #6e86ff 17%, #ff2882 55%, #ff98a4 103%); + --gradient-suggestion: linear-gradient(32deg, #fd538c 4%, #5aa6e0 47%, #ffdab2 98%); + --gradient-g1: linear-gradient(189deg, #ffacc6 6%, #b6e0f5 99%); + --gradient-g2: linear-gradient(34deg, #9796f0 9%, #fbc7d4 84%); + --gradient-g3: linear-gradient(to right, #ed4264, #ffedbc); + --gradient-g4: linear-gradient(232deg, #fedc2a 4%, #dd5789 56%, #7a2c9e 104%); + --gradient-g5: linear-gradient(32deg, #fc3bb2 6%, #f7906e 79%); + + /* Surf Gradients (semantic, auto-switch by mode) */ + --gradient-max: var(--gradient-max-light); + --gradient-pro: var(--gradient-pro-light); + --gradient-plus: var(--gradient-plus-light); + --gradient-upgrade: var(--gradient-upgrade-light); + + /* Spacing */ + --spacing-2: 2px; + --spacing-4: 4px; + --spacing-6: 6px; + --spacing-8: 8px; + --spacing-10: 10px; + --spacing-12: 12px; + --spacing-16: 16px; + --spacing-24: 24px; + --spacing-32: 32px; + --spacing-40: 40px; + --spacing-64: 64px; + --spacing-96: 96px; + --spacing-128: 128px; + + /* Border Radius */ + --radius-2: 2px; + --radius-4: 4px; + --radius-6: 6px; + --radius-8: 8px; + --radius-10: 10px; + --radius-12: 12px; + --radius-16: 16px; + --radius-20: 20px; + --radius-24: 24px; + --radius-full: 999px; + + /* Typography */ + --font-family-header: "Lato", "PingFang SC", sans-serif; + --font-family-body: "Lato", "PingFang SC", sans-serif; + --font-family-code: "Roboto Mono", monospace; +} + +/* ===== Dark Mode ===== */ +.dark { + /* shadcn semantic tokens (Surf Dark) */ + --background: hsl(0 0% 9%); + --foreground: hsl(0 0% 91%); + --card: hsl(0 0% 9%); + --card-foreground: hsl(0 0% 91%); + --popover: hsl(0 0% 15%); + --popover-foreground: hsl(0 0% 91%); + --primary: hsl(339 100% 58%); + --primary-foreground: hsl(0 0% 100%); + --secondary: hsl(0 0% 16%); + --secondary-foreground: hsl(0 0% 91%); + --muted: hsl(0 0% 16%); + --muted-foreground: hsl(0 0% 67%); + --accent: hsl(0 0% 16%); + --accent-foreground: hsl(0 0% 91%); + --destructive: hsl(359 100% 65%); + --destructive-foreground: hsl(0 0% 100%); + --border: hsl(0 0% 20%); + --input: hsl(0 0% 20%); + --ring: #e7e7e7; + + /* Surf Gradients (Dark) */ + --gradient-max: var(--gradient-max-dark); + --gradient-pro: var(--gradient-pro-dark); + --gradient-plus: var(--gradient-plus-dark); + --gradient-upgrade: var(--gradient-upgrade-dark); + + /* Surf Semantic Tokens (Dark) */ + --bg-subtle: rgba(255, 255, 255, 0.04); + --bg-subtle-hover: rgba(255, 255, 255, 0.12); + --bg-base: rgba(42, 42, 42, 0.8); + --bg-base-opaque: #171717; + --bg-menu: #252525; + --bg-chat: #101010; + --bg-chat-nav: #171717; + --fg-base: #e7e7e7; + --fg-subtle: #aaaaaa; + --fg-muted: #7a7a7a; + --fg-disabled: #5b5b5b; + --border-base: rgba(255, 255, 255, 0.04); + --border-strong: rgba(255, 255, 255, 0.08); + --border-contrast: rgba(255, 255, 255, 0.12); + --border-focus: rgba(255, 255, 255, 0.4); +} + +@layer base { + *, + ::after, + ::before { + border-color: var(--color-border); + } + body { + background-color: var(--color-background); + color: var(--color-foreground); + font-family: "Lato", "PingFang SC", sans-serif; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + } +} + +@media (max-width: 768px) { + :root { + --spacing-96: 64px; + --spacing-128: 64px; + } +} diff --git a/quanxue-src/src/quanxue/audio/engine.ts b/quanxue-src/src/quanxue/audio/engine.ts new file mode 100644 index 0000000000000000000000000000000000000000..0bc4357efde8bea30ba6f9b3f0326cbec7fce5de --- /dev/null +++ b/quanxue-src/src/quanxue/audio/engine.ts @@ -0,0 +1,188 @@ +// 音频引擎:旁白加载、实时播放调度(音频时钟为主时钟)、导出用 PCM 混音 +import { TL, DURATION } from '../timeline' +import { assetUrl } from '../fonts' +import { renderMusic, MUSIC_SR } from './music' +import { sfxData, SFX_SR } from './sfx' + +export const GAIN = { voice: 0.95, sfx: 0.62, music: 0.9 } + +type Clip = { t: number; data: Float32Array; sr: number; gain: number } + +export class AudioEngine { + voice = new Map() + music: AudioBuffer | null = null + musicPromise: Promise | null = null + ctx: AudioContext | null = null + private master: GainNode | null = null + private musicGain: GainNode | null = null + private nodes: AudioScheduledSourceNode[] = [] + private t0 = 0 + private off = 0 + playing = false + musicOn = true + onMusicReady?: () => void + + async loadVoices(onProgress?: (p: number) => void) { + const dec = new OfflineAudioContext(1, 1, 24000) + let done = 0 + await Promise.all(TL.lines.map(async (l) => { + const res = await fetch(assetUrl(`voice/${l.id}.mp3`)) + const buf = await dec.decodeAudioData(await res.arrayBuffer()) + this.voice.set(l.id, buf) + onProgress?.(++done / TL.lines.length) + })) + } + + loadMusic() { + if (!this.musicPromise) { + const fromFile = async () => { + const res = await fetch(assetUrl('music.mp3')) + if (!res.ok) throw new Error('no music file') + const dec = new OfflineAudioContext(2, 1, MUSIC_SR) + return dec.decodeAudioData(await res.arrayBuffer()) + } + // 优先加载预渲染的配乐;失败时在浏览器内实时合成同一份配乐 + this.musicPromise = fromFile().catch(() => renderMusic()).then((b) => { + this.music = b + if (this.playing && this.ctx) this.startMusicAt(this.time()) + this.onMusicReady?.() + return b + }) + } + return this.musicPromise + } + + private ensureCtx() { + if (!this.ctx) { + const Ctor = window.AudioContext || (window as any).webkitAudioContext + this.ctx = new Ctor({ latencyHint: 'playback' }) + const comp = this.ctx.createDynamicsCompressor() + comp.threshold.value = -4; comp.knee.value = 4; comp.ratio.value = 12; comp.attack.value = 0.003; comp.release.value = 0.2 + this.master = this.ctx.createGain(); this.master.gain.value = 1 + this.master.connect(comp); comp.connect(this.ctx.destination) + this.musicGain = this.ctx.createGain(); this.musicGain.gain.value = this.musicOn ? GAIN.music : 0 + this.musicGain.connect(this.master) + } + return this.ctx + } + + setMusic(on: boolean) { + this.musicOn = on + if (this.musicGain && this.ctx) this.musicGain.gain.setTargetAtTime(on ? GAIN.music : 0, this.ctx.currentTime, 0.1) + } + + time() { + if (!this.playing || !this.ctx) return this.off + return Math.min(DURATION, this.off + (this.ctx.currentTime - this.t0)) + } + + private startMusicAt(pos: number) { + const ctx = this.ctx! + if (!this.music) return + const s = ctx.createBufferSource(); s.buffer = this.music + s.connect(this.musicGain!) + const now = ctx.currentTime + s.start(now + 0.02, Math.max(0, pos + 0.02)) + this.nodes.push(s) + } + + async play(from: number) { + const ctx = this.ensureCtx() + if (ctx.state !== 'running') await ctx.resume() + this.stopNodes() + this.off = from + const lead = 0.06 + this.t0 = ctx.currentTime + lead + const at = (t: number) => this.t0 + (t - from) + for (const l of TL.lines) { + const b = this.voice.get(l.id) + if (!b || l.start + b.duration < from) continue + const s = ctx.createBufferSource(); s.buffer = b + const g = ctx.createGain(); g.gain.value = GAIN.voice + s.connect(g); g.connect(this.master!) + if (l.start >= from) s.start(at(l.start)); else s.start(this.t0, from - l.start) + this.nodes.push(s) + } + for (const c of TL.cues) { + const d = sfxData(c.type, c.seed ?? 1) + const dur = d.length / SFX_SR + if (c.t + dur < from) continue + const b = ctx.createBuffer(1, d.length, SFX_SR); b.copyToChannel(d as Float32Array, 0) + const s = ctx.createBufferSource(); s.buffer = b + const g = ctx.createGain(); g.gain.value = GAIN.sfx * (c.gain ?? 1) + s.connect(g); g.connect(this.master!) + if (c.t >= from) s.start(at(c.t)); else s.start(this.t0, from - c.t) + this.nodes.push(s) + } + if (this.music) { + const s = ctx.createBufferSource(); s.buffer = this.music + s.connect(this.musicGain!) + s.start(this.t0, from) + this.nodes.push(s) + } + this.playing = true + } + + pause() { + this.off = this.time() + this.playing = false + this.stopNodes() + } + + seek(t: number) { + this.off = Math.max(0, Math.min(DURATION, t)) + if (this.playing) this.play(this.off) + } + + private stopNodes() { + for (const n of this.nodes) { try { n.stop() } catch { /* already stopped */ } try { n.disconnect() } catch { /* ignore */ } } + this.nodes = [] + } + + // ---------------- 导出混音 ---------------- + clips(withMusic: boolean): { clips: Clip[]; music: AudioBuffer | null } { + const clips: Clip[] = [] + for (const l of TL.lines) { + const b = this.voice.get(l.id) + if (b) clips.push({ t: l.start, data: b.getChannelData(0), sr: b.sampleRate, gain: GAIN.voice }) + } + for (const c of TL.cues) clips.push({ t: c.t, data: sfxData(c.type, c.seed ?? 1), sr: SFX_SR, gain: GAIN.sfx * (c.gain ?? 1) }) + return { clips, music: withMusic ? this.music : null } + } +} + +/** 混出 [start, start+n) 区间的立体声 PCM(sr 采样率) */ +export function mixChunk(src: { clips: Clip[]; music: AudioBuffer | null }, start: number, n: number, sr: number): [Float32Array, Float32Array] { + const L = new Float32Array(n), R = new Float32Array(n) + const t0 = start / sr, t1 = (start + n) / sr + for (const c of src.clips) { + const cd = c.data.length / c.sr + if (c.t > t1 || c.t + cd < t0) continue + const ratio = c.sr / sr + const i0 = Math.max(0, Math.floor((c.t - t0) * sr)), i1 = Math.min(n, Math.ceil((c.t + cd - t0) * sr)) + for (let i = i0; i < i1; i++) { + const p = ((start + i) / sr - c.t) * c.sr + const k = Math.floor(p), f = p - k + if (k < 0 || k + 1 >= c.data.length) continue + const v = (c.data[k] * (1 - f) + c.data[k + 1] * f) * c.gain + L[i] += v; R[i] += v + } + void ratio + } + if (src.music) { + const ml = src.music.getChannelData(0), mr = src.music.getChannelData(1) + for (let i = 0; i < n; i++) { + const p = ((start + i) / sr) * src.music.sampleRate + const k = Math.floor(p), f = p - k + if (k + 1 >= ml.length) break + L[i] += (ml[k] * (1 - f) + ml[k + 1] * f) * GAIN.music + R[i] += (mr[k] * (1 - f) + mr[k + 1] * f) * GAIN.music + } + } + // 柔和限幅 + for (const ch of [L, R]) for (let i = 0; i < n; i++) { + const x = ch[i], a = Math.abs(x) + if (a > 0.85) ch[i] = Math.sign(x) * (0.85 + 0.15 * Math.tanh((a - 0.85) / 0.15)) + } + return [L, R] +} diff --git a/quanxue-src/src/quanxue/audio/music.ts b/quanxue-src/src/quanxue/audio/music.ts new file mode 100644 index 0000000000000000000000000000000000000000..5b848290c280c9d471e2989a72133e059265b7d4 --- /dev/null +++ b/quanxue-src/src/quanxue/audio/music.ts @@ -0,0 +1,234 @@ +// 背景音乐:古琴(Karplus-Strong 拨弦 + 泛音)、箫、低音铺底、卷积混响;旁白处自动闪避 +// 全部在 OfflineAudioContext 中确定性渲染,播放与导出使用同一份音乐 +import { TL, DURATION } from '../timeline' +import { clamp, rng } from '../engine/util' + +export const MUSIC_SR = 32000 +const mtof = (m: number) => 440 * Math.pow(2, (m - 69) / 12) +const PENTA = [0, 2, 4, 7, 9] // 宫 商 角 徵 羽(D 宫) +const deg2midi = (d: number, base = 50) => base + 12 * Math.floor(d / 5) + PENTA[((d % 5) + 5) % 5] + +function pluckData(f: number, dur: number, sr: number, seed: number, bright = 0.55) { + const n = Math.floor(dur * sr), out = new Float32Array(n) + const N = Math.max(2, Math.round(sr / f)) + const buf = new Float32Array(N), r = rng(seed) + let prev = 0 + for (let i = 0; i < N; i++) { prev = (1 - bright) * prev + bright * (r() * 2 - 1); buf[i] = prev } + const T60 = f < 120 ? 7 : f < 250 ? 5.5 : 4 + const decay = Math.pow(10, -3 / (f * T60)) + let idx = 0 + for (let i = 0; i < n; i++) { + const a = buf[idx], b = buf[(idx + 1) % N] + out[i] = a + buf[idx] = decay * (0.5 * (a + b)) + idx = (idx + 1) % N + } + // 指触噪声 + for (let i = 0; i < Math.min(n, sr * 0.02); i++) out[i] += (r() * 2 - 1) * 0.25 * (1 - i / (sr * 0.02)) + let m = 0 + for (let i = 0; i < n; i++) m = Math.max(m, Math.abs(out[i])) + for (let i = 0; i < n; i++) out[i] /= m || 1 + return out +} + +function harmonicData(f: number, dur: number, sr: number) { + const n = Math.floor(dur * sr), out = new Float32Array(n) + for (let i = 0; i < n; i++) { + const t = i / sr + out[i] = (Math.sin(2 * Math.PI * f * t) + 0.25 * Math.sin(2 * Math.PI * f * 2 * t) * Math.exp(-t * 2) + 0.1 * Math.sin(2 * Math.PI * f * 3.01 * t) * Math.exp(-t * 4)) * Math.exp(-t / 0.9) * Math.min(1, t / 0.003) + } + return out +} + +function makeIR(ctx: BaseAudioContext, sec: number) { + const n = Math.floor(sec * ctx.sampleRate), ir = ctx.createBuffer(2, n, ctx.sampleRate) + for (let ch = 0; ch < 2; ch++) { + const d = ir.getChannelData(ch), r = rng(91 + ch) + let y = 0 + for (let i = 0; i < n; i++) { + const t = i / ctx.sampleRate + const a = 0.85 - 0.7 * (i / n) + y += a * ((r() * 2 - 1) - y) + d[i] = y * Math.exp(-t / 1.15) * Math.min(1, t / 0.012) + } + } + return ir +} + +type Section = { start: number; end: number; level: number; root: number } +function sections(): Section[] { + const roots = [38, 35, 43, 45, 40, 38] + const out: Section[] = [{ start: 0, end: 9, level: 1, root: 38 }] + TL.chapters.forEach((c, i) => out.push({ start: c.start, end: c.end, level: 0.72, root: roots[i] })) + out.push({ start: TL.shots[TL.shots.length - 1].start, end: DURATION + 1, level: 1, root: 38 }) + return out +} + +/** 音乐总线电平曲线:段落强弱 × 旁白闪避 */ +export function musicLevel(t: number) { + let lvl = 0.72 + if (t < 9) lvl = 1 + for (const s of TL.shots) if ((s.vis === 'card' || s.vis === 'endcard') && t >= s.start - 0.3 && t < s.end) lvl = s.vis === 'card' ? 0.95 : 1 + const fin = TL.shots.find((s) => s.vis === 'finale')! + if (t > fin.start) lvl = Math.max(lvl, 0.9) + let duck = 0 + for (const l of TL.lines) { + if (t < l.start - 0.8 || t > l.end + 1.0) continue + const a = clamp((t - (l.start - 0.45)) / 0.35), b = clamp(((l.end + 0.55) - t) / 0.45) + duck = Math.max(duck, Math.min(a, b)) + } + return lvl * (1 - 0.62 * duck) +} + +export async function renderMusic(): Promise { + const D = DURATION + 1 + const sr = MUSIC_SR + const ctx = new OfflineAudioContext(2, Math.ceil(D * sr), sr) + const bus = ctx.createGain() + bus.connect(ctx.destination) + // 闪避曲线 + const step = 0.05, N = Math.ceil(D / step) + const curve = new Float32Array(N) + for (let i = 0; i < N; i++) curve[i] = musicLevel(i * step) * 1.35 + bus.gain.setValueAtTime(curve[0], 0) + bus.gain.setValueCurveAtTime(curve, 0.001, D - 0.01) + + const rev = ctx.createConvolver(); rev.buffer = makeIR(ctx, 4.5) + const wet = ctx.createGain(); wet.gain.value = 0.85 + rev.connect(wet); wet.connect(bus) + // 琴音色:低频温暖、中频木质 + const qin = ctx.createBiquadFilter(); qin.type = 'peaking'; qin.frequency.value = 240; qin.gain.value = 4; qin.Q.value = 0.9 + const qinLp = ctx.createBiquadFilter(); qinLp.type = 'lowpass'; qinLp.frequency.value = 3800 + qin.connect(qinLp) + const qinDry = ctx.createGain(); qinDry.gain.value = 0.7; qinLp.connect(qinDry); qinDry.connect(bus) + const qinWet = ctx.createGain(); qinWet.gain.value = 0.5; qinLp.connect(qinWet); qinWet.connect(rev) + + const r = rng(2024) + const pluckCache = new Map() + const getPluck = (m: number) => { + let b = pluckCache.get(m) + if (!b) { const d = pluckData(mtof(m), 6, sr, m * 13); b = ctx.createBuffer(1, d.length, sr); b.copyToChannel(d, 0); pluckCache.set(m, b) } + return b + } + const harmCache = new Map() + const getHarm = (m: number) => { + let b = harmCache.get(m) + if (!b) { const d = harmonicData(mtof(m), 4, sr); b = ctx.createBuffer(1, d.length, sr); b.copyToChannel(d, 0); harmCache.set(m, b) } + return b + } + + const note = (t: number, m: number, vel: number, opts: { harm?: boolean; slideTo?: number; pan?: number } = {}) => { + if (t < 0 || t > D - 1) return + const src = ctx.createBufferSource() + src.buffer = opts.harm ? getHarm(m) : getPluck(m) + const g = ctx.createGain(); g.gain.value = vel * (opts.harm ? 0.35 : 0.5) + const p = ctx.createStereoPanner(); p.pan.value = opts.pan ?? (r() - 0.5) * 0.5 + src.connect(g); g.connect(p); p.connect(qin) + // 吟猱 / 绰注(滑音) + if (!opts.harm) { + const len = 64, cv = new Float32Array(len), dur = 3 + const ratio = opts.slideTo !== undefined ? Math.pow(2, (opts.slideTo - m) / 12) : 1 + for (let i = 0; i < len; i++) { + const tt = (i / (len - 1)) * dur + const slide = opts.slideTo !== undefined ? 1 + (ratio - 1) * clamp((tt - 0.35) / 0.45) : 1 + const vib = 1 + 0.0045 * Math.sin(2 * Math.PI * 4.6 * tt) * clamp((tt - 0.4) / 0.6) * Math.exp(-tt / 2.5) + cv[i] = slide * vib + } + src.playbackRate.setValueCurveAtTime(cv, t, dur) + } + src.start(t) + src.stop(t + 6) + } + + // ---- 铺底和声 ---- + for (const s of sections()) { + const out = ctx.createGain(); out.gain.value = 0 + const lp = ctx.createBiquadFilter(); lp.type = 'lowpass'; lp.frequency.value = 650; lp.Q.value = 0.6 + out.connect(lp); lp.connect(bus) + const send = ctx.createGain(); send.gain.value = 0.5; lp.connect(send); send.connect(rev) + const voices: [number, number, OscillatorType][] = [[s.root, 0.05, 'sine'], [s.root + 7, 0.03, 'triangle'], [s.root + 12, 0.028, 'sine'], [s.root + 19, 0.012, 'triangle']] + voices.forEach(([m, a, type], i) => { + const o = ctx.createOscillator(); o.type = type; o.frequency.value = mtof(m) + const lfo = ctx.createOscillator(); lfo.frequency.value = 0.05 + i * 0.023 + const lg = ctx.createGain(); lg.gain.value = 5; lfo.connect(lg); lg.connect(o.detune) + const g = ctx.createGain(); g.gain.value = a + o.connect(g); g.connect(out) + o.start(Math.max(0, s.start - 2)); o.stop(Math.min(D, s.end + 4)); lfo.start(Math.max(0, s.start - 2)); lfo.stop(Math.min(D, s.end + 4)) + }) + const a0 = Math.max(0, s.start - 1.5) + out.gain.setValueAtTime(0, a0) + out.gain.linearRampToValueAtTime(s.level, a0 + 3) + out.gain.setValueAtTime(s.level, Math.max(a0 + 3, s.end - 1)) + out.gain.linearRampToValueAtTime(0, Math.min(D, s.end + 3.5)) + } + + // ---- 箫 ---- + const noiseBuf = ctx.createBuffer(1, sr * 2, sr) + { const d = noiseBuf.getChannelData(0), rr = rng(5); for (let i = 0; i < d.length; i++) d[i] = rr() * 2 - 1 } + const xiao = (t: number, m: number, dur: number, vel = 1) => { + if (t > D - 1) return + const f = mtof(m) + const g = ctx.createGain(); g.gain.value = 0 + const pan = ctx.createStereoPanner(); pan.pan.value = -0.15 + g.connect(pan); pan.connect(bus) + const s2 = ctx.createGain(); s2.gain.value = 0.9; pan.connect(s2); s2.connect(rev) + const peak = 0.06 * vel + g.gain.setValueAtTime(0, t); g.gain.linearRampToValueAtTime(peak, t + 0.35); g.gain.setValueAtTime(peak, t + Math.max(0.4, dur - 0.7)); g.gain.linearRampToValueAtTime(0, t + dur) + const vib = ctx.createOscillator(); vib.frequency.value = 4.8 + const vg = ctx.createGain(); vg.gain.setValueAtTime(0, t); vg.gain.linearRampToValueAtTime(f * 0.006, t + 0.9) + vib.connect(vg) + ;[[1, 1], [2, 0.12], [3, 0.04]].forEach(([h, a]) => { + const o = ctx.createOscillator(); o.frequency.value = f * h + vg.connect(o.frequency) + const og = ctx.createGain(); og.gain.value = a + o.connect(og); og.connect(g); o.start(t); o.stop(t + dur + 0.1) + }) + const nz = ctx.createBufferSource(); nz.buffer = noiseBuf; nz.loop = true + const bp = ctx.createBiquadFilter(); bp.type = 'bandpass'; bp.frequency.value = f * 1.5; bp.Q.value = 1.2 + const ng = ctx.createGain(); ng.gain.value = 0.18 + nz.connect(bp); bp.connect(ng); ng.connect(g); nz.start(t); nz.stop(t + dur + 0.1) + vib.start(t); vib.stop(t + dur + 0.1) + } + + // ---- 编排 ---- + // 片头 + note(1.62, 38, 1, { pan: 0 }); note(1.62, 50, 0.6, { harm: true, pan: 0.1 }) + xiao(2.8, 69, 2.6, 1); xiao(5.3, 71, 1.2, 0.9); xiao(6.4, 69, 2.4, 0.9) + ;[[3.2, 57], [3.9, 59], [4.5, 62], [5.6, 64, 66], [7.2, 62]].forEach(([t, m, sl]) => note(t, m, 0.7, sl ? { slideTo: sl } : {})) + // 章节卡 + TL.chapters.forEach((c, i) => { + note(c.start + 0.15, 38 + (i % 2 ? 7 : 0), 0.9, { pan: 0 }) + note(c.start + 0.15, 62, 0.5, { harm: true }) + xiao(c.start + 0.5, [74, 69, 71, 69, 66, 74][i], 2.9, 0.8) + }) + // 正文:稀疏、留白的琴句 + let t = 10.5 + let deg = 5 + while (t < DURATION - 10) { + const inCard = TL.shots.some((s) => s.vis === 'card' && t > s.start - 0.5 && t < s.end + 0.5) + if (inCard) { t += 1.2; continue } + const n = 3 + Math.floor(r() * 4) + for (let k = 0; k < n; k++) { + deg = Math.max(2, Math.min(11, deg + Math.round((r() - 0.5) * 4))) + const m = deg2midi(deg, 45) + const slide = r() < 0.25 ? deg2midi(deg + (r() < 0.5 ? 1 : -1), 45) : undefined + note(t, m, 0.42 + r() * 0.25, slide ? { slideTo: slide } : {}) + if (r() < 0.18) note(t, m + 12, 0.25, { harm: true }) + if (k === 0 && r() < 0.5) note(t, deg2midi(0, 38), 0.4, { pan: 0 }) + t += 0.55 + r() * 0.9 + (k === n - 1 ? 0.6 : 0) + } + deg = r() < 0.5 ? 5 : 8 + t += 3 + r() * 4 + } + // 结尾 + const fin = TL.shots.find((s) => s.vis === 'finale')! + const end = TL.shots[TL.shots.length - 1] + note(fin.start + 0.2, 38, 0.9, { pan: 0 }) + xiao(fin.end - 3.2, 74, 4.5, 1) + ;[[end.start + 0.4, 62], [end.start + 1.3, 64], [end.start + 2.1, 69, 71], [end.start + 3.6, 66], [end.start + 4.6, 62]].forEach(([tt, m, sl]) => note(tt, m, 0.6, sl ? { slideTo: sl } : {})) + note(end.start + 4.6, 74, 0.4, { harm: true }) + note(end.start + 4.6, 38, 0.8, { pan: 0 }) + xiao(end.start + 1.0, 69, 3.2, 0.8) + + return ctx.startRendering() +} diff --git a/quanxue-src/src/quanxue/audio/sfx.ts b/quanxue-src/src/quanxue/audio/sfx.ts new file mode 100644 index 0000000000000000000000000000000000000000..e2a616f93b120763a8d86fa0de95b104eddfbe90 --- /dev/null +++ b/quanxue-src/src/quanxue/audio/sfx.ts @@ -0,0 +1,194 @@ +// 程序化音效:全部用 JS 直接合成 PCM(确定性),播放与导出共用 +import type { SfxType } from '../timeline' +import { rng } from '../engine/util' + +export const SFX_SR = 48000 + +class Biquad { + b0 = 1; b1 = 0; b2 = 0; a1 = 0; a2 = 0; x1 = 0; x2 = 0; y1 = 0; y2 = 0 + set(type: 'lp' | 'hp' | 'bp', f: number, q: number, sr = SFX_SR) { + const w = (2 * Math.PI * Math.min(f, sr * 0.45)) / sr, cs = Math.cos(w), al = Math.sin(w) / (2 * q) + let b0, b1, b2 + if (type === 'lp') { b0 = (1 - cs) / 2; b1 = 1 - cs; b2 = (1 - cs) / 2 } + else if (type === 'hp') { b0 = (1 + cs) / 2; b1 = -(1 + cs); b2 = (1 + cs) / 2 } + else { b0 = al; b1 = 0; b2 = -al } + const a0 = 1 + al + this.b0 = b0 / a0; this.b1 = b1 / a0; this.b2 = b2 / a0; this.a1 = (-2 * cs) / a0; this.a2 = (1 - al) / a0 + return this + } + run(x: number) { + const y = this.b0 * x + this.b1 * this.x1 + this.b2 * this.x2 - this.a1 * this.y1 - this.a2 * this.y2 + this.x2 = this.x1; this.x1 = x; this.y2 = this.y1; this.y1 = y + return y + } +} + +const env = (t: number, a: number, d: number) => (t < a ? t / a : Math.exp(-(t - a) / d)) + +function make(dur: number, fn: (t: number, i: number, out: Float32Array) => number) { + const n = Math.floor(dur * SFX_SR), out = new Float32Array(n) + for (let i = 0; i < n; i++) out[i] = fn(i / SFX_SR, i, out) + // 去直流 + 末尾淡出 + let m = 0 + for (let i = 0; i < n; i++) m = Math.max(m, Math.abs(out[i])) + const fade = Math.min(n, SFX_SR * 0.05) + for (let i = 0; i < fade; i++) out[n - 1 - i] *= i / fade + return { data: out, peak: m } +} + +function normalize(d: Float32Array, peak: number, target: number) { + if (peak <= 0) return d + const k = target / peak + for (let i = 0; i < d.length; i++) d[i] *= k + return d +} + +function partials(t: number, list: [number, number, number][]) { + let s = 0 + for (const [f, a, dec] of list) s += a * Math.sin(2 * Math.PI * f * t) * Math.exp(-t / dec) + return s +} + +export function synthSfx(type: SfxType, seed = 1): Float32Array { + const r = rng(seed * 7919 + type.length * 31) + const noise = () => r() * 2 - 1 + switch (type) { + case 'drop': { + let ph = 0 + const { data, peak } = make(0.6, (t) => { + const f = 700 + 1300 * Math.min(1, t / 0.07) + ph += (2 * Math.PI * f) / SFX_SR + return Math.sin(ph) * env(t, 0.003, 0.06) + 0.3 * Math.sin(ph * 0.5) * env(t, 0.002, 0.03) + }) + return normalize(data, peak, 0.6) + } + case 'boom': { + const lp = new Biquad().set('lp', 220, 0.7) + let ph = 0 + const { data, peak } = make(4, (t) => { + const f = 38 + 30 * Math.exp(-t / 0.25) + ph += (2 * Math.PI * f) / SFX_SR + return Math.sin(ph) * env(t, 0.01, 1.1) + lp.run(noise()) * env(t, 0.005, 0.35) * 1.2 + }) + return normalize(data, peak, 0.95) + } + case 'brush': { + const bp = new Biquad(), hp = new Biquad().set('hp', 900, 0.7) + const { data, peak } = make(0.9, (t, i) => { + if (i % 32 === 0) bp.set('bp', 2200 + 3000 * Math.sin(Math.min(1, t / 0.6) * Math.PI), 1.2) + return bp.run(hp.run(noise())) * (t < 0.12 ? t / 0.12 : Math.exp(-(t - 0.12) / 0.22)) * (0.7 + 0.3 * Math.sin(t * 60)) + }) + return normalize(data, peak, 0.5) + } + case 'stamp': + case 'thud': { + const lp = new Biquad().set('lp', type === 'stamp' ? 700 : 400, 0.8) + let ph = 0 + const { data, peak } = make(1.0, (t) => { + const f = (type === 'stamp' ? 70 : 52) + 90 * Math.exp(-t / 0.04) + ph += (2 * Math.PI * f) / SFX_SR + return Math.sin(ph) * env(t, 0.002, 0.12) + lp.run(noise()) * env(t, 0.001, 0.05) * 0.8 + }) + return normalize(data, peak, 0.9) + } + case 'bell': { + const f = 146.83 + const { data, peak } = make(7, (t) => partials(t, [[f, 1, 3.2], [f * 1.004, 0.6, 3.6], [f * 2.76, 0.45, 1.6], [f * 5.4, 0.2, 0.7], [f * 8.93, 0.08, 0.35]]) * Math.min(1, t / 0.004)) + return normalize(data, peak, 0.65) + } + case 'chime': { + const f = 1174.66 + const { data, peak } = make(4, (t) => partials(t, [[f, 1, 1.6], [f * 1.003, 0.5, 1.8], [f * 2.4, 0.3, 0.6], [f * 3.9, 0.12, 0.3]]) * Math.min(1, t / 0.002)) + return normalize(data, peak, 0.35) + } + case 'whoosh': { + const bp = new Biquad() + const dur = 1.2 + r() * 0.4 + const { data, peak } = make(dur, (t, i) => { + const p = t / dur + if (i % 32 === 0) bp.set('bp', 300 + 2400 * Math.sin(p * Math.PI), 0.9) + return bp.run(noise()) * Math.pow(Math.sin(p * Math.PI), 2) + }) + return normalize(data, peak, 0.4) + } + case 'creak': { + const bp1 = new Biquad().set('bp', 520, 6), bp2 = new Biquad().set('bp', 1150, 5) + let acc = 0 + const { data, peak } = make(1.6, (t) => { + const rate = 28 + 18 * Math.sin(t * 3.1) + 10 * Math.sin(t * 7.3) + acc += rate / SFX_SR + let imp = 0 + if (acc >= 1) { acc -= 1; imp = 1 } + const x = imp + noise() * 0.02 + return (bp1.run(x) + 0.6 * bp2.run(x)) * Math.sin(Math.min(1, t / 1.6) * Math.PI) + }) + return normalize(data, peak, 0.5) + } + case 'fire': { + const lp = new Biquad().set('lp', 500, 0.7), hp = new Biquad().set('hp', 1500, 0.7) + const { data, peak } = make(3.6, (t) => { + const crack = r() < 0.0009 ? noise() * 3 : 0 + const w = Math.sin(Math.min(1, t / 3.6) * Math.PI) + return (lp.run(noise()) * 0.6 + hp.run(crack)) * w + }) + return normalize(data, peak, 0.45) + } + case 'tick': { + const hp = new Biquad().set('hp', 2500, 0.7) + const k = 0.9 + r() * 0.2 + const { data, peak } = make(0.35, (t) => hp.run(noise()) * env(t, 0.0005, 0.006) * 1.5 + partials(t, [[2400 * k, 0.5, 0.05], [3720 * k, 0.35, 0.035], [5150 * k, 0.2, 0.02], [180, 0.4, 0.04]])) + return normalize(data, peak, 0.6) + } + case 'rain': { + const lp = new Biquad().set('lp', 3800, 0.6), hp = new Biquad().set('hp', 400, 0.6) + const { data, peak } = make(4.5, (t) => { + const d = r() < 0.004 ? noise() * 2 : 0 + return (hp.run(lp.run(noise())) * 0.5 + d) * Math.sin(Math.min(1, t / 4.5) * Math.PI) + }) + return normalize(data, peak, 0.35) + } + case 'drip': { + let ph = 0 + const hits = [0, 0.55, 1.25] + const { data, peak } = make(2.2, (t) => { + let s = 0 + for (const h of hits) { + const tt = t - h + if (tt < 0) continue + const f = 900 + 900 * Math.min(1, tt / 0.05) + s += Math.sin(2 * Math.PI * f * tt) * env(tt, 0.002, 0.07) + } + ph += 0 + return s + }) + return normalize(data, peak, 0.45) + } + case 'wind': { + const lp = new Biquad() + const { data, peak } = make(4.5, (t, i) => { + if (i % 64 === 0) lp.set('bp', 350 + 500 * (0.5 + 0.5 * Math.sin(t * 1.3)) + 200 * Math.sin(t * 3.7), 0.8) + return lp.run(noise()) * Math.sin(Math.min(1, t / 4.5) * Math.PI) + }) + return normalize(data, peak, 0.4) + } + case 'water': { + const lp = new Biquad().set('lp', 900, 0.7) + const { data, peak } = make(4, (t) => lp.run(noise()) * (0.5 + 0.5 * Math.sin(t * 2 * Math.PI * 0.8)) * Math.sin(Math.min(1, t / 4) * Math.PI)) + return normalize(data, peak, 0.4) + } + case 'page': { + const hp = new Biquad().set('hp', 1800, 0.7) + const { data, peak } = make(0.7, (t) => hp.run(noise()) * (r() < 0.3 ? 1 : 0.3) * Math.sin(Math.min(1, t / 0.7) * Math.PI)) + return normalize(data, peak, 0.35) + } + } + return new Float32Array(1) +} + +const cache = new Map() +export function sfxData(type: SfxType, seed = 1) { + const key = type + ':' + (['whoosh', 'tick', 'brush'].includes(type) ? seed % 4 : 0) + let d = cache.get(key) + if (!d) { d = synthSfx(type, ['whoosh', 'tick', 'brush'].includes(type) ? seed % 4 : 0); cache.set(key, d) } + return d +} diff --git a/quanxue-src/src/quanxue/covers.ts b/quanxue-src/src/quanxue/covers.ts new file mode 100644 index 0000000000000000000000000000000000000000..d1b1b87f99ff2efb6dd0a6baae83ef0819c18044 --- /dev/null +++ b/quanxue-src/src/quanxue/covers.ts @@ -0,0 +1,144 @@ +// 封面生成:多套原创设计 × 4:3 / 3:4 / 16:9 +import { COL, F, background, brush, cached, dust, glow, hairline, inkBlob, makeCanvas, mountains, revealChar, rgba, scholar, seal, text, vignette, grain, type Ctx } from './engine/draw' +import { fbm2, lerp } from './engine/util' + +export type Ratio = '4:3' | '3:4' | '16:9' +export const RATIO_DIM: Record = { '16:9': [1920, 1080], '4:3': [1440, 1080], '3:4': [1080, 1440] } + +export type CoverDesign = { id: string; name: string; draw: (c: Ctx, W: number, H: number) => void } + +function paperBg(c: Ctx, W: number, H: number) { + const tex = cached('paper', W, H, (g, w, h) => { + g.fillStyle = '#ece2cb'; g.fillRect(0, 0, w, h) + const sw = Math.ceil(w / 6), sh = Math.ceil(h / 6) + const s = makeCanvas(sw, sh), sc = s.getContext('2d')!, img = sc.createImageData(sw, sh) + for (let y = 0; y < sh; y++) for (let x = 0; x < sw; x++) { + const v = (fbm2(x / sw * 6, y / sh * 6 * (h / w)) + 1) / 2, i = (y * sw + x) * 4 + img.data[i] = 236 - v * 26; img.data[i + 1] = 226 - v * 26; img.data[i + 2] = 203 - v * 30; img.data[i + 3] = 255 + } + sc.putImageData(img, 0, 0); g.globalAlpha = 0.8; g.drawImage(s, 0, 0, w, h); g.globalAlpha = 1 + for (let i = 0; i < 900; i++) { g.strokeStyle = `rgba(120,100,70,${Math.random() * 0.08})`; g.lineWidth = 0.6; const x = Math.random() * w, y = Math.random() * h, a = Math.random() * 6.28, l = 6 + Math.random() * 30; g.beginPath(); g.moveTo(x, y); g.quadraticCurveTo(x + Math.cos(a) * l * 0.5 + 4, y + Math.sin(a) * l * 0.5, x + Math.cos(a) * l, y + Math.sin(a) * l); g.stroke() } + const v = g.createRadialGradient(w / 2, h / 2, Math.min(w, h) * 0.3, w / 2, h / 2, Math.hypot(w, h) * 0.6) + v.addColorStop(0, 'rgba(0,0,0,0)'); v.addColorStop(1, 'rgba(80,60,30,0.28)') + g.fillStyle = v; g.fillRect(0, 0, w, h) + }) + c.drawImage(tex, 0, 0, W, H) +} + +const big = (c: Ctx, chars: string, x: number, y: number, size: number, vertical: boolean, color: string, fam = F.brush, lead = 1.08) => { + ;[...chars].forEach((ch, i) => revealChar(c, ch, vertical ? x : x + (i - (chars.length - 1) / 2) * size * lead, vertical ? y + (i - (chars.length - 1) / 2) * size * lead : y, size, fam, color, 1)) +} + +export const COVERS: CoverDesign[] = [ + { + id: 'ink', name: '墨韵 · 主标题', + draw(c, W, H) { + const u = Math.min(W, H) / 1080, P = H > W + background(c, W, H) + mountains(c, W, H, 3, { seed: 3, alpha: 0.75, y: P ? 260 * u : 120 * u }) + const X = P ? W / 2 : W * 0.42, Y = P ? H * 0.4 : H * 0.46 + inkBlob(c, X, Y, Math.min(W, H) * 0.42, 11, '#51473a', 0.8, 0.3) + glow(c, X, Y, Math.min(W, H) * 0.5, COL.gold, 0.1) + const size = (P ? 330 : 300) * u + big(c, '劝学', X, Y, size, P, COL.paper) + seal(c, P ? X + size * 0.75 : X + size * 1.2, P ? Y + size * 0.95 : Y + size * 0.38, 110 * u, '荀子', 1, -0.04) + const tx = P ? W / 2 : W * 0.8 + if (P) { + text(c, '高中语文 · 课文精讲', tx, H * 0.79, 52 * u, F.song, COL.gold, 1, 'center', 14 * u, 700) + text(c, '学不可以已', tx, H * 0.86, 44 * u, F.kai, COL.paper, 0.9, 'center', 18 * u) + } else { + for (const [s, x, sz, col] of [['课文精讲', tx + 40 * u, 64, COL.gold], ['学不可以已', tx - 50 * u, 46, COL.paper]] as const) { + ;[...s].forEach((ch, i) => revealChar(c, ch, x, H * 0.24 + i * sz * 1.2 * u, sz * u, F.kai, col, 1)) + } + } + text(c, '统编版 · 必修上册', P ? W / 2 : 90 * u, P ? 80 * u : 70 * u, 30 * u, F.song, COL.muted, 0.9, P ? 'center' : 'left', 8 * u) + vignette(c, W, H); grain(c, W, H, 1, 0.06) + }, + }, + { + id: 'paper', name: '宣纸 · 朱印', + draw(c, W, H) { + const u = Math.min(W, H) / 1080, P = H > W + paperBg(c, W, H) + const X = P ? W / 2 : W * 0.4, Y = P ? H * 0.42 : H * 0.5 + inkBlob(c, X + 40 * u, Y + 20 * u, Math.min(W, H) * 0.36, 31, '#8b8270', 0.35, 0.34) + const size = (P ? 320 : 300) * u + big(c, '劝学', X, Y, size, P, '#15120e') + seal(c, P ? X - size * 0.72 : X - size * 1.15, P ? Y - size * 0.85 : Y - size * 0.4, 100 * u, '荀子', 1, 0.05) + const quote = '青取之于蓝而青于蓝' + const qx = P ? W * 0.86 : W * 0.86, qy = P ? H * 0.12 : H * 0.14 + ;[...quote].forEach((ch, i) => revealChar(c, ch, qx, qy + i * 50 * u, 40 * u, F.kai, '#4b4236', 1)) + text(c, '荀子《劝学》深度精讲', P ? W / 2 : W * 0.4, P ? H * 0.82 : H * 0.86, 54 * u, F.song, '#2a241c', 1, 'center', 10 * u, 700) + hairline(c, (P ? W / 2 : W * 0.4) - 280 * u, (P ? H * 0.86 : H * 0.91), (P ? W / 2 : W * 0.4) + 280 * u, (P ? H * 0.86 : H * 0.91), 1, COL.red, 0.8, 2 * u) + text(c, '性恶 · 化性起伪 · 善假于物 · 积恒专', P ? W / 2 : W * 0.4, P ? H * 0.9 : H * 0.95, 30 * u, F.song, '#6b5d48', 1, 'center', 4 * u) + }, + }, + { + id: 'quote', name: '金句 · 锲而不舍', + draw(c, W, H) { + const u = Math.min(W, H) / 1080, P = H > W + background(c, W, H) + dust(c, W, H, 7, 70, 4, COL.gold, 0.4) + const size = (P ? 150 : 140) * u + const cols = ['锲而不舍', '金石可镂'] + cols.forEach((s, ci) => { + const x = (P ? W / 2 : W * 0.42) + (0.5 - ci) * size * 1.7 + ;[...s].forEach((ch, i) => revealChar(c, ch, x, (P ? H * 0.2 : H * 0.18) + i * size * 1.12 + size * 0.5, size, F.brush, ci === 1 ? COL.gold : COL.paper, 1)) + }) + const bx = P ? W / 2 : W * 0.78, by = P ? H * 0.8 : H * 0.5 + seal(c, bx, by - (P ? 0 : 150 * u), 110 * u, '劝学', 1) + text(c, '荀子《劝学》', bx, by + (P ? 120 : 0) * u, 56 * u, F.kai, COL.paper, 1, 'center', 8 * u) + text(c, '7 分钟读懂学习的本质', bx, by + (P ? 190 : 70) * u, 34 * u, F.song, COL.gold, 1, 'center', 6 * u) + vignette(c, W, H); grain(c, W, H, 2, 0.06) + }, + }, + { + id: 'question', name: '设问 · 三把钥匙', + draw(c, W, H) { + const u = Math.min(W, H) / 1080, P = H > W + background(c, W, H) + mountains(c, W, H, 5, { seed: 21, alpha: 0.5, y: P ? 300 * u : 160 * u }) + const X = W / 2 + text(c, '为什么', X, P ? H * 0.17 : H * 0.17, 70 * u, F.song, COL.muted, 1, 'center', 20 * u, 700) + text(c, '学不可以已?', X, P ? H * 0.3 : H * 0.36, (P ? 150 : 170) * u, F.brush, COL.paper, 1, 'center', 6 * u) + const sz = (P ? 170 : 150) * u + ;['积', '恒', '专'].forEach((s, i) => { + const x = X + (i - 1) * sz * 1.45, y = P ? H * 0.53 : H * 0.62 + inkBlob(c, x, y, sz * 0.8, 120 + i, '#3e372e', 0.6, 0.3) + seal(c, x, y, sz, s, 1, (i - 1) * 0.05) + }) + text(c, '读懂荀子《劝学》的三层逻辑', X, P ? H * 0.7 : H * 0.83, 54 * u, F.kai, COL.gold, 1, 'center', 8 * u) + if (P) text(c, '高中语文 · 课文精讲', X, H * 0.77, 36 * u, F.song, COL.muted, 1, 'center', 10 * u) + vignette(c, W, H); grain(c, W, H, 3, 0.06) + }, + }, + { + id: 'sunrise', name: '日出 · 行者', + draw(c, W, H) { + const u = Math.min(W, H) / 1080, P = H > W + background(c, W, H) + const sy = H * (P ? 0.52 : 0.55) + const g = c.createLinearGradient(0, 0, 0, H) + g.addColorStop(0, 'rgba(0,0,0,0)'); g.addColorStop(0.55, 'rgba(170,110,55,0.35)'); g.addColorStop(1, 'rgba(0,0,0,0)') + c.fillStyle = g; c.fillRect(0, 0, W, H) + glow(c, W / 2, sy, Math.min(W, H) * 0.55, '#f6c46f', 0.6) + c.beginPath(); c.arc(W / 2, sy, Math.min(W, H) * 0.08, 0, Math.PI * 2); c.fillStyle = 'rgba(251,226,176,0.95)'; c.fill() + mountains(c, W, H, 4, { seed: 71, tint: '#7a6a55', y: P ? 200 * u : 60 * u }) + const pts: [number, number][] = [] + for (let i = 0; i <= 50; i++) { const q = i / 50; pts.push([W * (0.5 + 0.18 * Math.sin(q * 6) * (1 - q)), lerp(H, H * (P ? 0.66 : 0.68), Math.pow(q, 0.7))]) } + brush(c, pts, 30 * u, 1, '#d8c7a4', 0.35, 8, 0.4) + scholar(c, pts[18][0], pts[18][1], 90 * u, COL.paper, 0.95, 'walk', 0.3) + big(c, '劝学', W / 2, P ? H * 0.2 : H * 0.22, (P ? 230 : 200) * u, false, COL.paper) + text(c, '天性给出起点 学习决定远方', W / 2, P ? H * 0.32 : H * 0.4, 44 * u, F.kai, COL.gold, 1, 'center', 8 * u) + seal(c, W / 2 + (P ? 260 : 240) * u, P ? H * 0.17 : H * 0.17, 80 * u, '荀子', 1) + vignette(c, W, H); grain(c, W, H, 4, 0.05) + }, + }, +] + +export function renderCover(design: CoverDesign, ratio: Ratio, scale = 1) { + const [w, h] = RATIO_DIM[ratio] + const cv = makeCanvas(w * scale, h * scale) + design.draw(cv.getContext('2d')!, cv.width, cv.height) + return cv +} diff --git a/quanxue-src/src/quanxue/dev.tsx b/quanxue-src/src/quanxue/dev.tsx new file mode 100644 index 0000000000000000000000000000000000000000..a99b5ada086cdf83bec0aa1957fd5e9e8f23d03f --- /dev/null +++ b/quanxue-src/src/quanxue/dev.tsx @@ -0,0 +1,76 @@ +// 开发工具页(仅在带查询参数时启用):帧质检、配乐预渲染导出 +import { useEffect, useRef } from 'react' +import { loadFonts } from './fonts' +import { renderFrame } from './render' + +export function Still() { + const ref = useRef(null) + useEffect(() => { + const q = new URLSearchParams(location.search) + const ts = (q.get('still') || '10').split(',').map(Number) + const P = q.get('o') === 'p' + const W = P ? 540 : 960, H = P ? 960 : 540 + loadFonts().then(() => { + const c = ref.current! + c.width = W; c.height = H * Math.min(ts.length, 12) + const ctx = c.getContext('2d')! + const tmp = document.createElement('canvas'); tmp.width = W; tmp.height = H + const tc = tmp.getContext('2d', { willReadFrequently: true })! + const stats: any[] = [] + ts.forEach((t, i) => { + const t0 = performance.now() + renderFrame(tc, W, H, t) + const ms = performance.now() - t0 + if (i < 12) ctx.drawImage(tmp, 0, i * H) + const d = tc.getImageData(0, 0, W, H).data + let sum = 0, n = 0, x0 = W, y0 = H, x1 = 0, y1 = 0 + for (let y = 0; y < H; y += 2) for (let x = 0; x < W; x += 2) { + const k = (y * W + x) * 4, l = 0.3 * d[k] + 0.59 * d[k + 1] + 0.11 * d[k + 2] + sum += l + if (l > 140) { n++; if (x < x0) x0 = x; if (x > x1) x1 = x; if (y < y0) y0 = y; if (y > y1) y1 = y } + } + stats.push({ t, ms: Math.round(ms), mean: Math.round(sum / (W * H / 4)), bright: +(n / (W * H / 4) * 100).toFixed(2), box: n ? [x0, y0, x1, y1].map((v, j) => +(v / (j % 2 ? H : W)).toFixed(2)) : null }) + }) + ;(window as any).__stats = stats + ;(window as any).__done = true + }) + }, []) + return +} + +export function MusicDump() { + useEffect(() => { + import('./audio/music').then(async ({ renderMusic }) => { + const m = await renderMusic() + const L = m.getChannelData(0), R = m.getChannelData(1) + const pcm = new Int16Array(L.length * 2) + for (let i = 0; i < L.length; i++) { pcm[2 * i] = Math.max(-1, Math.min(1, L[i])) * 32767; pcm[2 * i + 1] = Math.max(-1, Math.min(1, R[i])) * 32767 } + const bytes = new Uint8Array(pcm.buffer) + ;(window as any).__chunk = (i: number, size: number) => { let s = ''; const sub = bytes.subarray(i * size, (i + 1) * size); for (let k = 0; k < sub.length; k += 8192) s += String.fromCharCode(...sub.subarray(k, k + 8192)); return btoa(s) } + ;(window as any).__stats = [{ bytes: bytes.length, sr: m.sampleRate }] + ;(window as any).__done = true + }) + }, []) + return
music dump
+} + +export function ExportTest() { + useEffect(() => { + (async () => { + const q = new URLSearchParams(location.search) + const [res, fps, a, b, por, mus] = (q.get('exporttest') || '720P,30,0,6,0,1').split(',') + const { engine } = await import('./ui/store') + const { exportMp4 } = await import('./exporter') + await loadFonts(); await engine.loadVoices() + const t0 = performance.now() + try { + const r = await exportMp4(engine, { res: res as any, fps: +fps as any, portrait: por === '1', music: mus === '1', range: [+a, +b] }, () => {}, { cancelled: false }) + const buf = new Uint8Array(await r.blob!.arrayBuffer()) + ;(window as any).__chunk = (i: number, size: number) => { let s = ''; const sub = buf.subarray(i * size, (i + 1) * size); for (let k = 0; k < sub.length; k += 8192) s += String.fromCharCode(...sub.subarray(k, k + 8192)); return btoa(s) } + ;(window as any).__stats = [{ bytes: buf.length, codec: r.codec, ms: Math.round(performance.now() - t0) }] + } catch (e: any) { (window as any).__stats = [{ error: String(e?.message || e) }] } + ;(window as any).__done = true + })() + }, []) + return
export test
+} diff --git a/quanxue-src/src/quanxue/engine/draw.ts b/quanxue-src/src/quanxue/engine/draw.ts new file mode 100644 index 0000000000000000000000000000000000000000..55d24a9367d8a1c7da899fdd0a482fb4592710be --- /dev/null +++ b/quanxue-src/src/quanxue/engine/draw.ts @@ -0,0 +1,407 @@ +// 绘制工具:纹理缓存、水墨晕染、毛笔笔触、竖排文字、印章、人物剪影、尘埃粒子 +import { clamp, easeOut, fbm1, fbm2, hash, lerp, noise1, rng, isPunct, type Rect } from './util' + +export type Ctx = CanvasRenderingContext2D + +export const COL = { + ink: '#0d0c0a', + ink2: '#191713', + paper: '#efe6d2', + muted: '#9d927f', + dim: '#5f574b', + gold: '#cfa961', + red: '#b8392b', + redDeep: '#8f2a20', + indigo: '#28508a', + ice: '#d5ecf2', + bamboo: '#b39a68', + wood: '#8a6440', +} +export const F = { + brush: '"qx-brush", "qx-kai", serif', + kai: '"qx-kai", serif', + song: '"qx-song", serif', + cao: '"qx-cao", "qx-kai", serif', +} +export const font = (size: number, fam: string, weight = 400) => `${weight} ${Math.max(1, size).toFixed(1)}px ${fam}` + +export function rgba(hex: string, a: number) { + const n = parseInt(hex.slice(1), 16) + return `rgba(${(n >> 16) & 255},${(n >> 8) & 255},${n & 255},${clamp(a)})` +} + +export function makeCanvas(w: number, h: number) { + const c = document.createElement('canvas') + c.width = Math.max(1, Math.round(w)); c.height = Math.max(1, Math.round(h)) + return c +} + +const cache = new Map() +export function cached(key: string, w: number, h: number, paint: (c: Ctx, w: number, h: number) => void) { + const k = `${key}@${Math.round(w)}x${Math.round(h)}` + let c = cache.get(k) + if (!c) { + if (cache.size > 160) cache.clear() + c = makeCanvas(w, h) + paint(c.getContext('2d')!, c.width, c.height) + cache.set(k, c) + } + return c +} + +// ---------------- 背景与氛围 ---------------- +export function background(ctx: Ctx, W: number, H: number, warm = 1) { + const tex = cached('bg', W, H, (c, w, h) => { + c.fillStyle = COL.ink; c.fillRect(0, 0, w, h) + // 低分辨率 fbm 云纹,放大后形成柔和的宣纸墨韵 + const sw = Math.ceil(w / 10), sh = Math.ceil(h / 10) + const small = makeCanvas(sw, sh), sc = small.getContext('2d')! + const img = sc.createImageData(sw, sh) + for (let y = 0; y < sh; y++) for (let x = 0; x < sw; x++) { + const v = (fbm2(x / sw * 4, y / sh * 4 * (h / w)) + 1) / 2 + const i = (y * sw + x) * 4 + img.data[i] = 40 + v * 18; img.data[i + 1] = 35 + v * 15; img.data[i + 2] = 28 + v * 11; img.data[i + 3] = 255 + } + sc.putImageData(img, 0, 0) + c.globalAlpha = 0.55; c.imageSmoothingQuality = 'high'; c.drawImage(small, 0, 0, w, h); c.globalAlpha = 1 + const g = c.createRadialGradient(w * 0.5, h * 0.42, 0, w * 0.5, h * 0.45, Math.max(w, h) * 0.75) + g.addColorStop(0, 'rgba(70,58,40,0.35)'); g.addColorStop(0.6, 'rgba(20,18,14,0)'); g.addColorStop(1, 'rgba(0,0,0,0.5)') + c.fillStyle = g; c.fillRect(0, 0, w, h) + }) + ctx.drawImage(tex, 0, 0, W, H) + if (warm !== 1) { ctx.fillStyle = `rgba(0,0,0,${clamp(1 - warm) * 0.6})`; ctx.fillRect(0, 0, W, H) } +} + +export function vignette(ctx: Ctx, W: number, H: number, k = 1) { + const tex = cached('vig', W, H, (c, w, h) => { + const g = c.createRadialGradient(w / 2, h / 2, Math.min(w, h) * 0.35, w / 2, h / 2, Math.hypot(w, h) * 0.62) + g.addColorStop(0, 'rgba(0,0,0,0)'); g.addColorStop(1, 'rgba(0,0,0,0.78)') + c.fillStyle = g; c.fillRect(0, 0, w, h) + }) + ctx.globalAlpha = k; ctx.drawImage(tex, 0, 0, W, H); ctx.globalAlpha = 1 +} + +const grainTiles: HTMLCanvasElement[] = [] +function grainTile(i: number) { + if (!grainTiles[i]) { + const s = 256, c = makeCanvas(s, s), g = c.getContext('2d')!, img = g.createImageData(s, s), r = rng(1000 + i) + for (let p = 0; p < s * s; p++) { const v = r() * 255; img.data[p * 4] = v; img.data[p * 4 + 1] = v; img.data[p * 4 + 2] = v; img.data[p * 4 + 3] = 255 } + g.putImageData(img, 0, 0); grainTiles[i] = c + } + return grainTiles[i] +} +const patterns = new WeakMap() +export function grain(ctx: Ctx, W: number, H: number, t: number, amt = 0.07) { + let ps = patterns.get(ctx) + if (!ps) { ps = [0, 1, 2, 3].map((i) => ctx.createPattern(grainTile(i), 'repeat')!); patterns.set(ctx, ps) } + const f = Math.floor(t * 24) + const p = ps[f % 4] + ctx.save() + ctx.globalCompositeOperation = 'overlay'; ctx.globalAlpha = amt + const scale = Math.max(1, Math.min(W, H) / 900) + ctx.translate((hash(f) * 256) | 0, (hash(f + 7) * 256) | 0) + ctx.scale(scale, scale) + ctx.fillStyle = p; ctx.fillRect(-256, -256, W / scale + 512, H / scale + 512) + ctx.restore() +} + +/** 漂浮尘埃(光中微尘) */ +export function dust(ctx: Ctx, W: number, H: number, t: number, n = 60, seed = 1, color = COL.paper, a = 0.5) { + const u = Math.min(W, H) / 1080 + for (let i = 0; i < n; i++) { + const s = seed * 100 + i + const sp = 0.004 + hash(s + 3) * 0.012 + const x = ((hash(s) + t * sp * 0.6 + noise1(t * 0.1 + s) * 0.03) % 1 + 1) % 1 + const y = ((hash(s + 1) - t * sp) % 1 + 1) % 1 + const tw = 0.35 + 0.65 * (0.5 + 0.5 * Math.sin(t * (0.6 + hash(s + 5)) + s)) + const r = (0.8 + hash(s + 2) * 2.2) * u + ctx.fillStyle = rgba(color, a * tw * (0.3 + hash(s + 4) * 0.7)) + ctx.beginPath(); ctx.arc(x * W, y * H, r, 0, Math.PI * 2); ctx.fill() + } +} + +/** 远山:程序化山脊 + 皴擦,预渲染缓存 */ +export function mountainLayer(W: number, H: number, seed: number, base: number, amp: number, color: string, alpha: number, freq = 2.2) { + return cached(`mt${seed}_${base}_${amp}_${color}_${alpha}_${freq}`, W * 1.3, H, (c, w, h) => { + const ridge = (x: number) => h * base - h * amp * (0.55 + 0.45 * fbm1(x / w * freq + seed * 3.1, 6)) - h * amp * 0.6 * Math.pow(Math.max(0, Math.sin((x / w) * Math.PI * (1.2 + (seed % 3) * 0.4) + seed)), 3) + c.beginPath(); c.moveTo(0, h) + for (let x = 0; x <= w; x += 3) c.lineTo(x, ridge(x)) + c.lineTo(w, h); c.closePath() + const g = c.createLinearGradient(0, h * (base - amp * 1.6), 0, h * Math.min(1, base + 0.25)) + g.addColorStop(0, rgba(color, alpha)); g.addColorStop(0.45, rgba(color, alpha * 0.55)); g.addColorStop(1, rgba(color, 0)) + c.fillStyle = g; c.fill() + // 皴擦纹理 + c.save(); c.clip() + const r = rng(seed * 77) + c.lineCap = 'round' + for (let i = 0; i < w / 4; i++) { + const x = r() * w, y0 = ridge(x) + r() * h * 0.02 + const len = h * (0.02 + r() * 0.12) + c.strokeStyle = rgba(color, alpha * (0.15 + r() * 0.35)) + c.lineWidth = 0.6 + r() * 1.6 + c.beginPath(); c.moveTo(x, y0); c.quadraticCurveTo(x + (r() - 0.5) * len * 0.5, y0 + len * 0.5, x + (r() - 0.5) * len * 0.8, y0 + len); c.stroke() + } + c.restore() + }) +} + +/** 绘制一组带视差与雾气的山 */ +export function mountains(ctx: Ctx, W: number, H: number, t: number, opts: { seed?: number; y?: number; drift?: number; alpha?: number; tint?: string } = {}) { + const seed = opts.seed ?? 1, dy = opts.y ?? 0, drift = opts.drift ?? 1, A = opts.alpha ?? 1 + const tint = opts.tint ?? '#8e8676' + const layers = [ + { b: 0.62, a: 0.2, c: tint, al: 0.22, sp: 0.004, f: 1.6 }, + { b: 0.72, a: 0.18, c: '#5d574c', al: 0.45, sp: 0.008, f: 2.0 }, + { b: 0.84, a: 0.16, c: '#2c2924', al: 0.85, sp: 0.014, f: 2.6 }, + ] + layers.forEach((L, i) => { + const tex = mountainLayer(W, H, seed + i, L.b, L.a, L.c, L.al, L.f) + const off = W * 0.12 * (1 - Math.cos(t * L.sp * drift * 5)) + W * 0.03 * i + ctx.globalAlpha = A + ctx.drawImage(tex, -off, dy * (i + 1) * 0.5, W * 1.3, H) + // 雾带 + const my = H * (L.b + 0.02) + dy * (i + 1) * 0.5 + const g = ctx.createLinearGradient(0, my - H * 0.08, 0, my + H * 0.1) + g.addColorStop(0, 'rgba(30,27,22,0)'); g.addColorStop(0.5, `rgba(48,43,36,${0.35 * A})`); g.addColorStop(1, 'rgba(30,27,22,0)') + ctx.fillStyle = g; ctx.fillRect(0, my - H * 0.08, W, H * 0.18) + }) + ctx.globalAlpha = 1 +} + +// ---------------- 水墨 ---------------- +/** 墨晕:不规则边缘 + 湿边沉积 */ +export function inkBlob(ctx: Ctx, x: number, y: number, r: number, seed: number, color: string, alpha: number, rough = 0.28, t = 0) { + if (r <= 0 || alpha <= 0) return + const N = 120 + const path = (rr: number, k: number) => { + ctx.beginPath() + for (let i = 0; i <= N; i++) { + const a = (i / N) * Math.PI * 2 + const n = fbm1(Math.cos(a) * 1.6 + Math.sin(a) * 0.9 + seed * 9.7 + k + t * 0.05, 5) + 0.35 * fbm1(a * 6 + seed + t * 0.1, 3) + const R = rr * (1 + rough * n) + const px = x + Math.cos(a) * R, py = y + Math.sin(a) * R + if (i === 0) ctx.moveTo(px, py); else ctx.lineTo(px, py) + } + ctx.closePath() + } + const layers = [[1.0, 0.22], [0.88, 0.25], [0.7, 0.3], [0.45, 0.35]] + layers.forEach(([s, a], i) => { path(r * s, i * 1.3); ctx.fillStyle = rgba(color, alpha * a); ctx.fill() }) + path(r * 0.985, 0); ctx.strokeStyle = rgba(color, alpha * 0.35); ctx.lineWidth = Math.max(1, r * 0.012); ctx.stroke() +} + +/** 毛笔笔触:沿路径的变宽带状多边形 + 飞白 */ +export function brush(ctx: Ctx, pts: [number, number][], width: number, progress: number, color: string, alpha = 1, seed = 1, dry = 0.5) { + if (pts.length < 2 || progress <= 0) return + const L: number[] = [0] + for (let i = 1; i < pts.length; i++) L.push(L[i - 1] + Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1])) + const total = L[L.length - 1], lim = total * clamp(progress) + const left: [number, number][] = [], right: [number, number][] = [], mids: { p: [number, number]; n: [number, number]; w: number }[] = [] + for (let i = 0; i < pts.length; i++) { + if (L[i] > lim && i > 0) { + const k = (lim - L[i - 1]) / Math.max(1e-6, L[i] - L[i - 1]) + const p: [number, number] = [lerp(pts[i - 1][0], pts[i][0], k), lerp(pts[i - 1][1], pts[i][1], k)] + pushPt(p, i, lim) + break + } + pushPt(pts[i], i, L[i]) + } + function pushPt(p: [number, number], i: number, s: number) { + const a = pts[Math.max(0, i - 1)], b = pts[Math.min(pts.length - 1, i + 1)] + let nx = -(b[1] - a[1]), ny = b[0] - a[0] + const nl = Math.hypot(nx, ny) || 1; nx /= nl; ny /= nl + const u = s / total + const prof = Math.min(1, u / 0.08 + 0.25) * Math.min(1, (1 - u) / 0.18 + 0.15) + const w = width * prof * (1 + 0.18 * noise1(s / width * 0.6 + seed * 13)) / 2 + left.push([p[0] + nx * w, p[1] + ny * w]); right.push([p[0] - nx * w, p[1] - ny * w]); mids.push({ p, n: [nx, ny], w }) + } + ctx.beginPath() + left.forEach((p, i) => (i ? ctx.lineTo(p[0], p[1]) : ctx.moveTo(p[0], p[1]))) + for (let i = right.length - 1; i >= 0; i--) ctx.lineTo(right[i][0], right[i][1]) + ctx.closePath(); ctx.fillStyle = rgba(color, alpha * 0.92); ctx.fill() + // 飞白:几条细的暗色擦痕 + if (dry > 0 && mids.length > 3) { + const r = rng(seed) + for (let k = 0; k < 7; k++) { + const off = (r() * 2 - 1) * 0.8, st = Math.floor(mids.length * (0.3 + r() * 0.5)) + ctx.beginPath() + for (let i = st; i < mids.length; i++) { const m = mids[i]; const px = m.p[0] + m.n[0] * m.w * off, py = m.p[1] + m.n[1] * m.w * off; i === st ? ctx.moveTo(px, py) : ctx.lineTo(px, py) } + ctx.strokeStyle = `rgba(13,12,10,${dry * (0.25 + r() * 0.4) * alpha})`; ctx.lineWidth = width * (0.02 + r() * 0.05); ctx.stroke() + } + } +} + +/** 二次贝塞尔采样为点列 */ +export function bez(p0: [number, number], p1: [number, number], p2: [number, number], n = 40): [number, number][] { + const out: [number, number][] = [] + for (let i = 0; i <= n; i++) { const t = i / n, a = (1 - t) * (1 - t), b = 2 * (1 - t) * t, c = t * t; out.push([a * p0[0] + b * p1[0] + c * p2[0], a * p0[1] + b * p1[1] + c * p2[1]]) } + return out +} + +// ---------------- 文字 ---------------- +/** 单字显现:由虚到实、由大到正,如墨落纸面 */ +export function revealChar(ctx: Ctx, ch: string, x: number, y: number, size: number, fam: string, color: string, r: number, alpha = 1) { + if (r <= 0 || alpha <= 0) return + const e = easeOut(r) + ctx.save() + ctx.translate(x, y) + const s = 1 + 0.12 * (1 - e) + ctx.scale(s, s) + ctx.font = font(size, fam) + ctx.textAlign = 'center'; ctx.textBaseline = 'middle' + if (r < 1) { ctx.shadowColor = rgba(color, 0.8); ctx.shadowBlur = size * 0.25 * (1 - e) } + ctx.fillStyle = rgba(color, alpha * e) + ctx.fillText(ch, 0, size * 0.04) + ctx.restore() +} + +export function text(ctx: Ctx, s: string, x: number, y: number, size: number, fam: string, color: string, alpha = 1, align: CanvasTextAlign = 'center', spacing = 0, weight = 400) { + if (alpha <= 0) return + ctx.font = font(size, fam, weight) + ctx.textAlign = align; ctx.textBaseline = 'middle' + ctx.fillStyle = rgba(color, alpha) + if (spacing) { + try { (ctx as any).letterSpacing = `${spacing}px` } catch { /* ignore */ } + ctx.fillText(s, x + (align === 'center' ? spacing / 2 : 0), y) + try { (ctx as any).letterSpacing = '0px' } catch { /* ignore */ } + } else ctx.fillText(s, x, y) +} + +/** 竖排一列文字(逐字可控显现) */ +export function vtext(ctx: Ctx, s: string, x: number, y: number, size: number, fam: string, color: string, alpha = 1, lead = 1.12, rev?: (i: number) => number) { + let k = 0 + for (const ch of s) { + if (isPunct(ch)) continue + revealChar(ctx, ch, x, y + k * size * lead, size, fam, color, rev ? rev(k) : 1, alpha) + k++ + } +} + +export type Col = { chars: { ch: string; i: number; mark?: 'stop' | 'pause' }[] } +/** 把一句古文切成竖排列:按小句合并,每列不超过 max 字;句读改为朱色圈点 */ +export function columns(textS: string, max: number): Col[] { + const clauses: { ch: string; i: number; mark?: 'stop' | 'pause' }[][] = [] + let cur: { ch: string; i: number; mark?: 'stop' | 'pause' }[] = [] + ;[...textS].forEach((ch, i) => { + if (isPunct(ch)) { + if (cur.length && ',、:'.includes(ch)) cur[cur.length - 1].mark = 'pause' + if (cur.length && '。;?!'.includes(ch)) cur[cur.length - 1].mark = 'stop' + if (',。;:?!、'.includes(ch) && cur.length) { clauses.push(cur); cur = [] } + return + } + cur.push({ ch, i }) + }) + if (cur.length) clauses.push(cur) + const cols: Col[] = [] + for (const c of clauses) { + const last = cols[cols.length - 1] + const lastStop = last && last.chars[last.chars.length - 1].mark === 'stop' + if (last && last.chars.length + c.length <= max && !lastStop) last.chars.push(...c) + else if (c.length > max) { for (let k = 0; k < c.length; k += max) cols.push({ chars: c.slice(k, k + max) }) } + else cols.push({ chars: [...c] }) + } + return cols +} + +// ---------------- 印章 ---------------- +export function seal(ctx: Ctx, x: number, y: number, s: number, label: string, alpha = 1, rot = 0, yang = false) { + if (alpha <= 0) return + const tex = cached(`seal_${label}_${yang ? 1 : 0}`, 256, 256, (c, w) => { + const r = rng(label.charCodeAt(0) * 31 + label.length) + const m = w * 0.06 + c.fillStyle = COL.red + c.beginPath() + const pts = 28 + for (let i = 0; i < pts; i++) { + const side = Math.floor(i / 7), k = (i % 7) / 7 + let px = 0, py = 0 + if (side === 0) { px = lerp(m, w - m, k); py = m } else if (side === 1) { px = w - m; py = lerp(m, w - m, k) } else if (side === 2) { px = lerp(w - m, m, k); py = w - m } else { px = m; py = lerp(w - m, m, k) } + px += (r() - 0.5) * w * 0.018; py += (r() - 0.5) * w * 0.018 + i ? c.lineTo(px, py) : c.moveTo(px, py) + } + c.closePath() + if (yang) { c.lineWidth = w * 0.05; c.strokeStyle = COL.red; c.stroke() } else c.fill() + const chars = [...label] + c.fillStyle = yang ? COL.red : '#f3e6d6' + c.textAlign = 'center'; c.textBaseline = 'middle' + if (chars.length === 1) { c.font = font(w * 0.7, F.brush); c.fillText(chars[0], w / 2, w / 2 + w * 0.03) } + else if (chars.length === 2) { c.font = font(w * 0.4, F.brush); c.fillText(chars[0], w / 2, w * 0.3); c.fillText(chars[1], w / 2, w * 0.72) } + else { c.font = font(w * 0.38, F.brush); const pos = [[0.72, 0.3], [0.72, 0.72], [0.28, 0.3], [0.28, 0.72]]; chars.slice(0, 4).forEach((ch, i) => c.fillText(ch, w * pos[i][0], w * pos[i][1] + w * 0.02)) } + // 印泥斑驳 + c.globalCompositeOperation = 'destination-out' + for (let i = 0; i < 260; i++) { c.globalAlpha = 0.2 + r() * 0.6; c.beginPath(); c.arc(r() * w, r() * w, r() * w * 0.012 + 0.5, 0, Math.PI * 2); c.fill() } + c.globalAlpha = 1; c.globalCompositeOperation = 'source-over' + }) + ctx.save(); ctx.translate(x, y); ctx.rotate(rot); ctx.globalAlpha = alpha + ctx.drawImage(tex, -s / 2, -s / 2, s, s) + ctx.restore() +} + +/** 落印动画:从放大到压下 */ +export function stamp(ctx: Ctx, x: number, y: number, s: number, label: string, p: number, rot = -0.04) { + if (p <= 0) return + const e = clamp(p / 0.35) + const sc = 1 + 0.6 * Math.pow(1 - e, 2) + seal(ctx, x, y, s * sc, label, clamp(e * 1.4), rot) +} + +// ---------------- 人物剪影(古代士人) ---------------- +export function scholar(ctx: Ctx, x: number, y: number, h: number, color: string, alpha = 1, pose: 'stand' | 'tiptoe' | 'walk' | 'wave' = 'stand', t = 0) { + if (alpha <= 0) return + ctx.save(); ctx.translate(x, y); ctx.fillStyle = rgba(color, alpha); ctx.strokeStyle = rgba(color, alpha) + const lift = pose === 'tiptoe' ? h * 0.04 : 0 + const sway = pose === 'walk' ? Math.sin(t * 4) * h * 0.012 : 0 + ctx.translate(sway, -lift) + // 衣袍 + ctx.beginPath() + ctx.moveTo(-h * 0.07, -h * 0.78) + ctx.quadraticCurveTo(-h * 0.13, -h * 0.4, -h * 0.17 + (pose === 'walk' ? Math.sin(t * 4) * h * 0.02 : 0), 0) + ctx.lineTo(h * 0.17, 0) + ctx.quadraticCurveTo(h * 0.13, -h * 0.4, h * 0.07, -h * 0.78) + ctx.closePath(); ctx.fill() + // 头与发髻 + ctx.beginPath(); ctx.arc(0, -h * 0.86, h * 0.07, 0, Math.PI * 2); ctx.fill() + ctx.beginPath(); ctx.arc(0, -h * 0.955, h * 0.03, 0, Math.PI * 2); ctx.fill() + // 衣袖/手臂 + ctx.lineCap = 'round'; ctx.lineWidth = h * 0.05 + ctx.beginPath() + if (pose === 'wave') { + const a = -1.2 + Math.sin(t * 5) * 0.25 + ctx.moveTo(h * 0.05, -h * 0.72); ctx.lineTo(h * 0.05 + Math.cos(a) * h * 0.32, -h * 0.72 + Math.sin(a) * h * 0.32) + } else { + ctx.moveTo(-h * 0.06, -h * 0.7); ctx.quadraticCurveTo(-h * 0.16, -h * 0.5, -h * 0.05, -h * 0.42) + ctx.moveTo(h * 0.06, -h * 0.7); ctx.quadraticCurveTo(h * 0.16, -h * 0.5, h * 0.05, -h * 0.42) + } + ctx.stroke() + ctx.restore() +} + +/** 细金线 */ +export function hairline(ctx: Ctx, x1: number, y1: number, x2: number, y2: number, p: number, color = COL.gold, a = 0.8, w = 1) { + if (p <= 0) return + const mx = (x1 + x2) / 2, my = (y1 + y2) / 2 + ctx.strokeStyle = rgba(color, a); ctx.lineWidth = w + ctx.beginPath(); ctx.moveTo(lerp(mx, x1, p), lerp(my, y1, p)); ctx.lineTo(lerp(mx, x2, p), lerp(my, y2, p)); ctx.stroke() +} + +/** 金色细框 */ +export function frame(ctx: Ctx, r: Rect, p: number, color = COL.gold, a = 0.6, w = 1) { + if (p <= 0) return + const per = 2 * (r.w + r.h), lim = per * clamp(p) + ctx.strokeStyle = rgba(color, a); ctx.lineWidth = w + ctx.beginPath(); ctx.moveTo(r.x, r.y) + const segs: [number, number][] = [[r.x + r.w, r.y], [r.x + r.w, r.y + r.h], [r.x, r.y + r.h], [r.x, r.y]] + let used = 0, px = r.x, py = r.y + for (const [qx, qy] of segs) { + const len = Math.hypot(qx - px, qy - py) + if (used + len >= lim) { const k = (lim - used) / len; ctx.lineTo(lerp(px, qx, k), lerp(py, qy, k)); break } + ctx.lineTo(qx, qy); used += len; px = qx; py = qy + } + ctx.stroke() +} + +export function glow(ctx: Ctx, x: number, y: number, r: number, color: string, a: number) { + if (a <= 0 || r <= 0) return + const g = ctx.createRadialGradient(x, y, 0, x, y, r) + g.addColorStop(0, rgba(color, a)); g.addColorStop(0.4, rgba(color, a * 0.35)); g.addColorStop(1, rgba(color, 0)) + ctx.fillStyle = g; ctx.fillRect(x - r, y - r, r * 2, r * 2) +} diff --git a/quanxue-src/src/quanxue/engine/util.ts b/quanxue-src/src/quanxue/engine/util.ts new file mode 100644 index 0000000000000000000000000000000000000000..c82525fe42f7fc36e1f13b76a9ca151ec633e00b --- /dev/null +++ b/quanxue-src/src/quanxue/engine/util.ts @@ -0,0 +1,65 @@ +// 数学、随机、噪声、缓动 —— 渲染引擎的基础工具(全部确定性,保证导出与播放画面一致) + +export const clamp = (v: number, a = 0, b = 1) => (v < a ? a : v > b ? b : v) +export const lerp = (a: number, b: number, t: number) => a + (b - a) * t +export const inv = (a: number, b: number, v: number) => clamp((v - a) / (b - a)) +export const smooth = (t: number) => { t = clamp(t); return t * t * (3 - 2 * t) } +export const easeOut = (t: number) => 1 - Math.pow(1 - clamp(t), 3) +export const easeIn = (t: number) => Math.pow(clamp(t), 3) +export const easeInOut = (t: number) => { t = clamp(t); return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2 } +export const easeOutExpo = (t: number) => (t >= 1 ? 1 : 1 - Math.pow(2, -10 * clamp(t))) +export const easeOutBack = (t: number) => { t = clamp(t); const c1 = 1.70158, c3 = c1 + 1; return 1 + c3 * Math.pow(t - 1, 3) + c1 * Math.pow(t - 1, 2) } +/** 在 [a, a+d] 区间内从 0 平滑到 1 */ +export const ramp = (t: number, a: number, d = 0.6) => smooth((t - a) / d) +/** 淡入淡出窗口 */ +export const win = (t: number, a: number, b: number, f = 0.5) => Math.min(ramp(t, a, f), 1 - ramp(t, b - f, f)) + +export function rng(seed: number) { + let s = seed >>> 0 + return () => { + s = (s + 0x6d2b79f5) >>> 0 + let t = s + t = Math.imul(t ^ (t >>> 15), t | 1) + t ^= t + Math.imul(t ^ (t >>> 7), t | 61) + return ((t ^ (t >>> 14)) >>> 0) / 4294967296 + } +} + +export function hash(n: number) { + const x = Math.sin(n * 127.1 + 311.7) * 43758.5453 + return x - Math.floor(x) +} +export function hash2(x: number, y: number) { + const v = Math.sin(x * 127.1 + y * 311.7) * 43758.5453 + return v - Math.floor(v) +} + +export function noise1(x: number) { + const i = Math.floor(x), f = x - i + const u = f * f * (3 - 2 * f) + return lerp(hash(i), hash(i + 1), u) * 2 - 1 +} +export function noise2(x: number, y: number) { + const ix = Math.floor(x), iy = Math.floor(y) + const fx = x - ix, fy = y - iy + const ux = fx * fx * (3 - 2 * fx), uy = fy * fy * (3 - 2 * fy) + const a = hash2(ix, iy), b = hash2(ix + 1, iy), c = hash2(ix, iy + 1), d = hash2(ix + 1, iy + 1) + return lerp(lerp(a, b, ux), lerp(c, d, ux), uy) * 2 - 1 +} +export function fbm1(x: number, oct = 5) { + let v = 0, a = 0.5, f = 1 + for (let i = 0; i < oct; i++) { v += a * noise1(x * f + i * 17.3); f *= 2.03; a *= 0.5 } + return v +} +export function fbm2(x: number, y: number, oct = 4) { + let v = 0, a = 0.5, f = 1 + for (let i = 0; i < oct; i++) { v += a * noise2(x * f + i * 7.1, y * f - i * 3.3); f *= 2.01; a *= 0.5 } + return v +} + +export type Rect = { x: number; y: number; w: number; h: number } +export const cx = (r: Rect) => r.x + r.w / 2 +export const cy = (r: Rect) => r.y + r.h / 2 + +export const PUNCT = new Set(',。;:、?!“”‘’《》()—…·「」 ,.;:!?') +export const isPunct = (ch: string) => PUNCT.has(ch) diff --git a/quanxue-src/src/quanxue/exporter.ts b/quanxue-src/src/quanxue/exporter.ts new file mode 100644 index 0000000000000000000000000000000000000000..2098584a7baf4441ded9f142bc79252e3a5c10fe --- /dev/null +++ b/quanxue-src/src/quanxue/exporter.ts @@ -0,0 +1,118 @@ +// 浏览器本地导出 MP4:逐帧离线渲染 → WebCodecs 编码(H.264 / AAC)→ Mediabunny 封装 +import { AudioSample, AudioSampleSource, BufferTarget, CanvasSource, Mp4OutputFormat, Output, StreamTarget, canEncodeAudio, canEncodeVideo, type AudioCodec, type VideoCodec } from 'mediabunny' +import { DURATION } from './timeline' +import { renderFrame } from './render' +import { mixChunk, type AudioEngine } from './audio/engine' + +export type Res = '2K' | '1080P' | '720P' +export type ExportOpts = { res: Res; fps: 24 | 30 | 60; portrait: boolean; music: boolean; range?: [number, number] } +export type Progress = { phase: string; p: number; frame: number; total: number; fps: number; eta: number } + +export const RES_DIM: Record = { '2K': [2560, 1440], '1080P': [1920, 1080], '720P': [1280, 720] } +const BASE_BITRATE: Record = { '2K': 10_000_000, '1080P': 6_000_000, '720P': 3_000_000 } + +export function dims(o: ExportOpts): [number, number] { + const [a, b] = RES_DIM[o.res] + return o.portrait ? [b, a] : [a, b] +} +export function bitrate(o: ExportOpts) { + return Math.round(BASE_BITRATE[o.res] * (o.fps === 60 ? 1.4 : o.fps === 24 ? 0.85 : 1)) +} +export function estimateMB(o: ExportOpts) { + const len = o.range ? o.range[1] - o.range[0] : DURATION + return Math.round(((bitrate(o) + 192_000) * len) / 8 / 1024 / 1024) +} + +let aacRegistered = false +export function webCodecsSupported() { + return typeof window !== 'undefined' && 'VideoEncoder' in window && 'AudioEncoder' in window +} + +export async function pickCodecs(o: ExportOpts): Promise<{ video: VideoCodec | null; audio: AudioCodec | null }> { + const [w, h] = dims(o) + let video: VideoCodec | null = null + for (const c of ['avc', 'hevc', 'vp9', 'av1'] as VideoCodec[]) { + try { if (await canEncodeVideo(c, { width: w, height: h, bitrate: bitrate(o), frameRate: o.fps })) { video = c; break } } catch { /* next */ } + } + let audio: AudioCodec | null = null + // 浏览器若无原生 AAC 编码(如 Linux / 部分 Firefox),按需加载 WASM 版 AAC 编码器,保证 MP4 音轨兼容所有播放器与平台 + try { + if (!aacRegistered && !(await canEncodeAudio('aac', { numberOfChannels: 2, sampleRate: 48000, bitrate: 192_000 }))) { + const { registerAacEncoder } = await import('@mediabunny/aac-encoder') + registerAacEncoder(); aacRegistered = true + } + } catch { /* 回退 Opus */ } + for (const c of ['aac', 'opus'] as AudioCodec[]) { + try { if (await canEncodeAudio(c, { numberOfChannels: 2, sampleRate: 48000, bitrate: 192_000 })) { audio = c; break } } catch { /* next */ } + } + return { video, audio } +} + +export async function exportMp4(engine: AudioEngine, o: ExportOpts, onProgress: (p: Progress) => void, signal: { cancelled: boolean }, fileHandle?: any): Promise<{ blob?: Blob; savedToDisk: boolean; codec: string }> { + const [w, h] = dims(o) + onProgress({ phase: '准备编码器', p: 0, frame: 0, total: 0, fps: 0, eta: 0 }) + const { video, audio } = await pickCodecs(o) + if (!video) throw new Error('当前浏览器不支持该分辨率/帧率的视频编码,请降低分辨率或帧率,或使用最新版 Chrome / Edge。') + if (o.music) { onProgress({ phase: '加载配乐', p: 0, frame: 0, total: 0, fps: 0, eta: 0 }); await engine.loadMusic() } + + const canvas = document.createElement('canvas') + canvas.width = w; canvas.height = h + const ctx = canvas.getContext('2d', { alpha: false })! + + let writable: any = null + let target: BufferTarget | StreamTarget + if (fileHandle) { writable = await fileHandle.createWritable(); target = new StreamTarget(writable, { chunked: true }) } + else target = new BufferTarget() + const output = new Output({ format: new Mp4OutputFormat({ fastStart: fileHandle ? false : 'in-memory' }), target }) + const vsrc = new CanvasSource(canvas, { codec: video, bitrate: bitrate(o), keyFrameInterval: 2 }) + output.addVideoTrack(vsrc, { frameRate: o.fps }) + let asrc: AudioSampleSource | null = null + if (audio) { asrc = new AudioSampleSource({ codec: audio, bitrate: 192_000 }); output.addAudioTrack(asrc) } + await output.start() + + const [r0, r1] = o.range ?? [0, DURATION] + const total = Math.ceil((r1 - r0) * o.fps) + const SR = 48000 + const mixSrc = engine.clips(o.music) + let audioSec = 0 + const audioLen = r1 - r0 + const pushAudio = async (upTo: number) => { + if (!asrc) return + while (audioSec < Math.min(upTo, audioLen)) { + const n = Math.min(SR, Math.ceil((audioLen - audioSec) * SR)) + const [L, R] = mixChunk(mixSrc, Math.round((r0 + audioSec) * SR), n, SR) + const data = new Float32Array(n * 2); data.set(L, 0); data.set(R, n) + const s = new AudioSample({ data, format: 'f32-planar', numberOfChannels: 2, sampleRate: SR, timestamp: audioSec }) + await asrc.add(s) + s.close() + audioSec += n / SR + } + } + + const tStart = performance.now() + try { + for (let i = 0; i < total; i++) { + if (signal.cancelled) throw new Error('cancelled') + const t = r0 + i / o.fps + renderFrame(ctx, w, h, t) + await vsrc.add(i / o.fps, 1 / o.fps) + if (i % o.fps === 0) await pushAudio(i / o.fps + 2) + if (i % 6 === 0) { + const el = (performance.now() - tStart) / 1000 + const fps = (i + 1) / Math.max(0.001, el) + onProgress({ phase: '渲染编码中', p: (i + 1) / total, frame: i + 1, total, fps, eta: (total - i - 1) / Math.max(0.1, fps) }) + if (i % 30 === 0) await new Promise((r) => setTimeout(r, 0)) + } + } + await pushAudio(audioLen + 1) + onProgress({ phase: '封装 MP4', p: 1, frame: total, total, fps: 0, eta: 0 }) + await output.finalize() + } catch (e) { + try { await output.cancel() } catch { /* ignore */ } + throw e + } + const codec = `${video === 'avc' ? 'H.264' : video.toUpperCase()} + ${audio ? audio.toUpperCase() : '无音轨'}` + if (fileHandle) return { savedToDisk: true, codec } + const buf = (target as BufferTarget).buffer! + return { blob: new Blob([buf], { type: 'video/mp4' }), savedToDisk: false, codec } +} diff --git a/quanxue-src/src/quanxue/fonts.ts b/quanxue-src/src/quanxue/fonts.ts new file mode 100644 index 0000000000000000000000000000000000000000..4321b33e79f770778fa7e417cba3f10d2113eb8b --- /dev/null +++ b/quanxue-src/src/quanxue/fonts.ts @@ -0,0 +1,24 @@ +// 自托管字体(子集化 woff2),全部加载完成后才开始绘制,保证导出画面字体正确 +const FAMS: [string, string, FontFaceDescriptors?][] = [ + ['qx-kai', 'qx-kai.woff2'], + ['qx-brush', 'qx-brush.woff2'], + ['qx-cao', 'qx-cao.woff2'], + ['qx-song', 'qx-song.woff2', { weight: '200 900' }], +] + +let ready: Promise | null = null +export function assetUrl(p: string) { + return `${import.meta.env.BASE_URL}quanxue/${p}` +} +export function loadFonts() { + if (!ready) { + ready = Promise.all( + FAMS.map(async ([name, file, desc]) => { + const f = new FontFace(name, `url(${assetUrl('fonts/' + file)}) format("woff2")`, desc) + await f.load() + document.fonts.add(f) + }), + ).then(() => undefined) + } + return ready +} diff --git a/quanxue-src/src/quanxue/publish.ts b/quanxue-src/src/quanxue/publish.ts new file mode 100644 index 0000000000000000000000000000000000000000..1c3a343fd525251f3d581ae42de08dd8ea5a0398 --- /dev/null +++ b/quanxue-src/src/quanxue/publish.ts @@ -0,0 +1,58 @@ +// 四个平台的发布文案(标题、描述、话题),字数与话题数按平台规则校验 +import { TL } from './timeline' + +export type Platform = { + id: string; name: string; color: string + titleMax: number; tagMax: number | null; hashTag: boolean + titles: string[]; desc: string; tags: string[] +} + +const fmt = (t: number) => `${String(Math.floor(t / 60)).padStart(2, '0')}:${String(Math.floor(t % 60)).padStart(2, '0')}` +const chapterIndex = () => TL.chapters.map((c) => `${fmt(c.start)} ${c.no === '终' ? '终章' : '第' + c.no + '章'} ${c.title.replace(/\s/g, '')}`).join('\n') + +export const PLATFORMS: Platform[] = [ + { + id: 'xhs', name: '小红书', color: '#ff2442', titleMax: 20, tagMax: 10, hashTag: true, + titles: ['荀子《劝学》精讲|学习为何不可停止', '7分钟读懂《劝学》:后天胜过先天', '高中必背《劝学》,原来这么深刻'], + desc: `📜 《劝学》不只是一篇必背课文,更是荀子写给所有人的一套“学习方法论”。 + +🔹 为什么“学不可以已”?荀子主张“人之性恶,其善者伪也”——“伪”不是虚伪,而是“人为”。善是后天学出来的,学习就是“化性起伪”。 +🔹 青出于蓝、輮木为轮:学习带来的改变是根本的、不可逆的。 +🔹 善假于物:君子生非异也,差别在于是否善于借助前人的智慧。 +🔹 积·恒·专:积土成山、锲而不舍、用心一也。 + +水墨动画逐句精讲,原文朱笔圈点,高一预习复习、背诵默写都用得上✍️ 先收藏,慢慢看。`, + tags: ['劝学', '荀子', '高中语文', '文言文', '必修上册', '课文精讲', '学习方法', '国学经典', '传统文化', '水墨动画'], + }, + { + id: 'dy', name: '抖音', color: '#25f4ee', titleMax: 30, tagMax: 5, hashTag: true, + titles: ['两千年前的学习方法论:荀子《劝学》7分钟精讲', '为什么学不可以已?读懂《劝学》背后的人性论', '锲而不舍,金石可镂|《劝学》全篇深度解读'], + desc: '荀子说“人之性恶,其善者伪也”——善不是天生的,是学出来的。从青出于蓝、輮木为轮,到善假于物、锲而不舍,7分钟水墨动画带你读懂《劝学》的三层逻辑。', + tags: ['劝学', '荀子', '高中语文', '文言文', '学习方法'], + }, + { + id: 'wx', name: '微信视频号', color: '#fa9d3b', titleMax: 16, tagMax: null, hashTag: true, + titles: ['《劝学》精讲:学不可以已', '荀子:善,是学出来的', '7分钟读懂荀子《劝学》'], + desc: '两千多年前,荀子把“学”放在全书之首。性恶论、化性起伪、善假于物、积恒专——一部水墨动画,讲透这篇必背名篇的深层逻辑。学不可以已,与君共勉。', + tags: ['劝学', '荀子', '高中语文', '文言文', '语文课', '课文讲解', '国学', '传统文化', '学习方法', '终身学习', '读书', '水墨动画'], + }, + { + id: 'bili', name: '哔哩哔哩', color: '#00aeec', titleMax: 80, tagMax: 10, hashTag: false, + titles: ['【高中语文·课文精讲】荀子《劝学》深度解读:从“性恶论”到“化性起伪”,读懂学习的本质|水墨动画', '两千年前的学习方法论:荀子《劝学》逐句精讲(青出于蓝·善假于物·锲而不舍)', '【水墨动画】7分钟读懂《劝学》:为什么“学不可以已”?'], + desc: `荀子《劝学》(统编版高中语文必修上册)深度精讲。 + +不止于翻译与背诵:本期从荀子的“性恶论”出发——“人之性恶,其善者伪也”,“伪”即“人为”——理解为什么荀子要把《劝学》放在全书三十二篇之首,再逐段拆解原文的三层论证: +① 学不可以已:青出于蓝、冰寒于水、輮木为轮——后天胜过先天,改变不可逆; +② 善假于物:登高而招、顺风而呼、舆马舟楫——君子生非异也; +③ 积·恒·专:积土成山、骐骥驽马、锲而不舍、蚓与蟹。 + +章节: +${chapterIndex()} + +解说文案原创,旁白为 AI 配音;画面、配乐(古琴·箫)与音效均为程序化原创生成。学不可以已,与君共勉。`, + tags: ['劝学', '荀子', '高中语文', '文言文', '课文讲解', '必修上册', '国学', '学习方法', '水墨动画', '知识分享'], + }, +] + +export const countChars = (s: string) => [...s].length +export const tagText = (p: Platform) => p.tags.map((t) => (p.hashTag ? `#${t}` : t)).join(p.hashTag ? ' ' : ',') diff --git a/quanxue-src/src/quanxue/quanxue.css b/quanxue-src/src/quanxue/quanxue.css new file mode 100644 index 0000000000000000000000000000000000000000..6c62bd2297e42cf47c210df82cae7266182558b4 --- /dev/null +++ b/quanxue-src/src/quanxue/quanxue.css @@ -0,0 +1,19 @@ + +.qx-root { + background: + radial-gradient(1200px 600px at 50% -10%, rgba(120, 92, 52, 0.18), transparent 60%), + radial-gradient(900px 500px at 100% 100%, rgba(184, 57, 43, 0.06), transparent 60%), + #0b0a08; + font-family: 'qx-song', 'Noto Serif SC', 'Songti SC', serif; +} +.qx-brush { font-family: 'qx-brush', 'qx-kai', 'Kaiti SC', 'STKaiti', serif; font-weight: 400; } +.qx-kai { font-family: 'qx-kai', 'Kaiti SC', 'STKaiti', serif; } +.qx-song { font-family: 'qx-song', 'Noto Serif SC', 'Songti SC', serif; } +.qx-seal { + display: inline-flex; align-items: center; justify-content: center; + width: 30px; height: 30px; background: #b8392b; color: #f3e6d6; border-radius: 3px; + font-family: 'qx-brush', serif; font-size: 20px; line-height: 1; box-shadow: inset 0 0 0 2px rgba(0,0,0,0.12); +} +.qx-noscroll::-webkit-scrollbar { display: none; } +.qx-noscroll { scrollbar-width: none; } +.qx-root ::selection { background: rgba(207, 169, 97, 0.35); } diff --git a/quanxue-src/src/quanxue/render.ts b/quanxue-src/src/quanxue/render.ts new file mode 100644 index 0000000000000000000000000000000000000000..edf9c418b735d702e0660e03db5bb1278d46c36c --- /dev/null +++ b/quanxue-src/src/quanxue/render.ts @@ -0,0 +1,214 @@ +// 帧合成:镜头 → 墨晕转场 → 引文竖排 → 字幕 → 章节标识 → 暗角 → 胶片颗粒 +import { TL, DURATION, keyT, getLine, shotAt, chapterAt, type Line, type Shot } from './timeline' +import { clamp, easeInOut, fbm1, ramp, smooth, type Rect } from './engine/util' +import { COL, F, background, columns, font, grain, makeCanvas, revealChar, rgba, text, vignette, type Col, type Ctx } from './engine/draw' +import { SCENES } from './scenes' + +export type SceneCtx = { + c: Ctx; W: number; H: number; u: number; P: boolean + t: number; lt: number; dur: number; shot: Shot + /** 镜头内相对时间:某句某词被念出的时刻 */ + k: (id: string, sub: string, off?: number) => number + ls: (id: string) => number + le: (id: string) => number + art: Rect; txt: Rect; full: Rect +} + +export function layout(W: number, H: number) { + const P = H > W + const art: Rect = P ? { x: 0.05 * W, y: 0.385 * H, w: 0.9 * W, h: 0.42 * H } : { x: 0.045 * W, y: 0.1 * H, w: 0.57 * W, h: 0.73 * H } + const txt: Rect = P ? { x: 0.08 * W, y: 0.085 * H, w: 0.84 * W, h: 0.27 * H } : { x: 0.645 * W, y: 0.12 * H, w: 0.3 * W, h: 0.66 * H } + const full: Rect = P ? { x: 0.06 * W, y: 0.12 * H, w: 0.88 * W, h: 0.68 * H } : { x: 0.06 * W, y: 0.1 * H, w: 0.88 * W, h: 0.72 * H } + return { P, art, txt, full } +} + +function sceneCtx(c: Ctx, W: number, H: number, t: number, shot: Shot): SceneCtx { + const L = layout(W, H) + return { + c, W, H, u: Math.min(W, H) / 1080, P: L.P, t, lt: t - shot.start, dur: shot.end - shot.start, shot, + k: (id, sub, off = 0) => keyT(id, sub, off) - shot.start, + ls: (id) => getLine(id).start - shot.start, + le: (id) => getLine(id).end - shot.start, + art: L.art, txt: L.txt, full: L.full, + } +} + +// ---------------- 引文:竖排、乌丝栏、朱色句读 ---------------- +const quoteCache = new Map() +function fitQuote(line: Line, r: Rect, sizeMax: number) { + const key = `${line.id}_${r.w | 0}_${r.h | 0}_${sizeMax | 0}` + let q = quoteCache.get(key) + if (q) return q + let size = sizeMax + for (let it = 0; it < 40; it++) { + const max = Math.max(3, Math.floor(r.h / (size * 1.13))) + const cols = columns(line.text, max) + const maxLen = Math.max(...cols.map((c) => c.chars.length)) + if (cols.length * size * 1.62 <= r.w || it === 39) { q = { size, cols, maxLen }; break } + size *= 0.95 + } + quoteCache.set(key, q!) + return q! +} + +export function drawQuote(S: SceneCtx, line: Line, r: Rect, opts: { sizeMax?: number; fam?: string; color?: string; alpha?: number } = {}) { + const { c, u } = S + const t = S.t + if (t < line.start - 0.4) return + const q = fitQuote(line, r, (opts.sizeMax ?? 74) * u) + const { size, cols, maxLen } = q + const pitch = size * 1.62 + const totalW = cols.length * pitch + const x0 = r.x + r.w / 2 + totalW / 2 - pitch / 2 + const y0 = r.y + (r.h - maxLen * size * 1.13) / 2 + size * 0.5 + const dim = 1 - 0.55 * ramp(t, line.end + 0.3, 1.0) + const A = (opts.alpha ?? 1) * dim * clamp((t - line.start + 0.4) / 0.4) + // 乌丝栏 + c.lineWidth = Math.max(1, u * 1.1) + for (let i = 0; i <= cols.length; i++) { + const x = x0 + pitch / 2 - i * pitch + const p = ramp(t, line.start - 0.3 + i * 0.05, 0.9) + const yTop = y0 - size * 0.75, yBot = y0 + maxLen * size * 1.13 - size * 0.25 + c.strokeStyle = rgba(COL.gold, 0.22 * A) + c.beginPath(); c.moveTo(x, yTop); c.lineTo(x, yTop + (yBot - yTop) * p); c.stroke() + } + const fam = opts.fam ?? F.kai + const color = opts.color ?? COL.paper + cols.forEach((col, ci) => { + const x = x0 - ci * pitch + col.chars.forEach((ch, k) => { + const y = y0 + k * size * 1.13 + const ct = line.charT[ch.i] + const rv = (t - ct + 0.06) / 0.45 + revealChar(c, ch.ch, x, y, size, fam, color, clamp(rv), A) + if (ch.mark && rv > 0.4) { + // 朱笔圈点 + c.strokeStyle = rgba(COL.red, 0.9 * A); c.fillStyle = rgba(COL.red, 0.9 * A); c.lineWidth = Math.max(1, size * 0.04) + c.beginPath() + if (ch.mark === 'stop') { c.arc(x + size * 0.56, y + size * 0.38, size * 0.075, 0, Math.PI * 2); c.stroke() } + else { c.arc(x + size * 0.56, y + size * 0.4, size * 0.05, 0, Math.PI * 2); c.fill() } + } + }) + }) + if (line.src) { + const lastX = x0 - (cols.length - 1) * pitch - pitch * 0.85 + const by = y0 + maxLen * size * 1.13 - size * 0.4 + c.save(); c.translate(lastX, by) + c.font = font(size * 0.34, F.song); c.textAlign = 'center'; c.textBaseline = 'bottom' + c.fillStyle = rgba(COL.gold, 0.85 * A * ramp(t, line.end - 0.5, 0.8)) + let yy = 0 + for (const chh of [...line.src].reverse()) { if ('《》·'.includes(chh)) continue; c.fillText(chh, 0, yy); yy -= size * 0.4 } + c.restore() + } +} + +// ---------------- 字幕 ---------------- +function drawSubtitle(c: Ctx, W: number, H: number, t: number) { + const P = H > W, u = Math.min(W, H) / 1080 + const line = TL.lines.find((l) => l.kind === 'say' && t >= l.start - 0.2 && t <= l.end + 0.4) + if (!line) return + const chunks = P ? line.chunksP : line.chunksL + const ch = chunks.find((k) => t >= k.start && t < k.end) + if (!ch) return + const a = Math.min(clamp((t - ch.start) / 0.18), clamp((ch.end - t) / 0.18)) + const y = P ? H * 0.868 : H * 0.895 + const size = (P ? 46 : 42) * u + // 柔和底衬 + const g = c.createLinearGradient(0, y - size * 1.6, 0, y + size * 1.6) + g.addColorStop(0, 'rgba(8,7,6,0)'); g.addColorStop(0.5, `rgba(8,7,6,${0.5 * a})`); g.addColorStop(1, 'rgba(8,7,6,0)') + c.fillStyle = g; c.fillRect(0, y - size * 1.6, W, size * 3.2) + c.save() + c.shadowColor = 'rgba(0,0,0,0.8)'; c.shadowBlur = size * 0.3 + text(c, ch.text, W / 2, y, size, F.kai, COL.paper, a * 0.96, 'center', size * 0.06) + c.restore() +} + +function drawHud(c: Ctx, W: number, H: number, t: number) { + const ci = chapterAt(t) + if (ci < 0) return + const ch = TL.chapters[ci] + const shot = TL.shots[shotAt(t)] + if (shot.vis === 'card') return + const a = 0.75 * Math.min(ramp(t, ch.start + 3.6, 1), 1 - ramp(t, ch.end - 0.6, 0.6)) + if (a <= 0) return + const P = H > W, u = Math.min(W, H) / 1080 + const x = P ? W / 2 : 72 * u, y = P ? 62 * u : 60 * u + const label = `${ch.no === '终' ? '终章' : '第' + ch.no + '章'} ${ch.title}` + c.save() + if (P) { + text(c, label, x, y, 24 * u, F.song, COL.gold, a, 'center', 6 * u) + } else { + c.fillStyle = rgba(COL.red, a); c.fillRect(x, y - 9 * u, 6 * u, 18 * u) + text(c, label, x + 20 * u, y, 24 * u, F.song, COL.gold, a, 'left', 6 * u) + text(c, '劝学 · 荀子', W - 72 * u, y, 22 * u, F.song, COL.muted, a * 0.8, 'right', 8 * u) + } + c.restore() +} + +// ---------------- 镜头渲染 ---------------- +function renderShot(c: Ctx, W: number, H: number, t: number, shot: Shot) { + const S = sceneCtx(c, W, H, t, shot) + const sc = SCENES[shot.vis] + c.save() + background(c, W, H) + // 缓慢推镜 + const zoom = 1 + 0.035 * smooth(S.lt / Math.max(1, S.dur)) * (sc?.zoom ?? 1) + c.translate(W / 2, H / 2); c.scale(zoom, zoom); c.translate(-W / 2, -H / 2) + if (sc) sc.draw(S) + if (shot.quote && !sc?.customQuote) drawQuote(S, shot.quote, S.txt, { sizeMax: sc?.quoteSize }) + c.restore() +} + +let layer: HTMLCanvasElement | null = null +function inkMask(c: Ctx, W: number, H: number, p: number, seed: number) { + if (p >= 1) { c.fillRect(0, 0, W, H); return } + const R = Math.hypot(W, H) * 0.62 + const centers = [[0.5 + 0.2 * Math.sin(seed * 3.1), 0.5 + 0.15 * Math.cos(seed * 1.7)], [0.18 + 0.1 * Math.sin(seed), 0.3], [0.82, 0.72 + 0.1 * Math.cos(seed)]] + centers.forEach(([x, y], i) => { + const pp = clamp((p - i * 0.12) / (1 - i * 0.12)) + const r = R * easeInOut(pp) * (i === 0 ? 1.1 : 0.8) + if (r <= 0) return + for (const [s, a] of [[1.12, 0.25], [1.05, 0.5], [1, 1]] as const) { + c.globalAlpha = a + c.beginPath() + for (let k = 0; k <= 90; k++) { + const ang = (k / 90) * Math.PI * 2 + const n = fbm1(Math.cos(ang) * 1.5 + Math.sin(ang) + seed * 5 + i * 9, 5) + const rr = r * s * (1 + 0.25 * n) + const px = x * W + Math.cos(ang) * rr, py = y * H + Math.sin(ang) * rr + k ? c.lineTo(px, py) : c.moveTo(px, py) + } + c.fill() + } + }) + c.globalAlpha = 1 +} + +const TR = 0.95 +export function renderFrame(c: Ctx, W: number, H: number, t: number) { + t = clamp(t, 0, DURATION) + const i = shotAt(t) + const shot = TL.shots[i] + const inTr = i > 0 && t < shot.start + TR + if (inTr) { + const prev = TL.shots[i - 1] + renderShot(c, W, H, t, prev) + if (!layer || layer.width !== W || layer.height !== H) layer = makeCanvas(W, H) + const L = layer.getContext('2d')! + L.globalCompositeOperation = 'source-over' + L.clearRect(0, 0, W, H) + renderShot(L, W, H, t, shot) + L.globalCompositeOperation = 'destination-in' + L.fillStyle = '#000' + inkMask(L, W, H, (t - shot.start) / TR, i) + L.globalCompositeOperation = 'source-over' + c.drawImage(layer, 0, 0) + } else renderShot(c, W, H, t, shot) + drawSubtitle(c, W, H, t) + drawHud(c, W, H, t) + vignette(c, W, H) + grain(c, W, H, t, 0.075) + // 首尾淡入淡出 + const fade = Math.max(1 - clamp(t / 0.8), clamp((t - (DURATION - 1.6)) / 1.6)) + if (fade > 0) { c.fillStyle = `rgba(0,0,0,${fade})`; c.fillRect(0, 0, W, H) } +} diff --git a/quanxue-src/src/quanxue/scenes.ts b/quanxue-src/src/quanxue/scenes.ts new file mode 100644 index 0000000000000000000000000000000000000000..81c47b3cceeb03c141c70967f3dad6c9dd60f64c --- /dev/null +++ b/quanxue-src/src/quanxue/scenes.ts @@ -0,0 +1,4 @@ +import { partA, type Scene } from './scenes/partA' +import { partB } from './scenes/partB' + +export const SCENES: Record = { ...partA, ...partB } diff --git a/quanxue-src/src/quanxue/scenes/partA.ts b/quanxue-src/src/quanxue/scenes/partA.ts new file mode 100644 index 0000000000000000000000000000000000000000..4bac47dbaf13f492bcdf818a36676cf966ae1bee --- /dev/null +++ b/quanxue-src/src/quanxue/scenes/partA.ts @@ -0,0 +1,678 @@ +// 场景(上):片头、章节卡、其人其书、思想底色、学不可以已 +import type { SceneCtx } from '../render' +import { TL } from '../timeline' +import { clamp, easeIn, easeInOut, easeOut, easeOutBack, easeOutExpo, fbm1, hash, lerp, noise1, ramp, rng, smooth, win, type Rect } from '../engine/util' +import { COL, F, bez, brush, dust, font, frame, glow, hairline, inkBlob, mountains, revealChar, rgba, seal, stamp, text, vtext, type Ctx } from '../engine/draw' + +export type Scene = { draw: (S: SceneCtx) => void; customQuote?: boolean; zoom?: number; quoteSize?: number } + +export const two = (r: Rect, gap = 0.06): [Rect, Rect] => { + if (r.w >= r.h * 0.9) { const w = r.w * (1 - gap) / 2; return [{ x: r.x, y: r.y, w, h: r.h }, { x: r.x + r.w - w, y: r.y, w, h: r.h }] } + const h = r.h * (1 - gap) / 2; return [{ x: r.x, y: r.y, w: r.w, h }, { x: r.x, y: r.y + r.h - h, w: r.w, h }] +} +export const mn = (r: Rect) => Math.min(r.w, r.h) + +export function ellipse(c: Ctx, x: number, y: number, rx: number, ry: number, fill?: string, stroke?: string, lw = 1) { + c.beginPath(); c.ellipse(x, y, Math.max(0.1, rx), Math.max(0.1, ry), 0, 0, Math.PI * 2) + if (fill) { c.fillStyle = fill; c.fill() } + if (stroke) { c.strokeStyle = stroke; c.lineWidth = lw; c.stroke() } +} +/** 面板底部标注 */ +export function caption(S: SceneCtx, r: Rect, s: string, a: number, color = COL.gold, dy = 0) { + text(S.c, s, r.x + r.w / 2, r.y + r.h - 18 * S.u + dy, 32 * S.u, F.kai, color, a, 'center', 4 * S.u) +} +/** 箭头 */ +export function arrow(c: Ctx, x1: number, y1: number, x2: number, y2: number, color: string, a: number, w: number) { + if (a <= 0) return + const ang = Math.atan2(y2 - y1, x2 - x1), hl = w * 6 + c.strokeStyle = rgba(color, a); c.lineWidth = w; c.lineCap = 'round' + c.beginPath(); c.moveTo(x1, y1); c.lineTo(x2, y2) + c.moveTo(x2, y2); c.lineTo(x2 - Math.cos(ang - 0.45) * hl, y2 - Math.sin(ang - 0.45) * hl) + c.moveTo(x2, y2); c.lineTo(x2 - Math.cos(ang + 0.45) * hl, y2 - Math.sin(ang + 0.45) * hl) + c.stroke() +} +/** 一笔圆相(ensō) */ +export function enso(c: Ctx, x: number, y: number, R: number, p: number, color: string, a: number, w: number, seed = 1, start = -Math.PI / 2) { + const pts: [number, number][] = [] + for (let i = 0; i <= 120; i++) { + const ang = start + (i / 120) * Math.PI * 2 * 0.94 + const rr = R * (1 + 0.025 * noise1(i * 0.15 + seed)) + pts.push([x + Math.cos(ang) * rr, y + Math.sin(ang) * rr]) + } + brush(c, pts, w, p, color, a, seed, 0.6) +} + +const CH_KEY = ['荀', '性', '学', '假', '积', '止'] + +export const partA: Record = { + // ---------- 片头 ---------- + title: { + zoom: 0.6, + draw(S) { + const { c, W, H, u, P, lt } = S + const m = Math.min(W, H) + dust(c, W, H, lt, 46, 3, COL.paper, 0.32) + const X = W / 2, Y = P ? H * 0.4 : H * 0.44 + if (lt < 1.62) { + const y = lerp(-0.05 * H, Y, easeIn(lt / 1.62)) + ellipse(c, X, y, 4.5 * u, 11 * u, rgba(COL.paper, 0.9)) + glow(c, X, y, 30 * u, COL.paper, 0.25) + } + for (let i = 0; i < 3; i++) { + const p = (lt - 1.62 - i * 0.28) / 2.4 + if (p > 0 && p < 1) ellipse(c, X, Y, p * 0.55 * m, p * 0.16 * m, undefined, rgba(COL.paper, 0.4 * (1 - p)), 1.4 * u) + } + const g = (lt - 1.62) / 3.6 + if (g > 0) { + inkBlob(c, X, Y, easeOutExpo(g) * 0.4 * m, 11, '#51473a', 0.85, 0.3, lt) + inkBlob(c, X + 0.05 * m, Y - 0.03 * m, easeOutExpo(g * 1.2) * 0.26 * m, 23, '#2c2720', 0.9, 0.35, lt) + glow(c, X, Y, 0.5 * m, COL.gold, 0.08 * easeOut(g)) + } + const size = (P ? 290 : 250) * u + ;['劝', '学'].forEach((ch, i) => { + const r = (lt - 2.3 - i * 0.42) / 1.15 + const x = P ? X : X + (i - 0.5) * size * 1.12 + const y = P ? Y + (i - 0.5) * size * 1.08 : Y + revealChar(c, ch, x, y, size, F.brush, COL.paper, clamp(r)) + }) + const sx = P ? X + size * 0.78 : X + size * 1.3, sy = P ? Y + size * 0.98 : Y + size * 0.36 + stamp(c, sx, sy, 96 * u, '荀子', lt - 4.55) + const a = ramp(lt, 5.1, 1.1) + const ty = P ? Y + size * 1.62 : Y + size * 0.98 + text(c, '《荀子》首篇 · 课文精讲', X, ty, 32 * u, F.song, COL.gold, a, 'center', 12 * u) + hairline(c, X - 520 * u, ty, X - 290 * u, ty, a, COL.gold, 0.5 * a, u) + hairline(c, X + 290 * u, ty, X + 520 * u, ty, a, COL.gold, 0.5 * a, u) + text(c, 'XUNZI · AN EXHORTATION TO LEARNING', X, ty + 54 * u, 15 * u, F.song, COL.muted, a * 0.75, 'center', 6 * u) + }, + }, + + // ---------- 章节卡 ---------- + card: { + zoom: 1.4, + draw(S) { + const { c, W, H, u, P, lt } = S + const ci = S.shot.chapter, ch = TL.chapters[ci] + mountains(c, W, H, lt + ci * 9, { seed: 10 + ci, alpha: 0.3, y: 40 * u }) + dust(c, W, H, lt, 40, 7 + ci, COL.gold, 0.25) + const m = Math.min(W, H) + c.save(); c.translate(W / 2, H * 0.47); c.scale(1 + lt * 0.02, 1 + lt * 0.02) + text(c, CH_KEY[ci], 0, 0, m * 0.95, F.cao, COL.paper, 0.06 * ramp(lt, 0, 1.4)) + c.restore() + const Y = P ? H * 0.46 : H * 0.48 + const a0 = ramp(lt, 0.2, 0.8) + const no = ch.no === '终' ? '终 章' : `第 ${ch.no} 章` + text(c, no, W / 2, Y - 150 * u, 30 * u, F.song, COL.gold, a0, 'center', 12 * u) + const chars = [...ch.title.replace(/\s/g, '')] + const adv = chars.map((cc) => (cc === '·' ? 0.7 : 1.08)) + const totalAdv = adv.reduce((a, b) => a + b, 0) + const size = Math.min((chars.length > 5 ? 112 : 136) * u, (W * 0.82) / totalAdv) + let acc = -totalAdv / 2 + chars.forEach((cc, i) => { + const x = W / 2 + (acc + adv[i] / 2) * size + acc += adv[i] + revealChar(c, cc, x, Y, size, F.brush, cc === '·' ? COL.gold : COL.paper, clamp((lt - 0.55 - i * 0.12) / 0.8)) + }) + const hl = ramp(lt, 1.3, 1) + hairline(c, W / 2 - 300 * u, Y + 110 * u, W / 2 + 300 * u, Y + 110 * u, hl, COL.gold, 0.6, u) + text(c, ch.sub, W / 2, Y + 160 * u, 30 * u, F.song, COL.muted, ramp(lt, 1.6, 0.9), 'center', 8 * u) + seal(c, W / 2, Y + 250 * u, 58 * u, ch.no, ramp(lt, 1.0, 0.4)) + }, + }, + + // ---------- 壹 · 其人其书 ---------- + era: { + draw(S) { + const { c, W, H, u, P, lt } = S + const sy = lerp(H * 0.42, H * 0.3, smooth(lt / S.dur)) + glow(c, W * 0.66, sy, 0.3 * Math.min(W, H), '#e9d7ad', 0.16) + ellipse(c, W * 0.66, sy, 46 * u, 46 * u, 'rgba(236,222,190,0.22)') + mountains(c, W, H, lt, { seed: 3, drift: 1.4, y: P ? 120 * u : 0 }) + // 飞鸟 + for (let i = 0; i < 7; i++) { + const bx = W * (0.2 + i * 0.05) + lt * 22 * u + hash(i) * 60 * u, by = H * (0.26 + hash(i + 9) * 0.08) + Math.sin(lt * 2 + i) * 6 * u + const f = Math.sin(lt * 6 + i * 2) * 4 * u + c.strokeStyle = rgba(COL.paper, 0.5); c.lineWidth = 1.6 * u + c.beginPath(); c.moveTo(bx - 9 * u, by - f); c.quadraticCurveTo(bx - 3 * u, by - 2 * u, bx, by); c.quadraticCurveTo(bx + 3 * u, by - 2 * u, bx + 9 * u, by - f); c.stroke() + } + const x = P ? W * 0.5 : W * 0.84, y = P ? H * 0.12 : H * 0.18 + vtext(c, '战国末年', x, y, 76 * u, F.brush, COL.paper, 1, 1.12, (i) => (lt - 0.6 - i * 0.18) / 0.7) + vtext(c, '约公元前三世纪', x - 74 * u, y + 10 * u, 24 * u, F.song, COL.gold, ramp(lt, 1.6, 1), 1.5) + const kj = S.k('c1l1', '稷下学宫') + const lx = P ? W * 0.5 : W * 0.3, ly = P ? H * 0.6 : H * 0.62 + seal(c, lx - 120 * u, ly, 64 * u, '齐', ramp(lt, kj - 0.2, 0.4)) + text(c, '稷下学宫', lx + 10 * u, ly, 54 * u, F.kai, COL.paper, ramp(lt, kj, 0.8), 'center', 10 * u) + text(c, '百家争鸣之所', lx + 10 * u, ly + 52 * u, 22 * u, F.song, COL.muted, ramp(lt, kj + 0.6, 0.8), 'center', 8 * u) + }, + }, + + person: { + draw(S) { + const { c, W, H, u, P, lt } = S + const m = Math.min(W, H) + text(c, '荀', P ? W * 0.5 : W * 0.25, P ? H * 0.32 : H * 0.48, m * 0.95, F.brush, COL.paper, 0.07 * ramp(lt, 0, 1.5)) + dust(c, W, H, lt, 30, 5, COL.gold, 0.25) + const cards = [ + { t: '荀况', s: '赵人 · 世称荀卿', k: S.k('c1l2', '荀况') }, + { t: '祭酒', s: '三为稷下学宫祭酒', k: S.k('c1l2', '三次出任') }, + { t: '门生', s: '韩非 · 李斯', k: S.k('c1l2', '韩非') }, + ] + cards.forEach((cd, i) => { + // 竖排从右往左:第一张在最右 + const r: Rect = P + ? { x: W * (0.69 - i * 0.29) - W * 0.12, y: H * 0.36, w: W * 0.24, h: H * 0.38 } + : { x: W * (0.84 - i * 0.15) - W * 0.06, y: H * 0.2, w: W * 0.12, h: H * 0.58 } + const a = ramp(lt, cd.k - 0.3, 0.7) + if (a <= 0) return + c.fillStyle = rgba('#1b1915', 0.75 * a); c.fillRect(r.x, r.y, r.w, r.h) + frame(c, r, ramp(lt, cd.k - 0.3, 1.2), COL.gold, 0.55, 1.2 * u) + frame(c, { x: r.x + 8 * u, y: r.y + 8 * u, w: r.w - 16 * u, h: r.h - 16 * u }, ramp(lt, cd.k, 1.2), COL.gold, 0.25, u) + const size = 78 * u + vtext(c, cd.t, r.x + r.w * 0.56, r.y + r.h * 0.22, size, F.brush, COL.paper, 1, 1.15, (j) => (lt - cd.k - j * 0.15) / 0.6) + vtext(c, cd.s.replace(/ · /g, '·').replace(/·/g, ''), r.x + r.w * 0.2, r.y + r.h * 0.2, 24 * u, F.song, COL.gold, ramp(lt, cd.k + 0.5, 0.8), 1.3) + seal(c, r.x + r.w * 0.56, r.y + r.h - 44 * u, 40 * u, ['荀', '酒', '师'][i], ramp(lt, cd.k + 0.8, 0.3)) + }) + }, + }, + + slips: { + draw(S) { + const { c, W, H, u, P, lt } = S + const k0 = S.k('c1l3', '三十二篇'), kq = S.k('c1l3', '劝学'), kd = S.k('c1l4', '宣言') + const rows = P ? 2 : 1, per = 32 / rows + const totalW = (P ? 0.9 : 0.86) * W + const sw = (totalW / per) * 0.74, gap = totalW / per + const sh = P ? H * 0.24 : H * 0.5 + const top = P ? H * 0.22 : H * 0.17 + const focus = ramp(lt, kq - 0.2, 0.9) + for (let j = 0; j < 32; j++) { + const row = Math.floor(j / per), col = j % per + const x = W / 2 + totalW / 2 - gap / 2 - col * gap + const y = top + row * (sh + H * 0.05) + const ap = ramp(lt, k0 - 1.6 + j * 0.05, 0.5) + if (ap <= 0) continue + const first = j === 0 + const lift = first ? -focus * 24 * u : 0 + const yy = y + (1 - easeOut(ap)) * 40 * u + lift + const alpha = ap * (first ? 1 : 1 - 0.65 * focus) + const g = c.createLinearGradient(x - sw / 2, 0, x + sw / 2, 0) + g.addColorStop(0, rgba('#7d6640', alpha)); g.addColorStop(0.5, rgba(first ? '#d8bf88' : COL.bamboo, alpha)); g.addColorStop(1, rgba('#6e5a38', alpha)) + c.fillStyle = g + c.beginPath(); c.roundRect(x - sw / 2, yy, sw, sh, sw * 0.18); c.fill() + // 简上墨迹 + const r = rng(j * 13 + 1) + if (!first) for (let q = 0; q < 14; q++) { c.fillStyle = `rgba(30,24,16,${0.35 * alpha})`; c.fillRect(x - sw * 0.16, yy + sh * (0.08 + q * 0.062), sw * (0.22 + r() * 0.12), sh * 0.02 + r() * sh * 0.012) } + if (first) { + glow(c, x, yy + sh / 2, sh * 0.7, COL.gold, 0.18 * focus) + vtext(c, '劝学篇第一', x, yy + sh * 0.12, Math.min(sw * 0.72, sh / 6.2), F.kai, '#2a2015', 1, 1.14, (q) => (lt - kq - q * 0.12) / 0.5) + } + } + // 编绳 + for (let row = 0; row < rows; row++) { + const y = top + row * (sh + H * 0.05) + for (const f of [0.14, 0.86]) { + c.strokeStyle = rgba('#3a2a1a', 0.85 * ramp(lt, k0 - 0.4, 0.8)); c.lineWidth = 2.2 * u + c.beginPath(); c.moveTo(W / 2 - totalW / 2, y + sh * f); c.lineTo(W / 2 + totalW / 2, y + sh * f); c.stroke() + } + } + const by = P ? top + 2 * sh + H * 0.12 : top + sh + H * 0.1 + text(c, '《荀子》 三十二篇', W / 2, by, 44 * u, F.kai, COL.paper, ramp(lt, k0, 0.8) * (1 - 0.5 * ramp(lt, kd - 1.5, 1)), 'center', 12 * u) + text(c, '西汉 刘向 校定 · 劝学居首', W / 2, by + 52 * u, 22 * u, F.song, COL.muted, ramp(lt, k0 + 1, 0.8) * (1 - ramp(lt, kd - 1.5, 1)), 'center', 6 * u) + const da = ramp(lt, kd - 0.3, 0.8) + if (da > 0) { + text(c, '一种思想的宣言', W / 2, by + 10 * u, 58 * u, F.brush, COL.gold, da, 'center', 16 * u) + } + }, + }, + + // ---------- 贰 · 思想底色 ---------- + ren: { + draw(S) { + const { c, W, H, u, P, lt } = S + const hasQ = lt > S.ls('c2l2') - 0.6 + const shift = easeInOut(ramp(lt, S.ls('c2l2') - 0.9, 1.2)) + const cxp = P ? W / 2 : lerp(W / 2, W * 0.33, shift) + const cyp = P ? lerp(H * 0.48, H * 0.6, shift) : H * 0.47 + const s = Math.min(W, H) * (P ? 0.46 : 0.5) * (1 - 0.12 * shift) + inkBlob(c, cxp, cyp, s * 0.9 * easeOutExpo(ramp(lt, 0.1, 2.5)), 41, '#3b352c', 0.55, 0.32, lt) + dust(c, W, H, lt, 36, 9, COL.paper, 0.3) + const s1 = bez([cxp + s * 0.06, cyp - s * 0.5], [cxp - s * 0.02, cyp + 0.05 * s], [cxp - s * 0.46, cyp + s * 0.44]) + const s2 = bez([cxp - s * 0.04, cyp - s * 0.1], [cxp + s * 0.12, cyp + s * 0.3], [cxp + s * 0.5, cyp + s * 0.44]) + brush(c, s1, s * 0.15, easeInOut(ramp(lt, 0.4, 1.0)), COL.paper, 0.95, 3, 0.7) + brush(c, s2, s * 0.17, easeInOut(ramp(lt, 1.25, 1.0)), COL.paper, 0.95, 7, 0.7) + text(c, '人', cxp, cyp + s * 0.72, 26 * u, F.song, COL.gold, ramp(lt, 2.2, 1) * (hasQ ? 0 : 1), 'center', 8 * u) + text(c, '荀子如何看“人”?', cxp, cyp + s * 0.72, 30 * u, F.song, COL.gold, ramp(lt, 2.2, 1) * (1 - shift), 'center', 8 * u) + }, + }, + + wei: { + draw(S) { + const { c, W, H, u, P, lt } = S + const size = Math.min(W, H) * 0.44 + const X = W / 2, Y = P ? H * 0.42 : H * 0.42 + const kx = S.k('c2l3', '不是虚伪'), kr = S.k('c2l3', '而是'), kh = S.k('c2l3', '后天') + const sp = easeInOut(ramp(lt, kr - 0.2, 1.1)) + inkBlob(c, X, Y, size * 0.75, 51, '#3a342b', 0.5 * (1 - sp * 0.5), 0.3, lt) + const ra = clamp(lt / 0.8) + c.font = font(size, F.brush); c.textAlign = 'center'; c.textBaseline = 'middle' + const off = sp * size * 0.32 + const split = X - size * 0.17 + c.save(); c.beginPath(); c.rect(0, 0, split, H); c.clip() + revealChar(c, '伪', X - off, Y, size, F.brush, sp > 0 ? COL.gold : COL.paper, ra) + c.restore() + c.save(); c.beginPath(); c.rect(split, 0, W - split, H); c.clip() + revealChar(c, '伪', X + off, Y, size, F.brush, COL.paper, ra) + c.restore() + // 虚伪 ✗ + const xa = win(lt, kx - 0.1, kr + 0.4, 0.4) + if (xa > 0) { + const qx = P ? X : X + size * 0.95, qy = P ? Y + size * 0.72 : Y + text(c, '虚伪', qx, qy, 48 * u, F.kai, COL.muted, xa, 'center', 6 * u) + c.strokeStyle = rgba(COL.red, xa); c.lineWidth = 4 * u + c.beginPath(); c.moveTo(qx - 60 * u, qy + 4 * u); c.lineTo(qx - 60 * u + 120 * u * ramp(lt, kx + 0.5, 0.4), qy - 4 * u); c.stroke() + } + const la = ramp(lt, kr + 0.4, 0.7) + const ly = Y + size * 0.72 + text(c, '人', X - off - size * 0.1, ly, 64 * u, F.kai, COL.gold, la) + text(c, '+', X, ly, 40 * u, F.song, COL.muted, la) + text(c, '为', X + off + size * 0.06, ly, 64 * u, F.kai, COL.paper, la) + text(c, '伪 = 人为 · 后天的努力与塑造', X, ly + 96 * u, 34 * u, F.song, COL.paper, ramp(lt, kh, 0.8), 'center', 6 * u) + }, + }, + + mengxun: { + draw(S) { + const { c, W, H, u, P, lt } = S + const km = S.k('c2l4', '孟子'), kx = S.k('c2l4', '荀子'), kw = S.k('c2l4', '向外求取') + const [A, B] = P ? [{ x: 0, y: H * 0.1, w: W, h: H * 0.36 }, { x: 0, y: H * 0.48, w: W, h: H * 0.36 }] : [{ x: W * 0.06, y: H * 0.12, w: W * 0.42, h: H * 0.68 }, { x: W * 0.52, y: H * 0.12, w: W * 0.42, h: H * 0.68 }] + // 分隔金线 + if (P) hairline(c, W * 0.2, H * 0.47, W * 0.8, H * 0.47, ramp(lt, 0, 1), COL.gold, 0.4, u) + else hairline(c, W / 2, H * 0.18, W / 2, H * 0.78, ramp(lt, 0, 1), COL.gold, 0.4, u) + // 孟子:向内 + const aa = ramp(lt, km - 0.3, 0.8) + const ax = A.x + A.w / 2, ay = A.y + A.h * 0.5, R = mn(A) * 0.3 + for (let i = 0; i < 6; i++) { + const p = ((lt * 0.22 + i / 6) % 1) + const r = R * (1 - p) + ellipse(c, ax, ay, r, r, undefined, rgba(COL.paper, aa * 0.4 * p), 1.3 * u) + } + glow(c, ax, ay, R * 0.6, COL.gold, 0.5 * aa) + ellipse(c, ax, ay, 7 * u, 7 * u, rgba(COL.gold, aa)) + text(c, '孟子 · 性善', ax, A.y + A.h * 0.08, 46 * u, F.kai, COL.paper, aa, 'center', 6 * u) + text(c, '善端本具 · 向内寻回', ax, A.y + A.h * 0.92, 28 * u, F.song, COL.muted, aa, 'center', 6 * u) + // 荀子:向外筑起 + const ba = ramp(lt, kx - 0.3, 0.8) + const bx = B.x + B.w / 2, base = B.y + B.h * 0.78 + const bw = mn(B) * 0.13, bh = bw * 0.42 + let n = 0 + for (let row = 0; row < 6; row++) { + const cnt = 6 - row + for (let q = 0; q < cnt; q++) { + const tb = kw - 0.8 + n * 0.11 + const p = ramp(lt, tb, 0.35) + n++ + if (p <= 0) continue + const x = bx + (q - (cnt - 1) / 2) * bw * 1.06, y = base - row * bh * 1.12 - (1 - easeOutBack(p)) * 30 * u + c.fillStyle = rgba('#2b2721', p * ba); c.fillRect(x - bw / 2, y - bh, bw, bh) + c.strokeStyle = rgba(COL.gold, 0.7 * p * ba); c.lineWidth = 1.2 * u; c.strokeRect(x - bw / 2, y - bh, bw, bh) + } + } + text(c, '荀子 · 性恶', bx, B.y + B.h * 0.08, 46 * u, F.kai, COL.paper, ba, 'center', 6 * u) + text(c, '欲望本能 · 向外筑起', bx, B.y + B.h * 0.92, 28 * u, F.song, COL.muted, ba, 'center', 6 * u) + }, + }, + + road: { + draw(S) { + const { c, W, H, u, P, lt } = S + mountains(c, W, H, lt, { seed: 21, alpha: 0.45, y: P ? 200 * u : 60 * u }) + const pts: [number, number][] = [] + for (let i = 0; i <= 80; i++) { + const t = i / 80 + if (P) pts.push([W * (0.5 + 0.18 * Math.sin(t * Math.PI * 2.2)), lerp(H * 0.8, H * 0.2, t)]) + else pts.push([lerp(W * 0.1, W * 0.9, t), H * (0.6 - 0.12 * t + 0.06 * Math.sin(t * Math.PI * 2.4))]) + } + const pp = easeInOut(ramp(lt, 0.3, 2.6)) + brush(c, pts, 10 * u, pp, COL.paper, 0.75, 5, 0.6) + for (let i = 1; i <= 4; i++) { + const p = pts[i * 16], a = ramp(lt, 0.6 + i * 0.5, 0.5) + ellipse(c, p[0], p[1], 7 * u, 7 * u, rgba(COL.gold, a)) + text(c, '学', p[0] + (P ? 44 * u : 0), p[1] - (P ? 0 : 42 * u), 30 * u, F.kai, COL.gold, a * 0.9) + } + const mv = smooth(ramp(lt, 1, S.dur - 2)) + const idx = Math.min(80, Math.floor(mv * 80)), dot = pts[idx] + glow(c, dot[0], dot[1], 60 * u, COL.gold, 0.55 * ramp(lt, 1, 0.6)) + ellipse(c, dot[0], dot[1], 6 * u, 6 * u, rgba('#fff3d6', ramp(lt, 1, 0.6))) + const k1 = S.k('c2l5', '自然之人'), k2 = S.k('c2l5', '文明之人') + const s0 = pts[0], s1 = pts[80] + text(c, '自然之人', s0[0] + (P ? 0 : 20 * u), s0[1] + 56 * u, 40 * u, F.kai, COL.muted, ramp(lt, k1, 0.7), P ? 'center' : 'left', 6 * u) + text(c, '文明之人', s1[0] - (P ? 0 : 20 * u), s1[1] - 56 * u, 46 * u, F.kai, COL.gold, ramp(lt, k2, 0.7), P ? 'center' : 'right', 6 * u) + const ky = S.k('c2l5', '唯一道路') + stamp(c, P ? W * 0.82 : W * 0.5, P ? H * 0.5 : H * 0.78, 70 * u, '唯一', lt - ky) + }, + }, + + huaxing: { + draw(S) { + const { c, W, H, u, P, lt } = S + const k0 = S.k('c2l6', '化性起伪'), kz = S.k('c2l6', '总纲') + const size = (P ? 190 : 180) * u + ;['化', '性', '起', '伪'].forEach((ch, i) => { + const x = P ? W / 2 : W / 2 + (i - 1.5) * size * 1.3 + const y = P ? H * 0.2 + i * size * 1.18 : H * 0.42 + const tt = k0 + 0.25 + i * 0.32 + const p = ramp(lt, tt - 0.1, 0.9) + inkBlob(c, x, y, size * 0.7 * easeOutExpo(p), 60 + i, i === 3 ? '#6e2a20' : '#3e382f', 0.75, 0.3, lt) + revealChar(c, ch, x, y, size, F.brush, i === 3 ? COL.gold : COL.paper, clamp((lt - tt) / 0.6)) + }) + const ty = P ? H * 0.2 + 4 * size * 1.18 : H * 0.68 + const a = ramp(lt, kz - 0.4, 0.9) + text(c, '《劝学》 即此道之总纲', W / 2, ty, 36 * u, F.song, COL.gold, a, 'center', 10 * u) + hairline(c, W / 2 - 340 * u, ty + 40 * u, W / 2 + 340 * u, ty + 40 * u, a, COL.gold, 0.4, u) + text(c, '化:改造本性  起:兴起人为', W / 2, ty + 80 * u, 24 * u, F.song, COL.muted, ramp(lt, kz + 0.4, 0.9), 'center', 6 * u) + }, + }, + + // ---------- 叁 · 学不可以已 ---------- + five: { + customQuote: true, + draw(S) { + const { c, W, H, u, P, lt } = S + const L = S.shot.lines[0] + const kz = S.k('c3l2', '斩钉截铁'), ks = S.k('c3l2', '不可以停止') + const shake = Math.exp(-Math.max(0, lt - kz) * 7) * (lt > kz ? 1 : 0) * 9 * u + c.save(); c.translate(noise1(lt * 40) * shake, noise1(lt * 40 + 9) * shake) + const size = (P ? 200 : 190) * u + const chars = '学不可以已' + const base = L.text.indexOf('学') + text(c, '君子曰', P ? W / 2 : W / 2, P ? H * 0.12 : H * 0.24, 44 * u, F.kai, COL.muted, ramp(lt, L.charT[0] - S.shot.start, 0.6), 'center', 14 * u) + for (let i = 0; i < 5; i++) { + const x = P ? W / 2 : W / 2 + (i - 2) * size * 1.12 + const y = P ? H * 0.22 + i * size * 1.1 : H * 0.47 + const ct = L.charT[base + i] - S.shot.start + revealChar(c, chars[i], x, y, size, F.brush, i === 4 ? COL.gold : COL.paper, clamp((lt - ct) / 0.6)) + } + // 斩钉截铁:朱笔 + const bp = easeOut(ramp(lt, kz, 0.5)) + if (bp > 0) { + const pts: [number, number][] = P + ? Array.from({ length: 30 }, (_, i) => [W / 2 + size * 0.72 + Math.sin(i * 0.2) * 4 * u, H * 0.22 + size * 0.6 + i / 29 * size * 3.9] as [number, number]) + : Array.from({ length: 30 }, (_, i) => [W / 2 - size * 1.4 + i / 29 * size * 4.0, H * 0.47 + size * 0.72 + Math.sin(i * 0.2) * 4 * u] as [number, number]) + brush(c, pts, 16 * u, bp, COL.red, 0.9, 4, 0.4) + glow(c, W / 2, H / 2, Math.max(W, H) * 0.6, COL.paper, 0.12 * Math.exp(-Math.max(0, lt - kz) * 4)) + } + const qa = ramp(lt, ks, 0.7) + const ax = P ? W / 2 - size * 0.9 : W / 2 + size * 2.24, ay = P ? H * 0.22 + 4 * size * 1.1 : H * 0.47 - size * 0.85 + text(c, '已:停止', ax, ay, 30 * u, F.song, COL.gold, qa, 'center', 6 * u) + c.restore() + }, + }, + + indigo: { + quoteSize: 76, + draw(S) { + const { c, u, lt } = S + const [A, B] = two(S.art) + const k1 = S.k('c3l3', '青'), k2 = S.k('c3l3', '而青于蓝'), k3 = S.k('c3l3', '冰'), k4 = S.k('c3l3', '而寒于水') + const kt = S.k('c3l4', '提炼'), kn = S.k('c3l4', '凝结') + // 蓝 → 青 + const ax = A.x + A.w / 2, ay = A.y + A.h * 0.44, R = mn(A) * 0.42 + const g = ramp(lt, k1 - 0.3, 3) + const deep = ramp(lt, k2 - 0.6, 1.8) + const col = deep > 0 ? mix('#7fa2c9', '#132a58', deep) : '#7fa2c9' + for (let i = 0; i < 3; i++) inkBlob(c, ax + Math.cos(lt * 0.3 + i * 2) * R * 0.12, ay + Math.sin(lt * 0.3 + i * 2) * R * 0.12, R * (0.55 + i * 0.18) * easeOutExpo(g), 70 + i, col, 0.55 - i * 0.12, 0.3, lt) + glow(c, ax, ay, R, '#5c86c4', 0.12 * g) + const sw = 34 * u, sy = A.y + A.h * 0.84 + const ca = ramp(lt, k2 - 0.2, 0.6) + c.fillStyle = rgba('#7fa2c9', ca); c.fillRect(ax - 110 * u, sy - sw / 2, sw, sw) + c.fillStyle = rgba('#132a58', ca); c.fillRect(ax + 76 * u, sy - sw / 2, sw, sw) + c.strokeStyle = rgba(COL.gold, ca * 0.7); c.lineWidth = u; c.strokeRect(ax + 76 * u, sy - sw / 2, sw, sw) + text(c, '蓝', ax - 93 * u, sy + 46 * u, 26 * u, F.kai, COL.muted, ca) + text(c, '青', ax + 93 * u, sy + 46 * u, 26 * u, F.kai, COL.paper, ca) + arrow(c, ax - 60 * u, sy, ax + 60 * u, sy, COL.gold, ca, 1.6 * u) + text(c, '提炼', ax, sy - 30 * u, 22 * u, F.song, COL.gold, ramp(lt, kt, 0.6)) + // 水 → 冰 + const bx = B.x + B.w / 2, by = B.y + B.h * 0.44, BR = mn(B) * 0.4 + const gi = easeOut(ramp(lt, k3 - 0.2, Math.max(1, k4 - k3 + 1.5))) + glow(c, bx, by, BR * 1.3, '#bfe3ee', 0.18 * gi) + c.strokeStyle = rgba(COL.ice, 0.9 * Math.min(1, gi * 3)); c.lineCap = 'round' + for (let arm = 0; arm < 6; arm++) { + const ang = arm * Math.PI / 3 - Math.PI / 2 + const len = BR * gi + c.lineWidth = 2.4 * u + c.beginPath(); c.moveTo(bx, by); c.lineTo(bx + Math.cos(ang) * len, by + Math.sin(ang) * len); c.stroke() + for (let b = 1; b <= 4; b++) { + const d = (b / 5) * BR + if (d > len) break + const bl = Math.min(len - d, BR * 0.32 * (1 - b / 6)) + const px = bx + Math.cos(ang) * d, py = by + Math.sin(ang) * d + c.lineWidth = 1.6 * u + for (const s of [-1, 1]) { + const a2 = ang + s * Math.PI / 3 + c.beginPath(); c.moveTo(px, py); c.lineTo(px + Math.cos(a2) * bl, py + Math.sin(a2) * bl); c.stroke() + } + } + } + const ia = ramp(lt, k4 - 0.2, 0.6) + c.fillStyle = rgba('#5b6f78', ia); c.fillRect(bx - 110 * u, sy - sw / 2, sw, sw) + c.fillStyle = rgba(COL.ice, ia); c.fillRect(bx + 76 * u, sy - sw / 2, sw, sw) + text(c, '水', bx - 93 * u, sy + 46 * u, 26 * u, F.kai, COL.muted, ia) + text(c, '冰', bx + 93 * u, sy + 46 * u, 26 * u, F.kai, COL.paper, ia) + arrow(c, bx - 60 * u, sy, bx + 60 * u, sy, COL.gold, ia, 1.6 * u) + text(c, '凝结', bx, sy - 30 * u, 22 * u, F.song, COL.gold, ramp(lt, kn, 0.6)) + }, + }, + + surpass: { + draw(S) { + const { c, W, H, u, P, lt } = S + const X = W / 2, Y = P ? H * 0.44 : H * 0.46, R = Math.min(W, H) * 0.17 + const kb = S.k('c3l5', '本来面目'), kc = S.k('c3l5', '超越'), kh = S.k('c3l5', '后天') + const a0 = ramp(lt, 0.2, 0.8) + const g = c.createRadialGradient(X, Y, 0, X, Y, R) + g.addColorStop(0, rgba('#6b6253', 0.8 * a0)); g.addColorStop(1, rgba('#3a352d', 0.6 * a0)) + ellipse(c, X, Y, R, R, undefined); c.fillStyle = g; c.fill() + text(c, '本来面目', X, Y, 36 * u, F.kai, COL.paper, ramp(lt, kb - 0.2, 0.6), 'center', 6 * u) + text(c, '先天', X, Y + 46 * u, 22 * u, F.song, COL.muted, ramp(lt, kb, 0.6), 'center', 6 * u) + const ep = easeInOut(ramp(lt, kc - 0.4, 1.6)) + enso(c, X, Y, R * 1.75, ep, COL.gold, 0.9, 22 * u, 5) + glow(c, X, Y, R * 2.4, COL.gold, 0.1 * ep) + text(c, '学而后成', X, Y - R * 1.75 - 46 * u, 32 * u, F.kai, COL.gold, ramp(lt, kc + 0.6, 0.7), 'center', 8 * u) + const ha = ramp(lt, kh - 0.2, 0.7) + const ty = Y + R * 1.75 + 96 * u + text(c, '后天', X - 110 * u, ty, 62 * u, F.brush, COL.gold, ha) + text(c, '>', X, ty, 44 * u, F.song, COL.paper, ha) + text(c, '先天', X + 110 * u, ty, 62 * u, F.brush, COL.muted, ha) + }, + }, + + wheel: { + quoteSize: 66, + draw(S) { + const { c, u, lt } = S + const r = S.art + const ax = r.x + r.w / 2, ay = r.y + r.h * 0.46, R = mn(r) * 0.3 + const kStraight = S.k('c3l6', '木直中绳'), kb = S.k('c3l6', '輮以为轮'), kg = S.k('c3l6', '其曲中规'), ks = S.k('c3l6', '虽有槁暴'), kr = S.ls('c3l7'), kn = S.k('c3l7', '也不会重新挺直') + const L = 2 * Math.PI * R * 0.97 + const p = easeInOut(ramp(lt, kb, 2.4)) + const th = p * Math.PI * 2 * 0.97 + const kap = Math.max(1e-5, th / L) + const rot = lt > kr ? (lt - kr) * 0.25 : 0 + const pts: [number, number][] = [] + for (let i = 0; i <= 90; i++) { + const s = (i / 90 - 0.5) * L + const ph = s * kap + let x = ax + Math.sin(ph) / kap, y = ay + R - (1 - Math.cos(ph)) / kap + if (rot) { const dx = x - ax, dy = y - ay; x = ax + dx * Math.cos(rot) - dy * Math.sin(rot); y = ay + dx * Math.sin(rot) + dy * Math.cos(rot) } + pts.push([x, y]) + } + // 墨线(绳) + const sa = win(lt, kStraight - 0.2, kb + 0.3, 0.4) + if (sa > 0) { + c.strokeStyle = rgba(COL.gold, 0.8 * sa); c.lineWidth = 1.4 * u; c.setLineDash([10 * u, 8 * u]) + c.beginPath(); c.moveTo(ax - L / 2 - 30 * u, ay + R - 26 * u); c.lineTo(ax + L / 2 + 30 * u, ay + R - 26 * u); c.stroke(); c.setLineDash([]) + text(c, '绳', ax - L / 2 - 50 * u, ay + R - 26 * u, 30 * u, F.kai, COL.gold, sa) + } + // 火 + const fa = win(lt, kb - 0.3, kb + 3.2, 0.5) + 0.35 * win(lt, S.k('c3l7', '用火烘烤') - 0.2, S.k('c3l7', '弯成车轮') + 0.6, 0.4) + if (fa > 0) { + c.save(); c.globalCompositeOperation = 'lighter' + for (let i = 0; i < 14; i++) { + const fx = ax + (hash(i) - 0.5) * R * 1.2, ph = (lt * (1.4 + hash(i + 3)) + hash(i + 5)) % 1 + const fy = ay + R + 60 * u - ph * 110 * u + glow(c, fx + noise1(lt * 3 + i) * 10 * u, fy, (34 - ph * 24) * u, ph < 0.5 ? '#ff9a3c' : '#c4421f', 0.5 * fa * (1 - ph)) + } + c.restore() + } + // 木 + c.lineCap = 'round' + c.strokeStyle = rgba('#5d4026', 1); c.lineWidth = 30 * u + c.beginPath(); pts.forEach((q, i) => (i ? c.lineTo(q[0], q[1]) : c.moveTo(q[0], q[1]))); c.stroke() + c.strokeStyle = rgba('#a77d4f', 0.95); c.lineWidth = 22 * u; c.stroke() + c.strokeStyle = rgba('#d4ad78', 0.45); c.lineWidth = 3 * u; c.stroke() + // 辐条 + const spk = ramp(lt, kg - 0.2, 1.4) + if (spk > 0 && p > 0.98) { + const n = 12 + for (let i = 0; i < n; i++) { + const a = rot + (i / n) * Math.PI * 2, e = clamp(spk * n - i) + if (e <= 0) continue + c.strokeStyle = rgba('#8c6640', e); c.lineWidth = 6 * u + c.beginPath(); c.moveTo(ax + Math.cos(a) * R * 0.14, ay + Math.sin(a) * R * 0.14); c.lineTo(ax + Math.cos(a) * R * (0.14 + 0.82 * e), ay + Math.sin(a) * R * (0.14 + 0.82 * e)); c.stroke() + } + ellipse(c, ax, ay, R * 0.15, R * 0.15, rgba('#6e4c2e', spk), rgba('#d4ad78', 0.6 * spk), 2 * u) + // 规 + c.setLineDash([6 * u, 9 * u]); ellipse(c, ax, ay, R * 1.14, R * 1.14, undefined, rgba(COL.gold, 0.6 * win(lt, kg, ks + 1.5, 0.5)), 1.4 * u); c.setLineDash([]) + text(c, '规', ax + R * 1.22, ay - R * 0.9, 30 * u, F.kai, COL.gold, win(lt, kg, ks + 1.5, 0.5)) + } + // 槁暴:日晒风干 + const sa2 = win(lt, ks - 0.2, kr + 1, 0.6) + if (sa2 > 0) { + glow(c, r.x + r.w * 0.86, r.y + r.h * 0.1, R * 0.9, '#f2c46d', 0.5 * sa2) + for (let i = 0; i < 5; i++) { + const yy = r.y + r.h * (0.25 + i * 0.12), xx = r.x + ((lt * 0.3 + i * 0.23) % 1) * r.w + c.strokeStyle = rgba(COL.paper, 0.25 * sa2); c.lineWidth = 1.2 * u + c.beginPath(); c.moveTo(xx, yy); c.bezierCurveTo(xx + 40 * u, yy - 8 * u, xx + 80 * u, yy + 8 * u, xx + 130 * u, yy); c.stroke() + } + } + stamp(c, ax, ay + R + 90 * u, 70 * u, '不复', lt - kn) + }, + }, + + reshape: { + draw(S) { + const { c, W, H, u, P, lt } = S + const kg = S.k('c3l8', '根本的'), kt = S.k('c3l8', '涂上'), kz = S.k('c3l8', '重塑') + text(c, '根本 · 不可逆', W / 2, P ? H * 0.16 : H * 0.17, 64 * u, F.brush, COL.paper, ramp(lt, kg - 0.2, 0.8), 'center', 16 * u) + const [A, B] = two(P ? { x: W * 0.06, y: H * 0.28, w: W * 0.88, h: H * 0.5 } : { x: W * 0.12, y: H * 0.28, w: W * 0.76, h: H * 0.54 }) + const shape = (x: number, y: number, R: number, m: number, seed: number) => { + c.beginPath() + for (let i = 0; i <= 100; i++) { + const a = (i / 100) * Math.PI * 2 + const rr = R * (1 + (1 - m) * 0.32 * fbm1(Math.cos(a) * 1.3 + Math.sin(a) + seed, 4)) + const px = x + Math.cos(a) * rr, py = y + Math.sin(a) * rr + i ? c.lineTo(px, py) : c.moveTo(px, py) + } + c.closePath() + } + const aa = ramp(lt, kt - 0.4, 0.6), dimA = 1 - 0.55 * ramp(lt, kz - 0.2, 0.8) + const ax = A.x + A.w / 2, ay = A.y + A.h * 0.45, R = mn(A) * 0.3 + shape(ax, ay, R, 0, 3); c.fillStyle = rgba('#4d463b', aa * dimA); c.fill() + c.strokeStyle = rgba('#6f9ad0', aa * dimA * ramp(lt, kt, 0.9)); c.lineWidth = 7 * u; c.stroke() + caption(S, A, '涂上一层颜色', aa * dimA, COL.muted) + const ba = ramp(lt, kz - 0.4, 0.6) + const m = easeInOut(ramp(lt, kz, 2.2)) + const bx = B.x + B.w / 2, by = B.y + B.h * 0.45 + glow(c, bx, by, R * 1.8, COL.gold, 0.15 * m * ba) + shape(bx, by, R, m, 3) + const gg = c.createRadialGradient(bx - R * 0.3, by - R * 0.3, 0, bx, by, R * 1.2) + gg.addColorStop(0, rgba('#f3e7cc', ba)); gg.addColorStop(1, rgba('#a88a55', ba)) + c.fillStyle = gg; c.fill() + caption(S, B, '重塑人的形状', ba, COL.gold) + }, + }, + + rope: { + quoteSize: 62, + draw(S) { + const { c, u, lt } = S + const [A, B] = two(S.art) + const k1 = S.k('c3l9', '木受绳'), k2 = S.k('c3l9', '金就砺') + // 绳墨 + const aa = ramp(lt, k1 - 0.5, 0.6) + const px = A.x + A.w * 0.1, pw = A.w * 0.8, py = A.y + A.h * 0.5, ph = mn(A) * 0.13 + const g = c.createLinearGradient(0, py - ph / 2, 0, py + ph / 2) + g.addColorStop(0, rgba('#a9824f', aa)); g.addColorStop(1, rgba('#6b4b2a', aa)) + c.fillStyle = g; c.fillRect(px, py - ph / 2, pw, ph) + for (let i = 0; i < 9; i++) { c.strokeStyle = rgba('#4a321c', 0.4 * aa); c.lineWidth = u; c.beginPath(); c.moveTo(px, py - ph / 2 + ph * (i + 0.5) / 9 + Math.sin(i) * 2 * u); for (let x = 0; x <= pw; x += 20 * u) c.lineTo(px + x, py - ph / 2 + ph * (i + 0.5) / 9 + Math.sin(x * 0.01 + i) * 3 * u); c.stroke() } + const snap = k1 + 0.9 + const before = lt < snap + const amp = before ? 24 * u * Math.sin(Math.max(0, lt - k1 + 0.3) * 30) * ramp(lt, k1 - 0.3, 0.3) : 0 + c.strokeStyle = rgba('#141210', aa); c.lineWidth = 2.5 * u + c.beginPath(); c.moveTo(px - 10 * u, py - (before ? ph : 0)); c.quadraticCurveTo(px + pw / 2, py - (before ? ph : 0) + amp, px + pw + 10 * u, py - (before ? ph : 0)); c.stroke() + if (!before) { c.strokeStyle = rgba('#0b0a09', aa); c.lineWidth = 4 * u; c.beginPath(); c.moveTo(px, py); c.lineTo(px + pw, py); c.stroke() } + caption(S, A, '木受绳则直', aa) + // 金就砺 + const ba = ramp(lt, k2 - 0.5, 0.6) + const sx = B.x + B.w / 2, sy = B.y + B.h * 0.56, sw = B.w * 0.7, sh2 = mn(B) * 0.1 + c.fillStyle = rgba('#3d3b38', ba); c.beginPath(); c.roundRect(sx - sw / 2, sy, sw, sh2, 8 * u); c.fill() + const slide = Math.sin(Math.max(0, lt - k2) * 3.2) * sw * 0.18 + const bl = sw * 0.62 + const x0 = sx - bl / 2 + slide, y0 = sy - 4 * u + const bg = c.createLinearGradient(0, y0 - 40 * u, 0, y0) + bg.addColorStop(0, rgba('#8e9499', ba)); bg.addColorStop(1, rgba('#e8eef2', ba)) + c.fillStyle = bg + c.beginPath(); c.moveTo(x0, y0); c.lineTo(x0 + bl, y0); c.lineTo(x0 + bl - 20 * u, y0 - 34 * u); c.lineTo(x0 + 10 * u, y0 - 38 * u); c.closePath(); c.fill() + c.fillStyle = rgba('#3a2a1c', ba); c.fillRect(x0 - 60 * u, y0 - 34 * u, 62 * u, 26 * u) + const shine = ramp(lt, k2 + 0.4, 2.5) + glow(c, x0 + bl * ((lt * 0.6) % 1), y0 - 2 * u, 40 * u, '#ffffff', 0.5 * shine * ba) + if (lt > k2) { + c.save(); c.globalCompositeOperation = 'lighter' + for (let i = 0; i < 16; i++) { + const ph = (lt * 2 + hash(i)) % 1 + const spx = x0 + bl * 0.5 + (hash(i + 2) - 0.5) * bl * 0.8 + ph * 60 * u * (hash(i + 7) - 0.5) * 2, spy = y0 - ph * 50 * u + ph * ph * 80 * u + glow(c, spx, spy, 6 * u, '#ffc77a', ba * (1 - ph)) + } + c.restore() + } + caption(S, B, '金就砺则利', ba) + }, + }, + + rings: { + draw(S) { + const { c, W, H, u, P, lt } = S + const X = W / 2, Y = P ? H * 0.45 : H * 0.47, R = Math.min(W, H) * 0.29 + const kn = S.k('c3l10', '绳墨'), kb = S.k('c3l10', '博学'), kc = S.k('c3l10', '参省'), kz = S.k('c3l10', '知与行') + const sa = ramp(lt, kn - 0.2, 0.7) * (1 - 0.6 * ramp(lt, kb, 0.8)) + vtext(c, '绳墨', P ? W * 0.14 : W * 0.2, Y - 60 * u, 48 * u, F.kai, COL.muted, sa) + vtext(c, '砺石', P ? W * 0.86 : W * 0.8, Y - 60 * u, 48 * u, F.kai, COL.muted, sa) + text(c, '外在的规范', W / 2, P ? H * 0.12 : H * 0.12, 30 * u, F.song, COL.muted, sa, 'center', 10 * u) + const oa = ramp(lt, kb - 0.3, 0.8) + c.setLineDash([3 * u, 9 * u]); ellipse(c, X, Y, R, R, undefined, rgba(COL.paper, 0.6 * oa), 1.6 * u); c.setLineDash([]) + for (let i = 0; i < 12; i++) { + const a = (i / 12) * Math.PI * 2 + lt * 0.05 + const d = R + 10 * u + ((lt * 30 * u + i * 7) % (40 * u)) + arrow(c, X + Math.cos(a) * (R + 6 * u), Y + Math.sin(a) * (R + 6 * u), X + Math.cos(a) * d, Y + Math.sin(a) * d, COL.paper, 0.45 * oa, 1.4 * u) + } + text(c, '博学 · 向外求知', X, Y - R - 64 * u, 34 * u, F.kai, COL.paper, oa, 'center', 6 * u) + const ia = ramp(lt, kc - 0.3, 0.8) + const sp = ramp(lt, kc - 0.3, 2.2) + c.strokeStyle = rgba(COL.gold, 0.85 * ia); c.lineWidth = 2 * u + c.beginPath() + const turns = 2.6, N = Math.floor(180 * sp) + for (let i = 0; i <= N; i++) { const q = i / 180, a = -Math.PI / 2 + q * turns * Math.PI * 2 + lt * 0.15, rr = R * 0.66 * (1 - q * 0.9); const px = X + Math.cos(a) * rr, py = Y + Math.sin(a) * rr; i ? c.lineTo(px, py) : c.moveTo(px, py) } + c.stroke() + text(c, '参省 · 向内反省', X, Y + R + 64 * u, 34 * u, F.kai, COL.gold, ia, 'center', 6 * u) + const za = ramp(lt, kz - 0.2, 0.8) + glow(c, X, Y, R * 0.6, COL.gold, 0.35 * za) + text(c, '知行', X, Y, 96 * u, F.brush, COL.paper, za, 'center', 8 * u) + }, + }, +} + +function mix(a: string, b: string, t: number) { + const pa = parseInt(a.slice(1), 16), pb = parseInt(b.slice(1), 16) + const ch = (s: number) => Math.round(lerp((pa >> s) & 255, (pb >> s) & 255, clamp(t))) + return '#' + ((ch(16) << 16) | (ch(8) << 8) | ch(0)).toString(16).padStart(6, '0') +} +export { mix } diff --git a/quanxue-src/src/quanxue/scenes/partB.ts b/quanxue-src/src/quanxue/scenes/partB.ts new file mode 100644 index 0000000000000000000000000000000000000000..a55427cbd7185a83610d158d8d5305b93a685e95 --- /dev/null +++ b/quanxue-src/src/quanxue/scenes/partB.ts @@ -0,0 +1,697 @@ +// 场景(下):善假于物、积恒专、结语、片尾 +import type { SceneCtx } from '../render' +import { carveStrikes, getLine } from '../timeline' +import { clamp, easeInOut, easeOut, easeOutExpo, fbm1, hash, lerp, noise1, ramp, rng, smooth, win, type Rect } from '../engine/util' +import { COL, F, brush, cached, dust, font, glow, hairline, inkBlob, makeCanvas, mountains, revealChar, rgba, scholar, seal, stamp, text, vtext, type Ctx } from '../engine/draw' +import { arrow, caption, ellipse, mn, two, type Scene } from './partA' + +/** 山形剪影 */ +function hill(c: Ctx, x: number, base: number, w: number, h: number, seed: number, color: string, a: number) { + if (a <= 0 || h <= 0) return + c.beginPath(); c.moveTo(x - w / 2, base) + for (let i = 0; i <= 60; i++) { + const q = i / 60, px = x - w / 2 + q * w + const env = Math.pow(Math.sin(q * Math.PI), 1.4) + c.lineTo(px, base - h * env * (0.82 + 0.18 * fbm1(q * 5 + seed, 4))) + } + c.closePath() + const g = c.createLinearGradient(0, base - h, 0, base) + g.addColorStop(0, rgba(color, a)); g.addColorStop(1, rgba(color, a * 0.25)) + c.fillStyle = g; c.fill() +} +function ground(c: Ctx, r: Rect, y: number, a: number, u: number) { + c.strokeStyle = rgba(COL.paper, 0.35 * a); c.lineWidth = 1.2 * u + c.beginPath(); c.moveTo(r.x, y); c.lineTo(r.x + r.w, y); c.stroke() +} +function cone(c: Ctx, x: number, y: number, dir: number, spread: number, len: number, a: number) { + if (a <= 0) return + const g = c.createRadialGradient(x, y, 0, x, y, len) + g.addColorStop(0, rgba('#f6e2b0', 0.32 * a)); g.addColorStop(1, rgba('#f6e2b0', 0)) + c.fillStyle = g + c.beginPath(); c.moveTo(x, y); c.arc(x, y, len, dir - spread, dir + spread); c.closePath(); c.fill() +} + +// ---- 积土成山 / 积水成渊 / 积善成德 三个面板 ---- +function panelMountain(S: SceneCtx, r: Rect, p: number, rain: number) { + const { c, u, lt } = S + const base = r.y + r.h * 0.82, H0 = r.h * 0.58 + hill(c, r.x + r.w / 2, base, r.w * 0.86, H0 * easeOut(p), 5, '#8d8370', 0.95) + if (p < 1) for (let i = 0; i < 26; i++) { + const ph = (lt * 0.9 + hash(i)) % 1 + const x = r.x + r.w * (0.3 + hash(i + 4) * 0.4), y = lerp(r.y, base - H0 * p * 0.9, ph) + ellipse(c, x, y, 2 * u, 2 * u, rgba(COL.paper, 0.5 * (1 - p))) + } + if (rain > 0) { + const top = base - H0 - 30 * u + for (let i = 0; i < 5; i++) inkBlob(c, r.x + r.w * (0.32 + i * 0.09), top - (i % 2) * 20 * u, r.w * 0.11, 80 + i, '#6c665c', 0.6 * rain, 0.3, lt) + c.strokeStyle = rgba('#b7c3cb', 0.4 * rain); c.lineWidth = 1.1 * u + for (let i = 0; i < 40; i++) { + const ph = (lt * 1.6 + hash(i + 50)) % 1 + const x = r.x + r.w * (0.25 + hash(i + 9) * 0.5) - ph * 20 * u, y = top + ph * (H0 * 0.9) + c.beginPath(); c.moveTo(x, y); c.lineTo(x - 6 * u, y + 22 * u); c.stroke() + } + } +} +function panelAbyss(S: SceneCtx, r: Rect, p: number, dragon: number) { + const { c, u, lt } = S + const top = r.y + r.h * (0.62 - 0.32 * easeOut(p)), bot = r.y + r.h * 0.86 + const g = c.createLinearGradient(0, top, 0, bot) + g.addColorStop(0, rgba('#3d5a73', 0.75)); g.addColorStop(1, rgba('#0b1622', 0.95)) + c.fillStyle = g + c.beginPath(); c.moveTo(r.x + r.w * 0.08, top) + for (let i = 0; i <= 40; i++) c.lineTo(r.x + r.w * (0.08 + 0.84 * i / 40), top + Math.sin(i * 0.6 + lt * 2) * 3 * u) + c.lineTo(r.x + r.w * 0.92, bot); c.quadraticCurveTo(r.x + r.w / 2, bot + r.h * 0.08, r.x + r.w * 0.08, bot); c.closePath(); c.fill() + // 水滴 + if (p < 1) for (let i = 0; i < 4; i++) { + const ph = (lt * 0.7 + i / 4) % 1 + const x = r.x + r.w * (0.35 + i * 0.1), y = lerp(r.y + r.h * 0.05, top, ph * ph) + ellipse(c, x, y, 3 * u, 6 * u, rgba('#cfe4ef', 0.8)) + if (ph > 0.9) ellipse(c, x, top, (ph - 0.9) * 300 * u, (ph - 0.9) * 60 * u, undefined, rgba('#cfe4ef', 0.5), u) + } + if (dragon > 0) { + const pts: [number, number][] = [] + for (let i = 0; i <= 60; i++) { + const q = i / 60 + const x = r.x + r.w * (0.15 + 0.7 * q), y = lerp(top, bot, 0.5) + Math.sin(q * 9 - lt * 2.2) * (bot - top) * 0.22 + pts.push([x, y]) + } + brush(c, pts, 16 * u, easeInOut(dragon), COL.gold, 0.75, 9, 0.5) + const hd = pts[Math.min(60, Math.floor(60 * easeInOut(dragon)))] + glow(c, hd[0], hd[1], 26 * u, '#ffe1a0', 0.8 * dragon) + } +} +function panelHeart(S: SceneCtx, r: Rect, p: number) { + const { c, u, lt } = S + const x = r.x + r.w / 2, y = r.y + r.h * 0.45, R = mn(r) * 0.32 + for (let i = 0; i < 30; i++) { + const ph = (lt * 0.35 + hash(i)) % 1, a = hash(i + 3) * Math.PI * 2 + const d = R * 1.6 * (1 - ph) + ellipse(c, x + Math.cos(a) * d, y + Math.sin(a) * d, 2.2 * u, 2.2 * u, rgba(COL.gold, 0.7 * ph * p)) + } + glow(c, x, y, R * (0.6 + 0.9 * p), COL.gold, 0.55 * p) + ellipse(c, x, y, R * 0.12 * (0.5 + p), R * 0.12 * (0.5 + p), rgba('#fff2d0', p)) +} + +// 刻字遮罩 +let carveLayer: HTMLCanvasElement | null = null + +export const partB: Record = { + // ---------- 肆 · 善假于物 ---------- + climb: { + quoteSize: 62, + draw(S) { + const { c, u, lt } = S + const r = S.art + const kd = S.k('c4l1', '登高'), ks = S.k('c4l2', '空想'), kx = S.k('c4l2', '片刻的学习') + const gy = r.y + r.h * 0.8 + ground(c, r, gy, 1, u) + // 远方群山(登高后显现) + const reveal = ramp(lt, kd, 1.6) + for (let i = 0; i < 3; i++) hill(c, r.x + r.w * (0.25 + i * 0.25), gy, r.w * 0.5, r.h * (0.14 + 0.05 * i), 30 + i, '#57524a', 0.25 + 0.45 * reveal) + const tx = r.x + r.w * 0.18 + cone(c, tx + 10 * u, gy - mn(r) * 0.22, -0.15, 0.22, r.w * 0.22, 1) + scholar(c, tx, gy, mn(r) * 0.24, COL.paper, 0.9, 'tiptoe') + text(c, '跂而望', tx, gy + 40 * u, 26 * u, F.kai, COL.muted, ramp(lt, 0.4, 0.6)) + const mx = r.x + r.w * 0.66, mh = r.h * 0.55 + hill(c, mx, gy, r.w * 0.5, mh, 12, '#9a8f7a', 0.95) + const sa = ramp(lt, kd - 0.2, 0.7) + cone(c, mx, gy - mh - mn(r) * 0.12, Math.PI * 0.05, 0.9 * reveal, r.w * 0.75, sa) + scholar(c, mx, gy - mh + 6 * u, mn(r) * 0.14, COL.paper, sa) + text(c, '登高博见', mx, gy + 40 * u, 26 * u, F.kai, COL.gold, sa) + const la = ramp(lt, ks - 0.2, 0.6), lb = ramp(lt, kx - 0.2, 0.6) + text(c, '终日而思', r.x + r.w * 0.25, r.y + r.h * 0.08, 34 * u, F.kai, COL.muted, la) + text(c, '<', r.x + r.w * 0.5, r.y + r.h * 0.08, 34 * u, F.song, COL.paper, lb) + text(c, '须臾之学', r.x + r.w * 0.75, r.y + r.h * 0.08, 34 * u, F.kai, COL.gold, lb) + }, + }, + + wave: { + quoteSize: 62, + draw(S) { + const { c, u, lt } = S + const [A, B] = two(S.art) + const ka = S.k('c4l3', '登高而招'), kb = S.k('c4l3', '顺风而呼'), kw = S.k('c4l3', '而见者远'), kh = S.k('c4l3', '而闻者彰') + // 登高而招 + const aa = ramp(lt, ka - 0.4, 0.6) + const gy = A.y + A.h * 0.8 + hill(c, A.x + A.w * 0.28, gy, A.w * 0.5, A.h * 0.4, 7, '#8d8370', aa) + const px = A.x + A.w * 0.28, py = gy - A.h * 0.4 + 4 * u + scholar(c, px, py, mn(A) * 0.2, COL.paper, aa, 'wave', lt) + for (let i = 0; i < 4; i++) { + const p = ((lt - ka) * 0.5 + i / 4) % 1 + if (lt < ka) break + c.strokeStyle = rgba(COL.gold, 0.5 * (1 - p) * aa); c.lineWidth = 1.4 * u + c.beginPath(); c.arc(px, py - mn(A) * 0.18, p * A.w * 0.8, -0.6, 0.6); c.stroke() + } + const sa = ramp(lt, kw - 0.2, 0.6) + for (let i = 0; i < 3; i++) { const fx = A.x + A.w * (0.72 + i * 0.09), fy = gy; scholar(c, fx, fy, mn(A) * 0.09, i === 1 ? COL.gold : COL.paper, 0.4 + 0.6 * sa) } + caption(S, A, '见者远', aa) + // 顺风而呼 + const ba = ramp(lt, kb - 0.4, 0.6) + const gy2 = B.y + B.h * 0.8 + ground(c, B, gy2, ba, u) + const sx = B.x + B.w * 0.14 + scholar(c, sx, gy2, mn(B) * 0.2, COL.paper, ba) + for (let i = 0; i < 7; i++) { + const y = B.y + B.h * (0.28 + i * 0.07), ph = (lt * 0.5 + hash(i)) % 1 + const x = B.x + ph * B.w + c.strokeStyle = rgba(COL.paper, 0.25 * ba * Math.sin(ph * Math.PI)); c.lineWidth = 1.2 * u + c.beginPath(); c.moveTo(x - 60 * u, y); c.bezierCurveTo(x - 20 * u, y - 8 * u, x + 20 * u, y + 8 * u, x + 60 * u, y); c.stroke() + } + for (let i = 0; i < 5; i++) { + const p = ((lt - kb) * 0.45 + i / 5) % 1 + if (lt < kb) break + c.strokeStyle = rgba(COL.gold, 0.6 * (1 - p) * ba); c.lineWidth = 1.6 * u + c.beginPath(); c.arc(sx + 20 * u, gy2 - mn(B) * 0.17, 20 * u + p * B.w * 0.75, -0.35, 0.35); c.stroke() + } + const ha = ramp(lt, kh - 0.2, 0.6) + scholar(c, B.x + B.w * 0.86, gy2, mn(B) * 0.14, ha > 0.5 ? COL.gold : COL.paper, 0.4 + 0.6 * ha) + caption(S, B, '闻者彰', ba) + }, + }, + + boat: { + quoteSize: 62, + draw(S) { + const { c, u, lt } = S + const [A, B] = two(S.art) + const ka = S.k('c4l4', '假舆马'), kb = S.k('c4l4', '假舟楫') + // 舆马致千里 + const aa = ramp(lt, ka - 0.4, 0.6) + const vx = A.x + A.w / 2, vy = A.y + A.h * 0.3, by = A.y + A.h * 0.82 + c.strokeStyle = rgba(COL.paper, 0.5 * aa); c.lineWidth = 1.6 * u + c.beginPath(); c.moveTo(A.x + A.w * 0.05, by); c.lineTo(vx - 4 * u, vy); c.moveTo(A.x + A.w * 0.95, by); c.lineTo(vx + 4 * u, vy); c.stroke() + hill(c, vx - A.w * 0.25, vy + 2 * u, A.w * 0.5, A.h * 0.08, 41, '#5f594e', aa * 0.8) + hill(c, vx + A.w * 0.25, vy + 2 * u, A.w * 0.5, A.h * 0.06, 42, '#5f594e', aa * 0.8) + for (let i = 0; i < 8; i++) { + const q = ((lt * 0.35 + i / 8) % 1), z = Math.pow(q, 2.2) + const y = lerp(vy, by, z), w = lerp(1, 10, z) * u + c.fillStyle = rgba(COL.gold, 0.6 * aa); c.fillRect(vx - w / 2, y, w, lerp(2, 18, z) * u) + } + const cp = easeInOut(ramp(lt, ka, 4)), z = 1 - cp * 0.92 + const cy2 = lerp(vy, by - 20 * u, Math.pow(z, 1.6)), sc = z + const s = mn(A) * 0.22 * sc + if (s > 1) { + c.fillStyle = rgba('#c9b27f', aa); c.fillRect(vx - s * 0.5, cy2 - s * 0.7, s, s * 0.45) + c.fillStyle = rgba('#7e6440', aa); c.beginPath(); c.moveTo(vx - s * 0.6, cy2 - s * 0.7); c.lineTo(vx, cy2 - s * 0.98); c.lineTo(vx + s * 0.6, cy2 - s * 0.7); c.closePath(); c.fill() + for (const d of [-0.5, 0.5]) ellipse(c, vx + d * s, cy2 - s * 0.18, s * 0.08, s * 0.24, undefined, rgba(COL.paper, aa), Math.max(1, 3 * u * sc)) + } + text(c, '千里', vx, vy - 36 * u, 30 * u, F.kai, COL.gold, aa * ramp(lt, ka + 1.6, 0.8)) + caption(S, A, '假舆马 · 致千里', aa) + // 舟楫绝江河 + const ba = ramp(lt, kb - 0.4, 0.6) + const rt = B.y + B.h * 0.25, rb = B.y + B.h * 0.75 + const g = c.createLinearGradient(0, rt, 0, rb) + g.addColorStop(0, rgba('#20384a', 0.6 * ba)); g.addColorStop(0.5, rgba('#2c4c63', 0.75 * ba)); g.addColorStop(1, rgba('#20384a', 0.6 * ba)) + c.fillStyle = g; c.fillRect(B.x, rt, B.w, rb - rt) + for (let i = 0; i < 9; i++) { + const y = lerp(rt, rb, (i + 0.5) / 9) + c.strokeStyle = rgba('#a8c3d3', 0.22 * ba); c.lineWidth = u + c.beginPath(); for (let x = 0; x <= B.w; x += 12 * u) { const yy = y + Math.sin(x * 0.03 + lt * 1.5 + i) * 3 * u; x ? c.lineTo(B.x + x, yy) : c.moveTo(B.x + x, yy) } c.stroke() + } + const bp = easeInOut(ramp(lt, kb, 3.6)) + const bx = B.x + B.w / 2 + Math.sin(lt * 0.8) * 6 * u, byy = lerp(rb + 20 * u, rt - 10 * u, bp) + const bs = mn(B) * 0.22 + c.fillStyle = rgba('#d8c393', ba); c.beginPath(); c.moveTo(bx - bs * 0.6, byy); c.quadraticCurveTo(bx, byy + bs * 0.3, bx + bs * 0.6, byy); c.lineTo(bx + bs * 0.45, byy + bs * 0.1); c.lineTo(bx - bs * 0.45, byy + bs * 0.1); c.closePath(); c.fill() + scholar(c, bx, byy, bs * 0.65, COL.paper, ba) + c.strokeStyle = rgba(COL.paper, ba); c.lineWidth = 2 * u + const oa = Math.sin(lt * 2.4) * 0.3 + c.beginPath(); c.moveTo(bx + bs * 0.1, byy - bs * 0.35); c.lineTo(bx + bs * 0.6 + oa * bs, byy + bs * 0.25); c.stroke() + for (let i = 1; i < 5; i++) ellipse(c, bx, byy + i * 22 * u, i * 14 * u, i * 4 * u, undefined, rgba('#a8c3d3', 0.3 * ba * (1 - i / 5)), u) + caption(S, B, '假舟楫 · 绝江河', ba) + }, + }, + + jia: { + draw(S) { + const { c, u, lt } = S + const r = S.art + const k6 = S.ls('c4l6'), kd = S.k('c4l6', '生来'), kj = S.k('c4l6', '善于借助外物') + const ax = r.x + r.w / 2, ay = r.y + r.h * 0.45 + const a1 = ramp(lt, 0, 0.8) * (1 - ramp(lt, k6 - 0.6, 0.8)) + const s = mn(r) * 0.6 + inkBlob(c, ax, ay, s * 0.7, 91, '#3b352c', 0.6 * a1, 0.3, lt) + revealChar(c, '假', ax, ay, s, S.P ? F.brush : F.brush, COL.paper, clamp(lt / 0.9), a1) + text(c, '假:借助', ax, ay + s * 0.66, 32 * u, F.song, COL.gold, a1 * ramp(lt, 1, 0.8), 'center', 8 * u) + const a2 = ramp(lt, k6 - 0.3, 0.8) + if (a2 <= 0) return + const gy = r.y + r.h * 0.8 + ground(c, r, gy, a2, u) + const h = mn(r) * 0.36 + const lx = r.x + r.w * 0.3, rx = r.x + r.w * 0.7 + const lift = easeOut(ramp(lt, kj, 1.2)) * r.h * 0.2 + scholar(c, lx, gy, h, COL.paper, a2) + // 书卷台阶 + for (let i = 0; i < 4; i++) { + const bh = lift / 4 + if (bh <= 0) break + c.fillStyle = rgba(['#4a6283', '#7a3b2e', '#8a7344', '#3f5a4b'][i], a2) + c.fillRect(rx - h * (0.42 - i * 0.04), gy - bh * (i + 1), h * (0.84 - i * 0.08), bh * 0.92) + } + glow(c, rx, gy - lift - h * 0.5, h * 1.1, COL.gold, 0.3 * ramp(lt, kj, 1)) + scholar(c, rx, gy - lift, h, ramp(lt, kj, 1) > 0.5 ? '#f6e3b4' : COL.paper, a2) + c.setLineDash([4 * u, 6 * u]); c.strokeStyle = rgba(COL.gold, 0.5 * win(lt, kd - 0.2, kj + 0.2, 0.4)); c.lineWidth = u + c.beginPath(); c.moveTo(lx - h * 0.3, gy - h * 1.02); c.lineTo(rx + h * 0.3, gy - h * 1.02); c.stroke(); c.setLineDash([]) + text(c, '生非异也', ax, gy - h * 1.1 - 24 * u, 28 * u, F.kai, COL.gold, win(lt, kd - 0.2, kj + 0.2, 0.4)) + text(c, '常人', lx, gy + 40 * u, 28 * u, F.kai, COL.muted, a2) + text(c, '善假于物', rx, gy + 40 * u, 28 * u, F.kai, COL.gold, ramp(lt, kj, 0.6)) + }, + }, + + books: { + draw(S) { + const { c, W, H, u, P, lt } = S + const kq = S.k('c4l7', '前人积累'), kr = S.k('c4l7', '读一本书'), kh = S.k('c4l7', '登上一处高地'), kc = S.k('c4l7', '乘上一辆车马') + const names = ['诗', '书', '礼', '乐', '易', '春秋'] + const cols = ['#3d5674', '#7a3a2c', '#8c7546', '#3d5b4c', '#5b4a6e', '#8a5a36'] + const n = names.length + const bw = P ? W * 0.13 : W * 0.085, bh = P ? H * 0.045 : H * 0.075 + const x0 = P ? W * 0.12 : W * 0.2, y0 = P ? H * 0.78 : H * 0.8 + const dx = P ? (W * 0.76 - bw) / (n - 1) : W * 0.09, dy = P ? H * 0.065 : H * 0.075 + for (let i = 0; i < n; i++) { + const a = ramp(lt, kq - 0.6 + i * 0.28, 0.5) + if (a <= 0) continue + for (let j = 0; j <= i; j++) { + const x = x0 + i * dx, y = y0 - (j + 1) * dy - (1 - easeOut(a)) * 30 * u * (j === i ? 1 : 0) + c.fillStyle = rgba(cols[(i + j) % n], a); c.fillRect(x, y, bw, bh * 0.94) + c.fillStyle = rgba('#e9dcc0', 0.85 * a); c.fillRect(x + bw * 0.06, y + bh * 0.12, bw * 0.88, bh * 0.08) + if (j === i) text(c, names[i], x + bw / 2, y + bh * 0.58, bh * 0.42, F.kai, '#f3e6cd', a) + } + } + const climb = smooth(ramp(lt, kr - 0.3, Math.max(1, kh - kr + 0.6))) + const fi = climb * (n - 1) + const bi = Math.floor(fi), fr = fi - bi + const px = x0 + bw / 2 + fi * dx + const py = y0 - (Math.min(n - 1, bi) + 1) * dy - (bi < n - 1 ? easeOut(fr) * dy : 0) + const sa = ramp(lt, kr - 0.5, 0.5) + scholar(c, px, py, (P ? H * 0.09 : H * 0.17), COL.paper, sa, 'walk', lt) + const top = ramp(lt, kh, 1) + glow(c, px, py - H * 0.1, Math.min(W, H) * 0.35, COL.gold, 0.3 * top) + text(c, '站在前人的肩上', P ? W / 2 : W * 0.72, P ? H * 0.16 : H * 0.2, 54 * u, F.brush, COL.gold, ramp(lt, kc - 0.2, 0.9), 'center', 10 * u) + }, + }, + + // ---------- 伍 · 积 · 恒 · 专 ---------- + mountain: { + quoteSize: 60, + draw(S) { + const { c, u, lt } = S + const r = S.art + const ka = S.k('c5l1', '积土成山'), kr = S.k('c5l1', '风雨兴焉'), kb = S.k('c5l1', '积水成渊'), kd = S.k('c5l1', '蛟龙生焉'), kc = S.k('c5l1', '积善成德'), ke = S.k('c5l1', '圣心备焉') + const k2 = S.ls('c5l2'), kq = S.k('c5l2', '量的积累') + const tri = ramp(lt, k2 - 0.6, 1) + const pa = ramp(lt, ka - 0.3, 3), rain = ramp(lt, kr - 0.2, 0.8) + const pb = ramp(lt, kb - 0.3, 3), dr = ramp(lt, kd - 0.2, 2.4) + const pc = ramp(lt, kc - 0.2, 2.2) + const phase = lt < kb - 0.4 ? 0 : lt < kc - 0.4 ? 1 : 2 + const pf = (i: number) => (i === 0 ? 1 - ramp(lt, kb - 0.6, 0.6) : i === 1 ? ramp(lt, kb - 0.6, 0.6) * (1 - ramp(lt, kc - 0.6, 0.6)) : ramp(lt, kc - 0.6, 0.6)) + const labels = ['积土成山', '积水成渊', '积善成德'] + if (tri < 1) { + c.globalAlpha = 1 - tri + for (let i = 0; i < 3; i++) { + const a = pf(i) + if (a <= 0) continue + c.globalAlpha = a * (1 - tri) + if (i === 0) panelMountain(S, r, pa, rain) + if (i === 1) panelAbyss(S, r, pb, dr) + if (i === 2) panelHeart(S, r, pc) + caption(S, r, labels[i], 1) + } + c.globalAlpha = 1 + void phase + } + if (tri > 0) { + const P = S.P + const w = r.w / 3 + c.globalAlpha = tri + for (let i = 0; i < 3; i++) { + const q: Rect = P ? { x: r.x + i * w, y: r.y + r.h * 0.1, w, h: r.h * 0.7 } : { x: r.x + i * w, y: r.y + r.h * 0.12, w, h: r.h * 0.62 } + if (i === 0) panelMountain(S, q, 1, 1) + if (i === 1) panelAbyss(S, q, 1, 1) + if (i === 2) panelHeart(S, q, 1) + text(c, ['山', '渊', '德'][i], q.x + q.w / 2, q.y + q.h + 30 * u, 40 * u, F.brush, COL.paper, 1) + } + const qa = ramp(lt, kq - 0.2, 0.8) + const yy = r.y + r.h * 0.94 + text(c, '量变', r.x + r.w * 0.32, yy, 40 * u, F.kai, COL.muted, qa) + arrow(c, r.x + r.w * 0.42, yy, r.x + r.w * 0.58, yy, COL.gold, qa, 2 * u) + text(c, '质变', r.x + r.w * 0.68, yy, 40 * u, F.kai, COL.gold, qa) + c.globalAlpha = 1 + } + void ke + }, + }, + + steps: { + quoteSize: 66, + draw(S) { + const { c, u, lt } = S + const [A, B] = two(S.art) + const ka = S.k('c5l3', '不积跬步'), kq = S.k('c5l3', '千里'), kb = S.k('c5l3', '不积小流'), ke = S.k('c5l3', '江海') + // 跬步 → 千里 + const n = 26 + const pr = ramp(lt, ka - 0.2, Math.max(1, kq - ka + 0.6)) + hill(c, A.x + A.w * 0.5, A.y + A.h * 0.22, A.w * 0.8, A.h * 0.08, 61, '#5f594e', 0.8) + for (let i = 0; i < n; i++) { + const q = i / (n - 1), z = Math.pow(q, 0.8) + const x = A.x + A.w * (0.5 + 0.28 * Math.sin(q * 5) * (1 - z * 0.8)) + (i % 2 ? 1 : -1) * 10 * u * (1 - z) + const y = lerp(A.y + A.h * 0.86, A.y + A.h * 0.24, z) + const a = clamp(pr * n - i) + const s = lerp(9, 2, z) * u + ellipse(c, x, y, s * 0.6, s, rgba(COL.paper, 0.85 * a)) + } + text(c, '千里', A.x + A.w * 0.5, A.y + A.h * 0.12, 34 * u, F.kai, COL.gold, ramp(lt, kq, 0.6)) + caption(S, A, '跬步 · 半步', ramp(lt, ka, 0.6), COL.muted) + // 小流 → 江海 + const sp = ramp(lt, kb - 0.2, Math.max(1, ke - kb + 0.8)) + const sea = ramp(lt, ke - 0.2, 0.9) + const g = c.createLinearGradient(0, B.y + B.h * 0.12, 0, B.y + B.h * 0.3) + g.addColorStop(0, rgba('#d9e7ee', 0.0)); g.addColorStop(1, rgba('#9fbcd0', 0.45 * sea)) + c.fillStyle = g; c.fillRect(B.x, B.y + B.h * 0.12, B.w, B.h * 0.18) + glow(c, B.x + B.w / 2, B.y + B.h * 0.22, B.w * 0.5, '#cfe4ef', 0.3 * sea) + for (let i = 0; i < 5; i++) { + const sx = B.x + B.w * (0.08 + i * 0.21) + const pts: [number, number][] = [] + for (let j = 0; j <= 40; j++) { + const q = j / 40 + const x = lerp(sx, B.x + B.w / 2, Math.pow(q, 1.5)) + Math.sin(q * 8 + i) * 8 * u * (1 - q) + const y = lerp(B.y + B.h * 0.86, B.y + B.h * 0.3, q) + pts.push([x, y]) + } + brush(c, pts, lerp(4, 10, i === 2 ? 1 : 0.5) * u, sp, '#8fb3cc', 0.8, 20 + i, 0.3) + } + text(c, '江海', B.x + B.w / 2, B.y + B.h * 0.07, 34 * u, F.kai, COL.gold, sea) + caption(S, B, '小流 · 细水', ramp(lt, kb, 0.6), COL.muted) + }, + }, + + horse: { + quoteSize: 66, + draw(S) { + const { c, u, lt } = S + const r = S.art + const ka = S.k('c5l4', '骐骥一跃'), kb = S.k('c5l4', '驽马十驾'), kf = S.k('c5l4', '功在不舍'), kt = S.k('c5l5', '不是天赋'), ks = S.k('c5l5', '不肯停下') + const A: Rect = { x: r.x, y: r.y, w: r.w, h: r.h * 0.46 }, B: Rect = { x: r.x, y: r.y + r.h * 0.52, w: r.w, h: r.h * 0.46 } + const nums = '一二三四五六七八九十' + // 骐骥一跃 + const aa = ramp(lt, ka - 0.5, 0.6) + const gy = A.y + A.h * 0.75, x0 = A.x + A.w * 0.08, step = (A.w * 0.84) / 10 + ground(c, A, gy, aa, u) + for (let i = 0; i <= 10; i++) { + c.strokeStyle = rgba(COL.paper, 0.45 * aa); c.lineWidth = u + c.beginPath(); c.moveTo(x0 + i * step, gy - 6 * u); c.lineTo(x0 + i * step, gy + 6 * u); c.stroke() + if (i > 0) text(c, nums[i - 1], x0 + (i - 0.5) * step, gy + 26 * u, 18 * u, F.song, COL.muted, aa * 0.8) + } + const jp = easeOut(ramp(lt, ka, 1.3)) + const land = 8.3 + c.strokeStyle = rgba(COL.gold, 0.85 * aa); c.lineWidth = 2.4 * u + c.beginPath() + for (let i = 0; i <= 60 * jp; i++) { const q = i / 60, x = x0 + q * land * step, y = gy - Math.sin(q * Math.PI) * A.h * 0.55; i ? c.lineTo(x, y) : c.moveTo(x, y) } + c.stroke() + const hx = x0 + jp * land * step, hy = gy - Math.sin(jp * Math.PI) * A.h * 0.55 + glow(c, hx, hy, 30 * u, '#ffe1a0', aa); ellipse(c, hx, hy, 6 * u, 6 * u, rgba('#fff3d6', aa)) + text(c, '骐骥一跃 · 不能十步', A.x + A.w * 0.5, A.y + A.h * 0.08, 30 * u, F.kai, COL.paper, aa, 'center', 4 * u) + // 驽马十驾 + const ba = ramp(lt, kb - 0.5, 0.6) + const gy2 = B.y + B.h * 0.6 + ground(c, B, gy2, ba, u) + const wp = smooth(ramp(lt, kb, Math.max(2, ks - kb))) + for (let i = 0; i < 10; i++) { + const x = x0 + (i + 1) * step + const reached = wp * 10 >= i + 1 + ellipse(c, x, gy2, 4 * u, 4 * u, rgba(reached ? COL.gold : COL.dim, ba)) + text(c, nums[i] + '驾', x, gy2 + 28 * u, 18 * u, F.song, reached ? COL.gold : COL.muted, ba * 0.85) + } + for (let d = 0; d < wp * 10 * 6; d++) ellipse(c, x0 + (d / 6) * step, gy2 - 14 * u, 1.4 * u, 1.4 * u, rgba(COL.paper, 0.5 * ba)) + const mx = x0 + wp * 10 * step + ellipse(c, mx, gy2 - 14 * u, 6 * u, 6 * u, rgba(COL.paper, ba)) + const fa = ramp(lt, ks - 0.4, 0.8) + (wp > 0.99 ? 0.5 : 0) + glow(c, x0 + 10 * step, gy2 - 14 * u, 50 * u, COL.gold, 0.5 * clamp(fa)) + text(c, '驽马十驾 · 功在不舍', B.x + B.w * 0.5, B.y + B.h * 0.12, 30 * u, F.kai, COL.gold, ba, 'center', 4 * u) + const ta = ramp(lt, kt - 0.2, 0.6) + if (ta > 0) { + text(c, '天赋', A.x + A.w * 0.85, A.y + A.h * 0.3, 30 * u, F.kai, COL.muted, ta) + c.strokeStyle = rgba(COL.red, ta); c.lineWidth = 3 * u; c.beginPath(); c.moveTo(A.x + A.w * 0.85 - 40 * u, A.y + A.h * 0.3); c.lineTo(A.x + A.w * 0.85 - 40 * u + 80 * u * ramp(lt, kt + 0.3, 0.4), A.y + A.h * 0.3); c.stroke() + } + stamp(c, B.x + B.w * 0.9, B.y + B.h * 0.25, 64 * u, '不舍', lt - Math.max(kf + 0.5, ks)) + }, + }, + + carve: { + quoteSize: 70, + draw(S) { + const { c, u, lt, t } = S + const [A, B] = two(S.art) + const strikes = carveStrikes().map((x) => x - S.shot.start) + const kc = S.k('c5l6', '锲而不舍'), kz = S.k('c5l6', '朽木不折') + const past = strikes.filter((x) => x <= lt) + const lastStrike = past.length ? past[past.length - 1] : -9 + const split = strikes.findIndex((x) => x >= kc - 0.05) + const woodN = past.filter((_, i) => i < split).length, stoneN = past.length - woodN + const chisel = (x: number, y: number, a: number, active: boolean) => { + const dt = lt - lastStrike + const lift = active ? (dt < 0.08 ? 0 : Math.min(1, (dt - 0.08) / 0.14)) * 34 * u : 50 * u + c.save(); c.translate(x, y - lift); c.rotate(-0.5) + c.fillStyle = rgba('#c9ccd0', a); c.fillRect(-3 * u, -70 * u, 6 * u, 70 * u) + c.fillStyle = rgba('#6b4c2e', a); c.fillRect(-7 * u, -130 * u, 14 * u, 62 * u) + c.restore() + if (active && dt < 0.25) { c.save(); c.globalCompositeOperation = 'lighter'; for (let i = 0; i < 8; i++) { const ang = hash(i + past.length * 9) * Math.PI * 2, d = dt * 260 * u; glow(c, x + Math.cos(ang) * d, y + Math.sin(ang) * d * 0.6, 6 * u, '#ffcf8a', a * (1 - dt / 0.25)) } c.restore() } + } + // 朽木 + const aa = ramp(lt, 0, 0.6) + const wx = A.x + A.w / 2, wy = A.y + A.h * 0.5, ww = A.w * 0.7, wh = mn(A) * 0.3 + c.fillStyle = rgba('#5e4630', aa); c.beginPath(); c.roundRect(wx - ww / 2, wy - wh / 2, ww, wh, 16 * u); c.fill() + for (let i = 0; i < 6; i++) { c.strokeStyle = rgba('#2f2216', 0.6 * aa); c.lineWidth = 1.4 * u; c.beginPath(); c.moveTo(wx - ww * 0.45, wy - wh * 0.35 + i * wh * 0.14); c.bezierCurveTo(wx - ww * 0.1, wy - wh * 0.3 + i * wh * 0.14, wx + ww * 0.1, wy - wh * 0.4 + i * wh * 0.14, wx + ww * 0.45, wy - wh * 0.35 + i * wh * 0.14); c.stroke() } + for (let i = 0; i < woodN; i++) { c.fillStyle = rgba('#1e150d', aa); c.beginPath(); c.moveTo(wx - 8 * u + i * 4 * u, wy - wh / 2); c.lineTo(wx + i * 4 * u, wy - wh / 2 + (10 + i * 5) * u); c.lineTo(wx + 8 * u + i * 4 * u, wy - wh / 2); c.closePath(); c.fill() } + chisel(wx + woodN * 4 * u, wy - wh / 2, aa * (1 - ramp(lt, kz + 0.5, 0.5)), lt < kc - 0.05 && past.length > 0) + caption(S, A, '锲而舍之 · 朽木不折', aa, COL.muted) + // 金石 + const ba = ramp(lt, kz, 0.6) + const sx = B.x + B.w / 2, sy = B.y + B.h * 0.48, ss = mn(B) * 0.66 + const sg = c.createLinearGradient(sx - ss / 2, sy - ss / 2, sx + ss / 2, sy + ss / 2) + sg.addColorStop(0, rgba('#5c5a56', ba)); sg.addColorStop(1, rgba('#2e2d2b', ba)) + c.fillStyle = sg; c.beginPath(); c.roundRect(sx - ss / 2, sy - ss / 2, ss, ss, 10 * u); c.fill() + const cs = ss * 0.8 + const L = (carveLayer && carveLayer.width === Math.ceil(cs) ? carveLayer : (carveLayer = makeCanvas(cs, cs))) + const g = L.getContext('2d')! + g.clearRect(0, 0, L.width, L.height) + const r = rng(77) + const total = Math.max(1, strikes.length - split) + const full = ramp(lt, strikes[strikes.length - 1] + 0.3, 1.2) + g.fillStyle = '#000' + for (let i = 0; i < stoneN; i++) for (let k = 0; k < 26; k++) { g.beginPath(); g.arc(r() * cs, r() * cs, cs * (0.05 + r() * 0.05), 0, Math.PI * 2); g.fill() } + if (full > 0) { g.globalAlpha = full; g.fillRect(0, 0, cs, cs); g.globalAlpha = 1 } + g.globalCompositeOperation = 'source-in' + g.font = font(cs * 0.9, F.brush); g.textAlign = 'center'; g.textBaseline = 'middle' + g.fillStyle = '#e2c27f'; g.fillText('学', cs / 2, cs / 2 + cs * 0.04) + g.globalCompositeOperation = 'source-over' + c.globalAlpha = ba; c.drawImage(L, sx - cs / 2, sy - cs / 2); c.globalAlpha = 1 + glow(c, sx, sy, ss * 0.6, COL.gold, 0.2 * full * ba) + const cur = Math.min(stoneN, total) + chisel(sx - cs * 0.3 + (hash(cur) * cs * 0.6), sy - cs * 0.3 + hash(cur + 1) * cs * 0.6, ba * (1 - full), lt >= kc - 0.05) + caption(S, B, '锲而不舍 · 金石可镂', ba) + void t + }, + }, + + worm: { + quoteSize: 56, + draw(S) { + const { c, u, lt } = S + const [A, B] = two(S.art) + const kc = S.k('c5l7', '蟹六跪'), k1 = S.k('c5l7', '用心一也'), k2 = S.k('c5l7', '用心躁也') + const ky = S.k('c5l8', '专一'), kz = S.k('c5l8', '浮躁') + // 土层剖面 + const layers = ['#4a3b2a', '#3e3124', '#33291e', '#2a221a'] + for (let i = 0; i < 4; i++) { + c.fillStyle = rgba(layers[i], 0.9) + c.beginPath(); c.moveTo(A.x, A.y + A.h * (0.12 + i * 0.19)) + for (let x = 0; x <= A.w; x += 10 * u) c.lineTo(A.x + x, A.y + A.h * (0.12 + i * 0.19) + fbm1(x / A.w * 4 + i * 3) * 10 * u) + c.lineTo(A.x + A.w, A.y + A.h * 0.88); c.lineTo(A.x, A.y + A.h * 0.88); c.closePath(); c.fill() + } + const gq = c.createLinearGradient(0, A.y + A.h * 0.78, 0, A.y + A.h * 0.88) + gq.addColorStop(0, 'rgba(198,160,74,0)'); gq.addColorStop(1, 'rgba(198,160,74,0.55)') + c.fillStyle = gq; c.fillRect(A.x, A.y + A.h * 0.78, A.w, A.h * 0.1) + text(c, '埃土', A.x + A.w * 0.9, A.y + A.h * 0.07, 22 * u, F.song, COL.muted, 0.9) + text(c, '黄泉', A.x + A.w * 0.9, A.y + A.h * 0.93, 22 * u, F.song, COL.gold, 0.9) + // 蚯蚓:沿竖直蛇形路径往复 + const cyc = (lt * 0.08) % 2, ph = cyc < 1 ? cyc : 2 - cyc + const path = (q: number): [number, number] => [A.x + A.w * (0.5 + 0.22 * Math.sin(q * 10)), A.y + A.h * (0.1 + 0.74 * q)] + const pts: [number, number][] = [] + for (let i = 0; i < 24; i++) pts.push(path(clamp(ph - i * 0.012 * (cyc < 1 ? 1 : -1)))) + c.lineCap = 'round' + c.strokeStyle = rgba('#c58d7a', 0.95); c.lineWidth = 11 * u + c.beginPath(); pts.forEach((p, i) => (i ? c.lineTo(p[0], p[1]) : c.moveTo(p[0], p[1]))); c.stroke() + for (let i = 2; i < 24; i += 3) ellipse(c, pts[i][0], pts[i][1], 4 * u, 4 * u, undefined, 'rgba(90,50,40,0.7)', u) + caption(S, A, '用心一也', ramp(lt, k1 - 0.2, 0.6)) + // 蟹 + const ba = ramp(lt, kc - 0.4, 0.6) + const holes: [number, number][] = [[0.25, 0.7], [0.75, 0.72], [0.5, 0.45]] + holes.forEach(([hx, hy], i) => { + ellipse(c, B.x + B.w * hx, B.y + B.h * hy, B.w * 0.12, B.w * 0.04, rgba('#090807', 0.9 * ba)) + text(c, ['蛇穴', '鳝穴', '蛇穴'][i], B.x + B.w * hx, B.y + B.h * hy + 34 * u, 18 * u, F.song, COL.dim, ba) + }) + const tt = lt * 0.9 + const seg = Math.floor(tt), fr = tt - seg + const h0 = holes[seg % 3], h1 = holes[(seg + 1) % 3] + const e = easeInOut(fr) + const crx = B.x + B.w * (lerp(h0[0], h1[0], e) + noise1(lt * 7) * 0.03), cry = B.y + B.h * (lerp(h0[1], h1[1], e) - 0.12 + noise1(lt * 6 + 3) * 0.02) + drawCrab(c, crx, cry, mn(B) * 0.2, ba, lt) + caption(S, B, '用心躁也', ramp(lt, k2 - 0.2, 0.6)) + const ya = ramp(lt, ky - 0.2, 0.6), za = ramp(lt, kz - 0.2, 0.6) + text(c, '专一 · 上下自如', A.x + A.w / 2, A.y - 8 * u, 26 * u, F.song, COL.gold, ya, 'center', 4 * u) + text(c, '浮躁 · 无处安身', B.x + B.w / 2, B.y - 8 * u, 26 * u, F.song, COL.muted, za, 'center', 4 * u) + }, + }, + + keys: { + draw(S) { + const { c, W, H, u, P, lt } = S + const items = [ + { s: '积', w: '积累', d: '积土成山', k: S.k('c5l9', '积累') }, + { s: '恒', w: '坚持', d: '锲而不舍', k: S.k('c5l9', '坚持') }, + { s: '专', w: '专一', d: '用心一也', k: S.k('c5l9', '专一') }, + ] + const sz = Math.min(W, H) * (P ? 0.24 : 0.2) + items.forEach((it, i) => { + const x = P ? W / 2 : W / 2 + (i - 1) * W * 0.24 + const y = P ? H * (0.24 + i * 0.22) : H * 0.42 + const p = lt - it.k + inkBlob(c, x, y, sz * 0.85 * easeOutExpo(clamp(p / 1.2)), 120 + i, '#3e372e', 0.6, 0.3, lt) + stamp(c, x, y, sz, it.s, p, (i - 1) * 0.04) + const ty = P ? y : y + sz * 0.85 + const tx = P ? x + sz * 1.05 : x + text(c, it.w, tx, ty - (P ? 20 * u : 0), 44 * u, F.kai, COL.paper, ramp(lt, it.k + 0.3, 0.6), 'center', 8 * u) + text(c, it.d, tx, ty + (P ? 30 * u : 50 * u), 24 * u, F.song, COL.gold, ramp(lt, it.k + 0.6, 0.6), 'center', 6 * u) + }) + if (!P) hairline(c, W * 0.2, H * 0.42, W * 0.8, H * 0.42, ramp(lt, items[2].k + 0.5, 1.4), COL.gold, 0.18, u) + }, + }, + + // ---------- 终 · 学至乎没而后止 ---------- + traveler: { + draw(S) { + const { c, W, H, u, P, lt } = S + glow(c, W * 0.5, H * 0.52, Math.max(W, H) * 0.55, '#c7894a', 0.12) + mountains(c, W, H, lt, { seed: 51, tint: '#9b8a72', y: P ? 180 * u : 0 }) + const pts: [number, number][] = [] + for (let i = 0; i <= 60; i++) { + const q = i / 60 + pts.push([W * (0.5 + 0.2 * Math.sin(q * 6) * (1 - q)), lerp(H * 0.98, H * (P ? 0.68 : 0.62), Math.pow(q, 0.7))]) + } + brush(c, pts, 26 * u, 1, '#d8c7a4', 0.32, 8, 0.4) + const q = 0.15 + 0.6 * smooth(lt / S.dur) + const i = Math.floor(q * 60), p = pts[i] + scholar(c, p[0], p[1], lerp(110, 30, q) * u, COL.paper, 0.95, 'walk', lt) + const L1 = getLine('c6l1') + const qi = L1.text.indexOf('学至乎没') + const x = P ? W * 0.5 : W * 0.86, y = P ? H * 0.12 : H * 0.15 + const qs = '学至乎没而后止也' + ;[...qs].forEach((ch, j) => { + const ct = L1.charT[qi + j] - S.shot.start + revealChar(c, ch, x, y + j * 64 * u * (P ? 0.92 : 1.1), (P ? 54 : 62) * u, F.brush, COL.paper, clamp((lt - ct) / 0.6)) + }) + const ws = [['以自身为材料', S.k('c6l2', '以自身为材料')], ['日复一日', S.k('c6l2', '日复一日')], ['成为完整的人', S.k('c6l2', '完整的人')]] as const + ws.forEach(([w, k], j) => { + const xx = P ? W * (0.2 + j * 0.3) : W * (0.12 + j * 0.07) + const yy = P ? H * 0.42 : H * 0.18 + if (P) text(c, w, xx, yy + j * 0 , 26 * u, F.song, COL.gold, ramp(lt, k - 0.1, 0.8) * 0.9, 'center', 4 * u) + else vtext(c, w, xx, yy, 30 * u, F.kai, COL.gold, ramp(lt, k - 0.1, 0.8) * 0.9, 1.2) + }) + }, + }, + + sunrise: { + draw(S) { + const { c, W, H, u, P, lt } = S + const kt = S.k('c6l3', '天性'), kx = S.k('c6l3', '学习,决定') + const rise = easeOut(ramp(lt, 0, S.dur * 0.8)) + const sy = lerp(H * 0.72, H * 0.48, rise) + const g = c.createLinearGradient(0, 0, 0, H) + g.addColorStop(0, 'rgba(0,0,0,0)'); g.addColorStop(0.6, `rgba(160,104,52,${0.25 * rise})`); g.addColorStop(1, 'rgba(0,0,0,0)') + c.fillStyle = g; c.fillRect(0, 0, W, H) + c.save(); c.globalCompositeOperation = 'lighter' + for (let i = 0; i < 9; i++) { + const a = -Math.PI / 2 + (i - 4) * 0.22 + Math.sin(lt * 0.2 + i) * 0.02 + c.fillStyle = rgba('#f0c27a', 0.05 * rise) + c.beginPath(); c.moveTo(W / 2, sy); c.lineTo(W / 2 + Math.cos(a - 0.04) * W, sy + Math.sin(a - 0.04) * W); c.lineTo(W / 2 + Math.cos(a + 0.04) * W, sy + Math.sin(a + 0.04) * W); c.closePath(); c.fill() + } + glow(c, W / 2, sy, Math.min(W, H) * 0.5, '#f6c46f', 0.6 * rise) + c.restore() + ellipse(c, W / 2, sy, Math.min(W, H) * 0.07, Math.min(W, H) * 0.07, rgba('#fbe2b0', 0.95)) + mountains(c, W, H, lt, { seed: 71, tint: '#7a6a55', y: P ? 160 * u : 30 * u }) + const a1 = ramp(lt, kt - 0.2, 0.8), a2 = ramp(lt, kx - 0.2, 0.8) + const p1: [number, number] = P ? [W * 0.25, H * 0.8] : [W * 0.18, H * 0.78] + const p2: [number, number] = P ? [W * 0.72, H * 0.3] : [W * 0.78, H * 0.3] + text(c, '天性 · 出发的地方', p1[0], p1[1], 32 * u, F.kai, COL.paper, a1, 'center', 4 * u) + text(c, '学习 · 能走多远', p2[0], p2[1], 36 * u, F.kai, COL.gold, a2, 'center', 4 * u) + c.setLineDash([3 * u, 10 * u]); c.strokeStyle = rgba(COL.gold, 0.6 * a2); c.lineWidth = 1.6 * u + c.beginPath(); c.moveTo(p1[0], p1[1] - 30 * u); c.quadraticCurveTo(W * 0.5, H * 0.75, p2[0], p2[1] + 30 * u); c.stroke(); c.setLineDash([]) + dust(c, W, H, lt, 50, 31, '#f6d9a0', 0.4) + }, + }, + + finale: { + customQuote: true, + zoom: 0.5, + draw(S) { + const { c, W, H, u, P, lt } = S + const L = S.shot.lines[0] + const base = L.text.indexOf('学') + const m = Math.min(W, H) + const g = ramp(lt, 0, 3.5) + inkBlob(c, W / 2, H * 0.47, easeOutExpo(g) * m * 0.5, 201, '#4a4236', 0.7, 0.3, lt) + dust(c, W, H, lt, 60, 41, COL.gold, 0.35) + text(c, '君子曰', W / 2, P ? H * 0.13 : H * 0.22, 44 * u, F.kai, COL.muted, ramp(lt, L.charT[0] - S.shot.start, 0.6), 'center', 14 * u) + const size = (P ? 200 : 180) * u + for (let i = 0; i < 5; i++) { + const x = P ? W / 2 : W / 2 + (i - 2) * size * 1.12 + const y = P ? H * 0.23 + i * size * 1.1 : H * 0.47 + const ct = L.charT[base + i] - S.shot.start + revealChar(c, '学不可以已'[i], x, y, size, F.brush, COL.paper, clamp((lt - ct) / 0.7)) + } + const se = L.end - S.shot.start + 0.6 + const sx = P ? W / 2 + size * 0.8 : W / 2 + size * 3.0, sy = P ? H * 0.23 + 4 * size * 1.1 + size * 0.3 : H * 0.47 + size * 0.2 + stamp(c, sx, sy, 90 * u, '荀子', lt - se) + text(c, '— 《荀子 · 劝学》', W / 2, P ? H * 0.9 : H * 0.72, 28 * u, F.song, COL.gold, ramp(lt, se + 0.6, 1), 'center', 8 * u) + }, + }, + + endcard: { + zoom: 0.4, + draw(S) { + const { c, W, H, u, P, lt } = S + mountains(c, W, H, lt, { seed: 81, alpha: 0.35, y: 80 * u }) + dust(c, W, H, lt, 40, 51, COL.paper, 0.3) + const Y = P ? H * 0.36 : H * 0.36 + text(c, '劝 学', W / 2, Y, 120 * u, F.brush, COL.paper, ramp(lt, 0.3, 1), 'center', 10 * u) + text(c, '荀子 · 《荀子》第一篇', W / 2, Y + 100 * u, 30 * u, F.song, COL.gold, ramp(lt, 0.8, 1), 'center', 8 * u) + hairline(c, W / 2 - 260 * u, Y + 150 * u, W / 2 + 260 * u, Y + 150 * u, ramp(lt, 1.2, 1), COL.gold, 0.4, u) + const cr = ['原文 《荀子 · 劝学》 统编版高中语文必修上册', '文案原创 · AI 配音 · 画面 音乐 音效 程序化生成', '学不可以已 · 与君共勉'] + cr.forEach((s, i) => text(c, s, W / 2, Y + (200 + i * 50) * u, (i === 2 ? 30 : 22) * u, i === 2 ? F.kai : F.song, i === 2 ? COL.paper : COL.muted, ramp(lt, 1.6 + i * 0.5, 1), 'center', 4 * u)) + seal(c, W / 2, Y + 420 * u, 70 * u, '劝学', ramp(lt, 3, 0.5)) + }, + }, +} + +function drawCrab(c: Ctx, x: number, y: number, s: number, a: number, t: number) { + if (a <= 0) return + c.save(); c.translate(x, y) + c.strokeStyle = rgba('#b5523b', a); c.lineCap = 'round'; c.lineWidth = s * 0.05 + for (const side of [-1, 1]) { + for (let i = 0; i < 3; i++) { + const ox = side * s * 0.32, oy = (i - 1) * s * 0.14 + const wig = Math.sin(t * 14 + i * 2 + side) * s * 0.05 + c.beginPath(); c.moveTo(ox, oy); c.lineTo(ox + side * s * 0.28, oy - s * 0.12 + wig); c.lineTo(ox + side * s * 0.42, oy + s * 0.2 + wig); c.stroke() + } + // 螯 + c.beginPath(); c.moveTo(side * s * 0.22, -s * 0.2); c.lineTo(side * s * 0.4, -s * 0.48); c.stroke() + c.fillStyle = rgba('#c25d43', a) + c.beginPath(); c.ellipse(side * s * 0.44, -s * 0.56, s * 0.12, s * 0.08, side * 0.6, 0, Math.PI * 2); c.fill() + } + c.fillStyle = rgba('#a9472f', a) + c.beginPath(); c.ellipse(0, 0, s * 0.36, s * 0.24, 0, 0, Math.PI * 2); c.fill() + c.fillStyle = rgba('#e7d6b8', a) + for (const side of [-1, 1]) { c.beginPath(); c.arc(side * s * 0.1, -s * 0.24, s * 0.03, 0, Math.PI * 2); c.fill() } + c.restore() +} diff --git a/quanxue-src/src/quanxue/script.json b/quanxue-src/src/quanxue/script.json new file mode 100644 index 0000000000000000000000000000000000000000..fa951bb3bf4d99ac8f8e3e3a37a165bd806aeeaf --- /dev/null +++ b/quanxue-src/src/quanxue/script.json @@ -0,0 +1,76 @@ +{ + "title": "劝学", + "author": "荀子", + "chapters": [ + { + "id": "c1", "no": "壹", "title": "其人其书", "sub": "战国末年 · 稷下学宫", + "lines": [ + { "id": "c1l1", "kind": "say", "vis": "era", "text": "两千两百多年前,战国末年,一位年过半百的学者,来到齐国的稷下学宫。" }, + { "id": "c1l2", "kind": "say", "vis": "person", "text": "他叫荀况,赵国人,世人尊称荀卿。他三次出任学宫祭酒,是那个时代最有分量的学者;韩非与李斯,都出自他的门下。" }, + { "id": "c1l3", "kind": "say", "vis": "slips", "text": "后人整理的《荀子》共三十二篇,开卷第一篇,便是《劝学》。" }, + { "id": "c1l4", "kind": "say", "vis": "slips", "text": "把“学”放在一切之前——这不是偶然的编排,而是一种思想的宣言。" } + ] + }, + { + "id": "c2", "no": "贰", "title": "思想底色", "sub": "性恶 · 化性起伪", + "lines": [ + { "id": "c2l1", "kind": "say", "vis": "ren", "text": "要读懂《劝学》,先要读懂荀子对“人”的判断。" }, + { "id": "c2l2", "kind": "quote", "vis": "ren", "text": "人之性恶,其善者伪也。", "src": "《荀子·性恶》" }, + { "id": "c2l3", "kind": "say", "vis": "wei", "text": "这里的“伪”,不是虚伪,而是“人为”——人后天的努力与塑造。" }, + { "id": "c2l4", "kind": "say", "vis": "mengxun", "text": "孟子相信,善端本自具足,只需向内寻回;荀子却认为,人生来只有欲望与本能,善,必须向外求取,一点一点筑起。" }, + { "id": "c2l5", "kind": "say", "vis": "road", "text": "所以在荀子这里,学习不是锦上添花,而是一个人从“自然之人”走向“文明之人”的唯一道路。" }, + { "id": "c2l6", "kind": "say", "vis": "huaxing", "text": "这就是“化性起伪”。而《劝学》,正是这条道路的总纲。" } + ] + }, + { + "id": "c3", "no": "叁", "title": "学不可以已", "sub": "后天胜先天 · 改变不可逆", + "lines": [ + { "id": "c3l1", "kind": "quote", "vis": "five", "text": "君子曰:学不可以已。" }, + { "id": "c3l2", "kind": "say", "vis": "five", "text": "开篇五个字,斩钉截铁:学习,不可以停止。" }, + { "id": "c3l3", "kind": "quote", "vis": "indigo", "text": "青,取之于蓝,而青于蓝;冰,水为之,而寒于水。" }, + { "id": "c3l4", "kind": "say", "vis": "indigo", "text": "靛青从蓼蓝中提炼,颜色却比蓼蓝更深;冰由水凝结,却比水更寒冷。" }, + { "id": "c3l5", "kind": "say", "vis": "surpass", "text": "荀子借此说明:经过学习的人,可以超越自己的本来面目。后天,能够胜过先天。" }, + { "id": "c3l6", "kind": "quote", "vis": "wheel", "text": "木直中绳,輮以为轮,其曲中规。虽有槁暴,不复挺者,輮使之然也。", "tts": "木直众绳,柔以为轮,其曲众规。虽有搞瀑,不复挺者,柔使之然也。" }, + { "id": "c3l7", "kind": "say", "vis": "wheel", "text": "一根笔直的木头,用火烘烤,弯成车轮;即便再经日晒风干,也不会重新挺直。" }, + { "id": "c3l8", "kind": "say", "vis": "reshape", "text": "这是全篇最深刻的比喻:学习带来的改变,是根本的、不可逆的。它不是给人涂上一层颜色,而是重塑人的形状。" }, + { "id": "c3l9", "kind": "quote", "vis": "rope", "text": "故木受绳则直,金就砺则利,君子博学而日参省乎己,则知明而行无过矣。", "tts": "故木受绳则直,金就砺则利,君子博学而日餐醒乎己,则智明而行无过矣。" }, + { "id": "c3l10", "kind": "say", "vis": "rings", "text": "绳墨与砺石,是外在的规范;“博学”与“参省”,是向外求知与向内反省的结合。知与行,由此统一。", "tts": "绳墨与砺石,是外在的规范;“博学”与“餐醒”,是向外求知与向内反省的结合。知与行,由此统一。" } + ] + }, + { + "id": "c4", "no": "肆", "title": "善假于物", "sub": "站在前人的肩上", + "lines": [ + { "id": "c4l1", "kind": "quote", "vis": "climb", "text": "吾尝终日而思矣,不如须臾之所学也;吾尝跂而望矣,不如登高之博见也。", "tts": "吾尝终日而思矣,不如须臾之所学也;吾尝企而望矣,不如登高之博见也。" }, + { "id": "c4l2", "kind": "say", "vis": "climb", "text": "空想一整天,比不上片刻的学习;踮起脚尖眺望,比不上登上高处看得辽阔。荀子并不轻视思考,他反对的,是脱离积累的空想。" }, + { "id": "c4l3", "kind": "quote", "vis": "wave", "text": "登高而招,臂非加长也,而见者远;顺风而呼,声非加疾也,而闻者彰。" }, + { "id": "c4l4", "kind": "quote", "vis": "boat", "text": "假舆马者,非利足也,而致千里;假舟楫者,非能水也,而绝江河。" }, + { "id": "c4l5", "kind": "quote", "vis": "jia", "text": "君子生非异也,善假于物也。" }, + { "id": "c4l6", "kind": "say", "vis": "jia", "text": "君子与常人,生来并没有什么不同;差别只在于,是否善于借助外物。" }, + { "id": "c4l7", "kind": "say", "vis": "books", "text": "而人所能借助的最伟大的“物”,正是前人积累下来的知识与经验。读一本书,就是登上一处高地;学一门学问,就是乘上一辆车马。" } + ] + }, + { + "id": "c5", "no": "伍", "title": "积 · 恒 · 专", "sub": "学习的方法与态度", + "lines": [ + { "id": "c5l1", "kind": "quote", "vis": "mountain", "text": "积土成山,风雨兴焉;积水成渊,蛟龙生焉;积善成德,而神明自得,圣心备焉。" }, + { "id": "c5l2", "kind": "say", "vis": "mountain", "text": "土积成山,才会兴起风雨;水积成渊,才会孕育蛟龙。量的积累,终将引发质的飞跃。" }, + { "id": "c5l3", "kind": "quote", "vis": "steps", "text": "故不积跬步,无以至千里;不积小流,无以成江海。" }, + { "id": "c5l4", "kind": "quote", "vis": "horse", "text": "骐骥一跃,不能十步;驽马十驾,功在不舍。" }, + { "id": "c5l5", "kind": "say", "vis": "horse", "text": "千里马纵身一跃,也跳不出十步;劣马拉车走上十天,同样能抵达远方。决定成败的,不是天赋,而是不肯停下。" }, + { "id": "c5l6", "kind": "quote", "vis": "carve", "text": "锲而舍之,朽木不折;锲而不舍,金石可镂。" }, + { "id": "c5l7", "kind": "quote", "vis": "worm", "text": "蚓无爪牙之利,筋骨之强,上食埃土,下饮黄泉,用心一也。蟹六跪而二螯,非蛇鳝之穴无可寄托者,用心躁也。" }, + { "id": "c5l8", "kind": "say", "vis": "worm", "text": "蚯蚓柔弱,却因专一而上下自如;螃蟹强悍,却因浮躁而无处安身。" }, + { "id": "c5l9", "kind": "say", "vis": "keys", "text": "积累、坚持、专一——这是荀子交给我们的三把钥匙。" } + ] + }, + { + "id": "c6", "no": "终", "title": "学至乎没而后止", "sub": "以自身为材料的终身雕琢", + "lines": [ + { "id": "c6l1", "kind": "say", "vis": "traveler", "text": "荀子在后文写道:“学至乎没而后止也。”学习,要到生命终结才停止。", "tts": "荀子在后文写道:“学至乎末而后止也。”学习,要到生命终结才停止。" }, + { "id": "c6l2", "kind": "say", "vis": "traveler", "text": "在他看来,学习不只是获取知识,而是一个人以自身为材料,日复一日地雕琢、塑形,最终成为一个完整的人。" }, + { "id": "c6l3", "kind": "say", "vis": "sunrise", "text": "两千多年后,我们依然站在同样的起点上:天性给了我们出发的地方,而学习,决定我们能走多远。" }, + { "id": "c6l4", "kind": "quote", "vis": "finale", "text": "君子曰:学不可以已。" } + ] + } + ] +} diff --git a/quanxue-src/src/quanxue/timeline.ts b/quanxue-src/src/quanxue/timeline.ts new file mode 100644 index 0000000000000000000000000000000000000000..eec6200387f936c6f99a55db1a284ffaca709c06 --- /dev/null +++ b/quanxue-src/src/quanxue/timeline.ts @@ -0,0 +1,189 @@ +// 由旁白真实时长自动排布全片时间轴:章节卡、镜头、每句旁白、逐字时间、字幕分段、音效点 +import script from './script.json' +import voice from './voice.json' +import { isPunct } from './engine/util' + +type RawLine = { id: string; kind: 'say' | 'quote'; vis: string; text: string; tts?: string; src?: string } +type RawChapter = { id: string; no: string; title: string; sub: string; lines: RawLine[] } +type VoiceMeta = Record + +export type Chunk = { text: string; start: number; end: number } +export type Line = RawLine & { + start: number; dur: number; end: number + chapter: number + charT: number[] + chunksL: Chunk[]; chunksP: Chunk[] +} +export type Shot = { idx: number; vis: string; start: number; end: number; lines: Line[]; quote?: Line; chapter: number } +export type ChapterT = { id: string; no: string; title: string; sub: string; start: number; end: number } +export type SfxType = 'drop' | 'boom' | 'brush' | 'stamp' | 'bell' | 'chime' | 'whoosh' | 'creak' | 'fire' | 'tick' | 'rain' | 'drip' | 'wind' | 'water' | 'page' | 'thud' +export type Cue = { t: number; type: SfxType; gain?: number; seed?: number } + +export const INTRO = 9 +export const CARD = 3.8 +export const END_CARD = 9 +const FIRST_DELAY = 0.55 +const GAP = { say: 0.5, quote: 1.05 } + +const V = voice as VoiceMeta +const chapters = (script as { chapters: RawChapter[] }).chapters + +function charTimes(line: RawLine, start: number, dur: number): number[] { + const text = line.text + const tts = line.tts || line.text + const words = V[line.id]?.words || [] + const T: number[] = new Array(text.length).fill(NaN) + let p = 0 + for (const w of words) { + const chars = [...w.t].filter((c) => !isPunct(c)) + chars.forEach((c, k) => { + let q = p + while (q < tts.length && tts[q] !== c) q++ + if (q < tts.length) { T[q] = start + w.o + (w.d * k) / Math.max(1, chars.length); p = q + 1 } + }) + } + // 补齐未匹配字符:线性插值 + let last = start, lastI = -1 + for (let i = 0; i <= text.length; i++) { + if (i === text.length || !isNaN(T[i])) { + const next = i === text.length ? start + dur : T[i] + for (let j = lastI + 1; j < i; j++) T[j] = last + ((next - last) * (j - lastI)) / (i - lastI) + if (i < text.length) { last = T[i]; lastI = i } + } + } + return T +} + +const TRIM = /^[,。;:、\s]+|[,。;:、\s]+$/g +function chunks(text: string, T: number[], end: number, max: number): Chunk[] { + // 先按标点切成小句,再贪心合并到不超过 max 字 + const parts: { s: number; e: number }[] = [] + let s = 0 + for (let i = 0; i < text.length; i++) { + if (',。;:?!、—'.includes(text[i])) { + let e = i + 1 + while (e < text.length && ('—”'.includes(text[e]))) e++ + parts.push({ s, e }); s = e; i = e - 1 + } + } + if (s < text.length) parts.push({ s, e: text.length }) + const out: { s: number; e: number }[] = [] + for (const p of parts) { + const cur = out[out.length - 1] + const len = (a: number, b: number) => [...text.slice(a, b)].filter((c) => !isPunct(c)).length + if (cur && len(cur.s, p.e) <= max && !/[。?!]/.test(text[cur.e - 1])) cur.e = p.e + else out.push({ ...p }) + } + return out.map((p, i) => ({ + text: text.slice(p.s, p.e).replace(TRIM, '').replace(/——$/, ''), + start: T[p.s] - 0.08, + end: i + 1 < out.length ? T[out[i + 1].s] - 0.08 : end + 0.15, + })).filter((c) => c.text.length > 0) +} + +function build() { + const shots: Shot[] = [] + const lines: Line[] = [] + const chs: ChapterT[] = [] + const cues: Cue[] = [] + let t = 0 + shots.push({ idx: 0, vis: 'title', start: 0, end: INTRO, lines: [], chapter: -1 }) + cues.push({ t: 1.32, type: 'drop' }, { t: 1.62, type: 'boom', gain: 1 }, { t: 2.3, type: 'brush', gain: 0.8 }, { t: 4.55, type: 'stamp' }, { t: 5.1, type: 'chime', gain: 0.7 }) + t = INTRO + chapters.forEach((c, ci) => { + const cStart = t + shots.push({ idx: shots.length, vis: 'card', start: t, end: t + CARD, lines: [], chapter: ci }) + cues.push({ t: t + 0.15, type: 'bell', gain: 0.9 }, { t: t + 0.7, type: 'brush', gain: 0.6 }) + t += CARD + let shot: Shot | null = null + c.lines.forEach((rl) => { + if (!shot || shot.vis !== rl.vis) { + if (shot) shot.end = t + shot = { idx: shots.length, vis: rl.vis, start: t, end: t, lines: [], chapter: ci } + shots.push(shot) + cues.push({ t: t - 0.25, type: 'whoosh', gain: 0.45, seed: shots.length }) + t += FIRST_DELAY + } + const dur = V[rl.id]?.dur ?? 3 + const start = t + const charT = charTimes(rl, start, dur) + const line: Line = { ...rl, start, dur, end: start + dur, chapter: ci, charT, chunksL: chunks(rl.text, charT, start + dur, 20), chunksP: chunks(rl.text, charT, start + dur, 13) } + if (rl.kind === 'quote') { shot.quote = line; cues.push({ t: start - 0.15, type: 'brush', gain: 0.35, seed: lines.length }) } + shot.lines.push(line) + lines.push(line) + t = start + dur + GAP[rl.kind] + }) + t += 0.5 + if (ci === chapters.length - 1) t += 3.2 // 结尾定格 + if (shot) (shot as Shot).end = t + chs.push({ id: c.id, no: c.no, title: c.title, sub: c.sub, start: cStart, end: t }) + }) + shots.push({ idx: shots.length, vis: 'endcard', start: t, end: t + END_CARD, lines: [], chapter: -1 }) + cues.push({ t: t + 0.3, type: 'bell', gain: 0.8 }) + t += END_CARD + return { shots, lines, chapters: chs, cues, duration: t } +} + +export const TL = build() +export const DURATION = TL.duration + +const lineById = new Map(TL.lines.map((l) => [l.id, l])) +export const getLine = (id: string) => lineById.get(id)! + +/** 某句中某个词开始被念出的绝对时间 */ +export function keyT(id: string, sub: string, offset = 0): number { + const l = lineById.get(id) + if (!l) return 0 + const i = l.text.indexOf(sub) + if (i < 0) { console.warn('keyT miss', id, sub); return l.start } + return l.charT[i] + offset +} + +// ---- 与画面共享的音效节拍 ---- +/** 刻凿的敲击时间(锲而舍之 → 少量后停止;锲而不舍 → 持续) */ +export function carveStrikes(): number[] { + const a = keyT('c5l6', '锲而舍之'), b = keyT('c5l6', '朽木不折'), c = keyT('c5l6', '锲而不舍'), d = getLine('c5l6').end + 1.0 + const out: number[] = [] + for (let x = a; x < b - 0.2; x += 0.42) out.push(x) + for (let x = c; x < d; x += 0.26) out.push(x) + return out +} + +function addSceneCues() { + const C = TL.cues + C.push({ t: keyT('c1l3', '三十二篇'), type: 'page', gain: 0.6 }) + C.push({ t: keyT('c1l4', '宣言'), type: 'chime', gain: 0.55 }) + C.push({ t: keyT('c2l3', '人为'), type: 'thud', gain: 0.6 }) + C.push({ t: keyT('c2l6', '化性起伪'), type: 'boom', gain: 0.7 }) + ;['化', '性', '起', '伪'].forEach((ch, i) => C.push({ t: keyT('c2l6', '化性起伪') + 0.25 + i * 0.32, type: 'stamp', gain: 0.4 })) + C.push({ t: keyT('c3l2', '斩钉截铁'), type: 'boom', gain: 0.9 }) + C.push({ t: keyT('c3l3', '冰'), type: 'chime', gain: 0.4 }) + C.push({ t: keyT('c3l6', '輮以为轮'), type: 'fire', gain: 0.8 }) + C.push({ t: keyT('c3l6', '輮以为轮', 0.6), type: 'creak', gain: 0.7 }) + C.push({ t: keyT('c3l9', '金就砺'), type: 'tick', gain: 0.5, seed: 3 }) + C.push({ t: keyT('c4l1', '登高'), type: 'wind', gain: 0.4 }) + C.push({ t: keyT('c4l3', '顺风而呼'), type: 'wind', gain: 0.7 }) + C.push({ t: keyT('c4l4', '假舟楫'), type: 'water', gain: 0.7 }) + C.push({ t: keyT('c4l7', '读一本书'), type: 'page', gain: 0.6 }) + C.push({ t: keyT('c5l1', '风雨兴焉'), type: 'rain', gain: 0.7 }) + C.push({ t: keyT('c5l1', '积水成渊'), type: 'drip', gain: 0.8 }) + C.push({ t: keyT('c5l1', '蛟龙生焉'), type: 'boom', gain: 0.45 }) + C.push({ t: keyT('c5l1', '积善成德'), type: 'chime', gain: 0.6 }) + C.push({ t: keyT('c5l4', '骐骥一跃'), type: 'whoosh', gain: 0.6, seed: 91 }) + carveStrikes().forEach((x, i) => C.push({ t: x, type: 'tick', gain: 0.5, seed: i })) + ;['积累', '坚持', '专一'].forEach((w) => C.push({ t: keyT('c5l9', w), type: 'stamp', gain: 0.9 })) + C.push({ t: keyT('c6l3', '能走多远'), type: 'chime', gain: 0.5 }) + C.push({ t: keyT('c6l4', '学不可以已'), type: 'boom', gain: 0.8 }) + C.push({ t: getLine('c6l4').end + 0.6, type: 'stamp', gain: 1 }) + C.sort((a, b) => a.t - b.t) +} +addSceneCues() + +export function shotAt(t: number): number { + const S = TL.shots + for (let i = S.length - 1; i >= 0; i--) if (t >= S[i].start) return i + return 0 +} +export function chapterAt(t: number): number { + return TL.chapters.findIndex((c) => t >= c.start && t < c.end) +} diff --git a/quanxue-src/src/quanxue/ui/CoverPanel.tsx b/quanxue-src/src/quanxue/ui/CoverPanel.tsx new file mode 100644 index 0000000000000000000000000000000000000000..80a6c1c64a4b1b5aae14abd112135cb30d38d6be --- /dev/null +++ b/quanxue-src/src/quanxue/ui/CoverPanel.tsx @@ -0,0 +1,95 @@ +import { useEffect, useState } from 'react' +import { Check, Download, ImageDown } from 'lucide-react' +import { COVERS, RATIO_DIM, renderCover, type Ratio } from '../covers' +import { useAssets } from './store' + +const RATIOS: { r: Ratio; t: string; tip: string }[] = [ + { r: '3:4', t: '3:4 竖版', tip: '小红书 / 视频号' }, + { r: '4:3', t: '4:3 横版', tip: '视频号 / 公众号' }, + { r: '16:9', t: '16:9 宽屏', tip: 'B站 / 抖音横屏' }, +] + +function download(cv: HTMLCanvasElement, name: string) { + return new Promise((res) => cv.toBlob((b) => { + if (b) { const url = URL.createObjectURL(b); const a = document.createElement('a'); a.href = url; a.download = name; document.body.appendChild(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(url), 4000) } + res() + }, 'image/png')) +} + +export function CoverPanel() { + const assets = useAssets() + const [ratios, setRatios] = useState(['3:4', '4:3', '16:9']) + const [designs, setDesigns] = useState(COVERS.map((c) => c.id)) + const [previews, setPreviews] = useState>({}) + const [busy, setBusy] = useState(false) + + useEffect(() => { + if (!assets.fonts) return + let cancelled = false + ;(async () => { + const out: Record = {} + for (const d of COVERS) for (const { r } of RATIOS) { + if (cancelled) return + out[`${d.id}_${r}`] = renderCover(d, r, 0.36).toDataURL('image/jpeg', 0.86) + setPreviews({ ...out }) + await new Promise((res) => setTimeout(res, 0)) + } + })() + return () => { cancelled = true } + }, [assets.fonts]) + + const toggle = (arr: T[], v: T) => (arr.includes(v) ? arr.filter((x) => x !== v) : [...arr, v]) + const selected = COVERS.filter((d) => designs.includes(d.id)).flatMap((d) => ratios.map((r) => ({ d, r }))) + + const dlAll = async () => { + setBusy(true) + for (const { d, r } of selected) { await download(renderCover(d, r), `劝学封面_${d.name.replace(/\s|·/g, '')}_${r.replace(':', 'x')}.png`); await new Promise((res) => setTimeout(res, 350)) } + setBusy(false) + } + + return ( +
+
+
+
比例(可多选)
+
+ {RATIOS.map(({ r, t, tip }) => ( + + ))} +
+
+
+
设计(可多选)
+
+ {COVERS.map((d) => ( + + ))} +
+
+ +
+ {ratios.map((r) => ( +
+
{r} · {RATIO_DIM[r][0]}×{RATIO_DIM[r][1]}
+
+ {COVERS.filter((d) => designs.includes(d.id)).map((d) => ( +
+ {previews[`${d.id}_${r}`] ? {d.name} :
} +
+ {d.name} + +
+
+ ))} +
+
+ ))} +
+ ) +} diff --git a/quanxue-src/src/quanxue/ui/ExportPanel.tsx b/quanxue-src/src/quanxue/ui/ExportPanel.tsx new file mode 100644 index 0000000000000000000000000000000000000000..5c3927d96925b651a6f26ddf96d5330554ac10fa --- /dev/null +++ b/quanxue-src/src/quanxue/ui/ExportPanel.tsx @@ -0,0 +1,109 @@ +import { useEffect, useRef, useState } from 'react' +import { Download, Film, Loader2, X } from 'lucide-react' +import { DURATION } from '../timeline' +import { dims, estimateMB, exportMp4, pickCodecs, webCodecsSupported, type ExportOpts, type Progress, type Res } from '../exporter' +import { engine, fmtTime, useAssets } from './store' + +function Seg({ label, value, options, onChange, disabled }: { label: string; value: T; options: { v: T; t: string; sub?: string }[]; onChange: (v: T) => void; disabled?: boolean }) { + return ( +
+
{label}
+
+ {options.map((o) => ( + + ))} +
+
+ ) +} + +export function ExportPanel({ defaultPortrait }: { defaultPortrait: boolean }) { + const assets = useAssets() + const [o, setO] = useState({ res: '1080P', fps: 30, portrait: defaultPortrait, music: true }) + const [codecs, setCodecs] = useState<{ video: string | null; audio: string | null } | null>(null) + const [prog, setProg] = useState(null) + const [busy, setBusy] = useState(false) + const [result, setResult] = useState<{ url?: string; name: string; size?: number; disk: boolean; codec: string; secs: number } | null>(null) + const [err, setErr] = useState('') + const sig = useRef({ cancelled: false }) + const supported = webCodecsSupported() + useEffect(() => { setO((x) => ({ ...x, portrait: defaultPortrait })) }, [defaultPortrait]) + useEffect(() => { if (supported) pickCodecs(o).then((c) => setCodecs(c)).catch(() => setCodecs({ video: null, audio: null })) }, [o.res, o.fps, o.portrait, supported]) + + const [w, h] = dims(o) + const name = `劝学_荀子_${o.res}_${o.fps}fps_${o.portrait ? '竖屏' : '横屏'}${o.music ? '' : '_无背景音乐'}.mp4` + + const start = async () => { + setErr(''); setResult(null) + if (engine.playing) engine.pause() + let handle: any = null + const w = window as any + if (typeof w.showSaveFilePicker === 'function' && estimateMB(o) > 300) { + try { handle = await w.showSaveFilePicker({ suggestedName: name, types: [{ description: 'MP4 视频', accept: { 'video/mp4': ['.mp4'] } }] }) } catch (e: any) { if (e?.name === 'AbortError') return; handle = null } + } + sig.current = { cancelled: false } + setBusy(true) + const t0 = performance.now() + try { + const r = await exportMp4(engine, o, setProg, sig.current, handle) + const secs = (performance.now() - t0) / 1000 + if (r.blob) { + const url = URL.createObjectURL(r.blob) + setResult({ url, name, size: r.blob.size, disk: false, codec: r.codec, secs }) + const a = document.createElement('a'); a.href = url; a.download = name; document.body.appendChild(a); a.click(); a.remove() + } else setResult({ name, disk: true, codec: r.codec, secs }) + } catch (e: any) { + setErr(e?.message === 'cancelled' ? '已取消导出。' : '导出失败:' + (e?.message || e)) + } finally { setBusy(false); setProg(null) } + } + + const ready = assets.fonts && assets.voice >= 1 + return ( +
+
+ setO({ ...o, portrait: v === 'p' })} options={[{ v: 'l', t: '横屏', sub: '16:9' }, { v: 'p', t: '竖屏', sub: '9:16 手机' }]} /> + label="分辨率" value={o.res} disabled={busy} onChange={(v) => setO({ ...o, res: v })} options={[{ v: '2K', t: '2K', sub: '1440p' }, { v: '1080P', t: '1080P', sub: '全高清' }, { v: '720P', t: '720P', sub: '高清' }]} /> + label="帧率" value={o.fps} disabled={busy} onChange={(v) => setO({ ...o, fps: v as 24 | 30 | 60 })} options={[{ v: 24, t: '24 fps', sub: '电影感' }, { v: 30, t: '30 fps', sub: '标准' }, { v: 60, t: '60 fps', sub: '丝滑' }]} /> + setO({ ...o, music: v === 'y' })} options={[{ v: 'y', t: '导出背景音乐' }, { v: 'n', t: '不导出', sub: '仅旁白 + 音效' }]} /> +
+
+
导出设置
+
+
输出尺寸
{w} × {h}
+
时长 / 帧数
{fmtTime(DURATION)} · {Math.ceil(DURATION * o.fps).toLocaleString()} 帧
+
预计大小
约 {estimateMB(o)} MB
+
编码
{!supported ? '—' : codecs ? `${codecs.video ? (codecs.video === 'avc' ? 'H.264' : codecs.video.toUpperCase()) : '不支持'} + ${codecs.audio ? codecs.audio.toUpperCase() : '无音轨'}` : '检测中…'}
+
+ {!supported &&
当前浏览器不支持 WebCodecs,无法本地导出。请使用最新版 Chrome / Edge(电脑端效果最佳)。
} + {supported && codecs && !codecs.video &&
该分辨率 / 帧率组合超出本机编码能力,请降低分辨率或帧率。
} + {!busy ? ( + + ) : ( +
+
{prog?.phase ?? '准备中'}{Math.round((prog?.p ?? 0) * 100)}%
+
+
{prog?.total ? `${prog.frame.toLocaleString()} / ${prog.total.toLocaleString()} 帧 · ${prog.fps.toFixed(1)} 帧/秒 · 剩余约 ${fmtTime(prog.eta)}` : ''}
+ +
+ )} + {result && ( +
+ ✓ 导出完成({result.codec},用时 {fmtTime(result.secs)}){result.disk ? ',已直接保存到你选择的位置。' : `,${((result.size ?? 0) / 1024 / 1024).toFixed(1)} MB。`} + {result.url && 若未自动下载,点此保存 {result.name}} +
+ )} + {err &&
{err}
} +
    +
  • 全程在本机浏览器渲染编码,不上传任何数据。
  • +
  • 导出期间请保持本页在前台;2K / 60fps 耗时较长。
  • +
  • 文件较大时(Chrome / Edge)会请你先选择保存位置,边渲染边写入磁盘。
  • +
+
+
+ ) +} diff --git a/quanxue-src/src/quanxue/ui/Player.tsx b/quanxue-src/src/quanxue/ui/Player.tsx new file mode 100644 index 0000000000000000000000000000000000000000..9bda448bfa6f15e44a9b3ef514ab38b8ff8880ab --- /dev/null +++ b/quanxue-src/src/quanxue/ui/Player.tsx @@ -0,0 +1,155 @@ +import { useCallback, useEffect, useRef, useState } from 'react' +import { Maximize2, Minimize2, Music, Music2, Pause, Play, RectangleHorizontal, RectangleVertical, RotateCcw } from 'lucide-react' +import { DURATION, TL, chapterAt } from '../timeline' +import { renderFrame } from '../render' +import { engine, fmtTime, useAssets } from './store' + +export type Orient = 'landscape' | 'portrait' + +export function Player({ orient, setOrient, seekReq }: { orient: Orient; setOrient: (o: Orient) => void; seekReq: { t: number; n: number } }) { + const assets = useAssets() + const ready = assets.fonts && assets.voice >= 1 + const canvasRef = useRef(null) + const boxRef = useRef(null) + const wrapRef = useRef(null) + const [playing, setPlaying] = useState(false) + const [t, setT] = useState(0) + const [fs, setFs] = useState(false) + const [musicOn, setMusicOn] = useState(true) + const [hover, setHover] = useState(false) + const dirty = useRef(true) + const lastUi = useRef(0) + const P = orient === 'portrait' + + // 画布尺寸:容器尺寸 × DPR,长边不超过 1920 + useEffect(() => { + const box = boxRef.current, cv = canvasRef.current + if (!box || !cv) return + const ro = new ResizeObserver(() => { + const r = box.getBoundingClientRect() + const dpr = Math.min(2, window.devicePixelRatio || 1) + let w = r.width * dpr, h = r.height * dpr + const k = Math.min(1, 1920 / Math.max(w, h)) + w = Math.round(w * k); h = Math.round(h * k) + if (w > 10 && h > 10 && (cv.width !== w || cv.height !== h)) { cv.width = w; cv.height = h; dirty.current = true } + }) + ro.observe(box) + return () => ro.disconnect() + }, [orient, fs]) + + useEffect(() => { dirty.current = true }, [orient, ready]) + + // 渲染循环:播放时以音频时钟为准 + useEffect(() => { + let raf = 0 + const loop = () => { + raf = requestAnimationFrame(loop) + const cv = canvasRef.current + if (!cv || !assets.fonts) return + let now = engine.time() + if (engine.playing && now >= DURATION - 0.01) { engine.pause(); engine.seek(DURATION); setPlaying(false); now = DURATION } + if (engine.playing || dirty.current) { + renderFrame(cv.getContext('2d')!, cv.width, cv.height, now) + dirty.current = false + } + const ms = performance.now() + if (ms - lastUi.current > 120) { lastUi.current = ms; setT(now) } + } + raf = requestAnimationFrame(loop) + return () => cancelAnimationFrame(raf) + }, [assets.fonts]) + + const toggle = useCallback(async () => { + if (!ready) return + if (engine.playing) { engine.pause(); setPlaying(false) } + else { + const from = engine.time() >= DURATION - 0.1 ? 0 : engine.time() + await engine.play(from); setPlaying(true) + } + }, [ready]) + + const seek = useCallback((x: number) => { engine.seek(Math.max(0, Math.min(DURATION, x))); dirty.current = true; setT(engine.time()) }, []) + useEffect(() => { if (seekReq.n > 0) seek(seekReq.t) }, [seekReq, seek]) + + // 键盘:空格播放 / 左右快进 + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if ((e.target as HTMLElement)?.tagName === 'TEXTAREA' || (e.target as HTMLElement)?.tagName === 'INPUT') return + if (e.code === 'Space') { e.preventDefault(); toggle() } + if (e.code === 'ArrowRight') seek(engine.time() + 5) + if (e.code === 'ArrowLeft') seek(engine.time() - 5) + if (e.code === 'Escape' && fs) exitFs() + } + window.addEventListener('keydown', onKey) + return () => window.removeEventListener('keydown', onKey) + }) + + const enterFs = async () => { + setFs(true) + try { await wrapRef.current?.requestFullscreen?.() } catch { /* 伪全屏 */ } + try { await (screen.orientation as any)?.lock?.(P ? 'portrait' : 'landscape') } catch { /* ignore */ } + } + const exitFs = async () => { + setFs(false) + try { if (document.fullscreenElement) await document.exitFullscreen() } catch { /* ignore */ } + } + useEffect(() => { + const f = () => { if (!document.fullscreenElement) setFs(false) } + document.addEventListener('fullscreenchange', f) + return () => document.removeEventListener('fullscreenchange', f) + }, []) + + const barRef = useRef(null) + const scrub = (e: React.PointerEvent) => { + const r = barRef.current!.getBoundingClientRect() + seek(((e.clientX - r.left) / r.width) * DURATION) + } + const ci = chapterAt(t) + const showCtl = !playing || hover + + const boxStyle: React.CSSProperties = fs + ? (P ? { height: '100%', maxWidth: '100vw', aspectRatio: '9 / 16', maxHeight: '100vh' } : { width: '100%', maxHeight: '100vh', aspectRatio: '16 / 9', maxWidth: 'calc(100vh * 16 / 9)' }) + : (P ? { height: 'min(78vh, 900px)', aspectRatio: '9 / 16', maxWidth: '100%' } : { width: '100%', aspectRatio: '16 / 9' }) + + return ( +
+
{ setHover(true) }} onMouseLeave={() => setHover(false)}> + + {!ready && ( +
+
劝学
+
+
正在加载字体与旁白…
+ {assets.error &&
{assets.error}
} +
+ )} + {ready && !playing && ( + + )} +
+
{ (e.target as HTMLElement).setPointerCapture(e.pointerId); scrub(e) }} onPointerMove={(e) => { if (e.buttons) scrub(e) }}> +
+
+ {TL.chapters.map((c) =>
)} +
+
+
+ + {fmtTime(t)} / {fmtTime(DURATION)} + {ci >= 0 ? `· ${TL.chapters[ci].title}` : ''} +
+ {!assets.music && 配乐加载中} + + + +
+
+
+
+ ) +} diff --git a/quanxue-src/src/quanxue/ui/PublishPanel.tsx b/quanxue-src/src/quanxue/ui/PublishPanel.tsx new file mode 100644 index 0000000000000000000000000000000000000000..879ed20c9c511301ceba47124d7568a77888f212 --- /dev/null +++ b/quanxue-src/src/quanxue/ui/PublishPanel.tsx @@ -0,0 +1,58 @@ +import { useState } from 'react' +import { Check, Copy } from 'lucide-react' +import { PLATFORMS, countChars, tagText } from '../publish' +import { copyText } from './store' + +function CopyBtn({ text, label = '复制' }: { text: string; label?: string }) { + const [ok, setOk] = useState(false) + return ( + + ) +} + +export function PublishPanel() { + const [pid, setPid] = useState(PLATFORMS[0].id) + const p = PLATFORMS.find((x) => x.id === pid)! + const tags = tagText(p) + return ( +
+
+ {PLATFORMS.map((x) => ( + + ))} +
+
规则:标题 ≤ {p.titleMax} 字 · 话题 {p.tagMax ? `≤ ${p.tagMax} 个` : '不限数量'}
+
+
标题(任选其一)
+ {p.titles.map((t) => { + const n = countChars(t), ok = n <= p.titleMax + return ( +
+
{t}
+ {n}/{p.titleMax} + +
+ ) + })} +
+
+
描述
+