Spaces:
Paused
Paused
暮归江南 · v2 优化:性能(三角形 -60%、预烘焙天光、着色器预编译)、去闪烁(反向深度、稳定阴影、灯光平滑)、骨骼人物与精细民居
Browse filesFiles changed (21)
- README.md+4
- src/jiangnan/JiangnanApp.tsx+76-28
- src/jiangnan/assets/fonts/title.woff2+2-2
- src/jiangnan/assets/fonts/wenkai.woff2+2-2
- src/jiangnan/engine/Film.ts+136-46
- src/jiangnan/engine/figures.tsAdded+315
- src/jiangnan/engine/geom.ts+22
- src/jiangnan/engine/life.ts+40-219
- src/jiangnan/engine/post.ts+2-1
- src/jiangnan/engine/props.ts+9-7
- src/jiangnan/engine/sky.ts+6-1
- src/jiangnan/engine/terrain.ts+3-3
- src/jiangnan/engine/trees.ts+20-14
- src/jiangnan/engine/village.ts+148-4
- src/jiangnan/engine/water.ts+23-27
- src/jiangnan/export/covers.ts+2-1
- src/jiangnan/export/livegen.ts+2-1
- src/jiangnan/export/mp4.ts+5-1
- tools/jiangnan/analyze.py+3-5
- tools/jiangnan/t_flick4.pyAdded+26
- tools/jiangnan/t_perf.pyAdded+16
137 unmodified lines138139140141142143137 unmodified lines- **步骤 9** ✅ Blender 场景脚本 `blender/jiangnan_village.py`:已在沙盒里用 Blender 4.2 LTS(bpy)实际运行,生成 218 栋民居、178 盏灯笼(含关键帧点亮)、石拱桥、水车(旋转动画)、古樟、竹林、Nishita 天空 + 日落关键帧 + 蓝调天光、暮霭体积、10 个镜头(时间轴标记自动切换),并用 Cycles 试渲通过。- **步骤 10** ✅ 全片检查与调优:用无头浏览器逐镜头渲染(横屏 + 竖屏)并做构图 / 曝光量化检查,修正了:远山遮挡夕阳、开场机位、河面朝向、太阳水面倒影过曝导致的辉光泛白(加入高光压缩)、古樟镜头机位穿进民居、夜河镜头里看不到船、终章大全景构图、Blender 夜景镜头穿模与 Nishita 天空在日落后发黑;新增每个镜头独立曝光、水车水花、夜里河岸萤火虫;播放器加入音频时钟失效时的兜底;整页冒烟测试(加载、合成音频、播放、横竖屏切换、封面渲染)无报错。- **补充验证** ✅ 全尺寸实测:① 720p 60fps 导出(H.264 60/1、90 帧 + 音轨,ffmpeg 完整解码通过);② 1080×1440 实况图(90 帧 30fps H.264 + 同尺寸封面 JPEG,3.7 MB MOV),用 LiveCanvas 原版 `verify_pair` 与 `package_live_photo.py` 校验通过(内容标识一致、still-image-time = 1.5 s、单个时间样本、完整解码)。---137 unmodified lines138139140141142143144145146147137 unmodified lines- **步骤 9** ✅ Blender 场景脚本 `blender/jiangnan_village.py`:已在沙盒里用 Blender 4.2 LTS(bpy)实际运行,生成 218 栋民居、178 盏灯笼(含关键帧点亮)、石拱桥、水车(旋转动画)、古樟、竹林、Nishita 天空 + 日落关键帧 + 蓝调天光、暮霭体积、10 个镜头(时间轴标记自动切换),并用 Cycles 试渲通过。- **步骤 10** ✅ 全片检查与调优:用无头浏览器逐镜头渲染(横屏 + 竖屏)并做构图 / 曝光量化检查,修正了:远山遮挡夕阳、开场机位、河面朝向、太阳水面倒影过曝导致的辉光泛白(加入高光压缩)、古樟镜头机位穿进民居、夜河镜头里看不到船、终章大全景构图、Blender 夜景镜头穿模与 Nishita 天空在日落后发黑;新增每个镜头独立曝光、水车水花、夜里河岸萤火虫;播放器加入音频时钟失效时的兜底;整页冒烟测试(加载、合成音频、播放、横竖屏切换、封面渲染)无报错。- **补充验证** ✅ 全尺寸实测:① 720p 60fps 导出(H.264 60/1、90 帧 + 音轨,ffmpeg 完整解码通过);② 1080×1440 实况图(90 帧 30fps H.264 + 同尺寸封面 JPEG,3.7 MB MOV),用 LiveCanvas 原版 `verify_pair` 与 `package_live_photo.py` 校验通过(内容标识一致、still-image-time = 1.5 s、单个时间样本、完整解码)。- **步骤 11(v2 优化:卡顿 / 闪烁 / 模型)** ✅- **卡顿**:实测每帧从约 950 万三角形、近 1000 次绘制调用降到约 350 万、约 200 次(远山林木降面、竹林减段,地形 / 林木 / 小物件不再进入阴影与倒影通道,用 Three.js 图层 Layers 区分「主画面专用」与「可倒影」物体;树木、竹林在山茶与梯田镜头里不画水面反射);环境光(PMREM)改为加载时一次性预烘焙 173 张,播放中不再每 0.5 秒重算;所有镜头(横 / 竖、昼 / 夜)的着色器在加载时预编译,播放中不再出现「第一次出现某镜头时卡一下」;页面时间显示独立刷新,播放时不再整页重渲染;自适应分辨率加入迟滞与冷却,不会来回切换。新增画质档位(高 / 中 / 流畅,手机默认「中」)。- **闪烁**:启用 Three.js 反向深度缓冲(reversedDepthBuffer + 32 位浮点深度纹理),远处屋面、路面不再深度冲突;水面倒影改用裁剪平面(clippingPlanes),兼容反向深度;阴影取景框按镜头固定并在光源空间按纹素对齐,投影用的太阳方向每个镜头固定,阴影不再爬动;街上灯笼的点光源按「第 N+1 盏的距离」平滑淡入淡出,换灯时不再突亮突灭;树叶开启 alpha-to-coverage 抗锯齿;水面细波纹与碎金随距离淡化;胶片颗粒减弱。静态相机实测:除了在飞的白鹭与行人,逐帧跳变像素 ≈ 0%。导出 MP4 / 封面 / 实况图改为超采样渲染(1.4–2 倍分辨率再缩小),细节不抖。- **模型**:村民、牛车、白鹭改为骨骼蒙皮模型(每个角色一次绘制):车削建模的上衣、长衫、袖口、手、头部五官轮廓、发髻与蓝印花布头巾、竹编斗笠(内外两层)、扁担与箩筐;牛有桶形身体、肩峰、垂皮、口鼻、弯角、耳朵、尾巴、蹄子,走路时四腿交替、头尾摆动,车轮带辐条;白鹭有 S 形颈和带飞羽的翅膀。临街临河民居的屋面改为真实起伏的阴阳瓦(近处立体、远处自动淡化防锯齿),檐口加瓦当与滴水;门两侧贴红春联与横批,店铺挂黑底金字店招(米铺、茶馆、酱园、布庄、药铺、豆腐坊、酒坊、竹器),门口有水缸、柴垛、盆栽。---
123464 unmodified lines69707172737475147 unmodified lines2232242252262272282298 unmodified lines23823924024124224324420 unmodified lines26526626726826927027127227320 unmodified lines2942952962972982993003013023031 unmodified line30530630730830931031125 unmodified lines33733833934034134234334434534634734834935035135235335435535635735835936018 unmodified lines37938038138238338438538638738838987 unmodified lines47747847948048148248348448548648748865 unmodified lines55455555655755855956056156256336 unmodified lines60060160260360460560660760860958 unmodified lines668669670671672673674import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import './jiangnan.css'import { buildMix } from './audio/mixer'import blenderScript from './blender/jiangnan_village.py?raw'64 unmodified linesconst [load, setLoad] = useState({ p: 0, label: '准备中' })const [audioReady, setAudioReady] = useState(false)const [playing, setPlaying] = useState(false)const [time, setTime] = useState(0)const [aspect, setAspect] = useState<Aspect>(() => (typeof window !== 'undefined' && window.innerHeight > window.innerWidth && isMobile() ? 'portrait' : 'landscape'))const [subs, setSubs] = useState(true)const [muted, setMuted] = useState(false)147 unmodified linesconst seek = useCallback((t: number) => {const c = clockRef.currentc.t = Math.max(0, Math.min(DURATION, t))setTime(c.t)dirtyRef.current = trueif (c.playing) play(c.t)}, [play])8 unmodified linesif (!ready) returnlet raf = 0let ema = 16let lastUi = 0const loop = () => {raf = requestAnimationFrame(loop)const film = filmRef.current20 unmodified linesema = ema * 0.9 + dt * 0.1if (c.playing) {// adaptive resolution: keep playback smooth on slower devicesif (ema > 42 && scaleRef.current > 0.45) { scaleRef.current *= 0.85; ema = 30; resize() } else if (ema < 14 && scaleRef.current < 1) { scaleRef.current = Math.min(1, scaleRef.current * 1.1); ema = 20; resize() }}if (performance.now() - lastUi > 100) { setTime(t); lastUi = performance.now() }}raf = requestAnimationFrame(loop)return () => cancelAnimationFrame(raf)20 unmodified lineselse el.requestFullscreen?.().catch(() => say('当前浏览器不支持全屏'))}const curShot = shotAt(time)// ------------------------------------------------------------ busy wrapper (export / covers / live)const withBusy = async <T,>(fn: () => Promise<T>) => {pause()busyRef.current = truetry { return await fn() } finally {1 unmodified lineresize()dirtyRef.current = true}}return (<div className="jn">25 unmodified lines<div className="jn-controls"><button className="jn-btn primary" disabled={!ready} onClick={() => (playing ? pause() : play())}>{playing ? '暂停' : '播放'}</button><span className="jn-time">{fmt(time)} / {fmt(DURATION)}</span><div className="jn-scrub"><input type="range" min={0} max={DURATION} step={0.05} value={time} onChange={(e) => seek(Number(e.target.value))} disabled={!ready} /></div><button className={`jn-btn ${aspect === 'landscape' ? 'on' : ''}`} onClick={() => setAspect('landscape')}>横屏 16:9</button><button className={`jn-btn ${aspect === 'portrait' ? 'on' : ''}`} onClick={() => setAspect('portrait')}>竖屏 9:16</button><button className={`jn-btn ghost ${subs ? 'on' : ''}`} onClick={() => setSubs(!subs)}>字幕{subs ? '开' : '关'}</button><button className={`jn-btn ghost ${muted ? '' : 'on'}`} onClick={() => setMuted(!muted)}>{muted ? '已静音' : '声音开'}</button><button className="jn-btn ghost" onClick={fullscreen}>全屏</button></div>{!audioReady && ready && <div className="jn-note">配乐与旁白正在浏览器里合成,稍等几秒后播放会有声音。</div>}<div className="jn-shots">{SHOTS.map((s) => (<button key={s.id} className={`jn-chip ${curShot.id === s.id ? 'active' : ''}`} onClick={() => seek(s.t0 + 0.01)}>{String(s.id).padStart(2, '0')} {s.name}</button>))}</div><ExportSection film={filmRef} audio={audioRef} ready={ready && audioReady} withBusy={withBusy} /><CoverSection film={filmRef} ready={ready} withBusy={withBusy} />18 unmodified lines)}// ====================================================================== exporttype FilmRef = React.MutableRefObject<Film | null>type Busy = <T>(fn: () => Promise<T>) => Promise<T>function ExportSection({ film, audio, ready, withBusy }: { film: FilmRef; audio: React.MutableRefObject<{ buf: AudioBuffer | null }>; ready: boolean; withBusy: Busy }) {const [orient, setOrient] = useState<Aspect>('landscape')const [res, setRes] = useState<720 | 1080>(1080)const [fps, setFps] = useState<24 | 30 | 60>(30)87 unmodified lines<p className="jn-note">提示:1080p 60fps 共 {Math.round(DURATION * 60)} 帧,独立显卡电脑约 2–4 分钟;手机建议导出 720p。iPhone 上导出后点「保存」→「存储视频」。</p></section>)}// ====================================================================== coversinterface CoverItem { key: string; ratio: Ratio; name: string; url: string; blob: Blob }function CoverSection({ film, ready, withBusy }: { film: FilmRef; ready: boolean; withBusy: Busy }) {const [ratios, setRatios] = useState<Ratio[]>(['16:9', '4:3', '3:4'])const [designs, setDesigns] = useState<string[]>(COVER_DESIGNS.map((d) => d.key))const [items, setItems] = useState<CoverItem[]>([])65 unmodified lines</div></section>)}// ====================================================================== copyfunction CopySection({ say }: { say: (m: string) => void }) {const [tab, setTab] = useState(PLATFORMS[0].id)const [pick, setPick] = useState<Record<string, number>>({})const p = PLATFORMS.find((x) => x.id === tab)!36 unmodified lines</div></section>)}// ====================================================================== live photosfunction LiveSection({ film, ready, withBusy, say }: { film: FilmRef; ready: boolean; withBusy: Busy; say: (m: string) => void }) {const [prog, setProg] = useState<{ p: number; label: string } | null>(null)const [res, setRes] = useState<LiveResult | null>(null)const [err, setErr] = useState('')58 unmodified lines<TextDownload /></section>)}function TextDownload() {const all = () => {123464 unmodified lines69707172737475147 unmodified lines2232242252262272288 unmodified lines23723823924024124224320 unmodified lines26426526626726826927027127227320 unmodified lines2942952962972982993003013023031 unmodified line30530630730830931031125 unmodified lines33733833934034134234334434534634734834935035135218 unmodified lines37137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643787 unmodified lines52552652752852953053153253353453553665 unmodified lines60260360460560660760860961061136 unmodified lines64864965065165265365465565665758 unmodified lines716717718719720721722import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'import './jiangnan.css'import { buildMix } from './audio/mixer'import blenderScript from './blender/jiangnan_village.py?raw'64 unmodified linesconst [load, setLoad] = useState({ p: 0, label: '准备中' })const [audioReady, setAudioReady] = useState(false)const [playing, setPlaying] = useState(false)const nowRef = useRef<() => number>(() => 0)const [aspect, setAspect] = useState<Aspect>(() => (typeof window !== 'undefined' && window.innerHeight > window.innerWidth && isMobile() ? 'portrait' : 'landscape'))const [subs, setSubs] = useState(true)const [muted, setMuted] = useState(false)147 unmodified linesconst seek = useCallback((t: number) => {const c = clockRef.currentc.t = Math.max(0, Math.min(DURATION, t))dirtyRef.current = trueif (c.playing) play(c.t)}, [play])8 unmodified linesif (!ready) returnlet raf = 0let ema = 16let lastScale = performance.now()const loop = () => {raf = requestAnimationFrame(loop)const film = filmRef.current20 unmodified linesema = ema * 0.9 + dt * 0.1if (c.playing) {// adaptive resolution: keep playback smooth on slower devices// with hysteresis + cooldown so the resolution never oscillates (that reads as flicker)const since = performance.now() - lastScaleif (ema > 34 && scaleRef.current > 0.45 && since > 1500) { scaleRef.current *= 0.85; ema = 24; lastScale = performance.now(); resize() } else if (ema < 13 && scaleRef.current < 1 && since > 6000) { scaleRef.current = Math.min(1, scaleRef.current * 1.08); ema = 18; lastScale = performance.now(); resize() }}}raf = requestAnimationFrame(loop)return () => cancelAnimationFrame(raf)20 unmodified lineselse el.requestFullscreen?.().catch(() => say('当前浏览器不支持全屏'))}nowRef.current = now// ------------------------------------------------------------ busy wrapper (export / covers / live)const withBusy = useCallback(async <T,>(fn: () => Promise<T>) => {pause()busyRef.current = truetry { return await fn() } finally {1 unmodified lineresize()dirtyRef.current = true}}, [pause, resize]) as Busyreturn (<div className="jn">25 unmodified lines<div className="jn-controls"><button className="jn-btn primary" disabled={!ready} onClick={() => (playing ? pause() : play())}>{playing ? '暂停' : '播放'}</button><TimeReadout nowRef={nowRef} seek={seek} ready={ready} /><button className={`jn-btn ${aspect === 'landscape' ? 'on' : ''}`} onClick={() => setAspect('landscape')}>横屏 16:9</button><button className={`jn-btn ${aspect === 'portrait' ? 'on' : ''}`} onClick={() => setAspect('portrait')}>竖屏 9:16</button><button className={`jn-btn ghost ${subs ? 'on' : ''}`} onClick={() => setSubs(!subs)}>字幕{subs ? '开' : '关'}</button><button className={`jn-btn ghost ${muted ? '' : 'on'}`} onClick={() => setMuted(!muted)}>{muted ? '已静音' : '声音开'}</button><button className="jn-btn ghost" onClick={fullscreen}>全屏</button><QualityPicker /></div>{!audioReady && ready && <div className="jn-note">配乐与旁白正在浏览器里合成,稍等几秒后播放会有声音。</div>}<ShotChips nowRef={nowRef} seek={seek} /><ExportSection film={filmRef} audio={audioRef} ready={ready && audioReady} withBusy={withBusy} /><CoverSection film={filmRef} ready={ready} withBusy={withBusy} />18 unmodified lines)}function QualityPicker() {const cur = (new URLSearchParams(location.search).get('q') as Quality) || (isMobile() ? 'medium' : 'high')const set = (q: Quality) => {const u = new URL(location.href)u.searchParams.set('q', q)location.href = u.toString()}return (<select className="jn-btn ghost" value={cur} onChange={(e) => set(e.target.value as Quality)} aria-label="画质" style={{ paddingRight: 8 }}><option value="high">画质:高</option><option value="medium">画质:中(手机)</option><option value="low">画质:流畅</option></select>)}// ====================================================================== transport (own render cycle)function useFilmTime(nowRef: React.MutableRefObject<() => number>, hz = 8) {const [t, setT] = useState(0)useEffect(() => {let last = -1const id = window.setInterval(() => {const v = Math.round(nowRef.current() * 10) / 10if (v !== last) { last = v; setT(v) }}, 1000 / hz)return () => window.clearInterval(id)}, [nowRef, hz])return t}function TimeReadout({ nowRef, seek, ready }: { nowRef: React.MutableRefObject<() => number>; seek: (t: number) => void; ready: boolean }) {const time = useFilmTime(nowRef)return (<><span className="jn-time">{fmt(time)} / {fmt(DURATION)}</span><div className="jn-scrub"><input type="range" min={0} max={DURATION} step={0.05} value={time} onChange={(e) => seek(Number(e.target.value))} disabled={!ready} /></div></>)}function ShotChips({ nowRef, seek }: { nowRef: React.MutableRefObject<() => number>; seek: (t: number) => void }) {const time = useFilmTime(nowRef, 4)const cur = shotAt(time)return (<div className="jn-shots">{SHOTS.map((s) => (<button key={s.id} className={`jn-chip ${cur.id === s.id ? 'active' : ''}`} onClick={() => seek(s.t0 + 0.01)}>{String(s.id).padStart(2, '0')} {s.name}</button>))}</div>)}// ====================================================================== exporttype FilmRef = React.MutableRefObject<Film | null>type Busy = <T>(fn: () => Promise<T>) => Promise<T>const ExportSection = memo(function ExportSection({ film, audio, ready, withBusy }: { film: FilmRef; audio: React.MutableRefObject<{ buf: AudioBuffer | null }>; ready: boolean; withBusy: Busy }) {const [orient, setOrient] = useState<Aspect>('landscape')const [res, setRes] = useState<720 | 1080>(1080)const [fps, setFps] = useState<24 | 30 | 60>(30)87 unmodified lines<p className="jn-note">提示:1080p 60fps 共 {Math.round(DURATION * 60)} 帧,独立显卡电脑约 2–4 分钟;手机建议导出 720p。iPhone 上导出后点「保存」→「存储视频」。</p></section>)})// ====================================================================== coversinterface CoverItem { key: string; ratio: Ratio; name: string; url: string; blob: Blob }const CoverSection = memo(function CoverSection({ film, ready, withBusy }: { film: FilmRef; ready: boolean; withBusy: Busy }) {const [ratios, setRatios] = useState<Ratio[]>(['16:9', '4:3', '3:4'])const [designs, setDesigns] = useState<string[]>(COVER_DESIGNS.map((d) => d.key))const [items, setItems] = useState<CoverItem[]>([])65 unmodified lines</div></section>)})// ====================================================================== copyconst CopySection = memo(function CopySection({ say }: { say: (m: string) => void }) {const [tab, setTab] = useState(PLATFORMS[0].id)const [pick, setPick] = useState<Record<string, number>>({})const p = PLATFORMS.find((x) => x.id === tab)!36 unmodified lines</div></section>)})// ====================================================================== live photosconst LiveSection = memo(function LiveSection({ film, ready, withBusy, say }: { film: FilmRef; ready: boolean; withBusy: Busy; say: (m: string) => void }) {const [prog, setProg] = useState<{ p: number; label: string } | null>(null)const [res, setRes] = useState<LiveResult | null>(null)const [err, setErr] = useState('')58 unmodified lines<TextDownload /></section>)})function TextDownload() {const all = () => {
123version https://git-lfs.github.com/spec/v1oid sha256:8a0e19db8353edace27893e2bdd4572a167ed6492c5247363582b65a43843e62size 233272123version https://git-lfs.github.com/spec/v1oid sha256:75a02dc6da583ac655d671552f3c5945dbf1ff63cff1ecda40438a71a7f19e0csize 248288
123version https://git-lfs.github.com/spec/v1oid sha256:bc282ef76d0be3bc574df1397041696fbcf13c37cb1a1af64ce15a23adc9f6e8size 143264123version https://git-lfs.github.com/spec/v1oid sha256:6fec6cc3ef086bad9f6d65bb8199459345c55779ef648bcfaa225b20762f9745size 151272
21 unmodified lines2223242526272810 unmodified lines394041424344454647484950515213 unmodified lines666768697071727 unmodified lines808182838485861 unmodified line8889909192939424 unmodified lines1191201211221231241251261271281299 unmodified lines13914014114214314414514614714814915015115215315415515615735 unmodified lines1931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362371 unmodified line23924024124224324424513 unmodified lines25926026126226326426521 unmodified linesexport class Film {renderer: THREE.WebGLRendererscene = new THREE.Scene()camera = new THREE.PerspectiveCamera(40, 16 / 9, 0.3, 14000)post!: Postwater!: Watersky!: ReturnType<typeof createSky>10 unmodified linesenvSky!: THREE.MeshenvRT: THREE.WebGLRenderTarget | null = nullenvKey = -1width = 1280height = 720quality: Qualityready = falseconstructor(canvas: HTMLCanvasElement, quality: Quality = 'high') {this.quality = qualitythis.renderer = new THREE.WebGLRenderer({ canvas, antialias: false, powerPreference: 'high-performance', preserveDrawingBuffer: true, alpha: false })this.renderer.setPixelRatio(1)this.renderer.toneMapping = THREE.ACESFilmicToneMappingthis.renderer.toneMappingExposure = 113 unmodified linesgetTextures()progress(0.12, '生成天空与山谷')await tick()this.sky = createSky()s.add(this.sky.mesh)s.add(createTerrain())progress(0.3, '开垦梯田')7 unmodified liness.add(createEmbankments())progress(0.5, '修建粉墙黛瓦')await tick()this.village = createVillage()s.add(this.village.group)progress(0.62, '搭石桥、架水车、摆集市')await tick()1 unmodified lines.add(this.props.group)progress(0.72, '种下古樟与竹林')await tick()const trees = createTrees()s.add(trees.group)progress(0.86, '村民、牛车、白鹭与灯笼')await tick()24 unmodified linesground.position.y = -6this.envScene.add(ground)this.post = createPost(this.renderer, this.scene, this.camera, this.width, this.height, this.quality === 'low' ? 0 : 4)progress(0.95, '预热着色器')await tick()this.setSize(this.width, this.height)this.renderFrame(1)this.renderFrame(60)progress(1, '完成')this.ready = true}9 unmodified linesthis.water?.setSize(w * rs, h * rs)}private updateEnv(t: number, state: ReturnType<typeof skyState>) {const key = Math.floor(t * 2)if (key === this.envKey && this.envRT) returnthis.envKey = key// the env map uses the sky at quantised time so preview & export matchconst prevStar = this.sky.uniforms.uStarBoost.valuethis.sky.uniforms.uStarBoost.value = 0const old = this.envRTthis.envRT = this.pmrem.fromScene(this.envScene, 0.04, 0.1, 400)this.sky.uniforms.uStarBoost.value = prevStarthis.scene.environment = this.envRT.texturethis.scene.environmentIntensity = lerp(1.6, 1.1, state.night)old?.dispose()}/** Update every animated thing for film time t (seconds). */35 unmodified lines}private placeLights(t: number, st: ReturnType<typeof skyState>) {// shadow frustum follows the subject of the current shotconst shot = shotAt(t)const cam = this.cameraconst fwd = new THREE.Vector3()cam.getWorldDirection(fwd)let center: THREE.Vector3, size: numberif (shot.id === 1 || shot.id === 10) { center = new THREE.Vector3(-20, 0, -10); size = 380 } else if (shot.id === 7) { center = new THREE.Vector3(TERRACE.cx - 60, 80, TERRACE.cz + 80); size = 320 } else if (shot.id === 6) { center = new THREE.Vector3(TREE_POS.x + 6, 2, TREE_POS.z + 4); size = 70 } else {center = cam.position.clone().addScaledVector(fwd, 30)center.y = 2size = 90}const sc = this.sun.shadow.camera as THREE.OrthographicCamerasc.left = -size; sc.right = size; sc.top = size; sc.bottom = -sizesc.near = 1sc.far = 2400sc.updateProjectionMatrix()// snap to texels to avoid shimmeringconst texel = (size * 2) / this.sun.shadow.mapSize.xcenter.x = Math.round(center.x / texel) * texelcenter.z = Math.round(center.z / texel) * texelthis.sun.target.position.copy(center)this.sun.position.copy(center).addScaledVector(st.sunDir, 1000)this.sun.target.updateMatrixWorld()this.moon.target.position.copy(center)this.moon.target.updateMatrixWorld()// nearest lit lanterns become real point lightsconst cp = cam.positionconst cands = this.lanterns.list.filter((l) => t > l.on).map((l) => ({ l, d: l.p.distanceToSquared(cp) + (l.p.clone().sub(cp).dot(fwd) < -4 ? 4000 : 0) })).sort((a, b) => a.d - b.d)this.lamps.forEach((lamp, i) => {const c = cands[i]if (!c || c.d > 90 * 90) { lamp.intensity = 0; return }const lt = t - c.l.onconst on = smoothstep(0, 0.4, lt)const flick = 0.92 + 0.08 * Math.sin(t * 11 + c.l.seed * 50)lamp.position.copy(c.l.p).add(new THREE.Vector3(0, -0.45, 0))lamp.intensity = 26 * on * flick})}1 unmodified linerenderFrame(t: number) {if (!this.sky || !this.water || !this.life) returnconst st = this.update(t)const pose = cameraAt(t, this.width / this.height)applyPose(this.camera, pose)this.sky.mesh.position.copy(this.camera.position)this.updateEnv(t, st)13 unmodified linesthis.post.grade.uniforms.uNight.value = st.nightthis.post.grade.uniforms.uFade.value = fadeBlack(t)this.renderer.shadowMap.needsUpdate = truethis.water.renderReflection(this.renderer, this.scene, this.camera)this.post.composer.render()}}21 unmodified lines2223242526272810 unmodified lines39404142434445464748495051525354555657585960616213 unmodified lines767778798081827 unmodified lines909192939495961 unmodified line989910010110210310424 unmodified lines1291301311321331341351361371381391401411421431441451461471481491501511521531541559 unmodified lines16516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021135 unmodified lines2472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223231 unmodified line32532632732832933033133213 unmodified lines34634734834935035135235335435521 unmodified linesexport class Film {renderer: THREE.WebGLRendererscene = new THREE.Scene()camera = new THREE.PerspectiveCamera(40, 16 / 9, 0.4, 12000)post!: Postwater!: Watersky!: ReturnType<typeof createSky>10 unmodified linesenvSky!: THREE.MeshenvRT: THREE.WebGLRenderTarget | null = nullenvKey = -1envCache = new Map<number, THREE.WebGLRenderTarget>()shadowShot = -1shadowCenter = new THREE.Vector3()shadowDir = new THREE.Vector3(0, 1, 0)shadowSize = 90lampLevel = new Map<number, number>()width = 1280height = 720quality: Qualityready = false/** QA: freeze the camera at this film time (everything else keeps animating) */freezeCam: number | null = nullconstructor(canvas: HTMLCanvasElement, quality: Quality = 'high') {this.quality = qualitythis.renderer = new THREE.WebGLRenderer({ canvas, antialias: false, powerPreference: 'high-performance', preserveDrawingBuffer: false, alpha: false, reversedDepthBuffer: true, stencil: false })// see layers: 0 = everything reflected in the water, 1 = main view onlythis.camera.layers.enable(1)this.renderer.setPixelRatio(1)this.renderer.toneMapping = THREE.ACESFilmicToneMappingthis.renderer.toneMappingExposure = 113 unmodified linesgetTextures()progress(0.12, '生成天空与山谷')await tick()this.sky = createSky(this.renderer.capabilities.reversedDepthBuffer)s.add(this.sky.mesh)s.add(createTerrain())progress(0.3, '开垦梯田')7 unmodified liness.add(createEmbankments())progress(0.5, '修建粉墙黛瓦')await tick()this.village = createVillage(this.quality)s.add(this.village.group)progress(0.62, '搭石桥、架水车、摆集市')await tick()1 unmodified lines.add(this.props.group)progress(0.72, '种下古樟与竹林')await tick()const trees = createTrees(this.quality)s.add(trees.group)progress(0.86, '村民、牛车、白鹭与灯笼')await tick()24 unmodified linesground.position.y = -6this.envScene.add(ground)this.post = createPost(this.renderer, this.scene, this.camera, this.width, this.height, this.quality === 'low' ? 0 : 4)progress(0.9, '烘焙天光')await tick()await this.bakeEnvironment((p) => progress(0.9 + p * 0.05, '烘焙天光'))progress(0.95, '预热着色器')await tick()// warm-up: render every shot once (day and night states) at a tiny size so that every// shader variant (main, reflection clipping, shadow depth, skinning…) is compiled now,// not the first time a shot appears during playbackconst W0 = this.width, H0 = this.heightthis.setSize(96, 54)const warm = [0.5, 12, 20, 28, 36, 44, 51, 58.6, 60, 62, 68, 80]for (let i = 0; i < warm.length; i++) {this.renderFrame(warm[i])this.setSize(54, 96) // portrait framing variantsthis.renderFrame(warm[i])this.setSize(96, 54)progress(0.95 + (i / warm.length) * 0.05, '预热着色器')await tick()}this.shadowShot = -1this.setSize(W0, H0)progress(1, '完成')this.ready = true}9 unmodified linesthis.water?.setSize(w * rs, h * rs)}/** Environment light from the sky. Pre-baked every 0.5 s of film time (no runtime hitches). */private envFor(t: number) {const key = Math.max(0, Math.min(Math.round(t * 2), 9999))let rt = this.envCache.get(key)if (!rt) {// bake the sky as it is at the quantised timeconst st = skyState(key / 2)U.uSunDir.value.copy(st.sunDir)U.uNight.value = st.nightthis.sky.update(st)const prevStar = this.sky.uniforms.uStarBoost.valuethis.sky.uniforms.uStarBoost.value = 0rt = this.pmrem.fromScene(this.envScene, 0.04, 0.1, 400, { size: 64 })this.sky.uniforms.uStarBoost.value = prevStarthis.envCache.set(key, rt)}return rt}/** Bake all environment maps up-front (called during loading). */async bakeEnvironment(progress?: (p: number) => void) {const n = Math.ceil(86 * 2) + 1for (let k = 0; k <= n; k++) {this.envFor(k / 2)if (k % 12 === 0) { progress?.(k / n); await tick() }}}private updateEnv(t: number, state: ReturnType<typeof skyState>) {const key = Math.round(t * 2)if (key === this.envKey && this.envRT) returnthis.envKey = keyconst hit = this.envCache.has(Math.max(0, Math.min(Math.round(t * 2), 9999)))this.envRT = this.envFor(t)if (!hit) {this.sky.update(state)U.uSunDir.value.copy(state.sunDir)U.uNight.value = state.night}this.scene.environment = this.envRT.texturethis.scene.environmentIntensity = lerp(1.6, 1.1, state.night)}/** Update every animated thing for film time t (seconds). */35 unmodified lines}private placeLights(t: number, st: ReturnType<typeof skyState>) {const shot = shotAt(t)const cam = this.cameraconst fwd = new THREE.Vector3()cam.getWorldDirection(fwd)// shadow frustum: fixed for the whole shot (no per-frame re-centering → no shimmering)if (this.shadowShot !== shot.id) {this.shadowShot = shot.id// the sun direction used for shadows is frozen for the shot: a continuously rotating// shadow camera re-samples every texel each frame, which reads as crawling / flickerthis.shadowDir.copy(skyState(shot.t0 + (shot.t1 - shot.t0) * 0.5).sunDir)if (this.shadowDir.y < 0.02) this.shadowDir.y = 0.02this.shadowDir.normalize()const pose = cameraAt(shot.t0 + (shot.t1 - shot.t0) * 0.5, this.width / this.height)const dir = pose.target.clone().sub(pose.pos).setY(0).normalize()if (shot.id === 1 || shot.id === 10) { this.shadowCenter.set(-20, 0, -10); this.shadowSize = 380 } else if (shot.id === 7) { this.shadowCenter.set(TERRACE.cx - 60, 80, TERRACE.cz + 80); this.shadowSize = 320 } else if (shot.id === 6) { this.shadowCenter.set(TREE_POS.x + 6, 2, TREE_POS.z + 4); this.shadowSize = 60 } else {this.shadowCenter.copy(pose.pos).addScaledVector(dir, 34)this.shadowCenter.y = 2this.shadowSize = shot.id === 5 || shot.id === 8 ? 75 : 70}}const size = this.shadowSizeconst sc = this.sun.shadow.camera as THREE.OrthographicCameraif (sc.right !== size) {sc.left = -size; sc.right = size; sc.top = size; sc.bottom = -sizesc.near = 1sc.far = 2400sc.updateProjectionMatrix()}// snap the frustum origin to whole shadow-map texels in light spaceconst texel = (size * 2) / this.sun.shadow.mapSize.xconst lightRot = new THREE.Matrix4().lookAt(this.shadowDir, new THREE.Vector3(0, 0, 0), new THREE.Vector3(0, 1, 0))const inv = lightRot.clone().invert()const c = this.shadowCenter.clone().applyMatrix4(inv)c.x = Math.round(c.x / texel) * texelc.y = Math.round(c.y / texel) * texelc.applyMatrix4(lightRot)this.sun.target.position.copy(c)this.sun.position.copy(c).addScaledVector(this.shadowDir, 1000)this.sun.target.updateMatrixWorld()this.moon.target.position.copy(c)this.moon.target.updateMatrixWorld()// nearest lit lanterns become real point lights; intensities fade with distance so the// set of lights can change without anything visibly poppingconst cp = cam.positionconst R = 26, R0 = 15const cands: { i: number; d: number }[] = []const list = this.lanterns.listfor (let i = 0; i < list.length; i++) {const l = list[i]if (t <= l.on) continueconst dx = l.p.x - cp.x, dy = l.p.y - cp.y, dz = l.p.z - cp.zconst d = Math.sqrt(dx * dx + dy * dy + dz * dz)if (d > R) continueconst ahead = (dx * fwd.x + dy * fwd.y + dz * fwd.z) > -6if (ahead) cands.push({ i, d })}cands.sort((a, b) => a.d - b.d)// the fade-out distance is set by the first lantern that does NOT get a light, so a lantern// swapping in or out of the set always does so at ~zero intensityconst cutoff = Math.min(R, cands[this.lamps.length]?.d ?? R)this.lamps.forEach((lamp, k) => {const c2 = cands[k]if (!c2) { lamp.intensity = 0; return }const l = list[c2.i]const lt = t - l.onconst on = smoothstep(0, 0.4, lt)const flick = 0.92 + 0.08 * Math.sin(t * 11 + l.seed * 50)// fade out toward the edge of the radius, and for the last slots of the setconst edge = 1 - smoothstep(Math.min(R0, cutoff * 0.65), cutoff, c2.d)lamp.position.set(l.p.x, l.p.y - 0.45, l.p.z)lamp.intensity = 26 * on * flick * edge})}1 unmodified linerenderFrame(t: number) {if (!this.sky || !this.water || !this.life) returnconst st = this.update(t)const shot = shotAt(t)const pose = cameraAt(this.freezeCam ?? t, this.width / this.height)applyPose(this.camera, pose)this.sky.mesh.position.copy(this.camera.position)this.updateEnv(t, st)13 unmodified linesthis.post.grade.uniforms.uNight.value = st.nightthis.post.grade.uniforms.uFade.value = fadeBlack(t)this.renderer.shadowMap.needsUpdate = true// the river is not in frame in the camphor and terrace shots: skip the whole reflection passconst showWater = shot.id !== 6 && shot.id !== 7this.water.mesh.visible = showWaterif (showWater) this.water.renderReflection(this.renderer, this.scene, this.camera)this.post.composer.render()}}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315// Characters as single skinned meshes (one draw call each): villagers in// Jiangnan dress, the ox & cart, egrets. Parts are rigidly bound to bones.import * as THREE from 'three'import { std } from './materials'import { rrange } from './rng'
type RGB = [number, number, number]
class SkinBuilder { pos: number[] = [] nrm: number[] = [] col: number[] = [] idx: number[] = [] wgt: number[] = [] private v = new THREE.Vector3() private n = new THREE.Vector3() /** add geometry (already in bind pose / model space) bound to `bone` with a flat colour */ add(g: THREE.BufferGeometry, m: THREE.Matrix4, bone: number, color: RGB, shade = true) { const geo = g.index ? g.toNonIndexed() : g if (!geo.getAttribute('normal')) geo.computeVertexNormals() const p = geo.getAttribute('position'), nn = geo.getAttribute('normal') const nm = new THREE.Matrix3().getNormalMatrix(m) for (let i = 0; i < p.count; i++) { this.v.set(p.getX(i), p.getY(i), p.getZ(i)).applyMatrix4(m) this.n.set(nn.getX(i), nn.getY(i), nn.getZ(i)).applyMatrix3(nm).normalize() this.pos.push(this.v.x, this.v.y, this.v.z) this.nrm.push(this.n.x, this.n.y, this.n.z) // subtle ambient-occlusion-like darkening toward the bottom of each part const k = shade ? 0.85 + 0.15 * Math.min(1, Math.max(0, this.n.y * 0.5 + 0.5)) : 1 this.col.push(color[0] * k, color[1] * k, color[2] * k) this.idx.push(bone, 0, 0, 0) this.wgt.push(1, 0, 0, 0) } } build() { const g = new THREE.BufferGeometry() g.setAttribute('position', new THREE.Float32BufferAttribute(this.pos, 3)) g.setAttribute('normal', new THREE.Float32BufferAttribute(this.nrm, 3)) g.setAttribute('color', new THREE.Float32BufferAttribute(this.col, 3)) g.setAttribute('skinIndex', new THREE.Uint16BufferAttribute(this.idx, 4)) g.setAttribute('skinWeight', new THREE.Float32BufferAttribute(this.wgt, 4)) g.computeBoundingSphere() return g }}
const M = (x = 0, y = 0, z = 0, rx = 0, ry = 0, rz = 0, sx = 1, sy = 1, sz = 1) => new THREE.Matrix4().compose(new THREE.Vector3(x, y, z), new THREE.Quaternion().setFromEuler(new THREE.Euler(rx, ry, rz)), new THREE.Vector3(sx, sy, sz))
function lathe(profile: [number, number][], seg = 14) { return new THREE.LatheGeometry(profile.map(([r, y]) => new THREE.Vector2(Math.max(0.001, r), y)), seg)}
let charMat: THREE.Material | null = nullexport function characterMaterial() { if (!charMat) charMat = std({ vertexColors: true, roughness: 0.82, metalness: 0, side: THREE.DoubleSide }, { key: 'char' }) return charMat}
function makeSkinned(sb: SkinBuilder, bones: THREE.Bone[]) { const mesh = new THREE.SkinnedMesh(sb.build(), characterMaterial()) mesh.add(bones[0]) mesh.updateMatrixWorld(true) mesh.bind(new THREE.Skeleton(bones)) mesh.castShadow = true mesh.receiveShadow = true mesh.frustumCulled = false return mesh}
function bone(parent: THREE.Bone | null, x: number, y: number, z: number) { const b = new THREE.Bone() b.position.set(x, y, z) if (parent) parent.add(b) return b}
// ---------------------------------------------------------------- villagerconst CLOTH: RGB[] = [[0.07, 0.1, 0.22], [0.12, 0.17, 0.3], [0.26, 0.25, 0.23], [0.22, 0.14, 0.08], [0.32, 0.3, 0.27], [0.08, 0.08, 0.09], [0.36, 0.12, 0.08]]const SKIN: RGB[] = [[0.62, 0.43, 0.31], [0.55, 0.37, 0.26], [0.68, 0.5, 0.38]]
export interface Villager { mesh: THREE.SkinnedMesh root: THREE.Bone; hips: THREE.Bone; spine: THREE.Bone; head: THREE.Bone legL: THREE.Bone; legR: THREE.Bone; armL: THREE.Bone; armR: THREE.Bone; load: THREE.Bone hasPole: boolean hipY: number}
export function makeVillager(rng: () => number, opts: { pole?: boolean; hat?: boolean; seated?: boolean; female?: boolean; robe?: boolean }): Villager { const female = opts.female ?? rng() < 0.4 const robe = opts.robe ?? (!female && rng() < 0.25) const cloth = CLOTH[Math.floor(rng() * CLOTH.length)] const cloth2 = CLOTH[Math.floor(rng() * CLOTH.length)] const trouser: RGB = female ? CLOTH[Math.floor(rng() * 3)] : [0.05, 0.05, 0.06] const skin = SKIN[Math.floor(rng() * SKIN.length)] const hair: RGB = [0.025, 0.022, 0.02] const straw: RGB = [0.62, 0.5, 0.28] const H = rrange(rng, 0.94, 1.04) * (female ? 0.95 : 1)
// bones (bind pose = standing, facing +z) const root = bone(null, 0, 0, 0) const hips = bone(root, 0, 0.92 * H, 0) const spine = bone(hips, 0, 0.02, 0) const head = bone(spine, 0, 0.62 * H, 0) const legL = bone(hips, -0.09, 0, 0) const legR = bone(hips, 0.09, 0, 0) const armL = bone(spine, -0.2 * H, 0.54 * H, 0) const armR = bone(spine, 0.2 * H, 0.54 * H, 0) const load = bone(spine, 0, 0.6 * H, 0.0) const bones = [root, hips, spine, head, legL, legR, armL, armR, load] const B = { root: 0, hips: 1, spine: 2, head: 3, legL: 4, legR: 5, armL: 6, armR: 7, load: 8 } root.updateMatrixWorld(true) const sb = new SkinBuilder() const hy = 0.92 * H
// legs: trouser + cloth shoe for (const [sx, b] of [[-0.09, B.legL], [0.09, B.legR]] as const) { const leg = lathe([[0.04, 0], [0.05, 0.08], [0.058, 0.4], [0.075, 0.82], [0.07, 0.9]], 10) sb.add(leg, M(sx, hy - 0.9 * H, 0, 0, 0, 0, 1, H, 1), b, trouser) const shoe = new THREE.SphereGeometry(0.06, 10, 6, 0, Math.PI * 2, 0, Math.PI / 2) sb.add(shoe, M(sx, hy - 0.9 * H, 0.03, 0, 0, 0, 0.9, 0.7, 1.9), b, [0.04, 0.035, 0.03]) } // torso (jacket) — flattened lathe with shoulders const torso = lathe([[0.14, 0], [0.155, 0.12], [0.175, 0.32], [0.19, 0.48], [0.17, 0.55], [0.07, 0.6], [0.045, 0.62]], 16) sb.add(torso, M(0, hy, 0, 0, 0, 0, 1, H, 0.72), B.spine, cloth) // jacket hem / robe skirt if (robe || female) { const len = robe ? 0.82 : 0.32 const skirt = lathe([[0.15, 0], [0.17, -len * 0.4], [robe ? 0.22 : 0.2, -len]], 16) sb.add(skirt, M(0, hy + 0.04, 0, 0, 0, 0, 1, H, 0.8), robe ? B.hips : B.spine, robe ? cloth2 : cloth) } else { const hem = lathe([[0.15, 0], [0.165, -0.12]], 16) sb.add(hem, M(0, hy + 0.03, 0, 0, 0, 0, 1, H, 0.78), B.spine, cloth) } // sash sb.add(new THREE.CylinderGeometry(0.152, 0.152, 0.05, 16, 1, true), M(0, hy + 0.06, 0, 0, 0, 0, 1, 1, 0.74), B.spine, [0.12, 0.09, 0.06]) // arms: sleeve + forearm + hand for (const [sx, b] of [[-1, B.armL], [1, B.armR]] as const) { const sx0 = sx * 0.2 * H const sleeve = lathe([[0.062, 0], [0.06, -0.25], [0.07, -0.42], [0.072, -0.45]], 10) sb.add(sleeve, M(sx0, hy + 0.54 * H, 0, 0, 0, sx * 0.06, 1, H, 1), b, cloth) const fore = lathe([[0.035, -0.4], [0.032, -0.55]], 8) sb.add(fore, M(sx0 + sx * 0.03, hy + 0.54 * H, 0, 0, 0, sx * 0.06, 1, H, 1), b, skin) sb.add(new THREE.SphereGeometry(0.04, 8, 6), M(sx0 + sx * 0.04, hy + 0.54 * H - 0.6 * H, 0.01, 0, 0, 0, 0.8, 1.15, 0.6), b, skin) } // head & neck const hyH = hy + 0.62 * H sb.add(new THREE.CylinderGeometry(0.035, 0.04, 0.08, 8), M(0, hyH + 0.02, 0), B.head, skin) sb.add(new THREE.SphereGeometry(0.1, 16, 12), M(0, hyH + 0.15, 0.005, 0, 0, 0, 0.92, 1.12, 1), B.head, skin) sb.add(new THREE.SphereGeometry(0.03, 6, 4), M(0, hyH + 0.14, 0.095, 0, 0, 0, 0.6, 0.9, 0.5), B.head, skin) // nose for (const ex of [-0.093, 0.093]) sb.add(new THREE.SphereGeometry(0.022, 6, 4), M(ex, hyH + 0.15, 0, 0, 0, 0, 0.5, 1, 0.8), B.head, skin) // ears if (female) { sb.add(new THREE.SphereGeometry(0.106, 14, 10, 0, Math.PI * 2, 0, Math.PI * 0.62), M(0, hyH + 0.16, -0.008, -0.25, 0, 0, 1, 1.05, 1.02), B.head, hair) sb.add(new THREE.SphereGeometry(0.05, 10, 8), M(0, hyH + 0.17, -0.11), B.head, hair) // bun if (rng() < 0.6) sb.add(new THREE.SphereGeometry(0.112, 14, 8, 0, Math.PI * 2, 0, Math.PI * 0.42), M(0, hyH + 0.165, -0.01, -0.35, 0, 0, 1.02, 1, 1.05), B.head, [0.15, 0.22, 0.42]) // indigo headscarf } else { sb.add(new THREE.SphereGeometry(0.104, 14, 10, 0, Math.PI * 2, 0, Math.PI * 0.5), M(0, hyH + 0.16, -0.01, -0.2, 0, 0, 0.96, 1.02, 1.02), B.head, hair) } if (opts.hat) { // conical bamboo hat (斗笠) with a slightly concave profile + chin strap rim const hat = lathe([[0.4, 0], [0.33, 0.035], [0.2, 0.09], [0.06, 0.15], [0.0, 0.17]], 22) sb.add(hat, M(0, hyH + 0.21, 0), B.head, straw) const under = lathe([[0.0, 0.16], [0.06, 0.14], [0.2, 0.08], [0.33, 0.025], [0.4, -0.005]], 22) sb.add(under, M(0, hyH + 0.21, 0), B.head, [0.42, 0.34, 0.18]) } let hasPole = false if (opts.pole) { hasPole = true // shoulder pole across the right shoulder with two baskets const ly = hy + 0.6 * H const poleG = new THREE.CylinderGeometry(0.022, 0.022, 1.9, 6) poleG.rotateX(Math.PI / 2) sb.add(poleG, M(0.12, ly + 0.02, 0), B.load, [0.5, 0.45, 0.24]) for (const z of [-0.85, 0.85]) { for (const dx of [-0.13, 0.13]) { const rope = new THREE.CylinderGeometry(0.004, 0.004, 0.72, 3) sb.add(rope, M(0.12 + dx * 0.6, ly - 0.36, z + dx * 0.2, 0, 0, dx * 0.35), B.load, [0.3, 0.25, 0.15], false) } const basket = lathe([[0.16, 0], [0.24, 0.08], [0.26, 0.26], [0.25, 0.28], [0.0, 0.28]], 14) sb.add(basket, M(0.12, ly - 0.98, z), B.load, [0.55, 0.42, 0.22]) const fill = new THREE.SphereGeometry(0.23, 10, 6, 0, Math.PI * 2, 0, Math.PI / 2) const c: RGB = rng() < 0.5 ? [0.2, 0.36, 0.08] : [0.72, 0.32, 0.06] sb.add(fill, M(0.12, ly - 0.71, z, 0, 0, 0, 1, 0.5, 1), B.load, c) } } const mesh = makeSkinned(sb, bones) const v: Villager = { mesh, root, hips, spine, head, legL, legR, armL, armR, load, hasPole, hipY: hy } if (opts.pole) { armR.rotation.set(-2.5, 0, 0.35) // hand up on the pole load.rotation.y = 0.25 } if (opts.seated) { hips.position.y = 0.55 legL.rotation.x = legR.rotation.x = -1.45 armL.rotation.x = armR.rotation.x = -0.6 spine.rotation.x = 0.12 } return v}
export function walkVillager(v: Villager, phase: number, amp = 1) { const s = Math.sin(phase) v.legL.rotation.x = s * 0.46 * amp v.legR.rotation.x = -s * 0.46 * amp v.armL.rotation.x = -s * 0.36 * amp if (!v.hasPole) v.armR.rotation.x = s * 0.36 * amp v.hips.position.y = v.hipY + Math.abs(Math.cos(phase)) * 0.03 * amp v.hips.rotation.y = s * 0.06 * amp v.spine.rotation.y = -s * 0.08 * amp v.spine.rotation.x = v.hasPole ? 0.08 : 0.03 v.head.rotation.y = s * 0.03 if (v.hasPole) v.load.rotation.z = Math.sin(phase * 2) * 0.04}
// ---------------------------------------------------------------- ox & cartexport interface OxCart { mesh: THREE.SkinnedMesh legs: THREE.Bone[]; head: THREE.Bone; tail: THREE.Bone; wheels: THREE.Bone[]}
export function makeOxCart(): OxCart { const hide: RGB = [0.17, 0.11, 0.075], dark: RGB = [0.06, 0.045, 0.035], horn: RGB = [0.62, 0.56, 0.45] const wood: RGB = [0.3, 0.2, 0.12], hay: RGB = [0.6, 0.48, 0.24] const root = bone(null, 0, 0, 0) const body = bone(root, 0, 1.15, 0) const head = bone(body, 0, 0.12, 0.95) const tail = bone(body, 0, 0.15, -0.95) const legs = [[-0.24, 0.62], [0.24, 0.62], [-0.24, -0.62], [0.24, -0.62]].map(([x, z]) => bone(body, x, -0.15, z)) const wheels = [-0.82, 0.82].map((x) => bone(root, x, 0.62, -2.4)) const bones = [root, body, head, tail, ...legs, ...wheels] root.updateMatrixWorld(true) const sb = new SkinBuilder() // barrel body: lathe along z const barrel = lathe([[0.0, -0.95], [0.3, -0.88], [0.42, -0.5], [0.45, 0.1], [0.43, 0.6], [0.34, 0.9], [0.0, 1.0]], 18) sb.add(barrel, M(0, 1.15, 0, Math.PI / 2, 0, 0, 1, 1, 0.92), 1, hide) sb.add(new THREE.SphereGeometry(0.28, 12, 8), M(0, 1.42, 0.55, 0, 0, 0, 1, 0.8, 1.2), 1, hide) // hump sb.add(new THREE.SphereGeometry(0.2, 10, 8), M(0, 0.95, 0.75, 0, 0, 0, 1.3, 1, 1.4), 1, hide) // dewlap/chest // head with muzzle, horns, ears sb.add(new THREE.SphereGeometry(0.2, 14, 10), M(0, 1.3, 1.12, 0.3, 0, 0, 0.9, 1, 1.25), 2, hide) sb.add(new THREE.SphereGeometry(0.13, 12, 8), M(0, 1.14, 1.36, 0.3, 0, 0, 1.05, 0.85, 1), 2, dark) for (const sx of [-1, 1]) { const hornC = new THREE.TorusGeometry(0.16, 0.035, 6, 10, Math.PI * 0.7) sb.add(hornC, M(sx * 0.14, 1.48, 1.04, 0, Math.PI / 2, sx > 0 ? 0.2 : Math.PI - 0.2, 1, 1, 1), 2, horn) sb.add(new THREE.SphereGeometry(0.07, 8, 6), M(sx * 0.24, 1.38, 1.0, 0, 0, sx * 0.5, 1.4, 0.6, 0.5), 2, hide) sb.add(new THREE.SphereGeometry(0.03, 6, 4), M(sx * 0.12, 1.36, 1.27), 2, [0.02, 0.02, 0.02]) } // tail sb.add(new THREE.CylinderGeometry(0.02, 0.03, 0.7, 5), M(0, 0.95, -1.0, 0.15, 0, 0), 3, hide) sb.add(new THREE.SphereGeometry(0.05, 6, 6), M(0, 0.6, -1.05, 0, 0, 0, 1, 1.8, 1), 3, dark) // legs with hooves legs.forEach((_, i) => { const x = i % 2 ? 0.24 : -0.24, z = i < 2 ? 0.62 : -0.62 const leg = lathe([[0.05, -1.0], [0.06, -0.62], [0.075, -0.4], [0.11, -0.1], [0.12, 0.05]], 10) sb.add(leg, M(x, 1.0, z), 4 + i, hide) sb.add(new THREE.CylinderGeometry(0.06, 0.065, 0.08, 8), M(x, 0.04, z + 0.01), 4 + i, dark) }) // yoke + shafts + cart bed + hay + wheels sb.add(new THREE.CylinderGeometry(0.04, 0.04, 0.9, 6), M(0, 1.45, 0.75, 0, 0, Math.PI / 2), 1, wood) for (const sx of [-0.45, 0.45]) sb.add(new THREE.BoxGeometry(0.07, 0.07, 2.6), M(sx, 1.0, -1.0, -0.08, 0, 0), 0, wood) sb.add(new THREE.BoxGeometry(1.45, 0.1, 2.1), M(0, 0.98, -2.4), 0, wood) for (const sx of [-0.7, 0.7]) sb.add(new THREE.BoxGeometry(0.06, 0.32, 2.1), M(sx, 1.18, -2.4), 0, wood) sb.add(new THREE.SphereGeometry(0.75, 12, 8, 0, Math.PI * 2, 0, Math.PI / 2), M(0, 1.02, -2.4, 0, 0, 0, 0.88, 0.72, 1.25), 0, hay) ;[6, 7].forEach((bi, k) => { const sx = k ? 0.82 : -0.82 const rim = new THREE.TorusGeometry(0.6, 0.05, 6, 22) sb.add(rim, M(sx, 0.62, -2.4, 0, Math.PI / 2, 0), bi, wood) sb.add(new THREE.CylinderGeometry(0.1, 0.1, 0.16, 10), M(sx, 0.62, -2.4, 0, 0, Math.PI / 2), bi, wood) for (let s = 0; s < 8; s++) sb.add(new THREE.BoxGeometry(0.05, 1.15, 0.05), M(sx, 0.62, -2.4, (s / 8) * Math.PI, 0, 0), bi, [0.45, 0.35, 0.22]) }) const mesh = makeSkinned(sb, bones) return { mesh, legs, head, tail, wheels }}
export function animateOx(o: OxCart, dist: number, t: number) { const ph = dist * 2.6 o.legs.forEach((l, i) => { l.rotation.x = Math.sin(ph + (i === 0 || i === 3 ? 0 : Math.PI)) * 0.32 }) o.head.rotation.x = Math.sin(ph * 2) * 0.04 + 0.05 o.head.rotation.y = Math.sin(t * 0.4) * 0.08 o.tail.rotation.z = Math.sin(t * 1.7) * 0.25 o.wheels.forEach((w) => { w.rotation.x = dist / 0.62 })}
// ---------------------------------------------------------------- egretexport interface Egret { mesh: THREE.SkinnedMesh; root: THREE.Bone; wl: THREE.Bone; wr: THREE.Bone }
export function makeEgret(): Egret { const white: RGB = [0.93, 0.93, 0.91], beak: RGB = [0.78, 0.62, 0.16], legC: RGB = [0.05, 0.05, 0.05] const root = bone(null, 0, 0, 0) const wl = bone(root, -0.06, 0.02, 0.02) const wr = bone(root, 0.06, 0.02, 0.02) root.updateMatrixWorld(true) const sb = new SkinBuilder() sb.add(new THREE.SphereGeometry(0.12, 14, 10), M(0, 0, 0, 0, 0, 0, 0.95, 0.85, 2.3), 0, white) // S-curved neck tucked back in flight, head, beak sb.add(new THREE.CylinderGeometry(0.035, 0.05, 0.22, 8), M(0, 0.07, 0.3, 1.0, 0, 0), 0, white) sb.add(new THREE.SphereGeometry(0.055, 10, 8), M(0, 0.12, 0.4, 0, 0, 0, 0.9, 0.9, 1.3), 0, white) sb.add(new THREE.ConeGeometry(0.018, 0.17, 6), M(0, 0.11, 0.53, Math.PI / 2, 0, 0), 0, beak) sb.add(new THREE.CylinderGeometry(0.01, 0.01, 0.5, 4), M(-0.025, -0.02, -0.5, Math.PI / 2, 0, 0), 0, legC) sb.add(new THREE.CylinderGeometry(0.01, 0.01, 0.5, 4), M(0.025, -0.02, -0.5, Math.PI / 2, 0, 0), 0, legC) // wings: curved feathered shape (extruded thin) for each side const shape = new THREE.Shape() shape.moveTo(0, 0.12) shape.bezierCurveTo(0.35, 0.22, 0.8, 0.2, 1.12, 0.02) shape.lineTo(1.0, -0.04) for (let k = 0; k < 6; k++) shape.lineTo(0.95 - k * 0.15, -0.1 - (k % 2) * 0.05) // primary feathers shape.lineTo(0, -0.14) const wg = new THREE.ExtrudeGeometry(shape, { depth: 0.012, bevelEnabled: false, curveSegments: 10 }) wg.rotateX(-Math.PI / 2) sb.add(wg, M(0.06, 0.02, 0.02), 2, white) sb.add(wg.clone(), M(-0.06, 0.02, 0.02, 0, 0, 0, -1, 1, 1), 1, white) const mesh = makeSkinned(sb, [root, wl, wr]) mesh.castShadow = true return { mesh, root, wl, wr }}48 unmodified lines49505152535448 unmodified linesthis.pushVertex(c.x, c.y, c.z, nx, ny, nz, t[4], t[5])this.pushVertex(d.x, d.y, d.z, nx, ny, nz, t[6], t[7])}tri(a: THREE.Vector3Like, b: THREE.Vector3Like, c: THREE.Vector3Like, uvs?: number[]) {const e1 = new THREE.Vector3(b.x - a.x, b.y - a.y, b.z - a.z)const e2 = new THREE.Vector3(c.x - a.x, c.y - a.y, c.z - a.z)48 unmodified lines4950515253545556575859606162636465666768697071727374757648 unmodified linesthis.pushVertex(c.x, c.y, c.z, nx, ny, nz, t[4], t[5])this.pushVertex(d.x, d.y, d.z, nx, ny, nz, t[6], t[7])}/** quad whose 4 corners carry a relief height (aRH) and a relief slope across x (aRS) */quadRelief(a: THREE.Vector3Like, b: THREE.Vector3Like, c: THREE.Vector3Like, d: THREE.Vector3Like, hs: number[], uvs: number[]) {const dx = Math.abs(b.x - a.x) || 1const slope = (hs[1] - hs[0]) / dx * Math.sign(b.x - a.x || 1)const corners = [a, b, c, a, c, d]const hIdx = [0, 1, 2, 0, 2, 3]const uvIdx = [0, 1, 2, 0, 2, 3]const e1 = new THREE.Vector3(b.x - a.x, b.y - a.y, b.z - a.z)const e2 = new THREE.Vector3(d.x - a.x, d.y - a.y, d.z - a.z)const n = e1.cross(e2).normalize()for (let k = 0; k < 6; k++) {this.current['aRH'] = hs[hIdx[k]]this.current['aRS'] = slopeconst p = corners[k]this.pushVertexPublic(p.x, p.y, p.z, n.x, n.y, n.z, uvs[uvIdx[k] * 2], uvs[uvIdx[k] * 2 + 1])}this.current['aRH'] = 0this.current['aRS'] = 0}pushVertexPublic(x: number, y: number, z: number, nx: number, ny: number, nz: number, u: number, w: number) {this.pushVertex(x, y, z, nx, ny, nz, u, w)}tri(a: THREE.Vector3Like, b: THREE.Vector3Like, c: THREE.Vector3Like, uvs?: number[]) {const e1 = new THREE.Vector3(b.x - a.x, b.y - a.y, b.z - a.z)const e2 = new THREE.Vector3(c.x - a.x, c.y - a.y, c.z - a.z)
2 unmodified lines34567835 unmodified lines4445464748495073 unmodified lines12412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721825 unmodified lines24424524624724824925016 unmodified lines26726826927027127227310 unmodified lines2842852862872882892907 unmodified lines2982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953 unmodified lines39940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144232 unmodified lines47547647747847948077 unmodified lines55855956056156256348 unmodified lines61261361461561661743 unmodified lines66166266366466566666766812 unmodified lines6816826836846856866876886896901 unmodified line6926936946956966976986997007017022 unmodified linesimport * as THREE from 'three'import { Builder, V3 } from './geom'import { BRIDGE_S, GROUND_Y, MARKET_S0, MARKET_S1, quayPoint, riverAt, riverHalfWidth, riverPoint, riverSAtX, TREE_POS, VILLAGE_S0, VILLAGE_S1 } from './layout'import { patch, std, U } from './materials'import type { PropsOut } from './props'import { clamp, hash1, lerp, mulberry32, smoothstep } from './rng'35 unmodified lines// body: ribbed ellipsoid + caps + tasselconst b = new Builder()b.set('aPart', 0)const body = new THREE.SphereGeometry(0.3, 16, 12)body.scale(1, 1.25, 1)b.geometry(body, new THREE.Matrix4().makeTranslation(0, -0.42, 0))b.set('aPart', 1)73 unmodified linesreturn { mesh, glow, list }}// ------------------------------------------------------------------ villagersinterface Figure { root: THREE.Group; legL: THREE.Object3D; legR: THREE.Object3D; armL: THREE.Object3D; armR: THREE.Object3D; load?: THREE.Object3D }function makeFigure(rng: () => number, mats: Record<string, THREE.Material>, opts: { pole?: boolean; hat?: boolean; seated?: boolean }): Figure {const root = new THREE.Group()const cloth = [mats.indigo, mats.grey, mats.brown, mats.indigo2][Math.floor(rng() * 4)]const mk = (g: THREE.BufferGeometry, m: THREE.Material) => { const o = new THREE.Mesh(g, m); o.castShadow = true; return o }const hip = new THREE.Group()hip.position.y = 0.92root.add(hip)const torso = mk(new THREE.CylinderGeometry(0.17, 0.22, 0.62, 10), cloth)torso.position.y = 0.32hip.add(torso)const head = mk(new THREE.SphereGeometry(0.11, 12, 10), mats.skin)head.position.y = 0.78hip.add(head)const hair = mk(new THREE.SphereGeometry(0.112, 12, 8, 0, Math.PI * 2, 0, Math.PI * 0.55), mats.hair)hair.position.y = 0.79hip.add(hair)if (opts.hat) {const hat = mk(new THREE.ConeGeometry(0.38, 0.17, 18, 1, true), mats.straw)hat.position.y = 0.92hip.add(hat)}const leg = (x: number) => {const g = new THREE.Group()g.position.set(x, 0, 0)const l = mk(new THREE.CylinderGeometry(0.065, 0.075, 0.9, 8), opts.seated ? cloth : mats.trouser)l.position.y = -0.45g.add(l)const f = mk(new THREE.BoxGeometry(0.1, 0.06, 0.22), mats.hair)f.position.set(0, -0.9, 0.05)g.add(f)hip.add(g)return g}const arm = (x: number) => {const g = new THREE.Group()g.position.set(x, 0.58, 0)const a = mk(new THREE.CylinderGeometry(0.05, 0.045, 0.62, 8), cloth)a.position.y = -0.31g.add(a)hip.add(g)return g}const legL = leg(-0.09), legR = leg(0.09)const armL = arm(-0.23), armR = arm(0.23)let load: THREE.Object3D | undefinedif (opts.pole) {// shoulder pole (扁担) with two baskets hung on ropesconst p = new THREE.Group()p.position.set(0, 0.62, 0.02)const pole = mk(new THREE.BoxGeometry(0.05, 0.04, 1.8), mats.bamboo)pole.rotation.y = 0p.add(pole)for (const z of [-0.82, 0.82]) {const rope = mk(new THREE.CylinderGeometry(0.006, 0.006, 0.7, 3), mats.hair)rope.position.set(0, -0.35, z)p.add(rope)const bsk = mk(new THREE.CylinderGeometry(0.24, 0.19, 0.3, 12), mats.basket)bsk.position.set(0, -0.82, z)p.add(bsk)const veg = mk(new THREE.SphereGeometry(0.2, 8, 6, 0, Math.PI * 2, 0, Math.PI / 2), z > 0 ? mats.green : mats.orange)veg.position.set(0, -0.68, z)p.add(veg)}p.rotation.y = Math.PI / 2 + 0.25hip.add(p)load = parmR.rotation.x = -2.4armR.rotation.z = 0.2}if (opts.seated) {hip.position.y = 0.55legL.rotation.x = legR.rotation.x = -1.45}return { root, legL, legR, armL, armR, load }}function animateWalk(f: Figure, phase: number, amp = 1) {const s = Math.sin(phase)f.legL.rotation.x = s * 0.45 * ampf.legR.rotation.x = -s * 0.45 * ampf.armL.rotation.x = -s * 0.35 * ampif (!f.load) f.armR.rotation.x = s * 0.35 * ampconst hip = f.root.children[0]hip.position.y = 0.92 + Math.abs(Math.cos(phase)) * 0.035 * ampif (f.load) f.load.position.y = 0.62 + Math.sin(phase * 2) * 0.03}interface Walker { fig: Figure; path: (t: number) => { p: THREE.Vector3; dir: THREE.Vector3; dist: number } | null }25 unmodified lines// porter crossing the bridge (north → south) during the bridge shot{const fig = makeFigure(rng, mats, { pole: true, hat: true })group.add(fig.root)walkers.push({fig,path: (t) => {16 unmodified lines]for (const [x0, speed, lane, pole, dir] of streetPeople) {const fig = makeFigure(rng, mats, { pole, hat: pole || rng() < 0.4 })group.add(fig.root)const s0 = riverSAtX(x0)walkers.push({fig,10 unmodified linesconst tp = TREE_POSfor (const [a0, dir, spd] of [[2.6, 1, 1.0], [0.4, -1, 0.85]] as [number, number, number][]) {const fig = makeFigure(rng, mats, { pole: true, hat: true })group.add(fig.root)walkers.push({fig,path: (t) => {7 unmodified lines})}// seated elders & vendorsconst statics: THREE.Group[] = []{const elder = makeFigure(rng, mats, { seated: true })const a = 0.3elder.root.position.set(tp.x + Math.cos(a) * 5.2, GROUND_Y, tp.z + Math.sin(a) * 5.2)elder.root.rotation.y = -a - Math.PI / 2group.add(elder.root)statics.push(elder.root)for (let k = 0; k < 5; k++) {const s = MARKET_S0 + 12 + k * 24const p = riverPoint(s, -8.9)const v = makeFigure(rng, mats, { hat: rng() < 0.3 })v.root.position.set(p.x, GROUND_Y + 0.03, p.z)v.root.rotation.y = Math.atan2(-p.nx, -p.nz) + Math.PIv.armL.rotation.x = -0.6v.armR.rotation.x = -0.5group.add(v.root)statics.push(v.root)}}// ---------------------------------------------------------------- ox cartconst ox = new THREE.Group()const cartWheels: THREE.Object3D[] = []const oxLegs: THREE.Object3D[] = []{const mk = (g: THREE.BufferGeometry, mm: THREE.Material) => { const o = new THREE.Mesh(g, mm); o.castShadow = true; return o }const bodyG = new THREE.CapsuleGeometry(0.42, 1.3, 6, 12)bodyG.rotateX(Math.PI / 2)const body = mk(bodyG, mats.ox)body.position.set(0, 1.15, 0)ox.add(body)const hump = mk(new THREE.SphereGeometry(0.3, 10, 8), mats.ox)hump.position.set(0, 1.45, 0.55)ox.add(hump)const head = mk(new THREE.BoxGeometry(0.34, 0.36, 0.55), mats.ox)head.position.set(0, 1.25, 1.2)head.rotation.x = 0.5ox.add(head)for (const sx of [-1, 1]) {const horn = mk(new THREE.ConeGeometry(0.05, 0.38, 6), mats.horn)horn.position.set(sx * 0.2, 1.5, 1.1)horn.rotation.z = -sx * 1.0ox.add(horn)}for (const [lx, lz] of [[-0.22, 0.6], [0.22, 0.6], [-0.22, -0.6], [0.22, -0.6]]) {const g = new THREE.Group()g.position.set(lx, 0.95, lz)const l = mk(new THREE.CylinderGeometry(0.08, 0.06, 0.95, 6), mats.ox)l.position.y = -0.47g.add(l)ox.add(g)oxLegs.push(g)}// cart behind (−z)const cart = new THREE.Group()cart.position.set(0, 0, -2.4)const bed = mk(new THREE.BoxGeometry(1.4, 0.12, 2.0), mats.wood)bed.position.y = 0.95cart.add(bed)for (const sx of [-0.68, 0.68]) {const rail = mk(new THREE.BoxGeometry(0.06, 0.3, 2.0), mats.wood)rail.position.set(sx, 1.12, 0)cart.add(rail)const shaft = mk(new THREE.BoxGeometry(0.07, 0.07, 2.4), mats.wood)shaft.position.set(sx * 0.5, 1.0, 1.9)cart.add(shaft)}// load: hay & basketsconst hay = mk(new THREE.SphereGeometry(0.75, 10, 8, 0, Math.PI * 2, 0, Math.PI / 2), mats.straw)hay.scale.set(0.9, 0.7, 1.2)hay.position.y = 1.0cart.add(hay)for (const sx of [-0.78, 0.78]) {const wg = new THREE.Group()wg.position.set(sx, 0.62, 0)const wheel = mk(new THREE.CylinderGeometry(0.62, 0.62, 0.08, 18), mats.wood)wheel.rotation.z = Math.PI / 2wg.add(wheel)for (let k = 0; k < 6; k++) {const sp = mk(new THREE.BoxGeometry(0.1, 1.1, 0.06), mats.horn)sp.rotation.x = (k / 6) * Math.PIwg.add(sp)}cart.add(wg)cartWheels.push(wg)}ox.add(cart)group.add(ox)}const driver = makeFigure(rng, mats, { hat: true })group.add(driver.root)const oxS0 = riverSAtX(-175)const oxPath = (t: number) => {const s = oxS0 + (t - 28) * 0.953 unmodified lines}// ---------------------------------------------------------------- egretsconst egrets: { g: THREE.Group; wl: THREE.Object3D; wr: THREE.Object3D; seed: number }[] = []{const wingShape = new THREE.Shape()wingShape.moveTo(0, 0)wingShape.bezierCurveTo(0.3, 0.25, 0.8, 0.22, 1.05, 0.05)wingShape.bezierCurveTo(0.8, -0.05, 0.4, -0.12, 0, -0.18)const wingG = new THREE.ShapeGeometry(wingShape, 8)wingG.rotateX(-Math.PI / 2)for (let k = 0; k < 7; k++) {const g = new THREE.Group()const bodyG = new THREE.SphereGeometry(0.12, 10, 8)bodyG.scale(1, 0.9, 2.4)const body = new THREE.Mesh(bodyG, mats.egret)g.add(body)const neck = new THREE.Mesh(new THREE.CylinderGeometry(0.035, 0.05, 0.3, 6), mats.egret)neck.position.set(0, 0.06, 0.34)neck.rotation.x = 1.1g.add(neck)const beak = new THREE.Mesh(new THREE.ConeGeometry(0.02, 0.16, 5), mats.beak)beak.rotation.x = Math.PI / 2beak.position.set(0, 0.12, 0.55)g.add(beak)const legs = new THREE.Mesh(new THREE.CylinderGeometry(0.012, 0.012, 0.45, 4), mats.hair)legs.rotation.x = Math.PI / 2legs.position.set(0, -0.02, -0.5)g.add(legs)const wl = new THREE.Mesh(wingG, mats.egret)const wr = new THREE.Mesh(wingG, mats.egret);(wl.material as THREE.Material).side = THREE.DoubleSidewl.scale.set(-1, 1, 1)wl.position.x = -0.06wr.position.x = 0.06g.add(wl, wr)g.traverse((o) => { o.castShadow = true })g.scale.setScalar(1.25)group.add(g)egrets.push({ g, wl, wr, seed: k })}}const egretPos = (t: number) => {// two passes: low over the river by the bridge, then flying up toward the bamboo hills32 unmodified lines})const flock = new THREE.InstancedMesh(flockGeo, flockMat, flockN)flock.frustumCulled = falsegroup.add(flock)const flockOff = Array.from({ length: flockN }, (_, i) => V3((hash1(i, 1) - 0.5) * 22, (hash1(i, 2) - 0.5) * 7, (hash1(i, 3) - 0.5) * 22))const flockCenter = (t: number) => {77 unmodified linesconst smoke = new THREE.Mesh(smokeGeo, smokeMat)smoke.frustumCulled = falsesmoke.renderOrder = 5group.add(smoke)// ---------------------------------------------------------------- water-wheel splashes48 unmodified lines})const splash = new THREE.Points(g, m)splash.frustumCulled = falsegroup.add(splash)}43 unmodified lines// ---------------------------------------------------------------- night boat + boatman + bow lanternconst boat = props.movingBoatconst boatman = makeFigure(rng, mats, { hat: true })boatman.root.position.set(0, 0.45, -2.9)boat.add(boatman.root)const oar = new THREE.Mesh(new THREE.BoxGeometry(0.06, 0.06, 3.6), mats.wood)oar.position.set(0.25, 1.1, -3.6)oar.rotation.x = 0.5512 unmodified lines// walkersfor (const w of walkers) {const r = w.path(t)if (!r) { w.fig.root.visible = false; continue }w.fig.root.visible = truew.fig.root.position.copy(r.p)w.fig.root.rotation.y = Math.atan2(r.dir.x, r.dir.z)animateWalk(w.fig, r.dist * 3.2)}// ox cart1 unmodified lineox.position.copy(o.p)ox.rotation.y = Math.atan2(o.dir.x, o.dir.z)const dist = (t - 28) * 0.95oxLegs.forEach((l, i) => { l.rotation.x = Math.sin(dist * 2.6 + (i % 2 ? Math.PI : 0) + (i > 1 ? 1.2 : 0)) * 0.35 })cartWheels.forEach((wg) => { wg.rotation.x = dist / 0.62 })const side = V3(o.dir.z, 0, -o.dir.x)driver.root.position.copy(o.p).addScaledVector(o.dir, 0.4).addScaledVector(side, -1.0)driver.root.rotation.y = ox.rotation.yanimateWalk(driver, dist * 3.2)// egretsegrets.forEach((e, i) => {2 unmodified lines345678935 unmodified lines4546474849505173 unmodified lines12512612712812913013113213313425 unmodified lines16016116216316416516616 unmodified lines18318418518618718818910 unmodified lines2002012022032042052067 unmodified lines2142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452463 unmodified lines25025125225325425525625725825926026132 unmodified lines29429529629729829930077 unmodified lines37837938038138238338448 unmodified lines43343443543643743843943 unmodified lines48348448548648748848949012 unmodified lines5035045055065075085095105115121 unmodified line5145155165175185195205215225232 unmodified linesimport * as THREE from 'three'import { Builder, V3 } from './geom'import { BRIDGE_S, GROUND_Y, MARKET_S0, MARKET_S1, quayPoint, riverAt, riverHalfWidth, riverPoint, riverSAtX, TREE_POS, VILLAGE_S0, VILLAGE_S1 } from './layout'import { makeEgret, makeOxCart, makeVillager, animateOx, Villager, walkVillager } from './figures'import { patch, std, U } from './materials'import type { PropsOut } from './props'import { clamp, hash1, lerp, mulberry32, smoothstep } from './rng'35 unmodified lines// body: ribbed ellipsoid + caps + tasselconst b = new Builder()b.set('aPart', 0)const body = new THREE.SphereGeometry(0.3, 12, 8)body.scale(1, 1.25, 1)b.geometry(body, new THREE.Matrix4().makeTranslation(0, -0.42, 0))b.set('aPart', 1)73 unmodified linesreturn { mesh, glow, list }}// ------------------------------------------------------------------ villagers (skinned, see figures.ts)type Figure = Villagerconst makeFigure = (rng: () => number, _mats: unknown, opts: { pole?: boolean; hat?: boolean; seated?: boolean }) => makeVillager(rng, opts)const animateWalk = walkVillagerinterface Walker { fig: Figure; path: (t: number) => { p: THREE.Vector3; dir: THREE.Vector3; dist: number } | null }25 unmodified lines// porter crossing the bridge (north → south) during the bridge shot{const fig = makeFigure(rng, mats, { pole: true, hat: true })group.add(fig.mesh)walkers.push({fig,path: (t) => {16 unmodified lines]for (const [x0, speed, lane, pole, dir] of streetPeople) {const fig = makeFigure(rng, mats, { pole, hat: pole || rng() < 0.4 })group.add(fig.mesh)const s0 = riverSAtX(x0)walkers.push({fig,10 unmodified linesconst tp = TREE_POSfor (const [a0, dir, spd] of [[2.6, 1, 1.0], [0.4, -1, 0.85]] as [number, number, number][]) {const fig = makeFigure(rng, mats, { pole: true, hat: true })group.add(fig.mesh)walkers.push({fig,path: (t) => {7 unmodified lines})}// seated elders & vendorsconst statics: THREE.Object3D[] = []{const elder = makeFigure(rng, mats, { seated: true })const a = 0.3elder.mesh.position.set(tp.x + Math.cos(a) * 5.2, GROUND_Y, tp.z + Math.sin(a) * 5.2)elder.mesh.rotation.y = -a - Math.PI / 2group.add(elder.mesh)statics.push(elder.mesh)for (let k = 0; k < 5; k++) {const s = MARKET_S0 + 12 + k * 24const p = riverPoint(s, -8.9)const v = makeFigure(rng, mats, { hat: rng() < 0.3 })v.mesh.position.set(p.x, GROUND_Y + 0.03, p.z)v.mesh.rotation.y = Math.atan2(-p.nx, -p.nz) + Math.PIv.armL.rotation.x = -0.6v.armR.rotation.x = -0.5group.add(v.mesh)statics.push(v.mesh)}}// ---------------------------------------------------------------- ox cartconst oxCart = makeOxCart()const ox = oxCart.meshgroup.add(ox)const driver = makeFigure(rng, mats, { hat: true })group.add(driver.mesh)const oxS0 = riverSAtX(-175)const oxPath = (t: number) => {const s = oxS0 + (t - 28) * 0.953 unmodified lines}// ---------------------------------------------------------------- egretsconst egrets: { g: THREE.Object3D; wl: THREE.Bone; wr: THREE.Bone; seed: number }[] = []for (let k = 0; k < 7; k++) {const e = makeEgret()e.mesh.scale.setScalar(1.25)group.add(e.mesh)egrets.push({ g: e.mesh, wl: e.wl, wr: e.wr, seed: k })}const egretPos = (t: number) => {// two passes: low over the river by the bridge, then flying up toward the bamboo hills32 unmodified lines})const flock = new THREE.InstancedMesh(flockGeo, flockMat, flockN)flock.frustumCulled = falseflock.layers.set(1)group.add(flock)const flockOff = Array.from({ length: flockN }, (_, i) => V3((hash1(i, 1) - 0.5) * 22, (hash1(i, 2) - 0.5) * 7, (hash1(i, 3) - 0.5) * 22))const flockCenter = (t: number) => {77 unmodified linesconst smoke = new THREE.Mesh(smokeGeo, smokeMat)smoke.frustumCulled = falsesmoke.renderOrder = 5smoke.layers.set(1)group.add(smoke)// ---------------------------------------------------------------- water-wheel splashes48 unmodified lines})const splash = new THREE.Points(g, m)splash.frustumCulled = falsesplash.layers.set(1)group.add(splash)}43 unmodified lines// ---------------------------------------------------------------- night boat + boatman + bow lanternconst boat = props.movingBoatconst boatman = makeFigure(rng, mats, { hat: true })boatman.mesh.position.set(0, 0.45, -2.9)boat.add(boatman.mesh)const oar = new THREE.Mesh(new THREE.BoxGeometry(0.06, 0.06, 3.6), mats.wood)oar.position.set(0.25, 1.1, -3.6)oar.rotation.x = 0.5512 unmodified lines// walkersfor (const w of walkers) {const r = w.path(t)if (!r) { w.fig.mesh.visible = false; continue }w.fig.mesh.visible = truew.fig.mesh.position.copy(r.p)w.fig.mesh.rotation.y = Math.atan2(r.dir.x, r.dir.z)animateWalk(w.fig, r.dist * 3.2)}// ox cart1 unmodified lineox.position.copy(o.p)ox.rotation.y = Math.atan2(o.dir.x, o.dir.z)const dist = (t - 28) * 0.95animateOx(oxCart, dist, t)const side = V3(o.dir.z, 0, -o.dir.x)driver.mesh.position.copy(o.p).addScaledVector(o.dir, 0.4).addScaledVector(side, -1.0)driver.mesh.rotation.y = ox.rotation.yanimateWalk(driver, dist * 3.2)// egretsegrets.forEach((e, i) => {
61 unmodified lines6263646566676840 unmodified lines10911011111211311461 unmodified linestDiffuse: { value: null as THREE.Texture | null },uTime: { value: 0 },uVignette: { value: 0.32 },uGrain: { value: 0.035 },uFade: { value: 0 },uNight: { value: 0 },uRes: { value: new THREE.Vector2(1920, 1080) },40 unmodified linesexport function createPost(renderer: THREE.WebGLRenderer, scene: THREE.Scene, camera: THREE.Camera, w: number, h: number, samples = 4): Post {const rt = new THREE.WebGLRenderTarget(w, h, { type: THREE.HalfFloatType, samples })const composer = new EffectComposer(renderer, rt)composer.addPass(new RenderPass(scene, camera))const rays = new ShaderPass(GodRaysShader)61 unmodified lines6263646566676840 unmodified lines10911011111211311411561 unmodified linestDiffuse: { value: null as THREE.Texture | null },uTime: { value: 0 },uVignette: { value: 0.32 },uGrain: { value: 0.016 },uFade: { value: 0 },uNight: { value: 0 },uRes: { value: new THREE.Vector2(1920, 1080) },40 unmodified linesexport function createPost(renderer: THREE.WebGLRenderer, scene: THREE.Scene, camera: THREE.Camera, w: number, h: number, samples = 4): Post {const rt = new THREE.WebGLRenderTarget(w, h, { type: THREE.HalfFloatType, samples })rt.depthTexture = new THREE.DepthTexture(w, h, THREE.FloatType)const composer = new EffectComposer(renderer, rt)composer.addPass(new RenderPass(scene, camera))const rays = new ShaderPass(GodRaysShader)
260 unmodified lines261262263264265266267187 unmodified lines4554564574584594604614624634644651 unmodified line467468469470471472473474475476477260 unmodified lines}const jarGeos = [jarProfile(0.28, 0.7), jarProfile(0.4, 0.9), jarProfile(0.2, 0.45)]const basketGeo = new THREE.CylinderGeometry(0.42, 0.32, 0.35, 16, 1, true)const fruitGeo = new THREE.IcosahedronGeometry(0.075, 1)for (let s = MARKET_S0; s < MARKET_S1; s += rrange(rng, 5.5, 8)) {if (Math.abs(s - BRIDGE_S) < 12) continueconst p = riverPoint(s, -9.6)187 unmodified lineslanternSpots.push({ p: V3(0, 3.3, 0).applyMatrix4(m), on: 58.5 })}const add = (b: Builder, mat: THREE.Material, cast = true) => {if (!b.count) returnconst mesh = new THREE.Mesh(b.build(), mat)mesh.castShadow = castmesh.receiveShadow = truegroup.add(mesh)}add(stone, stoneMat)1 unmodified lineadd(dark, darkMat)add(red, redMat)add(roof, roofMat)add(goods, fruitMat)add(basket, basketMat)add(jars, jarMat)add(meat, meatMat)add(awning, awningMat)return {group, wheel,260 unmodified lines261262263264265266267187 unmodified lines4554564574584594604614624634644654661 unmodified line468469470471472473474475476477478479260 unmodified lines}const jarGeos = [jarProfile(0.28, 0.7), jarProfile(0.4, 0.9), jarProfile(0.2, 0.45)]const basketGeo = new THREE.CylinderGeometry(0.42, 0.32, 0.35, 16, 1, true)const fruitGeo = new THREE.IcosahedronGeometry(0.075, 0)for (let s = MARKET_S0; s < MARKET_S1; s += rrange(rng, 5.5, 8)) {if (Math.abs(s - BRIDGE_S) < 12) continueconst p = riverPoint(s, -9.6)187 unmodified lineslanternSpots.push({ p: V3(0, 3.3, 0).applyMatrix4(m), on: 58.5 })}const add = (b: Builder, mat: THREE.Material, cast = true, reflect = true) => {if (!b.count) returnconst mesh = new THREE.Mesh(b.build(), mat)mesh.castShadow = castmesh.receiveShadow = trueif (!reflect) mesh.layers.set(1)group.add(mesh)}add(stone, stoneMat)1 unmodified lineadd(dark, darkMat)add(red, redMat)add(roof, roofMat)// market goods: small, main view onlyadd(goods, fruitMat, false, false)add(basket, basketMat, false, false)add(jars, jarMat, false, false)add(meat, meatMat, true, false)add(awning, awningMat, true, false)return {group, wheel,
54 unmodified lines55565758596061106 unmodified lines1681691701711721731745 unmodified lines18018118218318418554 unmodified linesvDir = normalize(position);vec4 p = modelViewMatrix * vec4(position, 1.0);gl_Position = projectionMatrix * p;gl_Position.z = gl_Position.w * 0.99999;}`106 unmodified lines}`export function createSky() {const uniforms = {uSunDir: U.uSunDir,uMoonDir: { value: new THREE.Vector3(0, 0.4, 1).normalize() },5 unmodified linesconst mat = new THREE.ShaderMaterial({vertexShader: SKY_VS, fragmentShader: SKY_FS, uniforms,side: THREE.BackSide, depthWrite: false, fog: false,})const mesh = new THREE.Mesh(new THREE.SphereGeometry(5000, 64, 32), mat)mesh.frustumCulled = false54 unmodified lines5556575859606162636465106 unmodified lines1721731741751761771785 unmodified lines18418518618718818919054 unmodified linesvDir = normalize(position);vec4 p = modelViewMatrix * vec4(position, 1.0);gl_Position = projectionMatrix * p;#ifdef REVERSED_DEPTHgl_Position.z = gl_Position.w * 1e-6;#elsegl_Position.z = gl_Position.w * 0.99999;#endif}`106 unmodified lines}`export function createSky(reversed = false) {const uniforms = {uSunDir: U.uSunDir,uMoonDir: { value: new THREE.Vector3(0, 0.4, 1).normalize() },5 unmodified linesconst mat = new THREE.ShaderMaterial({vertexShader: SKY_VS, fragmentShader: SKY_FS, uniforms,side: THREE.BackSide, depthWrite: false, fog: false,defines: reversed ? { REVERSED_DEPTH: 1 } : {},})const mesh = new THREE.Mesh(new THREE.SphereGeometry(5000, 64, 32), mat)mesh.frustumCulled = false
74 unmodified lines757677787980818230 unmodified lines11311411511611711811974 unmodified linesexport function createTerrain() {const T = getTextures()const xs = axis(NEAR.x0, NEAR.x1, 2.2, 7, 280, 700)const zs = axis(NEAR.z0, NEAR.z1, 2.2, 7, 200, 640)const nx = xs.length, nz = zs.lengthconst pos = new Float32Array(nx * nz * 3)const col = new Float32Array(nx * nz * 3)30 unmodified linesconst mat = std({ vertexColors: true, roughness: 0.95, metalness: 0, map: T.ground }, { key: 'terrain' })const mesh = new THREE.Mesh(geo, mat)mesh.receiveShadow = truemesh.castShadow = truereturn mesh}74 unmodified lines757677787980818230 unmodified lines11311411511611711811974 unmodified linesexport function createTerrain() {const T = getTextures()const xs = axis(NEAR.x0, NEAR.x1, 2.5, 9, 280, 700)const zs = axis(NEAR.z0, NEAR.z1, 2.5, 9, 200, 640)const nx = xs.length, nz = zs.lengthconst pos = new Float32Array(nx * nz * 3)const col = new Float32Array(nx * nz * 3)30 unmodified linesconst mat = std({ vertexColors: true, roughness: 0.95, metalness: 0, map: T.ground }, { key: 'terrain' })const mesh = new THREE.Mesh(geo, mat)mesh.receiveShadow = truemesh.castShadow = falsereturn mesh}
13 unmodified lines14151617181920111 unmodified lines132133134135136137138100 unmodified lines23924024124224324424524624724825 unmodified lines2742752762772782792805 unmodified lines28628728828929029129229329429529629729814 unmodified lines31331431531631731831942 unmodified lines36236336436536636736836937037137237337437537637737837927 unmodified lines40740840941041141241316 unmodified lines43043143243343443543643713 unmodified linesfunction leafMaterial(map: THREE.Texture, opts: { center?: THREE.Vector3; sway?: number; key: string }) {const center = opts.center || new THREE.Vector3()const mat = patch(new THREE.MeshStandardMaterial({ map, alphaTest: 0.45, side: THREE.DoubleSide, roughness: 0.82, metalness: 0 }), {key: opts.key,vertexPars: 'uniform vec3 uCrown; uniform float uSway; attribute vec3 instanceTint; varying vec3 vTint;',vertex: `111 unmodified linesexport interface TreesOut { group: THREE.Group; camphorTop: THREE.Vector3 }export function createTrees(): TreesOut {const T = getTextures()const group = new THREE.Group()const rng = mulberry32(777)100 unmodified lines}// ------------------------------------------------ bamboo grovesgroup.add(createBamboo(rng))// ------------------------------------------------ hillside forestgroup.add(createForest(rng))// ------------------------------------------------ reedsgroup.add(createReeds(rng))25 unmodified linesreturn inst}function createBamboo(rng: Rng) {const T = getTextures()const group = new THREE.Group()// one clump: culms + leaf cards5 unmodified linesconst h = 9 + clumpRng() * 5const lean = new THREE.Vector3(Math.cos(a), 0, Math.sin(a)).multiplyScalar(0.06 + clumpRng() * 0.1)const base = new THREE.Vector3(Math.cos(a) * r, 0, Math.sin(a) * r)const segs = 7for (let i = 0; i < segs; i++) {const f0 = i / segs, f1 = (i + 1) / segsconst p0 = base.clone().add(new THREE.Vector3(lean.x * h * f0 * f0 * 2, h * f0, lean.z * h * f0 * f0 * 2))const p1 = base.clone().add(new THREE.Vector3(lean.x * h * f1 * f1 * 2, h * f1, lean.z * h * f1 * f1 * 2))const d = p1.clone().sub(p0)const g = new THREE.CylinderGeometry(0.045 * (1 - f1 * 0.6), 0.05 * (1 - f0 * 0.6), d.length(), 5, 1, true)culms.geometry(g, new THREE.Matrix4().compose(p0.clone().addScaledVector(d, 0.5), new THREE.Quaternion().setFromUnitVectors(UP, d.clone().normalize()), new THREE.Vector3(1, 1, 1)))if (f0 > 0.45) {for (let k = 0; k < 2; k++) {14 unmodified linesconst houses = buildHouses()const spots: THREE.Matrix4[] = []const tints: number[] = []for (let tries = 0; tries < 9000 && spots.length < 900; tries++) {const x = rrange(rng, -520, 560), z = rrange(rng, -420, 380)const q = riverQuery(x, z)if (q.d < 22) continue42 unmodified linesconst leafInst = new THREE.InstancedMesh(leafGeo, leafMat, spots.length)spots.forEach((m, i) => { culmInst.setMatrixAt(i, m); leafInst.setMatrixAt(i, m) })leafGeo.setAttribute('instanceTint', new THREE.InstancedBufferAttribute(new Float32Array(tints), 3))culmInst.castShadow = leafInst.castShadow = trueleafInst.receiveShadow = trueculmInst.computeBoundingSphere()leafInst.computeBoundingSphere()group.add(culmInst, leafInst)return group}function createForest(rng: Rng) {const group = new THREE.Group()// broadleaf blob + fir cone, vertex-noise deformedconst blob = new THREE.IcosahedronGeometry(1, 2){const p = blob.getAttribute('position') as THREE.BufferAttributefor (let i = 0; i < p.count; i++) {27 unmodified linesconst lists: THREE.Matrix4[][] = [[], []]const tints: number[][] = [[], []]const area = { x0: -1500, x1: 1500, z0: -1300, z1: 1200 }for (let tries = 0; tries < 60000 && lists[0].length + lists[1].length < 9000; tries++) {const x = rrange(rng, area.x0, area.x1), z = rrange(rng, area.z0, area.z1)const q = riverQuery(x, z)if (q.d < 70) continue16 unmodified linesconst inst = new THREE.InstancedMesh(g, mats[gi], lists[gi].length)lists[gi].forEach((m, i) => inst.setMatrixAt(i, m))g.setAttribute('instanceTint', new THREE.InstancedBufferAttribute(new Float32Array(tints[gi]), 3))inst.castShadow = trueinst.receiveShadow = trueinst.computeBoundingSphere()group.add(inst)})13 unmodified lines14151617181920111 unmodified lines132133134135136137138139100 unmodified lines24024124224324424524624724824925 unmodified lines2752762772782792802815 unmodified lines28728828929029129229329429529629729829914 unmodified lines31431531631731831932042 unmodified lines36336436536636736836937037137237337437537637737837938038138238327 unmodified lines41141241341441541641716 unmodified lines43443543643743843944044144244313 unmodified linesfunction leafMaterial(map: THREE.Texture, opts: { center?: THREE.Vector3; sway?: number; key: string }) {const center = opts.center || new THREE.Vector3()const mat = patch(new THREE.MeshStandardMaterial({ map, alphaTest: 0.3, alphaToCoverage: true, side: THREE.DoubleSide, roughness: 0.82, metalness: 0 }), {key: opts.key,vertexPars: 'uniform vec3 uCrown; uniform float uSway; attribute vec3 instanceTint; varying vec3 vTint;',vertex: `111 unmodified linesexport interface TreesOut { group: THREE.Group; camphorTop: THREE.Vector3 }export function createTrees(quality: 'low' | 'medium' | 'high' = 'high'): TreesOut {const density = quality === 'high' ? 1 : quality === 'medium' ? 0.55 : 0.32const T = getTextures()const group = new THREE.Group()const rng = mulberry32(777)100 unmodified lines}// ------------------------------------------------ bamboo grovesgroup.add(createBamboo(rng, density))// ------------------------------------------------ hillside forestgroup.add(createForest(rng, density))// ------------------------------------------------ reedsgroup.add(createReeds(rng))25 unmodified linesreturn inst}function createBamboo(rng: Rng, density = 1) {const T = getTextures()const group = new THREE.Group()// one clump: culms + leaf cards5 unmodified linesconst h = 9 + clumpRng() * 5const lean = new THREE.Vector3(Math.cos(a), 0, Math.sin(a)).multiplyScalar(0.06 + clumpRng() * 0.1)const base = new THREE.Vector3(Math.cos(a) * r, 0, Math.sin(a) * r)const segs = 4for (let i = 0; i < segs; i++) {const f0 = i / segs, f1 = (i + 1) / segsconst p0 = base.clone().add(new THREE.Vector3(lean.x * h * f0 * f0 * 2, h * f0, lean.z * h * f0 * f0 * 2))const p1 = base.clone().add(new THREE.Vector3(lean.x * h * f1 * f1 * 2, h * f1, lean.z * h * f1 * f1 * 2))const d = p1.clone().sub(p0)const g = new THREE.CylinderGeometry(0.045 * (1 - f1 * 0.6), 0.05 * (1 - f0 * 0.6), d.length(), 4, 1, true)culms.geometry(g, new THREE.Matrix4().compose(p0.clone().addScaledVector(d, 0.5), new THREE.Quaternion().setFromUnitVectors(UP, d.clone().normalize()), new THREE.Vector3(1, 1, 1)))if (f0 > 0.45) {for (let k = 0; k < 2; k++) {14 unmodified linesconst houses = buildHouses()const spots: THREE.Matrix4[] = []const tints: number[] = []for (let tries = 0; tries < 9000 && spots.length < Math.round(650 * density); tries++) {const x = rrange(rng, -520, 560), z = rrange(rng, -420, 380)const q = riverQuery(x, z)if (q.d < 22) continue42 unmodified linesconst leafInst = new THREE.InstancedMesh(leafGeo, leafMat, spots.length)spots.forEach((m, i) => { culmInst.setMatrixAt(i, m); leafInst.setMatrixAt(i, m) })leafGeo.setAttribute('instanceTint', new THREE.InstancedBufferAttribute(new Float32Array(tints), 3))culmInst.castShadow = falseleafInst.castShadow = trueleafInst.receiveShadow = trueculmInst.layers.set(1)leafInst.layers.set(1)culmInst.computeBoundingSphere()leafInst.computeBoundingSphere()group.add(culmInst, leafInst)return group}function createForest(rng: Rng, density = 1) {const group = new THREE.Group()// broadleaf blob + fir cone, vertex-noise deformedconst blob = new THREE.IcosahedronGeometry(1, 1){const p = blob.getAttribute('position') as THREE.BufferAttributefor (let i = 0; i < p.count; i++) {27 unmodified linesconst lists: THREE.Matrix4[][] = [[], []]const tints: number[][] = [[], []]const area = { x0: -1500, x1: 1500, z0: -1300, z1: 1200 }for (let tries = 0; tries < 60000 && lists[0].length + lists[1].length < Math.round(9000 * density); tries++) {const x = rrange(rng, area.x0, area.x1), z = rrange(rng, area.z0, area.z1)const q = riverQuery(x, z)if (q.d < 70) continue16 unmodified linesconst inst = new THREE.InstancedMesh(g, mats[gi], lists[gi].length)lists[gi].forEach((m, i) => inst.setMatrixAt(i, m))g.setAttribute('instanceTint', new THREE.InstancedBufferAttribute(new Float32Array(tints[gi]), 3))// distant hillside forest: main view only (no shadow / reflection passes)inst.castShadow = falseinst.receiveShadow = falseinst.layers.set(1)inst.computeBoundingSphere()group.add(inst)})
19 unmodified lines202122232425262 unmodified lines29303132333432 unmodified lines676869707172120 unmodified lines1931941951961971981993 unmodified lines20320420520620720828 unmodified lines23723823924024124237 unmodified lines28028128228328428561 unmodified lines3473483493503513523533543553563573583593603613623633643 unmodified lines36836937037137237337437537619 unmodified linesconst FLOOR_H = 3.3export function createVillage(): VillageOut {const T = getTextures()const houses = buildHouses()const wall = new Builder(), roof = new Builder(), dark = new Builder(), wood = new Builder(), stone = new Builder(), glow = new Builder()2 unmodified linesconst eaveAnchors: VillageOut['eaveAnchors'] = []const shopFronts: VillageOut['shopFronts'] = []for (const h of houses) buildHouse(h)function windowOn(h: HouseSpec, k: number) {32 unmodified linesconst base = Math.max(GROUND_Y, gy)const m = trs(h.x, base, h.z, h.rot)const H = floors * FLOOR_H + 0.5const rise = d * 0.27const ridge = H + riseconst n = h.gableSteps120 unmodified linesconst y0 = slopeY(u0), y1 = slopeY(u1)const L = eaveZ * Math.hypot(1, (ridge - eaveY) / eaveZ)const v0 = (u0 * L) / 1.2, v1 = (u1 * L) / 1.2if (zsgn > 0) roof.quad(V3(rx0, y0, z0), V3(rx1, y0, z0), V3(rx1, y1, z1), V3(rx0, y1, z1), [rx0 / 1.2, v0, rx1 / 1.2, v0, rx1 / 1.2, v1, rx0 / 1.2, v1])else roof.quad(V3(rx1, y0, z0), V3(rx0, y0, z0), V3(rx0, y1, z1), V3(rx1, y1, z1), [rx1 / 1.2, v0, rx0 / 1.2, v0, rx0 / 1.2, v1, rx1 / 1.2, v1])// soffit undersidedark.setMatrix(m)3 unmodified lines// eave fascia boardwood.setMatrix(m)wood.box(0, eaveY - 0.08, zsgn * eaveZ, rx1 - rx0, 0.16, 0.08)}// ridge with upturned endsdark.setMatrix(m)28 unmodified lines// warm interior light (lights up with the windows)addWindow(m, (xa + xb) / 2, (sh - 0.3 + 1.0) / 2 + 0.1, hd - 0.58, xb - xa - 0.35, sh - 1.5, windowOn(h, 50 + b) - 1.5, h.seed + b, 1)shopFronts.push({ p: new THREE.Vector3((xa + xb) / 2, 0, hd + 0.6).applyMatrix4(m), rot: h.rot, w: xb - xa, s: h.s })} else {for (let p = 0; p < 4; p++) {const x0 = xa + 0.1 + ((xb - xa - 0.2) * p) / 437 unmodified linesdark.setMatrix(m)dark.box(doorX, 3.38, hd + 0.05, 2.7, 0.12, 0.16)dark.quad(V3(doorX - 1.3, 3.25, hd), V3(doorX + 1.3, 3.25, hd), V3(doorX + 1.3, 2.9, hd + 0.75), V3(doorX - 1.3, 2.9, hd + 0.75))if (h.lantern) {eaveAnchors.push({ p: new THREE.Vector3(doorX - 0.95, 2.85, hd + 0.5).applyMatrix4(m), s: h.s, side: h.side, facing: h.rot })eaveAnchors.push({ p: new THREE.Vector3(doorX + 0.95, 2.85, hd + 0.5).applyMatrix4(m), s: h.s, side: h.side, facing: h.rot })61 unmodified lines}const group = new THREE.Group()const wallMat = std({ map: T.wall, normalMap: T.wallN, normalScale: new THREE.Vector2(0.5, 0.5), roughness: 0.93, color: new THREE.Color(0.95, 0.94, 0.9) }, { key: 'wall' })const roofMat = std({ map: T.roof, normalMap: T.roofN, roughness: 0.62, metalness: 0.05, color: new THREE.Color(0.95, 0.95, 1.0) }, { key: 'roof' })const darkMat = std({ color: new THREE.Color(0.045, 0.045, 0.05), roughness: 0.7 }, { key: 'dark' })const woodMat = std({ map: T.wood, roughness: 0.78, color: new THREE.Color(0.8, 0.75, 0.7) }, { key: 'wood' })const stoneMat = std({ map: T.stone, normalMap: T.stoneN, roughness: 0.88, color: new THREE.Color(0.75, 0.76, 0.74) }, { key: 'stone' })const paveMat = std({ map: T.slab, normalMap: T.slabN, roughness: 0.55, color: new THREE.Color(0.85, 0.88, 0.92) }, { key: 'pave' })const glowMat = windowMaterial(T.lattice)const add = (b: Builder, mat: THREE.Material, cast = true) => {if (!b.count) returnconst mesh = new THREE.Mesh(b.build(), mat)mesh.castShadow = castmesh.receiveShadow = truegroup.add(mesh)}add(wall, wallMat)3 unmodified linesadd(stone, stoneMat)add(pave, paveMat, false)add(glow, glowMat, false)return { group, houses, chimneys, eaveAnchors, shopFronts }}function riverPointS(x: number) {// nearest arc length for an x coordinate (river runs west→east)let best = 0, bd = 1e919 unmodified lines202122232425262 unmodified lines2930313233343536373839404142434445464748495032 unmodified lines83848586878889120 unmodified lines2102112122132142152162172182192202212222232242252262272282292303 unmodified lines23423523623723823924024124224324424524624728 unmodified lines27627727827928028128228328428528628728828929037 unmodified lines32832933033133233333433533633733833934034134234334434534634734834935035135235361 unmodified lines4154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494503 unmodified lines45445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952019 unmodified linesconst FLOOR_H = 3.3export function createVillage(quality: 'low' | 'medium' | 'high' = 'high'): VillageOut {const T = getTextures()const houses = buildHouses()const wall = new Builder(), roof = new Builder(), dark = new Builder(), wood = new Builder(), stone = new Builder(), glow = new Builder()2 unmodified linesconst eaveAnchors: VillageOut['eaveAnchors'] = []const shopFronts: VillageOut['shopFronts'] = []roof.set('aRelief', 0).set('aRH', 0).set('aRS', 0)const tileEnds = new Builder()const endCap = new THREE.CylinderGeometry(0.075, 0.075, 0.05, 7)endCap.rotateX(Math.PI / 2)const dripShape = new THREE.Shape()dripShape.moveTo(-0.1, 0.03); dripShape.lineTo(0.1, 0.03); dripShape.lineTo(0, -0.07); dripShape.closePath()const dripTile = new THREE.ExtrudeGeometry(dripShape, { depth: 0.04, bevelEnabled: false })const tileRelief = (x: number) => {const f = Math.sin((Math.PI * x) / 0.2)return f > 0 ? f * 0.07 : f * 0.022}const couplets = new Builder() // red door couplets (uv into the sign atlas)const signs = new Builder() // shop signboards (uv into the sign atlas)const clutter = new Builder() // water jars, firewood, potted plants (vertex-coloured)clutter.set('aTint', 0)for (const h of houses) buildHouse(h)function windowOn(h: HouseSpec, k: number) {32 unmodified linesconst base = Math.max(GROUND_Y, gy)const m = trs(h.x, base, h.z, h.rot)const H = floors * FLOOR_H + 0.5const detailed = quality === 'high' ? h.lantern : quality === 'medium' ? h.shop : false // street/river fronts get full roof reliefconst rise = d * 0.27const ridge = H + riseconst n = h.gableSteps120 unmodified linesconst y0 = slopeY(u0), y1 = slopeY(u1)const L = eaveZ * Math.hypot(1, (ridge - eaveY) / eaveZ)const v0 = (u0 * L) / 1.2, v1 = (u1 * L) / 1.2if (detailed) {// real 阴阳瓦 relief: convex cover tiles over concave pan tiles (0.4 m period,// aligned with the tile texture), so ridges catch the low sun and cast tiny shadowsconst nx = Math.max(2, Math.round((rx1 - rx0) / 0.1))for (let c = 0; c < nx; c++) {const xa = rx0 + ((rx1 - rx0) * c) / nx, xb = rx0 + ((rx1 - rx0) * (c + 1)) / nxconst ha = tileRelief(xa), hb = tileRelief(xb)const ua = xa / 1.2, ub = xb / 1.2// relief is applied in the vertex shader (and faded out with distance → no shimmer)roof.set('aRelief', 1)if (zsgn > 0) roof.quadRelief(V3(xa, y0, z0), V3(xb, y0, z0), V3(xb, y1, z1), V3(xa, y1, z1), [ha, hb, hb, ha], [ua, v0, ub, v0, ub, v1, ua, v1])else roof.quadRelief(V3(xb, y0, z0), V3(xa, y0, z0), V3(xa, y1, z1), V3(xb, y1, z1), [hb, ha, ha, hb], [ub, v0, ua, v0, ua, v1, ub, v1])roof.set('aRelief', 0)}} else if (zsgn > 0) roof.quad(V3(rx0, y0, z0), V3(rx1, y0, z0), V3(rx1, y1, z1), V3(rx0, y1, z1), [rx0 / 1.2, v0, rx1 / 1.2, v0, rx1 / 1.2, v1, rx0 / 1.2, v1])else roof.quad(V3(rx1, y0, z0), V3(rx0, y0, z0), V3(rx0, y1, z1), V3(rx1, y1, z1), [rx1 / 1.2, v0, rx0 / 1.2, v0, rx0 / 1.2, v1, rx1 / 1.2, v1])// soffit undersidedark.setMatrix(m)3 unmodified lines// eave fascia boardwood.setMatrix(m)wood.box(0, eaveY - 0.08, zsgn * eaveZ, rx1 - rx0, 0.16, 0.08)if (detailed) {// round tile ends (瓦当) on every cover row and pointed drip tiles (滴水) on the panstileEnds.setMatrix(m)for (let x = Math.ceil((rx0 - 0.1) / 0.4) * 0.4 + 0.1; x < rx1 - 0.05; x += 0.4) {tileEnds.geometry(endCap, new THREE.Matrix4().compose(V3(x, eaveY + 0.04, zsgn * (eaveZ + 0.02)), new THREE.Quaternion().setFromAxisAngle(V3(0, 1, 0), zsgn > 0 ? 0 : Math.PI), V3(1, 1, 1)))if (x + 0.2 < rx1) tileEnds.geometry(dripTile, new THREE.Matrix4().compose(V3(x + 0.2, eaveY - 0.03, zsgn * (eaveZ + 0.02)), new THREE.Quaternion().setFromAxisAngle(V3(0, 1, 0), zsgn > 0 ? 0 : Math.PI), V3(1, 1, 1)))}}}// ridge with upturned endsdark.setMatrix(m)28 unmodified lines// warm interior light (lights up with the windows)addWindow(m, (xa + xb) / 2, (sh - 0.3 + 1.0) / 2 + 0.1, hd - 0.58, xb - xa - 0.35, sh - 1.5, windowOn(h, 50 + b) - 1.5, h.seed + b, 1)shopFronts.push({ p: new THREE.Vector3((xa + xb) / 2, 0, hd + 0.6).applyMatrix4(m), rot: h.rot, w: xb - xa, s: h.s })if (b === Math.floor(bays / 2)) {// black lacquer signboard with gilded characters (店招)const si = Math.floor(rng() * 8)const cx = (xa + xb) / 2, sw = Math.min(2.2, xb - xa - 0.1)dark.setMatrix(m)dark.box(cx, sh + 0.1, hd + 0.06, sw + 0.12, 0.62, 0.06)signs.setMatrix(m)signs.quad(V3(cx - sw / 2, sh - 0.17, hd + 0.1), V3(cx + sw / 2, sh - 0.17, hd + 0.1), V3(cx + sw / 2, sh + 0.37, hd + 0.1), V3(cx - sw / 2, sh + 0.37, hd + 0.1), [(si % 4) / 4, (si < 4 ? 0 : 0.125), ((si % 4) + 1) / 4, (si < 4 ? 0 : 0.125), ((si % 4) + 1) / 4, (si < 4 ? 0.125 : 0.25), (si % 4) / 4, (si < 4 ? 0.125 : 0.25)])}} else {for (let p = 0; p < 4; p++) {const x0 = xa + 0.1 + ((xb - xa - 0.2) * p) / 437 unmodified linesdark.setMatrix(m)dark.box(doorX, 3.38, hd + 0.05, 2.7, 0.12, 0.16)dark.quad(V3(doorX - 1.3, 3.25, hd), V3(doorX + 1.3, 3.25, hd), V3(doorX + 1.3, 2.9, hd + 0.75), V3(doorX - 1.3, 2.9, hd + 0.75))// red couplets either side of the door and a horizontal scroll above itcouplets.setMatrix(m)const cs = Math.floor(rng() * 3)const cu = (i: number) => [i * 0.125, 0.5, (i + 1) * 0.125, 0.5, (i + 1) * 0.125, 1, i * 0.125, 1]const zc = hd + 0.015couplets.quad(V3(doorX - 1.24, 0.75, zc), V3(doorX - 0.98, 0.75, zc), V3(doorX - 0.98, 2.45, zc), V3(doorX - 1.24, 2.45, zc), cu(cs * 2 + 1))couplets.quad(V3(doorX + 0.98, 0.75, zc), V3(doorX + 1.24, 0.75, zc), V3(doorX + 1.24, 2.45, zc), V3(doorX + 0.98, 2.45, zc), cu(cs * 2))const bu = [cs / 3, 0.25, (cs + 1) / 3, 0.25, (cs + 1) / 3, 0.5, cs / 3, 0.5]couplets.quad(V3(doorX - 0.75, 2.78, zc), V3(doorX + 0.75, 2.78, zc), V3(doorX + 0.75, 3.0, zc), V3(doorX - 0.75, 3.0, zc), bu)// clutter by the door: glazed water jar, firewood stack or a potted plantclutter.setMatrix(m)const side = doorX > 0 ? -1 : 1const kind = Math.floor(rng() * 3)if (kind === 0) { clutter.set('aTint', 0); clutter.geometry(jarGeo, new THREE.Matrix4().makeTranslation(doorX + side * 1.75, 0, hd + 0.55)) } else if (kind === 1) {clutter.set('aTint', 1)for (let k = 0; k < 9; k++) clutter.geometry(logGeo, new THREE.Matrix4().compose(V3(doorX + side * (1.9 + (k % 3) * 0.02), 0.1 + Math.floor(k / 3) * 0.17, hd + 0.35 + (k % 3) * 0.17), new THREE.Quaternion().setFromAxisAngle(V3(0, 0, 1), Math.PI / 2), V3(1, 1, 1)))} else {clutter.set('aTint', 2); clutter.geometry(potGeo, new THREE.Matrix4().makeTranslation(doorX + side * 1.6, 0, hd + 0.5))clutter.set('aTint', 3); clutter.geometry(shrubGeo, new THREE.Matrix4().makeTranslation(doorX + side * 1.6, 0.62, hd + 0.5))}if (h.lantern) {eaveAnchors.push({ p: new THREE.Vector3(doorX - 0.95, 2.85, hd + 0.5).applyMatrix4(m), s: h.s, side: h.side, facing: h.rot })eaveAnchors.push({ p: new THREE.Vector3(doorX + 0.95, 2.85, hd + 0.5).applyMatrix4(m), s: h.s, side: h.side, facing: h.rot })61 unmodified lines}const group = new THREE.Group()const atlas = signAtlas()const signMat = std({ map: atlas, roughness: 0.55, metalness: 0.0 }, { key: 'sign' })const clutterMat = std({ roughness: 0.6 }, {key: 'clutter', vertexPars: 'attribute float aTint; varying float vTint;', vertex: 'vTint = aTint;', fragmentPars: 'varying float vTint;',colorFrag: 'diffuseColor.rgb = vTint < 0.5 ? vec3(0.09, 0.06, 0.04) : vTint < 1.5 ? vec3(0.34, 0.22, 0.12) : vTint < 2.5 ? vec3(0.42, 0.2, 0.1) : vec3(0.1, 0.22, 0.06);',})const wallMat = std({ map: T.wall, normalMap: T.wallN, normalScale: new THREE.Vector2(0.5, 0.5), roughness: 0.93, color: new THREE.Color(0.95, 0.94, 0.9) }, { key: 'wall' })const roofMat = std({ map: T.roof, normalMap: T.roofN, normalScale: new THREE.Vector2(0.8, 0.8), roughness: 0.66, metalness: 0.05, color: new THREE.Color(0.95, 0.95, 1.0) }, {key: 'roof',vertexPars: 'attribute float aRelief; attribute float aRH;',vertex: `{// tile relief: full near the camera, flattened beyond ~45 m (keeps far roofs from aliasing)vec3 wp0 = (modelMatrix * vec4(position, 1.0)).xyz;float fade = 1.0 - smoothstep(22.0, 48.0, distance(wp0, cameraPosition));transformed.y += aRH * aRelief * fade;}`,})const darkMat = std({ color: new THREE.Color(0.045, 0.045, 0.05), roughness: 0.7 }, { key: 'dark' })const woodMat = std({ map: T.wood, roughness: 0.78, color: new THREE.Color(0.8, 0.75, 0.7) }, { key: 'wood' })const stoneMat = std({ map: T.stone, normalMap: T.stoneN, roughness: 0.88, color: new THREE.Color(0.75, 0.76, 0.74) }, { key: 'stone' })const paveMat = std({ map: T.slab, normalMap: T.slabN, roughness: 0.55, color: new THREE.Color(0.85, 0.88, 0.92) }, { key: 'pave' })const glowMat = windowMaterial(T.lattice)const add = (b: Builder, mat: THREE.Material, cast = true, reflect = true) => {if (!b.count) returnconst mesh = new THREE.Mesh(b.build(), mat)mesh.castShadow = castmesh.receiveShadow = trueif (!reflect) mesh.layers.set(1)group.add(mesh)}add(wall, wallMat)3 unmodified linesadd(stone, stoneMat)add(pave, paveMat, false)add(glow, glowMat, false)add(couplets, signMat, false, false)add(signs, signMat, false, false)add(tileEnds, darkMat, false, false)add(clutter, clutterMat, false, false)return { group, houses, chimneys, eaveAnchors, shopFronts }}const jarGeo = new THREE.LatheGeometry([[0.05, 0], [0.32, 0.08], [0.4, 0.35], [0.36, 0.62], [0.3, 0.7], [0.32, 0.72], [0.26, 0.72]].map(([r, y]) => new THREE.Vector2(r, y)), 14)const logGeo = new THREE.CylinderGeometry(0.08, 0.08, 0.9, 6)const potGeo = new THREE.LatheGeometry([[0.05, 0], [0.18, 0.02], [0.24, 0.4], [0.26, 0.45], [0.2, 0.45]].map(([r, y]) => new THREE.Vector2(r, y)), 12)const shrubGeo = new THREE.IcosahedronGeometry(0.34, 1)/** Atlas: row 0-1 = 8 shop signs, row 2 = 3 horizontal scrolls, row 3 = 6 couplet strips. */function signAtlas() {const W = 1024, H = 1024const c = document.createElement('canvas')c.width = Wc.height = Hconst g = c.getContext('2d')!const font = (px: number) => `${px}px JNTitle, "STKaiti", "KaiTi", serif`g.textAlign = 'center'g.textBaseline = 'middle'// shop signs: black lacquer with gold characters (v 0 – 0.25 → canvas bottom quarter... flipY)const SIGNS = ['米铺', '茶馆', '酱园', '布庄', '药铺', '豆腐坊', '酒坊', '竹器']SIGNS.forEach((t, i) => {const x = (i % 4) * 256, y = H - (Math.floor(i / 4) + 1) * 128g.fillStyle = '#120c08'g.fillRect(x, y, 256, 128)g.strokeStyle = '#8a6a2a'g.lineWidth = 6g.strokeRect(x + 8, y + 8, 240, 112)g.fillStyle = '#d8b25a'g.font = font(t.length > 2 ? 64 : 80)g.fillText(t, x + 128, y + 68)})// horizontal scrolls (横批)const BANNERS = ['福满江南', '人寿年丰', '耕读传家']BANNERS.forEach((t, i) => {const x = (i * W) / 3, y = H * 0.5g.fillStyle = '#b3241b'g.fillRect(x + 4, y, W / 3 - 8, H * 0.25)g.fillStyle = '#1a0a05'g.font = font(70)g.fillText(t, x + W / 6, y + H * 0.125)})// couplet strips (vertical), 6 strips = 3 pairsconst PAIRS = [['一溪春水绕门过', '两岸灯花照客来'], ['小桥流水千家月', '古巷炊烟万户春'], ['白墙黛瓦藏诗意', '细雨斜阳入画中']]PAIRS.flat().forEach((t, i) => {const x = i * 128, y = 0g.fillStyle = '#b8261c'g.fillRect(x + 6, y, 116, H * 0.5)g.fillStyle = '#1a0a05'g.font = font(54)Array.from(t).forEach((ch, k) => g.fillText(ch, x + 64, y + 40 + k * 68))})const tex = new THREE.CanvasTexture(c)tex.colorSpace = THREE.SRGBColorSpacetex.anisotropy = 8return tex}function riverPointS(x: number) {// nearest arc length for an x coordinate (river runs west→east)let best = 0, bd = 1e9
38 unmodified lines39404142434445464748495051525354555657585960616212 unmodified lines7576777879808138 unmodified lines12012112212312412510 unmodified lines1361371381391401411421431441451461476 unmodified lines15415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618738 unmodified linesreturn mix(mix(h21(i), h21(i + vec2(1, 0)), u.x), mix(h21(i + vec2(0, 1)), h21(i + vec2(1, 1)), u.x), u.y);}// height of the water surface ripplesfloat wave(vec2 p) {float t = uTime;float h = 0.0;h += sin(dot(p, vec2(0.62, 0.21)) * 1.1 + t * 1.3) * 0.5;h += sin(dot(p, vec2(-0.35, 0.78)) * 1.7 + t * 1.7) * 0.32;h += sin(dot(p, vec2(0.9, -0.5)) * 2.9 + t * 2.3) * 0.18;h += vn(p * 1.3 + vec2(t * 0.35, t * 0.12)) * 0.6;h += vn(p * 3.7 - vec2(t * 0.6, -t * 0.2)) * 0.25;h += vn(p * 9.0 + vec2(t * 0.9, t * 0.4)) * 0.1;return h;}void main() {vec2 p = vWorld.xz;float e = 0.08;float h0 = wave(p);vec2 grad = vec2(wave(p + vec2(e, 0.0)) - h0, wave(p + vec2(0.0, e)) - h0) / e;float amp = mix(0.09, 0.022, vCalm);vec3 N = normalize(vec3(-grad.x * amp, 1.0, -grad.y * amp));vec3 V = normalize(cameraPosition - vWorld);12 unmodified lines// sun glittervec3 R = reflect(-V, N);float sd = max(dot(R, uSunDir), 0.0);col += uSunCol * (pow(sd, 900.0) * 5.0 + pow(sd, 120.0) * 0.45) * uSunI * smoothstep(-0.01, 0.03, uSunDir.y);col = applyWorldFog(col, vWorld);if (uDebug > 1.5) col = vec3(uv, 0.0);else if (uDebug > 0.5) col = refl;38 unmodified linesgeo.computeBoundingSphere()const rt = new THREE.WebGLRenderTarget(512, 512, { type: THREE.HalfFloatType, samples: 0 })const textureMatrix = new THREE.Matrix4()const uniforms: Record<string, THREE.IUniform> = {tReflect: { value: rt.texture },10 unmodified linesmesh.receiveShadow = falseconst mirror = new THREE.PerspectiveCamera()const normal = new THREE.Vector3(0, 1, 0)const plane = new THREE.Plane()const clip = new THREE.Vector4()const q = new THREE.Vector4()const camPos = new THREE.Vector3(), look = new THREE.Vector3(), target = new THREE.Vector3(), rot = new THREE.Matrix4()const origin = new THREE.Vector3(0, 0, 0)const renderReflection = (renderer: THREE.WebGLRenderer, scene: THREE.Scene, camera: THREE.PerspectiveCamera) => {camPos.setFromMatrixPosition(camera.matrixWorld)6 unmodified linesmirror.position.copy(view)mirror.up.set(0, 1, 0).applyMatrix4(rot).reflect(normal)mirror.lookAt(target)mirror.far = camera.farmirror.near = camera.nearmirror.updateMatrixWorld()mirror.projectionMatrix.copy(camera.projectionMatrix)textureMatrix.set(0.5, 0, 0, 0.5, 0, 0.5, 0, 0.5, 0, 0, 0.5, 0.5, 0, 0, 0, 1)textureMatrix.multiply(mirror.projectionMatrix).multiply(mirror.matrixWorldInverse)plane.setFromNormalAndCoplanarPoint(normal, new THREE.Vector3(0, -0.05, 0))plane.applyMatrix4(mirror.matrixWorldInverse)clip.set(plane.normal.x, plane.normal.y, plane.normal.z, plane.constant)const pm = mirror.projectionMatrixq.x = (Math.sign(clip.x) + pm.elements[8]) / pm.elements[0]q.y = (Math.sign(clip.y) + pm.elements[9]) / pm.elements[5]q.z = -1q.w = (1 + pm.elements[10]) / pm.elements[14]clip.multiplyScalar(2 / clip.dot(q))pm.elements[2] = clip.xpm.elements[6] = clip.ypm.elements[10] = clip.z + 1pm.elements[14] = clip.wmirror.projectionMatrixInverse.copy(pm).invert()mesh.visible = falseconst prevRT = renderer.getRenderTarget()const prevShadow = renderer.shadowMap.autoUpdaterenderer.shadowMap.autoUpdate = falserenderer.setRenderTarget(rt)renderer.clear()renderer.render(scene, mirror)renderer.setRenderTarget(prevRT)renderer.shadowMap.autoUpdate = prevShadowmesh.visible = true}38 unmodified lines394041424344454647484950515253545556575859606162636412 unmodified lines7778798081828338 unmodified lines12212312412512612712812910 unmodified lines1401411421431441451461471481491501511526 unmodified lines15916016116216316416516616716816917017117217317417517617717817918018118218338 unmodified linesreturn mix(mix(h21(i), h21(i + vec2(1, 0)), u.x), mix(h21(i + vec2(0, 1)), h21(i + vec2(1, 1)), u.x), u.y);}// height of the water surface ripplesfloat wave(vec2 p, float detail) {float t = uTime;float h = 0.0;h += sin(dot(p, vec2(0.62, 0.21)) * 1.1 + t * 1.3) * 0.5;h += sin(dot(p, vec2(-0.35, 0.78)) * 1.7 + t * 1.7) * 0.32;h += sin(dot(p, vec2(0.9, -0.5)) * 2.9 + t * 2.3) * 0.18;h += vn(p * 1.3 + vec2(t * 0.35, t * 0.12)) * 0.6;h += vn(p * 3.7 - vec2(t * 0.6, -t * 0.2)) * 0.25 * detail;h += vn(p * 9.0 + vec2(t * 0.9, t * 0.4)) * 0.1 * detail * detail;return h;}void main() {vec2 p = vWorld.xz;float camDist = length(cameraPosition - vWorld);float detail = 1.0 - smoothstep(25.0, 140.0, camDist);float e = mix(0.08, 0.6, smoothstep(20.0, 200.0, camDist));float h0 = wave(p, detail);vec2 grad = vec2(wave(p + vec2(e, 0.0), detail) - h0, wave(p + vec2(0.0, e), detail) - h0) / e;float amp = mix(0.09, 0.022, vCalm) * mix(1.0, 0.45, smoothstep(40.0, 300.0, camDist));vec3 N = normalize(vec3(-grad.x * amp, 1.0, -grad.y * amp));vec3 V = normalize(cameraPosition - vWorld);12 unmodified lines// sun glittervec3 R = reflect(-V, N);float sd = max(dot(R, uSunDir), 0.0);col += uSunCol * (pow(sd, 900.0) * 5.0 * detail + pow(sd, 120.0) * 0.45) * uSunI * smoothstep(-0.01, 0.03, uSunDir.y);col = applyWorldFog(col, vWorld);if (uDebug > 1.5) col = vec3(uv, 0.0);else if (uDebug > 0.5) col = refl;38 unmodified linesgeo.computeBoundingSphere()const rt = new THREE.WebGLRenderTarget(512, 512, { type: THREE.HalfFloatType, samples: 0 })// float depth: together with the reversed depth buffer this removes distant z-fightingrt.depthTexture = new THREE.DepthTexture(512, 512, THREE.FloatType)const textureMatrix = new THREE.Matrix4()const uniforms: Record<string, THREE.IUniform> = {tReflect: { value: rt.texture },10 unmodified linesmesh.receiveShadow = falseconst mirror = new THREE.PerspectiveCamera()mirror.layers.set(0) // objects on layer 1 (vegetation, people, small props…) are not reflectedconst normal = new THREE.Vector3(0, 1, 0)const camPos = new THREE.Vector3(), look = new THREE.Vector3(), target = new THREE.Vector3(), rot = new THREE.Matrix4()const origin = new THREE.Vector3(0, 0, 0)// clip everything below the water surface (works with any depth convention)const clipPlanes = [new THREE.Plane(new THREE.Vector3(0, 1, 0), 0.05)]const noClip: THREE.Plane[] = []const renderReflection = (renderer: THREE.WebGLRenderer, scene: THREE.Scene, camera: THREE.PerspectiveCamera) => {camPos.setFromMatrixPosition(camera.matrixWorld)6 unmodified linesmirror.position.copy(view)mirror.up.set(0, 1, 0).applyMatrix4(rot).reflect(normal)mirror.lookAt(target)mirror.fov = camera.fovmirror.aspect = camera.aspectmirror.near = camera.nearmirror.far = camera.farmirror.updateProjectionMatrix()mirror.updateMatrixWorld()// x/y rows of the projection are identical for standard and reversed depthtextureMatrix.set(0.5, 0, 0, 0.5, 0, 0.5, 0, 0.5, 0, 0, 0.5, 0.5, 0, 0, 0, 1)textureMatrix.multiply(mirror.projectionMatrix).multiply(mirror.matrixWorldInverse)mesh.visible = falseconst prevRT = renderer.getRenderTarget()const prevShadow = renderer.shadowMap.autoUpdaterenderer.shadowMap.autoUpdate = falserenderer.clippingPlanes = clipPlanesrenderer.setRenderTarget(rt)renderer.clear()renderer.render(scene, mirror)renderer.setRenderTarget(prevRT)renderer.clippingPlanes = noCliprenderer.shadowMap.autoUpdate = prevShadowmesh.visible = true}
25 unmodified lines26272829303132333435363725 unmodified linesconst R = RATIOS.find((r) => r.id === ratio)!const W = R.w, H = R.hconst prevW = film.width, prevH = film.heightfilm.setSize(W, H)film.renderFrame(d.t)const c = document.createElement('canvas')c.width = Wc.height = Hconst g = c.getContext('2d')!g.drawImage(film.renderer.domElement, 0, 0, W, H)film.setSize(prevW, prevH)const u = Math.min(W, H)25 unmodified lines2627282930313233343536373825 unmodified linesconst R = RATIOS.find((r) => r.id === ratio)!const W = R.w, H = R.hconst prevW = film.width, prevH = film.heightfilm.setSize(Math.round(W * 1.5), Math.round(H * 1.5)) // supersampledfilm.renderFrame(d.t)const c = document.createElement('canvas')c.width = Wc.height = Hconst g = c.getContext('2d')!g.imageSmoothingQuality = 'high'g.drawImage(film.renderer.domElement, 0, 0, W, H)film.setSize(prevW, prevH)const u = Math.min(W, H)
65 unmodified lines6667686970717265 unmodified linescomp.height = Hconst g = comp.getContext('2d')!const prevW = film.width, prevH = film.heightfilm.setSize(W, H)try {for (let ci = 0; ci < clips.length; ci++) {const clip = clips[ci]65 unmodified lines666768697071727365 unmodified linescomp.height = Hconst g = comp.getContext('2d')!const prevW = film.width, prevH = film.heightfilm.setSize(Math.round(W * 1.4), Math.round(H * 1.4)) // supersampledg.imageSmoothingQuality = 'high'try {for (let ci = 0; ci < clips.length; ci++) {const clip = clips[ci]
105 unmodified lines106107108109110111112105 unmodified linescomp.height = Hconst g = comp.getContext('2d')!const prevW = film.width, prevH = film.heightfilm.setSize(W, H)const t0 = performance.now()try {for (let i = 0; i < total; i++) {105 unmodified lines106107108109110111112113114115116105 unmodified linescomp.height = Hconst g = comp.getContext('2d')!const prevW = film.width, prevH = film.height// supersampling: render larger, then filter down → crisp edges, no crawling on fine detailconst ss = W * H <= 1280 * 720 ? 2 : 1.5film.setSize(Math.round(W * ss), Math.round(H * ss))g.imageSmoothingEnabled = trueg.imageSmoothingQuality = 'high'const t0 = performance.now()try {for (let i = 0; i < total; i++) {
76 unmodified lines77787980818283848586878889909192939495969776 unmodified linespg.on('console', lambda m: logs.append(m.type + ': ' + m.text) if m.type in ('error', 'warning') else None)pg.on('pageerror', lambda e: logs.append('PAGEERROR: ' + str(e)))t0 = time.time()pg.goto(f'{BASE}?w={w}&h={h}&t={times[0]}', timeout=180000)pg.wait_for_function("document.title === 'ready' || document.title === 'error'", timeout=900000)print('init', round(time.time() - t0, 1), 's', pg.title())for t in times:print(f'\n===== t={t} =====')if mode in ('both', 'final'):pg.evaluate(f"window.__film.renderFrame({t})")data = pg.evaluate("document.querySelector('canvas').toDataURL('image/jpeg', 0.9)")img = Image.open(io.BytesIO(base64.b64decode(data.split(',')[1])))img.save(f'{out}/t{t:05.1f}.jpg')print(stats(img))print(ascii_lum(img))if mode in ('both', 'ids'):pg.evaluate(f"window.__ids({t})")data = pg.evaluate("document.querySelector('canvas').toDataURL('image/png')")img = Image.open(io.BytesIO(base64.b64decode(data.split(',')[1])))img.save(f'{out}/ids{t:05.1f}.png')print(ascii_ids(img))76 unmodified lines7778798081828384858687888990919293949576 unmodified linespg.on('console', lambda m: logs.append(m.type + ': ' + m.text) if m.type in ('error', 'warning') else None)pg.on('pageerror', lambda e: logs.append('PAGEERROR: ' + str(e)))t0 = time.time()pg.goto(f'{BASE}?w={w}&h={h}&noaudio=1&t={times[0]}', timeout=180000)pg.wait_for_function("document.title === 'ready' || document.title === 'error'", timeout=900000)print('init', round(time.time() - t0, 1), 's', pg.title())for t in times:print(f'\n===== t={t} =====')if mode in ('both', 'final'):data = pg.evaluate(f"(() => {{ window.__film.renderFrame({t}); return window.__film.renderer.domElement.toDataURL('image/jpeg', 0.9) }})()")img = Image.open(io.BytesIO(base64.b64decode(data.split(',')[1])))img.save(f'{out}/t{t:05.1f}.jpg')print(stats(img))print(ascii_lum(img))if mode in ('both', 'ids'):data = pg.evaluate(f"(() => {{ window.__ids({t}); return window.__film.renderer.domElement.toDataURL('image/png') }})()")img = Image.open(io.BytesIO(base64.b64decode(data.split(',')[1])))img.save(f'{out}/ids{t:05.1f}.png')print(ascii_ids(img))
1234567891011121314151617181920212223242526import sys, io, base64sys.path.insert(0, '/workspaces/space/tools')from analyze import *times = [float(x) for x in sys.argv[1].split(',')]with sync_playwright() as p: b = p.chromium.launch(args=['--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--ignore-gpu-blocklist', '--disable-dev-shm-usage']) pg = b.new_page(viewport={'width': 1000, 'height': 600}) pg.goto(BASE + '?w=960&h=540&noaudio=1', timeout=180000) pg.wait_for_function("document.title === 'ready' || document.title === 'error'", timeout=900000) pg.evaluate("window.__film.post.grade.uniforms.uGrain.value = 0") for t0 in times: pg.evaluate(f"window.__film.freezeCam = {t0}") fr = [] for k in range(3): d = pg.evaluate(f"(() => {{ window.__film.renderFrame({t0 + k / 30}); return window.__film.renderer.domElement.toDataURL('image/png') }})()") fr.append(list(Image.open(io.BytesIO(base64.b64decode(d.split(',')[1]))).convert('L').getdata())) d = pg.evaluate(f"(() => {{ window.__ids({t0 + 1 / 30}); return window.__film.renderer.domElement.toDataURL('image/png') }})()") ids = list(Image.open(io.BytesIO(base64.b64decode(d.split(',')[1]))).convert('RGB').getdata()) cnt, tot, n = {}, {}, 0 for i in range(len(ids)): c = classify(ids[i]); tot[c] = tot.get(c, 0) + 1 x, y, z = fr[0][i], fr[1][i], fr[2][i] if abs(y - x) > 12 and abs(y - z) > 12 and (y - x) * (y - z) > 0: cnt[c] = cnt.get(c, 0) + 1; n += 1 print(f't={t0} static-camera flicker pixels {n / len(ids) * 100:.3f}% ' + ' '.join(f'{c}:{cnt[c] / tot[c] * 100:.2f}%' for c in sorted(cnt, key=lambda k: -cnt[k])[:8]), flush=True) b.close()12345678910111213141516import sys, time, jsonsys.path.insert(0, '/workspaces/space/tools')from analyze import *times = [float(x) for x in sys.argv[1].split(',')]with sync_playwright() as p: b = p.chromium.launch(args=['--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--ignore-gpu-blocklist', '--disable-dev-shm-usage']) pg = b.new_page(viewport={'width': 400, 'height': 300}) pg.goto(BASE + '?w=320&h=180&noaudio=1', timeout=180000) pg.wait_for_function("document.title === 'ready' || document.title === 'error'", timeout=900000) for t in times: r = pg.evaluate(f"""(() => {{ const f = window.__film; const i = f.renderer.info; i.autoReset = false; i.reset(); const t0 = performance.now(); f.renderFrame({t}); const dt = performance.now() - t0; const o = {{ calls: i.render.calls, tris: i.render.triangles, points: i.render.points, ms: Math.round(dt), progs: i.programs.length, tex: i.memory.textures, geo: i.memory.geometries }}; i.autoReset = true; return JSON.stringify(o) }})()""") print(t, r, flush=True) b.close()README.md+4
src/jiangnan/JiangnanApp.tsx+76-28
src/jiangnan/assets/fonts/title.woff2+2-2
src/jiangnan/assets/fonts/wenkai.woff2+2-2
src/jiangnan/engine/Film.ts+136-46
src/jiangnan/engine/figures.tsAdded+315
src/jiangnan/engine/geom.ts+22
src/jiangnan/engine/life.ts+40-219
src/jiangnan/engine/post.ts+2-1
src/jiangnan/engine/props.ts+9-7
src/jiangnan/engine/sky.ts+6-1
src/jiangnan/engine/terrain.ts+3-3
src/jiangnan/engine/trees.ts+20-14
src/jiangnan/engine/village.ts+148-4
src/jiangnan/engine/water.ts+23-27
src/jiangnan/export/covers.ts+2-1
src/jiangnan/export/livegen.ts+2-1
src/jiangnan/export/mp4.ts+5-1
tools/jiangnan/analyze.py+3-5
tools/jiangnan/t_flick4.pyAdded+26
tools/jiangnan/t_perf.pyAdded+16