feat(ui): 保时捷语法复刻收尾(ADR-0008/0009/0011/0012/0013) #65
No files matched your search
+43
@@ -362,6 +362,10 @@ deliverables/logo-redesign-2026-10-13/landing/*.png
|
||||
deliverables/logo-redesign-2026-10-13/landing/*.ico
|
||||
deliverables/logo-redesign-2026-10-13/assets-delivery/*.png
|
||||
deliverables/logo-redesign-2026-10-13/assets-delivery/*.ico
|
||||
# 企业微信资产包同理:18 张 PNG 全部由 wecom-pack.cjs 从**已入库的** SVG 源重新栅格化
|
||||
# 得到(判据见 WECOM-MANIFEST.md 与 check-wecom.py 的 64 项),二进制留本地即可。
|
||||
# 生成脚本、校验脚本、清单与 pack-report.json 必须入库 —— 那才是「怎么做的」真源。
|
||||
deliverables/logo-redesign-2026-10-13/assets-wecom/*.png
|
||||
# 公司介绍包:PPTX 二进制走交付网盘不进 git,大纲 md 属对外文案稿
|
||||
deliverables/company-deck/
|
||||
# 历史 PR 描述稿与一次性线上探针
|
||||
@@ -369,3 +373,42 @@ deliverables/company-deck/
|
||||
.tmp-*.mjs
|
||||
|
||||
/src/generated/prisma
|
||||
|
||||
# ============================================================
|
||||
# 验收证据的体积边界(2026-11-25 收尾轮裁定)
|
||||
# ============================================================
|
||||
# 规则:docs/acceptance/<日期>-<主题>/ 的**文字与结构化读数**(README / FIXES /
|
||||
# defects*.json / summary.json / coverage-matrix / axe 结果 / 复现脚本)一律入库 ——
|
||||
# 它们才是「这条结论怎么来的」的可复查部分;而**逐页截图**只在排查当时有用,
|
||||
# 全量截图一次 60–80MB,入 git 会把每次 clone 与 diff 都拖垮(本仓已有
|
||||
# 2026-10-20-prod-about 等 2.9MB 级目录入库,但 77MB/95MB 这一档不属同一量级)。
|
||||
# 因此只忽略下面这些**明确点名的大块二进制目录**,不做按扩展名的一刀切:
|
||||
# · 按扩展名忽略 *.png 会把 e2e/visual-snapshots/** 的基线一起挡掉(那批必须入库)。
|
||||
docs/acceptance/2026-10-21-full-qa/screenshots/
|
||||
docs/acceptance/2026-10-21-full-qa/contact-sheets/
|
||||
docs/acceptance/2026-10-21-full-qa/prod-compare/
|
||||
docs/acceptance/2026-10-24-full-qa/sweep/screenshots/
|
||||
docs/acceptance/2026-10-24-full-qa/sweep-after-fix/screenshots/
|
||||
docs/acceptance/2026-10-24-full-qa/contact-sheets/
|
||||
docs/acceptance/2026-10-24-full-qa/prod-readonly/
|
||||
# 2026-10-24 修复轮的**逐页取证截图**(v3 页修复前后、admin 390 档、指标裁切等 13 张 1.4MB)。
|
||||
# 同一条规则:文字与 JSON 读数(defects.json / coverage-matrix.md / tools/*.mjs / 各 probe.json)入库,
|
||||
# 只挡像素。注意这里的 .json 是同目录里 probe 的**读数**,必须留在库里,不能按扩展名一刀切。
|
||||
docs/acceptance/2026-10-24-full-qa/visual/*.png
|
||||
# Gitea 品牌化线的验收产物:4 张截图 + README + 探针脚本。整目录归 `feature/gitea-branding`
|
||||
# (逐文件 sha256 与该分支一致,见 qa-tracker §18.7),本分支不提交,故整目录忽略以免污染 git status。
|
||||
# 注意:忽略不等于删除 —— 文件仍在工作树里,切到那条分支时它们由该分支自己的提交负责。
|
||||
docs/acceptance/2026-10-22-gitea-branding/
|
||||
# Gitea 品牌化线的实现文件(44 个)。逐文件 sha256 与 `feature/gitea-branding` 上已提交版本
|
||||
# **完全一致**(qa-tracker §18.7 实测 50/50),本分支不提交以免同一批文件出现两份历史。
|
||||
# 规则对**已跟踪**文件无效,所以切到那条分支时这些文件照常由该分支的提交管理。
|
||||
infra/cicd/gitea/
|
||||
infra/cicd/gitea-custom/
|
||||
|
||||
# 首页主图备选素材(ImageGen 草图,本机产物,不入库)
|
||||
# 用途记录在 deliverables/logo-redesign-2026-10-13/quan.py:277 的「形研究来源」注释里;
|
||||
# 站内实际引用的图在 public/images/,这里只是生成过程中的中间件。
|
||||
vibe_images/
|
||||
|
||||
# DeepSeek Harness 的运行期 job 日志(每次会话数千个小文件),非项目产物
|
||||
.pi-dsh/
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"*.{js,jsx,ts,tsx}": [
|
||||
"!(public)/**/*.{js,jsx,ts,tsx}": [
|
||||
"eslint --fix"
|
||||
]
|
||||
}
|
||||
@@ -53,6 +53,7 @@ npm run test:functional # 仅功能 project(chromium / chromium-mobile
|
||||
npm run test:e2e # Same as test:functional
|
||||
npm run test:smoke # Only @smoke-tagged tests
|
||||
npm run test:e2e:prod # @smoke+@critical+@journey 打构建产物(E2E_TARGET=production → node dist/standalone/server.js,CI 门禁)
|
||||
npm run test:e2e:write-db # 写库型 11 例(cms-workflow 3 + user-journey 8):目标库是 /tmp 一次性 SQLite,prisma/dev.db 全程不被写
|
||||
npm run test:visual # Visual regression (Desktop Chrome)
|
||||
npm run test:visual:all # Visual regression (all projects)
|
||||
npm run test:visual:update # Update visual snapshots
|
||||
@@ -95,7 +96,7 @@ npm run check:axe # 双引擎(chromium/firefox)×双主题(light/da
|
||||
# docs/acceptance/2026-09-21-axe/axe-evidence.json。需一个生产服务在 :3100:
|
||||
# PORT=3100 HOSTNAME=127.0.0.1 node dist/standalone/server.js(先拷 dist/static 与 public,见上文)
|
||||
# CI 侧由 Jenkinsfile「♿♿ 全站 axe 节点计数」阶段(仅 main)自动串起
|
||||
npm run test:all # type-check + lint + test:coverage + test:integration:real + check:a11y + test:e2e:fast + test:security:headers
|
||||
npm run test:all # type-check + check:package-keys + type-check:e2e + lint + test:coverage + test:integration:real + check:a11y + check:visual + test:e2e:fast + test:security:headers
|
||||
npm run test:e2e:prod # E2E_TARGET=production(构建产物目标);harness **不代跑构建**,须先 `npm run build`
|
||||
# (standalone 根目录的 dist/static + public 由 postbuild 自动装配,见上文)
|
||||
npm run lighthouse # Lighthouse CI(配置 config/test/lighthouserc.json;axe critical/serious 逐条 minScore:1;inspector-issues 亦判红——CSP/弃用类问题只走 DevTools issue 通道,errors-in-console 与 0.9 分类阈值都看不见它;报告落 lighthouse-reports/)
|
||||
|
||||
+85
-1
@@ -84,6 +84,29 @@ Switch / Slider 的白底圆钮。
|
||||
|
||||
决策状态:✅ 2026-06-29 确认
|
||||
|
||||
#### ~~例外:首屏 3D 场景分镜~~ [已撤回]
|
||||
|
||||
**2026-12-02 晚撤回**:该例外唯一的作用对象(`src/components/home/hero-scene.tsx`,机房分镜)
|
||||
已整体退役,理由是**题材不成立**,不是实现有缺陷:
|
||||
|
||||
- 机房语义是「数据的存放地」,而首屏要讲的是「数据如何变成判断」—— 画面里从来没有
|
||||
「选项 / 判据 / 结论」这些对象,任何光效最多表达「设备在运行」;
|
||||
- 换成「抽象数据场」后,三拍仍是分镜式编排,但**例外条款本身不再需要**:
|
||||
它当初是为了给「循环」开一档窄口子,而新的三拍节奏(43.26s)由具体实现自行满足
|
||||
①–④,没有再走例外。
|
||||
|
||||
随之撤回的还有:`check:grammar` 的 **R26**(其唯一判据就是解析该文件的 `ms:` 与 `DIP_MS`)、
|
||||
海报帧 `hero-scene-poster.webp`、CC0 资产 `server-rack.glb`,以及 R22 登记表里的对应条目
|
||||
(登记表因此归零 —— 首屏回到**零视觉层**)。
|
||||
|
||||
⚠ **对新场景的约束已随落地重建(2026-12-02 晚)**:抽象数据场已进
|
||||
`src/components/home/hero-field.tsx`(flag `NEXT_PUBLIC_HERO_FIELD` 样期,默认关),
|
||||
R26 **已重建并指向新组件**(判据同前:周期上限 / reduced-motion 定格 / 离屏停 / 禁自转)。
|
||||
海报帧 `hero-field-poster.webp` 由 `scripts/capture-hero-field-poster.mjs` 生成(登记于 asset-provenance §6)。
|
||||
R22 登记表从归零恢复为一条(marker `HeroField`)。flag 关 ⇒ 首屏仍是 E 案,基线零影响。
|
||||
|
||||
决策状态:❌ 2026-12-02 撤回(ADR-0016 §12 撤回段)
|
||||
|
||||
### 服务编号+色条编码(Service Number + Color Bar)
|
||||
服务模块的区分方式,取代纯颜色编码:
|
||||
- **主要区分**:大号数字编号(01、02、03...)
|
||||
@@ -145,6 +168,44 @@ Novalon 的 6 个核心产品,互为互补关系,常以组合形式出现在
|
||||
### Design Tokens
|
||||
`.impeccable.md` 中定义的设计令牌系统,包含颜色、排版、间距、卡片系统、Section 背景交替规则。当前状态:**文档已定义,代码中 globals.css 有对应 CSS 变量,但组件层未完全落地**。
|
||||
|
||||
### 签名件 (Signature Parts) · 2026-11-03
|
||||
|
||||
⚠ **2026-11-24 更正**:原写「逐字移植」,实现层只对**路径数据**成立,viewBox 是重新推导的
|
||||
(原物是两份独立 `<img>` 各自定位,本仓用一份 SVG 内两枚 `<path>` + `transform` 表达偏移,
|
||||
故包围盒必须含偏移量:right 实测 `150.08×145` vs 声称 `112×145`;down `23.938×29.48` vs `23.938×22`)。
|
||||
现登记为「**同构再造**」——几何真源与 0.34 偏移比仍是实测值,但不可按字面逐字比对。
|
||||
`check:grammar` R18 只查「有没有第二份手抄」,查不出「第一份的包围盒与自己声称的不同」。
|
||||
详见 ADR-0009 的更正表。
|
||||
|
||||
四件几何全部走 `src/components/ui/` 下的真源组件,
|
||||
营销页手抄第二份由 `check:grammar` **R18** 判红(上限 0):
|
||||
|
||||
- **斜线纹 (Hatch)**:20×20 tile、`rotate(140deg)`、1px。CSS 等价形的垂距是 **12.86px**
|
||||
(= 20 × sin140°),照抄 20px 会稀掉一半。只允许出现在黑底/ink 底纹理与**接缝**处。
|
||||
- **双 V (Double Chevron)**:**两枚不同的形**(向下 / 向右),第二枚按实测 **0.34** 的比例错位。
|
||||
不是一枚旋转,也不做动画(原物的 6s infinite 脉冲与「禁循环装饰动画」冲突)。
|
||||
- **斜杠 (Slash)**:18×17 平行四边形,用于 `01 / 04` 计数器与 `›` 前导符。
|
||||
- **空白带 (Band Spacer)**:`--spacer-band` = `6.6667rem`,对标两条独立 120px 空模块的节奏件。
|
||||
⚠ 2026-11-24 更正:原值 `7.5rem` 的注释称「16px 根字号下 = 120px」,但本仓 ≥1024px 的根字号是 **18px** ⇒ 实测 135px,比对标的 120px 大 12.5%,空白带就此失去可比性。现取 `20/3 rem`:×18px = 120px(桌面对比口径)。机器判据 `src/components/ui/band-spacer.test.tsx`(读 globals.css、按 18px 复算,±1px)。
|
||||
|
||||
### 接缝 (Seam) · 2026-11-03
|
||||
白底与黑带的交界处压一块斜线纹(上半压白、下半压黑)。对标用**纹理**代替渐变过渡,
|
||||
它是「黑带从哪里开始」的唯一视觉信号。
|
||||
|
||||
### 编辑舞台 (Story Stage) · 2026-11-03
|
||||
`4 × 100vh` + `sticky h-screen` 的滚动驱动舞台,4 屏共用一块黑底,切换只由滚动进度决定。
|
||||
服务端首帧恒为 `flow`(纵向堆叠、全可见),仅在桌面且未开启「减少动效」时切 `pinned` ——
|
||||
这条不是优化,是 2026-10-20 白屏那轮的硬约束(首帧必须与 SSR 一致)。
|
||||
|
||||
### 字重分裂声明 (Weight-Split Statement) · 2026-11-03
|
||||
同字号、同色,只换字重(实测 64/700 下一行 64/400)。层级来自 **字号 × 字重** 两个独立轴,
|
||||
而不是「更粗」这一个轴 —— 所以 `font-extrabold`(800)在营销面由 **R19** 判红。
|
||||
|
||||
### 结构件列表 (.list-plain) · 2026-11-03
|
||||
正文列表有品牌红菱形项目符号与 `--color-text-secondary` 字色。导航行 / 标签行 / 序号列 /
|
||||
指标行是**结构**不是正文,必须用 `.list-plain` 摘掉这两层「文气」,否则黑底上的 `01/04` 会变灰、
|
||||
一屏红菱形会花光「红面积 ≤10%」的额度。
|
||||
|
||||
## 关键决策
|
||||
|
||||
| 术语 | 含义 | 决策状态 |
|
||||
@@ -222,7 +283,30 @@ Novalon 的 6 个核心产品,互为互补关系,常以组合形式出现在
|
||||
| 动效时长判据按用途 | 红线只管**入场**;令牌声明不携带用途 ⇒ 判红发生在消费点(非 infinite 且 >700ms) | ✅ DEC-N3(`--transition-gentle` 实测零消费) |
|
||||
| 案例发布门槛 | 授权 + ≥1 个 `basis===verified` + 禁词扫描,三处共用(成果槽 / CaseStudies / detail-trust) | ✅ DEC-N4;⚠ CMS `caseStudies` schema 尚无这两个字段,业务出案例前须先扩 schema |
|
||||
| e2e / scripts 静态口径 | `e2e/**` 不在根 tsconfig 内(须 `type-check:e2e`);`scripts/**/*.mjs` 同理,只有真跑才暴露 | ✅ DEC-N6 |
|
||||
|
||||
| **首屏构图:拼贴,不是居中声明** | ADR-0009 原记录「首屏 = 全幅影像 + 居中声明 100/700」取自 `opacity:0` 的视频轮播层(只在 ~13s 淡入 0.8s),**已推翻**。真正常驻的是拼贴:全幅影像 + 黑底文字块(内嵌 40/700 短句)+ 双 V + 第二张照片错位。本仓按此重做首屏,并用**既有素材**(`hero-architecture` + `industry-manufacturing`)承担构图 —— 对标那半信息量来自人物照,本仓禁人物入镜(零编造 + 肖像授权),题材换建筑/工业、语法不变。title 字阶随之从 90px 降到桌面 44px(100/700 是过渡帧字号)。**判据补丁**:任何「抄对标某个视觉参数」的读数必须同时记录该元素静止态是否可见(`opacity>0` 且沿祖先链累积) | ⚠ 2026-12-01 **部分作废**:拼贴骨骼保留、**影像层已整批撤除**(见本节末行);原判 ✅ 2026-11-24(ADR-0009「更正一」、`docs/lessons-learned.md` §5.53)|
|
||||
| **首屏不强调初创身份**(推翻同日早先的「诚实信号前置」裁定) | 用户明确裁定:**首屏不强调首批共创、初创身份与成立时间**。落地:eyebrow 改为纯领域定位 `企业数字化转型`(CMS `hero-banner.eyebrow` → 兜底 `HERO_EYEBROW`);副标题去成立时间,`canonicalHeroSubheading` 消毒 CMS 历史快照后回落 `COMPANY_INFO.description`。**撤下的只是「首屏」这个位置**:`EARLY_ACCESS` / `foundedFull` 在案例页空态、L3 替代信号等需要如实说明处继续使用。判据 `home-content-v17.test.tsx`(负对照:关掉消毒器即转红) | ✅ 2026-11-24(用户裁定,覆盖同日早先条目;ADR-0009「更正一」第 3 条已改为作废态)|
|
||||
| **裸 alpha 必须落在 opacity scale 内** | `bg-bg-primary/98`、`bg-[#0B0A08]/92` 这类 scale 外的裸数字 alpha 被 Tailwind **静默丢弃**:class 在源码里,computed 是 `rgba(0,0,0,0)`,type-check / lint / build / 单测四道全绿也拦不住。门禁 = `check:grammar` **R20**(全 `src`,上限 0 硬禁,任意值 `/[0.92]` 豁免,三向自证 + 真实树负对照)。该闸上线当天即抓到第二处同类失误 | ✅ 2026-11-24(`docs/lessons-learned.md` §5.54、`docs/development/quality-gates.md` §5)|
|
||||
| **内页证据密度优先于铺签名件**(Batch 2) | 用户裁定「Batch 2 = 内页证据密度」,并在方案三种走法里选了「派生式扩写」。核心判断:签名件解决「像不像」,缺证据解决「有没有用」,后者优先。① **正文只从既有真源派生**(METHODOLOGY 四阶段 / SERVICES 四组 / PRODUCTS 六款 / commitments 响应承诺),零新增客户案例、零新增效果数字;② 详情页正文改「小标题 + 段落」结构(`src/lib/news-article.ts`),判据 = 单行 + ≤20 字 + 不以句末标点收尾三条(误判成标题比漏判更糟);③ 详情页末尾必须有站内公开入口,且 href 由单测反查 products/services 常量 + 文件系统 `page.tsx` 存在性,**不接受手写一条不存在的路由**;④ 阅读时长由字数实时算(450 字/分钟),不手写;⑤ **不新增 `/insights/[slug]`** —— 聚合页只能「读」不能「拥有」别的模型的实体(`navigation.ts` 不变式),把归属地写在卡片上而不是复制一份内容。判据:`news-article.test.ts` 11 例 + `news-detail-content-v3.test.tsx` 4 例(负对照各已做)+ e2e UJ-04/UJ-10 三条新断言(负对照:注回整块渲染后 UJ-04 转红) | ✅ 2026-11-25(用户裁定 + 实现与门禁落地;基线重采 5 张,只读复跑 130/0)|
|
||||
| **压在图片上的半透明文字须逐像素量对比度** | axe 对「文字压在图片/渐变上」只出 **incomplete**(不计违规);`check:contrast` 只断令牌配对,而此处底色是图 + 半透明层,令牌表里没有这一对。⇒ 只能在浏览器里量:文字置 `visibility:hidden` 截图、取文字盒内**最亮**像素、按 `color` 的实际 alpha 合成后再算 WCAG。**必须同时隐藏固定外壳**(页头/TabBar/cookie 条),否则会读出假红。实测首屏移动档 `text-white/70` 仅 **2.44:1**(AA 需 4.5),修后 9 视口 × 54 文字盒最低 5.84:1 | ✅ 2026-11-24(`docs/lessons-learned.md` §5.55)|
|
||||
| **「已修」是关于动作的陈述,不是关于代码状态的陈述** | 2026-10-24 修复轮的 `FIXES.md` 通篇「已修 + GREEN 读数」,但四项 P2 缺陷一个月后全部还开着 —— 改动躺在 `stash@{0}` 从未 apply,两个「新建」的源文件在树里却零调用点。**引用上一轮「已修」前必须给现取的 `grep`/`git diff` 读数**,不能引用结论句;`git stash list` 是必看的状态位(它不在 `git status` 也不在任何门禁里)。最有辨识度的判据:`check:dead` 报「某文件仅测试引用」时,第二个读法是**「它是一次没落地的修复」** | ✅ 2026-11-25(`docs/lessons-learned.md` §5.61,qa-tracker §18.1)|
|
||||
| **「class 在源码里」的第三族死样式:类名从未定义** | R20 管的是 Tailwind 因 alpha 超 scale 而静默不生成;**R21 管的是这个名字根本没人定义** —— `container-wide` 在 6 个文件里用了两年,`globals.css` 里从来没有 `.container-wide`,于是 privacy/terms/not-found/error/SkeletonHero/standalone 详情的内容全部贴左边缘。type-check / lint / build / 单测 / axe 五道全绿都看不见它。判据刻意收窄到本仓 `@layer utilities` 手工定义的族(container-/section-/bain-/editorial-/signature-)+ 精确名 `list-plain`:**不能按 `list-` 前缀收**(Tailwind 原生 `list-none`/`list-disc`/`list-inside` 会全被误判),`prose*` 属未安装的 typography 插件族故登记为已知缺口而非进闸(闸一上线就恒红只会逼人把闸调瞎) | ✅ 2026-11-25(`docs/lessons-learned.md` §5.62,`check:grammar` R21)|
|
||||
| **「有基线」不等于「有保障」** | 95 张全页基线(139MB)在磁盘上、在版本库里,但 `VISUAL_TEST_PAGES` 里没有对应用例 ⇒ 一个字节的守卫都没有,且**全部过期**。门禁盲区在于:`--update-snapshots=none` 不会去点没有用例的文件,所以「有基线没用例」不在任何判据里。补法 = 把路由接回列表 + 按预测数重采(§5.58 判据),而不是删掉资产 | ✅ 2026-11-25(`docs/lessons-learned.md` §5.63,覆盖 16→34 页,170/0)|
|
||||
| **大块验收产物入库按目录点名,不按扩展名一刀切** | 77MB/95MB 的验收目录里绝大多数是逐页截图。`.gitignore` 里写 `*.webp` 会连带挡掉 `e2e/visual-snapshots/**` 的基线(那是视觉回归唯一参照),而 gitignore **静默生效**,下一轮没人会发现基线没提交。判据:**「这条结论怎么来的」必须入库**(README/FIXES/defects.json/summary/axe/脚本),**「排查当时的截图」只服务当时**。按目录点名后 172MB → 8.2MB | ✅ 2026-11-25(`docs/lessons-learned.md` §5.64)|
|
||||
| **seed 的默认值是「补缺」,不是「覆盖」** | `seedItems()` 原本一律 `upsert` 全字段覆盖、案例还无条件 `deleteMany` ⇒「跑一次 seed」等于「把 CMS 里改过的文案冲掉」(§5.60 的真实事故)。2026-11-25 反转默认值:已存在的同 slug 行**跳过**并计入汇总(全跳过时日志明写「未写任何一行」),只有显式 `--force` 才覆盖/删除,未知参数直接中止。判据只认「行是否存在 + 是否 --force」,**不**做内容指纹/`updatedAt` 比对(那会造第二个真相源)。`src/lib/seed-write-policy.ts` + 14 例单测 | ✅ 2026-11-25(OPEN-08 关闭) |
|
||||
| **`.prose` 是零特异性默认值层,不是覆盖层** | privacy/terms 写了两年 `prose prose-lg`,而仓里**没装** `@tailwindcss/typography` ⇒ 这两个类从未生成过任何规则(§18.6-1)。手写一份 `.prose`(ADR-0010),**整层裹 `:where()`**:库里已存的法律页 HTML 自带 `text-2xl font-bold text-[var(--color-text-primary)]` 这类 inline utility,层若按 `.prose p`(0,1,1) 写就会盖掉它们 —— 实测把 `/terms` 呼出块标签染灰 329px、日期行高 1.65→1.85 共 1222px。行高与节奏**刻意不收进层**(留标记上,逐段不同)。判据:`src/app/__tests__/prose-layer.test.ts`(11 例,含「层内不许裸选择器」反方向守卫)+ `/privacy` `/terms` × 5 project 视觉零差异 | ✅ 2026-11-25(OPEN-09 关闭) |
|
||||
| **自证闸的夹具必须从真源派生,不能手写第二份路径** | `check:accents:selftest` 在 HEAD 上恒红 8/10,`check:visual` 因此整段失效。真因不是判据:夹具 `B_PROPAGATION` 写死了 `detail-hero.tsx`,而该组件 2026-11-03 已改名 `detail-page-hero.tsx`——**豁免表改了、夹具没改**,于是每个情景多一条「新增透传点」+ 一条「豁免腐化」。修法不是改路径(只是把同一个错推迟到下次改名),而是从 `ALLOWLIST_INLINE_COLOR` 派生夹具。裁定:**恒红的自证闸比没有自证闸更坏**——它让人把整段当噪声跳过,连带后面的真判据一起失去判定力,故「pre-existing 红」按 P0 修,不许只登记 | ✅ 2026-11-26(OPEN-15 关闭,`docs/lessons-learned.md` §5.68)|
|
||||
| **改了默认值,必须同时改所有断言它的地方——e2e 与单测是两套断言** | DEF-09 把 GA `analytics_storage` 默认从 `granted` 改成 `denied`(opt-in),实现与单测都改了,`e2e/ga4-event-tracking.spec.ts` 仍断言 `granted`。它能藏住是因为那 4 个 `@critical` GA4 用例**只在 `test:e2e:prod` 下真正执行**(dev 下 `test.skip`)⇒「本地全绿」看不见。修法不是改成 `denied` 就完,而是**同时钉两件事**:default 是 `denied`、已存偏好由 `consent update` 在 `config` 之前放行;只改前者会让「偏好回放坏了」变成新盲区 | ✅ 2026-11-26(`docs/lessons-learned.md` §5.69)|
|
||||
| **写库 E2E 走一次性临时库,不写 `dev.db`** | 11 例写库用例(`cms-workflow` 3 + `user-journey` 8)此前一直「未授权」,因为默认 harness 的库是本地开发与其它门禁的共享状态。现在 `npm run test:e2e:write-db` 用 `scripts/e2e/serve-temp-db.sh`:`/tmp` 建库 → `migrate deploy` → seed → 路由预热 → `next dev -p 3101`,跑完即弃。三条踩坑(cookie domain 字面量 `localhost` / revalidate 密钥要同一来源 / dev 懒编译需预热)见 lessons §5.66。判据:11 passed / 0 failed / EXIT=0,且 `prisma/dev.db` 的 inode+size+mtime 跑前跑后不变 | ✅ 2026-11-25(AUTH-D4 = OPEN-07 关闭) |
|
||||
| **首屏影像按四类资产准入,第三方地标及其剪影/单色变体一律禁用** | 原 `DESIGN.md:120` 只放行「本地生成」的氛围图 ⇒ **实景照与矢量重绘都在规则之外**,此时换图会四道门禁同时放行一个越界变更(R16 只扫类名+内联、看不见位图像素;R12 只对账比例数字、不读图片文件;「面积 ≤10%」全程无门禁)。ADR-0011 定四分类:A 本地生成 / B 自有矢量重绘(须声明「不参考具体建筑造型」)/ C 实景照(须台账登记授权)/ **D 第三方地标及其剪影·单色·去字变体硬禁**。`OPEN-01` 的资产路线随之从「生成 ~10 张照片」改判为「1 件 B 类原语 + 6 组参数」——实测 `public/images/hub/` 是空目录、六个 hub 组件 `<Image` 命中数为 0,缺口是「一处图都没有」而不是「图不够好」。判据:`docs/adr/0011` + `docs/design/asset-provenance.md` 台账 + 换图验收五步 | ⚠ 2026-12-01 **部分作废**:四分类本身仍有效,但「A 类允许进首屏引言区」条款已废(见本节末行);原判 ✅ 2026-11-26(ADR-0011,`OPEN-01` 阻塞理由改写) |
|
||||
| **导航签名拆两半:做内缩白浮条,不做滚动收方汉堡** | 页头从「全宽 fixed 贴顶条」改为**内缩白浮条**(`top: 48px` / 高 `64px`,左右对齐 `container-x`)。值一律走 **px 令牌**(`--header-inset-top` / `--header-height`),不用 rem 档——根字号随断点 `16/17/18px` 漂移,`top-12` 实测会变成 48/51/54 三个值。外壳保持 `top-0` 不画底色,营销内容让位 112px;删除随滚动的 80→64 高度动画。**02b(滚动 >80 收成左上白方汉堡)不做**:会让 `nav-dropdown` 4 例与 `nav-keyboard` 6 例两条可达性契约失效(前者守桌面 hover 一级导航,后者守无指针设备可达性);翻转需 ADR-0012 §6 四条同时满足。判据:`chrome-persistence` 断言内缩层 `paddingTop === 48px`、浮条 `rect.top === 48` / `height === 64`(滚动前后一致);195 张基线重采后独立只读复跑 225 passed / 0 failed | ✅ 2026-11-27(ADR-0012,`OPEN-02a` 关闭 / 02b 判不做)|
|
||||
| **语法棘轮分批清零:只做批 1+2,批 3 保留棘轮** | 54 处存量不做「一次性清零」:**批 1** 删除 3 个零渲染点组件(`detail/service-value` / `solution-value` / `micro-interactions`)并从 `detail/index.ts` 移除导出(21 处、零基线);**批 2** 清 `/about/brand` 18 处(5 张基线);**批 3** 详情件 + 4 个 hub 列表 + 首页共 15 处跨 19 个受守卫页面,需 95 张基线 + 逐页归因,**保留棘轮**,随模板批再做。上限同批下调为 `R13 3 · R14 5 · R15 1 · R16 5 · R17 1`;棘轮仍有牙(新增一处即判红)。`R16` 清零前须先裁「红不做面」的替代色 | ✅ 2026-11-26(ADR-0013;`OPEN-05a` 关闭 / 05b 判保留)|
|
||||
| **死码判据是符号级可达性,不是「被 barrel 导出过」** | `dead-modules.mjs` 原把 `export { X } from './x'` 当成引用边 ⇒ barrel 把 3 个零渲染点组件伪装成「有引用」。现改为:任何含 `export … from` 的模块按**桶**处理(不只 `index.ts`——`src/lib/constants.ts` 就是具名再导出门面);桶的再导出边**不再无条件传播**,消费者按名 import 时才解析到落点文件;`export *` / `import * as` / 副作用导入按保守方向算活(宁可漏判,不可误删)。解析前须**剥离注释**(字符串感知):`constants.ts` 注释里的示例导入曾让 `export { … } from` 正则提前收口、真语句漏匹配。判据:`scripts/dead-modules.selftest.mjs` 6 情景双向(桶再导出判死 / 按名经桶判活 / 直接导入判活 / `export *` 判活 / namespace 判活 / 门面→子桶链 + 注释伪导入);`check:dead` = 自证 + 报告两段。真树随之浮出 5 个 barrel-only 模块,处置见 `OPEN-18` | ✅ 2026-11-28(`OPEN-16` 关闭)|
|
||||
| **营销面影像整批退役:正文改内容图、首屏纯排版** | 四次否决(矢量条 / 混凝土 / 技术静物 / 首页底图)指向同一件事:**照片不承担语义**——本仓没有真实项目摄影,替代品只能是装饰,而「实施流程 / 企业套装 / 解决方案」说的是关系与阶段。撤除 `hub/**` 4 张、`body/**` 14 张、`home/hero-architecture` 1 张,以及 `ui/hero-plate.tsx`、`ui/editorial-figure.tsx` 两个组件。正文改 `StageIndex`(序号脊线,数据取 `process` / `solutions`)与 `BandIndex`(满幅文字索引带,取方案 / 新闻条目);17 个营销首屏退为纯排版。判据同时掉头:**R22** 由「必须有影像」改为「零影像即判红」(分母 16→17,首页并入且只扫首屏区块),**R23** 改按载体标记判型(分母 9→5,`/cases` 零数据不进表)。⚠ 首屏「排版支点」没有机器判据,只能由视觉基线 + 人工评审兜 | ✅ 2026-12-01(ADR-0011 §8.5 / §8.6;台账 `public/images/LEDGER.md`)|
|
||||
| **首页首屏右栏:双 V 滚动提示 + 工程网格,持久态底部锚定不转译** | 影像退役后右 4 栏成纯虚空(8 栏骨架是全幅影像时代遗留)。实测保时捷持久态同样 66% 靠左(`c-collageOverlay__textbox` col 1/5),右侧靠视频 + 错位副图 + 双V scroller 兜底;其「居中声明」只是 2–14.3s 开场过场。零影像转译只取第三件:右栏 `DoubleChevron(down)` `text-white/40` **静态**(对标 6s 循环脉冲被禁)+ 复用 `hero-grid-overlay--dark`;移动/md 档 hidden。红不出 eyebrow+主 CTA。**底部对齐 + 贴左缘实块裁定不转译**:其为「错位副图从下方升起」服务,无副图时沉底即失衡 | ✅ 2026-12-02(E 案;台账 §28;attribution `docs/acceptance/2026-12-02-baselines/`)|
|
||||
| **首页首屏全幅 3D 场景(数据中心走廊,三镜头分镜)** | 用户裁定「做成保时捷那样一组多场景动画」⇒ 首屏改全幅 three.js 场景:S1 走廊纵深 16s / S2 俯视阵列 13s / S3 柜排斜看 13s,镜头间压黑 420ms,一轮 43.26s。E 案退役为**降级层与移动档正选**。三条不改的约束:reduced-motion 定格、<1024px 不跑 WebGL、WebGL 失败静默回落。资产调研结论:高保真机房资产均为 UE/Unity 工程(Fab《Data Center》仅 UE 5.6–5.7),能直接进 three.js 的最高精度是单柜级(EntropyNine 27.8k 面 GLB,CC BY 4.0,需署名),走廊靠实例化拼 | ✅ 2026-12-02(ADR-0016 §1–§12;台账 §31;证据 `docs/acceptance/2026-12-02-hero-scene/`)。同日 **R22 改「视觉层登记制」**(载体白名单 + 海报存在性 + 表过期)、**R26 新增「场景契约」**(周期/定格/离屏停/禁自转)。U5 落地:轮换的是**场景角标**(不改 h1),真源 `lib/constants/hero-scenes.ts`,切镜事件 `hero-scene:shot` |
|
||||
| **产品独立站化:每条产品线一个独立 landing 站,官网退为入口层** | 用户裁定 ERP 等产品最终都像睿视 NovaVis 一样做独立站。模式四要素(ADR-0014 §2):纯静态零 CDN / 独立子域 `{product}.p.novalon.cn` / 官网导航 = 外链 + 状态徽标(badge 状态机与独立站上线事实强制同步)/ landing 四道门禁 + 生产 CSP 实测(零内联脚本硬约束)。官网镜像 `public/{product}/` 原样拷贝不承担演进;**第二等产品镜像起必须子目录化 + rewrites 前缀映射并回溯睿视**(睿视按源站形态暂占 `/css` `/js` `/assets` 根命名空间)。阶段:睿视 Phase 0 ✅ → ERP Phase 1 → BI/CRM Phase 2 → 其余 Phase 3,入口判据 = 产品事实可验证,非时间表 | ✅ 2026-12-02(ADR-0014;睿视镜像 commit `901e1025`,与源站 novavis.p.novalon.cn 逐字段一致)|
|
||||
| **02b 翻转:桌面端滚动收成白方汉堡 + 左侧抽屉;键盘契约方向改为「正文位置 Shift+Tab 向上」** | 用户裁定翻转 ADR-0012 的「02b 不做」。规格(ADR-0015 §3):`scrollY>20`(仅 `md+`)浮条收窄成 64×64 方块(`md:w-[var(--header-height)]`,**px 令牌**——`w-16` 在 ≥1024 根字号 18px 下漂到 72px)、内联导航/CTA **卸载**(不留焦点幽灵站)、logo `md:hidden`(CSS 级隐藏,明暗双版恒挂载契约不破);抽屉左侧滑入 250ms,`DrawerNavList` 与移动抽屉**同源渲染**完整双轴 + ThemeToggle + CTA。连带修掉一个真缺陷:**带 scroll restoration 的整页刷新不触发 scroll 事件**,页头在滚动位仍显示顶部态——挂载时补一拍同步(`header.tsx` `didMountRef` effect,单测钉住)。⚠ 键盘契约方向的教训:从 body 正向 Tab 的第一站是顶部跳转链接,浏览器为显焦把页面滚回页首、收起态**正确地**撤销——「Tab 到汉堡」在收起态不是可达语义,契约改写为「正文位置 8 次 Shift+Tab 内到达」(页首态正向 Tab 契约原样保留)。判据:`data-header-collapsed` + 浮条 border-box 64×64 + 内联导航 count 0;原 nav-dropdown/nav-keyboard 断言一字未改;移动端 5 spec 69 passed / 7 skipped;基线预测 0 张重采 | ✅ 2026-12-02(ADR-0015;`OPEN-02b` 关闭)|
|
||||
| **「红不做面」替代色 = 中性面留红点缀;语法棘轮批 3 清零、R13–R17 上限归 0** | ADR-0013 §6 三翻转条件满足后清零批 3 存量 15 处(detail 件 10 + hub 箭头 3 + erp-upgrade 卡片 2)。R16 替代色用户裁定 A 方案:红底面(`bg-brand-soft`/30、`/80`)→ 中性面(`bg-bg-elevated` / `bg-bg-primary/80`),红色降级为 `text-brand-ink` 文字/图标点缀——与 L3 卡片主体、批 2「去面留点」、保时捷「红只点缀」语法一致。归因教训:**11-26 的「95 张/19 页」基线成本口径是静态估算**——R14 两处是 hover 态改动静态零漂移、`l3-signals-slot` 所在首页实际渲染 L3 空态兜底 ⇒ 实写仅 35 张(erp-upgrade-v3 ×5 + services ×12 + solutions ×18,预测==git status)。判据:`check:grammar` 25/25 · R13–R17 实测 0 / 上限 0(棘轮转硬禁)· selftest 双向 · jest 161/1899 · 独立只读复跑 225/0 | ✅ 2026-12-02(ADR-0013 §8;`OPEN-05b` 关闭;attribution `docs/acceptance/2026-12-02-grammar-batch3/`)|
|
||||
#### 门禁断言的有效性口径(chain6/chain7 新增)
|
||||
|
||||
验收期间发现 `config/test/lighthouserc.json` 有 3 条 `warn` 级断言(`autocomplete-valid` / `presentation-role-conflict` / `svg-img-alt`)**在 Lighthouse 里根本没有对应审计项**:把 chain6 全部 21 份报告的 `audits` 键取并集(175 个 id)比对 62 个非 `categories:` 断言键,只有这 3 条缺席;`@lhci/cli@0.15.1` 用的是它自带的 `lighthouse@12.6.1`(不是顶层的 13.4.1),其 `core/audits/accessibility/` 64 个审计文件里没有这三个。它们每轮稳定打印 `"…" is not a known audit. found: 0`,因为是 warn 级永不判红 —— 于是"57 项 a11y 断言全过"里混进了 3 项什么都没测的条目。
|
||||
|
||||
@@ -117,7 +117,20 @@ Novalon 的界面是一份可以逐条审计的经营宣言。它模仿顶级咨
|
||||
|
||||
第二支柱是「诚实语法」:不虚构案例、不伪造数据。未发布的内容明说「内测中 / 首批共创 / 敬请期待」,每个数字带来源角注。这份克制本身被当作差异化资产,视觉系统配合它:宁可有大面积留白与「暂未发布」,不放一张假图、一句空话。
|
||||
|
||||
**氛围图边界(2026-10-20 补充)**:首页允许使用本地生成的建筑/工业/桌面氛围图承担构图与情绪,但必须同时满足:画面无人物、无可读文字、无客户或第三方标识、不暗示真实客户现场;图片一律 `aria-hidden`,且不进入任何「客户成果 / 团队现场」证据位。证据位仍只放可点开的真实产物(案例、文档、实测数字)。「零编造」禁止的是把假图当证据,不是禁止装饰性视觉。
|
||||
**氛围图边界(2026-10-20 制定,2026-11-26 按 [ADR-0011](docs/adr/0011-hero-imagery-asset-route.md) 扩为四分类)**:
|
||||
|
||||
| 类别 | 准入条件 | 外部授权 | 台账 | 允许落点 |
|
||||
|---|---|---|---|---|
|
||||
| **A 本地生成图片** | 无人物、无可读文字、无客户或第三方标识、不暗示真实客户现场 | 不需要 | 记生成方式与日期 | 氛围位(`aria-hidden`) |
|
||||
| **B 自有矢量重绘** | A 的四条 **+ 声明「不参考任何具体建筑/作品的造型」** | 不需要 | 记 SVG 源文件与作者 | 氛围位 + 构图位 |
|
||||
| **C 实景照片(自有拍摄或已授权)** | A 的四条 + 台账登记来源 / 权利人 / 授权方式 / 期限 | **必须** | **必须** | 证据位优先;用作氛围位须单独立项 |
|
||||
| **D 第三方地标及其剪影/单色/去字变体** | — | — | — | **禁止** |
|
||||
|
||||
任何类别一律 `aria-hidden`,且不进入任何「客户成果 / 团队现场」证据位。证据位仍只放可点开的真实产物(案例、文档、实测数字)。「零编造」禁止的是把假图当证据,不是禁止装饰性视觉。
|
||||
|
||||
**为什么 D 类是硬禁而不是「可讨论」**:剪影不是「更少复制」而是「更纯复制」——它剥掉材质与色彩,只留下受保护的那部分(造型轮廓);地标的朱红还落在品牌红 20° 判定带内(`ADR-0008` 决策五),而 R16 只扫类名与内联样式、**看不见位图像素**。裁定见 ADR-0011 §3.1/§3.2。
|
||||
|
||||
**换图验收五步**(缺任一步 = 「看起来做了」):① 类别与准入对照 → ② 台账登记(`docs/design/asset-provenance.md`)→ ③ 9 视口逐像素对比度量法(`docs/lessons-learned.md` §5.55)→ ④ 基线重采前先归因(§5.57 / §5.58)→ ⑤ `npm run check:grammar` 21 条全绿。
|
||||
|
||||
深色模式不是附属品而是一等公民:主题由 `html[data-theme]` 驱动,仅覆盖 CSS 变量,每个文字令牌附带实测对比度注释(全部达 WCAG AA),品牌红走「底色 / 文字」双通道以保证反色后仍达标。
|
||||
|
||||
@@ -193,6 +206,17 @@ Novalon 的界面是一份可以逐条审计的经营宣言。它模仿顶级咨
|
||||
- Section 背景在 Paper ↔ Mist 间交替,上下以 1px 发线收边;深色/深红区块作为全幅打断。
|
||||
- Hero 四档音量(2026-09-19 layout+distill 定型,critique 复评补第四档;**2026-10-20 首页改版**):**首页** `min-h-[74vh] md:min-h-[80vh]` + 全幅氛围图 + 压在照片上的黑底内容块,全站唯一全幅宣言档;粒子场已移除,改用「照片 + 红条 + 黑底面板 + 右手叠图」的 Porsche 式构图;**hub 目录页**(products/solutions/services)与**叶子详情**(service-detail)为紧凑引言:无 min-h、`py-16 sm:py-20 lg:py-28`、标题封顶 `lg:text-6xl xl:text-7xl`,其下重复的 Hero 数据条已删;**信任页**(about/team)`min-h-[60vh]`、`lg:py-40`、标题封顶 `lg:text-7xl`,保留宣言气场与 CMS 驱动数据条;**独立内容页**(cases `70vh` / news `75vh` / methodology `60vh` / product-detail·solution-detail `80vh`)允许中等音量引言,但**转化页不得用**——/contact 已改紧凑档(无 min-h、`py-16 sm:py-20 lg:py-28`,表单回到首屏视野)。/about/brand 为遗产豁免(90vh,随页面退役一并处理)。
|
||||
|
||||
**接缝与节奏(2026-11-03)**:`.o-module` 式「段内 padding 全 0 + 独立 120px 空模块」只借了
|
||||
后半句 —— 本仓 20+ 段依赖 `py-16 md:py-24`,归零会让全站段距失去定义。所以**只新增** `BandSpacer`,
|
||||
不改段内 padding(偏差记在 ADR-0009)。白↔黑交替处用斜线纹接缝,不用渐变。
|
||||
|
||||
**编辑舞台(Story Stage)**:`4 × 100vh` 外层 + `sticky top-0 h-[100vh]` 内层,滚动进度切 4 屏。
|
||||
服务端首帧恒为 `data-mode="flow"`(4 屏纵向堆叠、全部可见),挂载后仅在
|
||||
`(min-width:768px) and (prefers-reduced-motion:no-preference)` 时切 `pinned`。
|
||||
pinned 下非活动屏 `visibility:hidden` + `aria-hidden`(移出 tab 序)。
|
||||
⚠ 前提:`body` 的 `overflow-x` 必须是 `clip` 而不是 `hidden` —— `hidden` 会把 body 变成
|
||||
非滚动的滚动容器,`position: sticky` 永不吸附(实测 stickyTop 恒等于 `-scrollY`)。
|
||||
|
||||
## Elevation & Depth
|
||||
|
||||
分层靠「几乎看不见的边框 + 真实柔和的阴影」完成:`--color-border-primary` 被刻意软化,卡片默认 `--shadow-sm`/card-shadow 贴地。
|
||||
@@ -227,6 +251,30 @@ Bain 与 Porsche Consulting 抽样元素 `border-radius` 全部为 0,`rounded-
|
||||
`clip-slant` 斜切(Accenture 遗产,仅装饰带使用)。卡片在 1px 淡边框与阴影之间只声明一次
|
||||
elevation(边框为 hairline 级)。
|
||||
|
||||
## 签名件(Signature Parts · 2026-11-03 起)
|
||||
|
||||
四件几何从 Porsche Consulting 首页原物逐字移植(**借语法不借色相**:`#D6001D` 一律换成朱砂
|
||||
`#C41E3A`)。它们是「一眼认出这是对标语法」的全部来源,必须走真源组件,营销页禁止手抄第二份
|
||||
(`check:grammar` **R18** 硬禁,上限 0)。
|
||||
|
||||
| 件 | 真源 | 几何(实测原物) |
|
||||
|---|---|---|
|
||||
| 斜线纹 Hatch | `ui/hatch-field.tsx` + `.hatch-field` | 20×20 tile、`rotate(140deg)`、1px 描边。CSS 等价形:`repeating-linear-gradient(140deg, …)`,垂距 **12.86px**(= 20 × sin140°) |
|
||||
| 双 V DoubleChevron | `ui/double-chevron.tsx` | **两枚不同的形**:向下(23.938×22,第二枚下偏 26/77)与向右(112×145,第二枚右偏 36/106) |
|
||||
| 斜杠 Slash | `ui/slash-mark.tsx` | 18×17 平行四边形(`01 / 04` 与 `›` 前导符) |
|
||||
| 空白带 BandSpacer | `ui/band-spacer.tsx` | `--spacer-band`(7.5rem = 16px 根字号下的 120px)。对标两条独立 120px 空模块 |
|
||||
|
||||
**接缝(Seam)**:白↔黑交界处压一块斜线纹,上半压白、下半压黑 —— 对标用**纹理**代替渐变过渡。
|
||||
这是全站唯一允许的「非按钮红面」,且必须跨在交界上,不能浮在单侧当装饰。
|
||||
|
||||
**面积纪律**:每段 ≤ 1 处、单块 ≤ 640×520、绝不压正文。双 V 与斜杠不算面积(图形,非面)。
|
||||
**双 V 静止**:原物挂着 6s infinite 的引导脉冲,但 `CONTEXT.md:81` 禁循环装饰动画 —— 双 V 本身
|
||||
已经是「还有下文」的信号,不需要动。
|
||||
|
||||
**结构件列表用 `.list-plain`**:globals 的 `ul li::before` 给所有列表加 6×6 品牌红菱形(正文的
|
||||
项目符号)。导航行 / 标签行 / 序号列 / 指标行是**结构**不是正文 —— 一屏重复 6~9 次红菱形会把
|
||||
「红面积 ≤10%」的额度花光,且 `ul, ol` 的 `color: --color-text-secondary` 会让黑底上的 `01/04` 变灰。
|
||||
|
||||
## Components
|
||||
|
||||
### Buttons(CTAButton,全站行动召唤)
|
||||
|
||||
@@ -39,7 +39,16 @@
|
||||
- [x] **数字口径结构强制(2026-09-20,critique P0 收尾)**:共享数字样式渲染的指标(`metrics`/`outcomes`/`dataProofs`)统一携带 `basis: target|team-history|verified`,渲染端自动附口径角注、未声明保守回落 `target`;CMS 新增 `basis` select 录入字段;删除产品详情页「每一项指标都源自真实客户案例」「经实际场景验证」等虚构佐证并补注角注;`metrics-basis.test.ts` 机械校验声明完整性并拦截虚构佐证禁词
|
||||
- [x] **五轮系统性 QA 封版(2026-09-21…28 修复,2026-09-30 封版)**:Q-1…Q-10 / S-1…S-24 共 30 处缺陷修复入库(假登出清服务端令牌、登录 IP 限流、停用令牌 fail-closed 收口、workflow 状态+审计交互式 `$transaction` 原子化、编辑器 richtext 防换行静默损毁、`StaggerReveal` 吞网格类致详情页塌成单列、首页 CMS 数组逐条守卫、about/contact/erp-upgrade 补 ISR=3600 等),每处带判别性 RED→GREEN 测试。跨周期台账 `docs/acceptance/qa-tracker.md`(§9 为现行段落),封版判定书与全部原始门禁输出见 `docs/acceptance/2026-09-30-seal/`。**判定 = 封版通过(含例外清单)**:例外为「待业务口径」(4 条互斥 SLA、erp-upgrade 无 basis 数字)与「待授权项」(写库 E2E 11 例、全量变异、生产 `db:seed`、`check:motion` 23 处)——视觉基线追认已于 2026-10-08 闭合,见下条;均非代码质量问题
|
||||
- [x] **作者侧 agentic 工具化 + 视觉基线闭合(2026-10-08)**:① 选型判定采用 Playwright 1.60 自带 Test Agents(planner/generator/healer,`.claude/agents/*.md` + `.mcp.json`,**未新增依赖、运行期零模型**),淘汰 `tester-army/e2e` 等的判据全表见 `docs/testing/agentic-test-authoring.md`;② 补主导航键盘契约 `e2e/nav-keyboard.spec.ts`(4 例 `@a11y`,dev 10/6、production 10/2、稳定性 24/24,并定性两条引擎/目标差异);③ **AUTH-D3 视觉基线闭合**:写入 38 张(25 新 + 13 覆盖,逐张读图追认)后独立只读复跑 **125/0 / EXIT=0**,取证 `docs/acceptance/2026-10-08-baselines/`;④ 台账 §9 + `docs/lessons-learned.md` §5.33(基线判红须对「采集树 vs 当前树」,本轮内作废了自己一条「运行期漂移」错判)
|
||||
- [x] **对标语法批:Bain / Porsche Consulting 实测驱动的 UI·UE·UX 重构(2026-10-17,tracer-bullet 一批)**:对标取证不是二手描述——Bain 走 archive.org 快照 2026-08-31(1600×846)绕开 Cloudflare、Porsche 取 live 国际站,逐元素 `getComputedStyle` 抽样。实测**证伪了 ADR-0004 的两条视觉判据**(决策四「关键数字 = 超大字号 + 品牌色」:Bain 成果数字实为 40px / 字重 500 / 纯黑;决策一「4px 色条为辅」:两家都不用颜色给内容分类),已在同一笔里改文档。四项裁定与落地见 [ADR-0008](docs/adr/0008-benchmark-grammar-takeover.md):① **借语法不借色相** —— radius 收进 0–4px 记档 + 新增 `--radius-cta: 0`(CTA 由 pill 改直角)、彩色阴影 `--shadow-brand/-brand-hover/-glow` 退役、`.bain-card` hover 去抬升,**`--radius-full` 保持 9999px**(承载 avatar/switch/slider/radio/progress 的功能性真圆,一并归零即方角化后台所有旋钮);② **一级导航改行业 × 能力 + 洞察双轴**,「产品」退出一级(入口降为能力面板里的产品矩阵总览),且把导航真源**从 DB 行反转为代码**(CMS 行须满足 IA 契约才采纳,否则 fail closed —— 实测复现过「一条自洽的旧行」让页脚各列静默变空);③ **信任层走零编造透明路线**:`ResultsSlot` 可判别空态 + `casePublishBlockers()` 反伪造不变量 + L3 替代信号槽,承诺条款收进 `commitments.ts` 单一真源;④ **范围只到首页 + 一条承载详情页**,其余模板待验收。新增三台可失败仪器并常驻门禁:`check:grammar`(R1–R11,含 R2 正向守卫、R9 双向、R10 递减棘轮、R11 僵尸令牌守卫)、`check:accents`(营销面类名通道,豁免按名登记且**豁免腐化亦判红**)、`check:dead`(import 闭包可达性);`check:visual` 已并入 `test:all` 且**自证先跑**(自证失败即宣布绿灯作废)。证据与台账见 `docs/acceptance/qa-tracker.md` §11、探针 7 份存 `docs/acceptance/2026-10-17-ia-e2e/`;经验教训 `docs/lessons-learned.md` §5.38–§5.41(含「`npm run lint | tail` 吞掉 2 个 error」与「注释写在 JSX children 位会渲染成页面文字,而 type-check/1747 例单测/build 三道全绿」)。**§12 轮(2026-10-17)对这批待拍的处置**:`DEC-N5` 后台发布/更新/删除已接上缓存失效(新增 `src/lib/cms/revalidation.ts` 单一真源);`DEC-N3` `check:motion` 8 处归零,且时长判据从令牌声明移到消费点;`DEC-N4` 授权+basis 门槛下沉成 `case-publish-gate.ts` 供三处共用(实测门槛下隐藏条目 0 条,属前瞻加固);`DEC-N1` 彩色编码**第二条通道已收进 `check:accents` 判据 B**(产品线色相保留为受控例外:按 文件+色值 登记、棘轮 7、豁免腐化亦判红),落盘即抓到一条绕开真源抄主题的真漂移;`DEC-N6` e2e 进类型口径(`type-check:e2e` 并入 `test:all`)+ `.husky/pre-commit` 索引位 100755 + axe 证据按轮次落盘;**`DEC-N2` 被证伪**:`staggerDelay` 默认一直是 0.05(50ms),`git log -S` 查「0.15」在该文件历史里无任何提交 ⇒ 台账里那个数是叙述抄本而非仪器读数;**AUTH-VISUAL** 基线重采与 `--radius-cta` 负对照的证据落 `docs/acceptance/2026-10-17-final/`;**AUTH-NAV**(CMS navigation 行改写)仍未执行 —— 现行由代码 fail-closed 供数,不改库也能上线。
|
||||
- [x] **对标语法批:Bain / Porsche Consulting 实测驱动的 UI·UE·UX 重构(2026-10-17,tracer-bullet 一批)**:对标取证不是二手描述——Bain 走 archive.org 快照 2026-08-31(1600×846)绕开 Cloudflare、Porsche 取 live 国际站,逐元素 `getComputedStyle` 抽样。实测**证伪了 ADR-0004 的两条视觉判据**(决策四「关键数字 = 超大字号 + 品牌色」:Bain 成果数字实为 40px / 字重 500 / 纯黑;决策一「4px 色条为辅」:两家都不用颜色给内容分类),已在同一笔里改文档。四项裁定与落地见 [ADR-0008](docs/adr/0008-benchmark-grammar-takeover.md):① **借语法不借色相** —— radius 收进 0–4px 记档 + 新增 `--radius-cta: 0`(CTA 由 pill 改直角)、彩色阴影 `--shadow-brand/-brand-hover/-glow` 退役、`.bain-card` hover 去抬升,**`--radius-full` 保持 9999px**(承载 avatar/switch/slider/radio/progress 的功能性真圆,一并归零即方角化后台所有旋钮);② **一级导航改行业 × 能力 + 洞察双轴**,「产品」退出一级(入口降为能力面板里的产品矩阵总览),且把导航真源**从 DB 行反转为代码**(CMS 行须满足 IA 契约才采纳,否则 fail closed —— 实测复现过「一条自洽的旧行」让页脚各列静默变空);③ **信任层走零编造透明路线**:`ResultsSlot` 可判别空态 + `casePublishBlockers()` 反伪造不变量 + L3 替代信号槽,承诺条款收进 `commitments.ts` 单一真源;④ **范围只到首页 + 一条承载详情页**,其余模板待验收。新增三台可失败仪器并常驻门禁:`check:grammar`(R1–R20,含 R2 正向守卫、R9 双向、R10 递减棘轮、R11 僵尸令牌守卫、**R20 裸 alpha 必须在 opacity scale 内**)、`check:accents`(营销面类名通道,豁免按名登记且**豁免腐化亦判红**)、`check:dead`(import 闭包可达性);`check:visual` 已并入 `test:all` 且**自证先跑**(自证失败即宣布绿灯作废)。证据与台账见 `docs/acceptance/qa-tracker.md` §11、探针 7 份存 `docs/acceptance/2026-10-17-ia-e2e/`;经验教训 `docs/lessons-learned.md` §5.38–§5.41(含「`npm run lint | tail` 吞掉 2 个 error」与「注释写在 JSX children 位会渲染成页面文字,而 type-check/1747 例单测/build 三道全绿」)。**§12 轮(2026-10-17)对这批待拍的处置**:`DEC-N5` 后台发布/更新/删除已接上缓存失效(新增 `src/lib/cms/revalidation.ts` 单一真源);`DEC-N3` `check:motion` 8 处归零,且时长判据从令牌声明移到消费点;`DEC-N4` 授权+basis 门槛下沉成 `case-publish-gate.ts` 供三处共用(实测门槛下隐藏条目 0 条,属前瞻加固);`DEC-N1` 彩色编码**第二条通道已收进 `check:accents` 判据 B**(产品线色相保留为受控例外:按 文件+色值 登记、棘轮 7、豁免腐化亦判红),落盘即抓到一条绕开真源抄主题的真漂移;`DEC-N6` e2e 进类型口径(`type-check:e2e` 并入 `test:all`)+ `.husky/pre-commit` 索引位 100755 + axe 证据按轮次落盘;**`DEC-N2` 被证伪**:`staggerDelay` 默认一直是 0.05(50ms),`git log -S` 查「0.15」在该文件历史里无任何提交 ⇒ 台账里那个数是叙述抄本而非仪器读数;**AUTH-VISUAL** 基线重采与 `--radius-cta` 负对照的证据落 `docs/acceptance/2026-10-17-final/`;**AUTH-NAV**(CMS navigation 行改写)仍未执行 —— 现行由代码 fail-closed 供数,不改库也能上线。
|
||||
- [x] **内页证据密度(2026-11-25,Batch 2)**:补的是「内容」不是「语法」——`/news` 与 `/insights` 此前各只有 250 字左右的正文,一个只有两篇文章的新闻栏目与一个正文撑不起来的洞察枢纽。① 两篇公开正文由 **238/313 字扩到 914/758 字**,全部从既有真源派生(`METHODOLOGY` 四阶段、`SERVICES` 四组能力、`PRODUCTS` 六款套装、`commitments.ts` 的响应承诺),**不新增任何客户案例、不新造任何效果数字**:文中「不承诺未经测算的收益」「不用行业最佳实践代替方案」等段落本身就是零编造原则的转述;② 详情页从「一整块 `whitespace-pre-line` 文本」改为**小标题 + 段落**结构(`src/lib/news-article.ts` 的 `parseArticleBlocks`,三条判据 + 5 例负例),并新增**正文末尾的站内公开入口**(`NEWS_RELATED_LINKS`:方法论 / 战略咨询 / 企业软件 / 产品矩阵,逐条反查 products 与 services 常量确认真实存在)—— 此前详情页是死胡同,只有「返回列表」与「预约咨询」两个出口;③ 阅读时长由**正文字数实时算出**(`readingMinutes`,450 字/分钟),不手写、不落库,正文一改它跟着改;④ `/insights` 卡片显式写出「收录于」哪个原生栏目(技术观点在 `/news`、方法论在 `/methodology`),**不新增 `/insights/[slug]`** —— 那会把同一 ContentItem 挂在两个 URL 下造成 canonical 冲突,与 `navigation.ts` 的「轴 = 视图,模型 = 真源」不变式相悖。判据:单测 `news-article.test.ts`(11 例,含正文厚度下限与路由存在性反查)+ `news-detail-content-v3.test.tsx`(4 例,负对照已做:关掉解析器 3 条转红)+ e2e UJ-04/UJ-10 新增「≥2 个 h2 / 相关入口 ≥3 条 / 阅读时长存在」三条断言(负对照:注回整块渲染后 UJ-04 转红)。视觉基线重采 **5 张**(news-detail × 5 project,`git status` 张数 == 预测数),独立只读复跑 **130 passed / 0 failed**
|
||||
- [x] **全项目未收口事项收尾(2026-11-25)**:本轮不是新功能,是**把已经写在文档里的「已修」逐条核实到代码**。① **发现 2026-10-24 修复轮整批从未落地** —— `FIXES.md` 写着「已修」的四项 P2 缺陷全部还开着,两个「新建」的源文件在树里却零调用点(`check:dead` 实测判死码即物证),实际躺在 `stash@{0}`;逐文件比对后只移植仍然成立的部分(`metric-value.ts` 接线让 `3-6个月` 不再渲染成 `36`、`MobileTabBarGate` 关掉 admin 底栏泄漏、admin 表格 `min-w-[760px]` + `nowrap` 恢复横滚、GA 默认改 opt-in 且 `/admin` 不加载)。② **技术债**:`container-wide` 这个**全仓从未定义**的类名在 6 个文件里用了两年(privacy/terms/not-found/error/SkeletonHero/standalone 详情内容因此贴左边缘),全部换成真实的 `container-x`,并新增**语法闸 R21**(`check:grammar` 20→21 条)把这类「class 在、CSS 不在」的第三族死样式钉住;移除零引用的 `@ant-design/icons`;修 `dead-modules.mjs` 漏扫 `prisma/` 导致的 `seed-target.ts` 误判。③ **视觉覆盖缺口**:95 张基线(139MB)有文件、无用例、且**全部过期**,18 条真实路由因此没有任何视觉守卫 —— 接回 `VISUAL_TEST_PAGES`(16 页 → **35 页**)并修正一条拼错的 news slug,重采 **105 张**(孤儿基线归零:225 张 / 0 条无人消费),独立只读复跑 **225 passed / 0 failed**。门禁:type-check / type-check:e2e / lint(0 error / 84 warning)/ jest(**160 套件 1878 例**)/ check:grammar(21/21)/ motion / accents / brand-token / contrast / package-keys / dead(**0 死码**)全部通过。详见 `docs/acceptance/qa-tracker.md` §18 与 `docs/lessons-learned.md` §5.61–§5.64。
|
||||
|
||||
- [x] **三个「默认值写错方向」的收尾(2026-11-25,第二轮)**:三件事的共同点是**默认值本来就在鼓励做错事**。① **seed 从「无条件覆盖」改成「补缺」**:此前 `seedItems()` 一律 `upsert` 全字段覆盖、案例还无条件 `deleteMany`,于是「跑一次 seed」等于「把 CMS 里改过的文案冲掉」(§5.60 的真实事故)。现在默认跳过已存在的行、日志显式写「未写任何一行」,只有显式 `--force` 才覆盖/删除,未知参数直接中止(`src/lib/seed-write-policy.ts` + 14 例单测;三向负对照在临时库实测:人工编辑存活 / `--force` 还原 / `--forced` 零写入)。② **`prose` 排版层从「从未定义」变成「真规则」**:privacy/terms 写了两年 `prose prose-lg` 而仓里没装 `@tailwindcss/typography`,两个类一直没有生成过任何 CSS。手写一份 `.prose`(不吃依赖),**整层裹 `:where()` 保持零特异性**——因为库里已存的法律页 HTML 自带 inline utility,层若按 `.prose p`(0,1,1) 写就会盖掉它们:实测把 `/terms` 呼出块标签染灰 329px、日期行高 1.65→1.85 共 1222px。判据:`prose-layer.test.ts` 11 例(含「层内不许裸选择器」的反方向守卫)+ `/privacy` `/terms` × 5 project 视觉**零差异**。③ **写库型 E2E 从「未授权」变成「可随时跑」**:11 例改成指向 `/tmp` 下一次性的 SQLite(迁移 → seed → 预热 → dev server),`npm run test:e2e:write-db` ⇒ **11 passed / 0 failed**,跑前跑后 `prisma/dev.db` 的 inode+size+mtime 不变。详见 `docs/acceptance/qa-tracker.md` §19 与 `docs/lessons-learned.md` §5.65–§5.67。
|
||||
- [x] **收尾第三轮:修掉一个恒红的自证闸,并把「已修」的断言补齐(2026-11-26)**:本轮不是新功能,起因是 `npm run check:visual` **在干净树上就是红的**——一个恒红的自证闸会让 `test:all` 整段失去判定力,所以先修门禁可信度。① **OPEN-15 真因**:自证夹具 `B_PROPAGATION` 写死了 `detail-hero.tsx`,而该组件 2026-11-03 已改名 `detail-page-hero.tsx`(豁免表改了、夹具没改)⇒ 每个情景多一条「新增透传点」+ 一条「豁免腐化」,10 个情景 8 红。修法**不是改路径**(那只是把同一个错推迟到下次改名),而是**从豁免表派生夹具**,改名自动跟随 ⇒ `check:accents:selftest` 11/11 / EXIT=0,`check:visual` EXIT=0。② **OPEN-14 `stash@{0}` 逐项判定**:36 个文件按「stash 新增行是否已在 HEAD」实测,7 个文件 0 缺失(stash 是旧形态,现行版本更好),6 处仍成立且已移植,3 处属 `feature/gitea-branding` / 运维线不代改;未 drop(不可逆,需用户确认)。③ **一条门禁与实现脱钩(新发现)**:DEF-09 把 GA `analytics_storage` 默认改成 `denied`,但 `e2e/ga4-event-tracking.spec.ts:132` 仍断言 `granted`——而该用例**只在 `test:e2e:prod` 下执行**(dev 下 `test.skip`),所以「本地全绿」看不见它;现改为同时钉「default=denied」与「已存偏好由 consent update 在 config 前放行」。④ **覆盖分母补记**:headings 11→**34 页**(实测 34/34、0 问题)、axe `settle()` 改逐屏步进(`main *` 内 `opacity:0` 未清零即抛错,不再出假读数)、视觉 15→**35 页 / 225 例 / 227 张基线**,三者写进 `docs/development/quality-gates.md` §13。⑤ **OPEN-12 证据目录口径**:`git status -uall` 从 55 条降到只剩归属明确项——文字与 JSON 读数 + 复现脚本入库,逐页截图(172MB)按目录点名忽略,Gitea 线(50 文件与 `feature/gitea-branding` sha256 全等)整目录忽略。门禁实测:type-check / type-check:e2e EXIT=0、lint 0 error / 88 warning、jest **162 套件 1904 例**、check:visual / motion / contrast / brand-token / package-keys / dead 全 EXIT=0、headings 34/34、axe **35 路由 × 4 组合 140 rows 全 0**。详见 `docs/acceptance/qa-tracker.md` §20 与 `docs/lessons-learned.md` §5.68–§5.69。
|
||||
- [x] **语法棘轮分批清零(批 1+2,2026-11-26,OPEN-05a)**:不做「一次性清零 54 处」(ADR-0013)——**批 1** 删 3 个零渲染点组件(`detail/service-value` / `solution-value` / `micro-interactions`)并从 `detail/index.ts` 移除导出(21 处、零基线);**批 2** 清 `/about/brand` 18 处并重采 5 张基线。五条上限同批下调为 `R13 3 · R14 5 · R15 1 · R16 5 · R17 1`(剩余 15 处即批 3)。判据:`check:grammar` 21/21、自证双向通过、`test:coverage` 159 套件 / 1883 例、只读视觉 **225 passed / 0 failed**。批 3(详情件 + 4 个 hub 列表 + 首页,需 95 张基线)保留棘轮,翻转条件见 ADR-0013 §6。
|
||||
- [x] **导航签名·内缩白浮条(2026-11-27,OPEN-02a)**:页头从「全宽 fixed 贴顶条」改为内缩白浮条——`top: 48px` / 高 `64px`,左右对齐 `container-x`;值走 **px 令牌**(`--header-inset-top` / `--header-height`),不用 rem(根字号 16/17/18 会漂移)。外壳保持 `top-0` 不画底色,营销内容让位 112px;删除随滚动的 80→64 高度动画;新增 `data-header-state="top|scrolled"`。六档几何恒定 top 48 / 高 64;滚动收成左上白方汉堡(02b)**不做**(会让 `nav-dropdown` 4 例与 `nav-keyboard` 6 例两条可达性契约失效)。判据:`chrome-persistence` 新用例 + 导航三 spec **52 passed / 8 skipped**;基线**实写 195 张**,独立只读复跑 **225 passed / 0 failed**。
|
||||
- [x] **分支收尾(2026-11-28)**:① **OPEN-16 修复**——`dead-modules.mjs` 从「import 闭包」升级为**符号级可达性**:任何含 `export … from` 的模块按桶处理,再导出不再无条件传播,按名 import 才解析到落点,`export *` / namespace / 副作用导入保守判活;解析前剥离注释(`constants.ts` 注释里的示例导入曾骗过正则)。新增 `scripts/dead-modules.selftest.mjs`(6 情景),`check:dead` 改为「自证 + 报告」两段。真树浮出 5 个 barrel-only 模块,登记 **OPEN-18**,未擅删(其中 3 处是 `constants` 门面的公共 API/类型面)。② **文档同步**:README 补记 OPEN-05a / 02a;CONTEXT 决策表补 ADR-0012 / 0013 / 符号级死码判据;qa-tracker 增 §25 与 **OPEN-17**(1600 档 gutter 差 8–9px),并更正 §24.3 的「32 页」笔误(实为 **35 页**);lessons §5.71 记「文件名不是结构、注释不是代码」两处判据自欺。③ **门禁**:`test:all` **EXIT=0**(lint 0 error / 88 warning、jest 159 套件 / 1883 例、`check:grammar` 21/21、`test:e2e:fast` 59 passed、安全头 8/8)+ 只读视觉 **225 passed / 0 failed**;未验证项与完整读数见 `docs/acceptance/2026-11-28-wrap-up/`,`test:e2e:prod` / `test:e2e:write-db` / `lighthouse` 留 PR 门禁。**OPEN-01**(hub 六页 B 类原语)留表、独立分支。
|
||||
- [x] **OPEN-17 闭环:1600 档浮条/内容栅格对齐保时捷网格(2026-12-02)**:`OPEN-02a` 残留的 8–9px 根因定位——本仓 ≥1024 根字号 18px,站点通用 rem 档 gutter `lg:px-10` 实为 **45px**(非名义 40px),1600 档左缘 = (1600−1360)/2+45 = 165。修法 **`--container-max: 1360→1342px`**(globals.css 一行,25+ 个 `lg:px-10` 调用点零改动):1600 档实测 **174…1426**(对标 173…1426,差 ≤1px,判据 ≤2px ✓),内容栅格同步落 174、宽 1252 ≈ 保时捷 1248(ADR-0009「浮条与栅格同边」口径);**1342 只在 ≥1343px 视口参与**,390/640/768/1024/1280 五档逐格不变。门禁:tsc 0 error、eslint 0 error / 31 warning、jest **161 套件 / 1899 例全通过**、全 5 visual project 只读复跑 **225 passed / 0 failed** ⇒ **零基线重采**。详见 `docs/acceptance/qa-tracker.md` §30 与 ADR-0012 §8.5。
|
||||
- [ ] **信任证据补齐·阶段 1/2(待内测/试点客户素材)**:如实披露「共创中/内测中/已交付」三档 + 经授权客户(脱敏);有交付成果后经授权公示可量化结果(零编造原则)——口径字段与 admin 录入口已就绪,待真实数据把 `basis` 从 `target` 升级为 `verified`
|
||||
|
||||
## 技术栈
|
||||
@@ -376,3 +385,4 @@ Jenkins Pipeline(`Jenkinsfile`)在部署阶段调用 `./scripts/deploy.sh de
|
||||
## 许可证
|
||||
|
||||
Copyright © 2026 四川睿新致远科技有限公司
|
||||
- [x] **语法棘轮批 3 清零(2026-12-02,OPEN-05b)**:ADR-0013 §6 三翻转条件满足后清零剩余 15 处——detail 件 10(直角化 / R16 红面→中性面 / CTA 标题 900→700 / 去 hover 阴影)+ hub 列表箭头去竖直分量 3 + erp-upgrade 卡片去抬升 2。**R16「红不做面」用户裁定 A 方案**:红底面→中性面(`bg-bg-elevated` / `bg-bg-primary/80`),红降级为 `text-brand-ink` 点缀。归因教训:11-26 的「95 张/19 页」是静态估算——R14 是 hover 态改动静态零漂移、首页实际渲染 L3 空态兜底 ⇒ 基线**实写 35 张**(预测==`git status`,零外溢),L2 卡片 1 例为选择器超时(单跑复验过,非像素)。判据:`check:grammar` **25/25 · R13–R17 实测 0 / 上限 0(棘轮转硬禁)**、selftest 双向、tsc 0、eslint 0 error、jest **161 套件 / 1899 例**、独立只读复跑 **225 passed / 0 failed**。归因表 `docs/acceptance/2026-12-02-grammar-batch3/attribution.md`,详见 ADR-0013 §8 与 qa-tracker OPEN-05b 行。
|
||||
@@ -0,0 +1,49 @@
|
||||
# 首屏主图换成都金融城双子塔 —— 待办(额度恢复后执行)
|
||||
|
||||
- **状态**:⏸ 被上游图片生成额度阻塞(`trae image: code=3003 / LLMRawChatV2 4008 Your requests have exceeded the quota`,连续两次、间隔 35s 复测仍报同一错误 ⇒ 额度用尽,非冷却)
|
||||
- **裁定**(2026-11-24,用户确认):
|
||||
- 方案 **A**:等额度恢复后生成,再接入
|
||||
- 首屏文案 **不配**「立足成都」一类地点表述(图只承担情绪,不承载位置主张)
|
||||
|
||||
## 事实边界(必须先读)
|
||||
|
||||
| 项 | 值 |
|
||||
|---|---|
|
||||
| 注册地址 | 成都市**龙泉驿区**幸福路12号 |
|
||||
| 金融城双子塔 | 成都**高新区**天府大道沿线 |
|
||||
| 两者距离 | 约 20 公里,是两个不同城区 |
|
||||
|
||||
**风险**:用高新区地标为龙泉驿注册的公司做首屏,等于一处可被追问的位置暗示。
|
||||
底线来自 `DESIGN.md`「氛围图边界」:氛围图**只承担构图与情绪**,一律 `aria-hidden`,
|
||||
不进入「客户成果 / 团队现场」证据位。因此:
|
||||
- ✅ 允许:图单独作为首屏视觉背景
|
||||
- ❌ 禁止:图上或紧邻处配「立足成都 / 我们在高新区」这类把图变成位置证据的文案
|
||||
- ❌ 禁止:把该图放进任何「案例 / 团队 / 资质」位
|
||||
|
||||
## 执行步骤
|
||||
|
||||
1. **生成**:`trae_draw_image`,尺寸 `3072x1248`(工具要求总像素 ≥3,686,400;1920×765 不够)。
|
||||
prompt 必须包含否定约束,且生成后逐条自检:
|
||||
- 无人物 / 无人影
|
||||
- 无可读文字、招牌、广告牌
|
||||
- 无品牌 logo、水印、可识别公司名
|
||||
- 整体偏暗(首屏白字可读性依赖它)
|
||||
2. **切图**:降到 `1920×765` 存 `public/images/home/hero-twin-towers.webp`,
|
||||
与现有 `hero-architecture.webp` 同规格(`fill` + `object-cover`)。
|
||||
3. **接线**:只改 `src/app/(marketing)/home-content-v17.tsx` 的一行 —— `HERO_IMAGE` 常量
|
||||
(第 80 行)。布局、压暗层、字号锚点、拼贴栅格一律不动。
|
||||
4. **必做的对比度复验**(不是可选项):换图后重跑逐像素量法 ——
|
||||
把 hero 内文字临时 `visibility:hidden` → 截图 → 取文字盒内**最亮**像素 →
|
||||
按 `color` 实际 alpha 合成 → 算 WCAG。判据:9 视口 × 全部文字盒 ≥ 4.5:1(大字 ≥3:1)。
|
||||
⚠ 现网这组数是 5.84:1(修完 `/85` 之后)。换亮图会掉,掉到线下就调压暗层或字色,
|
||||
**不要靠眼睛判断**。方法见 `docs/lessons-learned.md` §5.55。
|
||||
5. **基线**:首页 4 张(home-fullpage / theme-light-main / theme-dark-main,
|
||||
各 project)+ 若图使页高变化则连带重采。按 `--update-snapshots=changed`,
|
||||
完成后核对 `git status` 张数 == 预期张数(§5.58:`passed` 数不是完成证据)。
|
||||
6. **文档**:ADR-0009「更正一」补一句主图来源;`docs/lessons-learned.md` 若踩到新坑再记。
|
||||
|
||||
## 不要做的事
|
||||
|
||||
- 不要用「假图 + 文案」冒充公司位置
|
||||
- 不要为了配图新增「立足成都」类文案(用户已明确裁定不配)
|
||||
- 不要把这张图塞进任何证据位
|
||||
@@ -0,0 +1,48 @@
|
||||
# 企业微信资产包 · 清单(第五十二刀)
|
||||
|
||||
生成:`wecom-pack.cjs`(18 张 PNG + `pack-report.json`)
|
||||
门禁:`check-wecom.py` → **判红 0 / 通过 64 / 预期红 2 / EXIT=0**
|
||||
对照页:`wecom.html`(手写件,非生成 —— 所以不配标签配平闸,改由浏览器实验 20 张图 0 破图)
|
||||
|
||||
## 一、两类载体,两套判据
|
||||
|
||||
| 用途 | 文件 | 关键判据(实测,非声明) |
|
||||
|---|---|---|
|
||||
| 企业微信头像·标准 | `wecom-avatar-full-512.png` `…-144.png` | 圆即底板(内切圆外 0 像素);中心 (196,30,58)=朱砂;源 `avatar-standard.svg`,face 0.80 |
|
||||
| 企业微信头像·仪式 | `wecom-avatar-ring2-512.png` `…-144.png` | 同上;粗白环 4.5% + 字面 0.68,源 `avatar-ceremonial.svg` |
|
||||
| 企业logo·名+号 | `wecom-logo-stacked-702x180-{white,transparent,reversed}.png` | 墨 462×180、左右各空 120、居中差 ≤1px;朱砂 0.47%(含红的 A) |
|
||||
| 企业logo·只走名 | `wecom-logo-name-702x180-{white,transparent,reversed}.png` | 墨 702×154、上下各空 13、居中差 0;朱砂恰 0(源不含号 ⇒ 无 A 可加彩) |
|
||||
| 留白备版 | 上两组的 `-pad-` 三件套 | 板内四周内缩 13px 后重装;stacked 墨 395×154、name 墨 676×148 |
|
||||
| @2x 高清备份 | `wecom-logo-{stacked,name}-2x-1404x360-white.png` | 只出白底板;上传框按 702×180 用 |
|
||||
|
||||
## 二、这一刀量出来的三条,推翻了我自己先前的说法
|
||||
|
||||
1. **「方印塞圆裁会咬字」不成立。** 实测两版白字最远极径都在内切圆内:方版余量 10.3%、圆版 8.0%;40px 下逐格差异只有 9.4%。
|
||||
真正的差别是语义 —— 方版被裁后那道圆边是**被裁出来的**,「印是方的」这层意思当场没了;圆版那道圆按 `face ≤ 0.866`(真迹最远极径 0.5773×max)设计。
|
||||
判据 B 因此改述为「圆即底板」,不再宣称保护可读性。
|
||||
2. **字标 SVG 的 viewBox 上下带空盒,按画布排必偏心。** 实测 `public/logo.svg` 墨只占画布高 **72.8%**、`name-alone.svg` 只占 **51.1%**;
|
||||
上一版按画布顶天立地排,门禁当场报出上下差 9–30px。改成**先裁墨盒再定标**后才归零。
|
||||
⚠ 这与记忆里那条「承载尺寸的空盒会污染一切由它换算出来的数」是同一个 bug 的第三次现身(前两次:主锁定 viewBox 写死 460、名墨右 255.6)。
|
||||
3. **`name` 的墨宽高比实测 4.557,比 702×180 的板(3.900)还扁** ⇒ 它只能按宽限死。
|
||||
记忆里「新横排名 2.663」是**画布**比不是**墨**比;`name-alone.svg` 那个 96 单位高的画布是空盒。
|
||||
|
||||
## 三、装配层踩过的三个坑(都靠门禁或实测拦住,没进交付)
|
||||
|
||||
- `assertPurePaths` 把注释里的「现网那份用 `<text>`」判成违规 —— 判据先剥 XML 注释才对。
|
||||
- `sharp.resize(宽, 高)` 参数顺序写反,墨块被排成 180×384,合成时才报「比底板大」。
|
||||
- **负对照的预期红被计进失败数** ⇒ 闸越准、EXIT 越红。已按「退出码分档 + 预期红登记」改掉,并加条数下限(<2 条即宣布负对照没跑成、上面所有 ok 不作数)。
|
||||
|
||||
## 四、两条必须随文件交接的存疑
|
||||
|
||||
1. **702×180 是半核实。** 口径来自转述官方后台提示的二手文(CSDN 教程、建站问答),官方帮助中心正文为 JS 渲染、抓不到正文。
|
||||
上传前以管理后台【我的企业 → 企业信息 → 企业logo】的提示框为准;若比例不同,改 `wecom-pack.cjs` 顶部 `PLATE` 一个常量即可重出全套。
|
||||
2. **没做的部分**:自建应用图标、群机器人头像、对外名片 —— 官方尺寸没有可信来源,不拿猜的数当交付。
|
||||
|
||||
## 五、待拍(对照页第四节)
|
||||
|
||||
- **W1** 头像 full / ring2 → 推荐 **full**(企业微信是最小、压最狠、重复最多的载体,ring2 那道环正是实测会碎成 38 块的那一档)
|
||||
- **W2** 企业logo 名+号 / 只走名 → 推荐 **名+号**(与 2026-10-20「导航必须带英文」同口径;代价量化:书法实高 102px vs 154px,号占 61px、缝 17px)
|
||||
- **W3** 底板 满版 / 留白版 → 推荐 **满版**(启动页那块系统本就留边,再自缩 14.5% 会显小)
|
||||
|
||||
拍完:选定版去掉后缀转正式件,未选版进 `alt/`,本文件补裁定段。
|
||||
本包属站外载体,**不进 `public/`**、不改站点代码。
|
||||
@@ -0,0 +1,279 @@
|
||||
{
|
||||
"plate": {
|
||||
"w": 702,
|
||||
"h": 180
|
||||
},
|
||||
"pad": 0.86,
|
||||
"files": {
|
||||
"wecom-avatar-full-512.png": {
|
||||
"source": "assets-delivery/avatar-standard.svg",
|
||||
"size": "512x512",
|
||||
"kind": "avatar"
|
||||
},
|
||||
"wecom-avatar-full-144.png": {
|
||||
"source": "assets-delivery/avatar-standard.svg",
|
||||
"size": "144x144",
|
||||
"kind": "avatar"
|
||||
},
|
||||
"wecom-avatar-ring2-512.png": {
|
||||
"source": "assets-delivery/avatar-ceremonial.svg",
|
||||
"size": "512x512",
|
||||
"kind": "avatar"
|
||||
},
|
||||
"wecom-avatar-ring2-144.png": {
|
||||
"source": "assets-delivery/avatar-ceremonial.svg",
|
||||
"size": "144x144",
|
||||
"kind": "avatar"
|
||||
},
|
||||
"wecom-logo-stacked-702x180-white.png": {
|
||||
"source": "../../public/logo.svg",
|
||||
"size": "702x180",
|
||||
"kind": "plate",
|
||||
"ink": {
|
||||
"w": 462,
|
||||
"h": 180
|
||||
},
|
||||
"pad": {
|
||||
"l": 120,
|
||||
"r": 120,
|
||||
"t": 0,
|
||||
"b": 0
|
||||
},
|
||||
"limit": "height",
|
||||
"inkAspect": 2.565,
|
||||
"inkOverCanvas": 0.728
|
||||
},
|
||||
"wecom-logo-stacked-702x180-transparent.png": {
|
||||
"source": "../../public/logo.svg",
|
||||
"size": "702x180",
|
||||
"kind": "plate",
|
||||
"ink": {
|
||||
"w": 462,
|
||||
"h": 180
|
||||
},
|
||||
"pad": {
|
||||
"l": 120,
|
||||
"r": 120,
|
||||
"t": 0,
|
||||
"b": 0
|
||||
},
|
||||
"limit": "height",
|
||||
"inkAspect": 2.565,
|
||||
"inkOverCanvas": 0.728
|
||||
},
|
||||
"wecom-logo-stacked-702x180-reversed.png": {
|
||||
"source": "../../public/logo-white.svg",
|
||||
"size": "702x180",
|
||||
"kind": "plate",
|
||||
"ink": {
|
||||
"w": 462,
|
||||
"h": 180
|
||||
},
|
||||
"pad": {
|
||||
"l": 120,
|
||||
"r": 120,
|
||||
"t": 0,
|
||||
"b": 0
|
||||
},
|
||||
"limit": "height",
|
||||
"inkAspect": 2.565,
|
||||
"inkOverCanvas": 0.728
|
||||
},
|
||||
"wecom-logo-stacked-2x-1404x360-white.png": {
|
||||
"source": "../../public/logo.svg",
|
||||
"size": "1404x360",
|
||||
"kind": "plate",
|
||||
"ink": {
|
||||
"w": 923,
|
||||
"h": 360
|
||||
},
|
||||
"pad": {
|
||||
"l": 240,
|
||||
"r": 241,
|
||||
"t": 0,
|
||||
"b": 0
|
||||
}
|
||||
},
|
||||
"wecom-logo-stacked-pad-702x180-white.png": {
|
||||
"source": "../../public/logo.svg",
|
||||
"size": "702x180",
|
||||
"kind": "plate",
|
||||
"ink": {
|
||||
"w": 395,
|
||||
"h": 154
|
||||
},
|
||||
"pad": {
|
||||
"l": 154,
|
||||
"r": 153,
|
||||
"t": 13,
|
||||
"b": 13
|
||||
},
|
||||
"limit": "height",
|
||||
"inkAspect": 2.565,
|
||||
"inkOverCanvas": 0.728
|
||||
},
|
||||
"wecom-logo-stacked-pad-702x180-transparent.png": {
|
||||
"source": "../../public/logo.svg",
|
||||
"size": "702x180",
|
||||
"kind": "plate",
|
||||
"ink": {
|
||||
"w": 395,
|
||||
"h": 154
|
||||
},
|
||||
"pad": {
|
||||
"l": 154,
|
||||
"r": 153,
|
||||
"t": 13,
|
||||
"b": 13
|
||||
},
|
||||
"limit": "height",
|
||||
"inkAspect": 2.565,
|
||||
"inkOverCanvas": 0.728
|
||||
},
|
||||
"wecom-logo-stacked-pad-702x180-reversed.png": {
|
||||
"source": "../../public/logo-white.svg",
|
||||
"size": "702x180",
|
||||
"kind": "plate",
|
||||
"ink": {
|
||||
"w": 395,
|
||||
"h": 154
|
||||
},
|
||||
"pad": {
|
||||
"l": 154,
|
||||
"r": 153,
|
||||
"t": 13,
|
||||
"b": 13
|
||||
},
|
||||
"limit": "height",
|
||||
"inkAspect": 2.565,
|
||||
"inkOverCanvas": 0.728
|
||||
},
|
||||
"wecom-logo-name-702x180-white.png": {
|
||||
"source": "assets-delivery/name-alone.svg",
|
||||
"size": "702x180",
|
||||
"kind": "plate",
|
||||
"ink": {
|
||||
"w": 702,
|
||||
"h": 154
|
||||
},
|
||||
"pad": {
|
||||
"l": 0,
|
||||
"r": 0,
|
||||
"t": 13,
|
||||
"b": 13
|
||||
},
|
||||
"limit": "width",
|
||||
"inkAspect": 4.557,
|
||||
"inkOverCanvas": 0.511
|
||||
},
|
||||
"wecom-logo-name-702x180-transparent.png": {
|
||||
"source": "assets-delivery/name-alone.svg",
|
||||
"size": "702x180",
|
||||
"kind": "plate",
|
||||
"ink": {
|
||||
"w": 702,
|
||||
"h": 154
|
||||
},
|
||||
"pad": {
|
||||
"l": 0,
|
||||
"r": 0,
|
||||
"t": 13,
|
||||
"b": 13
|
||||
},
|
||||
"limit": "width",
|
||||
"inkAspect": 4.557,
|
||||
"inkOverCanvas": 0.511
|
||||
},
|
||||
"wecom-logo-name-702x180-reversed.png": {
|
||||
"source": "assets-delivery/name-alone-reversed.svg",
|
||||
"size": "702x180",
|
||||
"kind": "plate",
|
||||
"ink": {
|
||||
"w": 702,
|
||||
"h": 154
|
||||
},
|
||||
"pad": {
|
||||
"l": 0,
|
||||
"r": 0,
|
||||
"t": 13,
|
||||
"b": 13
|
||||
},
|
||||
"limit": "width",
|
||||
"inkAspect": 4.557,
|
||||
"inkOverCanvas": 0.511
|
||||
},
|
||||
"wecom-logo-name-2x-1404x360-white.png": {
|
||||
"source": "assets-delivery/name-alone.svg",
|
||||
"size": "1404x360",
|
||||
"kind": "plate",
|
||||
"ink": {
|
||||
"w": 1404,
|
||||
"h": 308
|
||||
},
|
||||
"pad": {
|
||||
"l": 0,
|
||||
"r": 0,
|
||||
"t": 26,
|
||||
"b": 26
|
||||
}
|
||||
},
|
||||
"wecom-logo-name-pad-702x180-white.png": {
|
||||
"source": "assets-delivery/name-alone.svg",
|
||||
"size": "702x180",
|
||||
"kind": "plate",
|
||||
"ink": {
|
||||
"w": 676,
|
||||
"h": 148
|
||||
},
|
||||
"pad": {
|
||||
"l": 13,
|
||||
"r": 13,
|
||||
"t": 16,
|
||||
"b": 16
|
||||
},
|
||||
"limit": "width",
|
||||
"inkAspect": 4.557,
|
||||
"inkOverCanvas": 0.511
|
||||
},
|
||||
"wecom-logo-name-pad-702x180-transparent.png": {
|
||||
"source": "assets-delivery/name-alone.svg",
|
||||
"size": "702x180",
|
||||
"kind": "plate",
|
||||
"ink": {
|
||||
"w": 676,
|
||||
"h": 148
|
||||
},
|
||||
"pad": {
|
||||
"l": 13,
|
||||
"r": 13,
|
||||
"t": 16,
|
||||
"b": 16
|
||||
},
|
||||
"limit": "width",
|
||||
"inkAspect": 4.557,
|
||||
"inkOverCanvas": 0.511
|
||||
},
|
||||
"wecom-logo-name-pad-702x180-reversed.png": {
|
||||
"source": "assets-delivery/name-alone-reversed.svg",
|
||||
"size": "702x180",
|
||||
"kind": "plate",
|
||||
"ink": {
|
||||
"w": 676,
|
||||
"h": 148
|
||||
},
|
||||
"pad": {
|
||||
"l": 13,
|
||||
"r": 13,
|
||||
"t": 16,
|
||||
"b": 16
|
||||
},
|
||||
"limit": "width",
|
||||
"inkAspect": 4.557,
|
||||
"inkOverCanvas": 0.511
|
||||
}
|
||||
},
|
||||
"avatars": [
|
||||
"full",
|
||||
"ring2"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
企业微信资产包门禁(第五十二刀)
|
||||
|
||||
跑法:/usr/bin/python3 check-wecom.py
|
||||
退出码分档(不是"红=1"一把梭):0 全绿 / 1 判红 / 2 门禁自身崩溃或夹具缺失
|
||||
|
||||
四条判据都配了**负对照**,负对照不判红就等于这条判据没有约束力:
|
||||
B 圆即底板 ← 现网 assets-delivery/icon-512x512.png(圆角方版)必须被判红
|
||||
D 板内居中 ← 故意平移 6px 的副本必须被判红
|
||||
E 朱砂面积带 ← 把红涂满整板的副本必须被判红
|
||||
F 反白无彩 ← 给反白版塞一枚朱砂 A 的副本必须被判红
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
try:
|
||||
from PIL import Image
|
||||
except Exception as e: # 解释器选错会读成"依赖缺失",见记忆 reference-python-pillow-path
|
||||
print("FATAL 需要 Pillow,且必须用 /usr/bin/python3 跑:", e)
|
||||
sys.exit(2)
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
PKG = os.path.join(HERE, "assets-wecom")
|
||||
RED = (196, 30, 58) # #C41E3A
|
||||
ALPHA_EDGE = 8 # 视为"全透明"的上限
|
||||
fails, oks, expected = [], [], []
|
||||
|
||||
|
||||
def ok(msg):
|
||||
oks.append(msg)
|
||||
print(f" ok {msg}")
|
||||
|
||||
|
||||
def bad(msg):
|
||||
fails.append(msg)
|
||||
print(f" RED {msg}")
|
||||
|
||||
|
||||
def name_size(fn):
|
||||
m = re.search(r"(\d+)x(\d+)", fn)
|
||||
if m:
|
||||
return int(m.group(1)), int(m.group(2))
|
||||
m = re.search(r"-(\d+)\.png$", fn)
|
||||
return (int(m.group(1)), int(m.group(1))) if m else (None, None)
|
||||
|
||||
|
||||
def is_red(px):
|
||||
return abs(px[0] - RED[0]) + abs(px[1] - RED[1]) + abs(px[2] - RED[2]) <= 30
|
||||
|
||||
|
||||
def red_ratio(im):
|
||||
"""朱砂像素占全板比例(%)。透明像素不算红。"""
|
||||
im = im.convert("RGBA")
|
||||
w, h = im.size
|
||||
px = im.load()
|
||||
n = 0
|
||||
for y in range(h):
|
||||
for x in range(w):
|
||||
p = px[x, y]
|
||||
if p[3] > 128 and is_red(p):
|
||||
n += 1
|
||||
return 100.0 * n / (w * h)
|
||||
|
||||
|
||||
def ink_mask(im):
|
||||
"""返回 (mask, w, h)。mask[y][x]=1 表示该像素是"墨"。
|
||||
白底板:非白即墨;透明底:不透明即墨。"""
|
||||
im = im.convert("RGBA")
|
||||
w, h = im.size
|
||||
px = im.load()
|
||||
opaque_white = 0
|
||||
total = 0
|
||||
mask = []
|
||||
for y in range(h):
|
||||
row = []
|
||||
for x in range(w):
|
||||
r, g, b, a = px[x, y]
|
||||
total += 1
|
||||
if a <= ALPHA_EDGE:
|
||||
row.append(0)
|
||||
continue
|
||||
if r >= 245 and g >= 245 and b >= 245 and a >= 250:
|
||||
row.append(0)
|
||||
continue
|
||||
row.append(1)
|
||||
mask.append(row)
|
||||
return mask, w, h, px
|
||||
|
||||
|
||||
def bbox(mask, w, h):
|
||||
xs = [x for row in mask for x, v in enumerate(row) if v]
|
||||
ys = [y for y, row in enumerate(mask) if any(row)]
|
||||
if not xs or not ys:
|
||||
return None
|
||||
return min(xs), min(ys), max(xs), max(ys)
|
||||
|
||||
|
||||
def check_circle_lossless(path, label, must_fail=False):
|
||||
"""内切圆**之外**的像素必须全透明 —— 头像版是"圆即底板",方版被圆裁掉的是底板四角。
|
||||
⚠ 这条**不是**"咬字"判据:实测两版白字最远极径都在内切圆内(余量 8.0% / 10.3%),
|
||||
它判的是"这枚圆是被设计的,还是被裁出来的"。"""
|
||||
im = Image.open(path).convert("RGBA")
|
||||
w, h = im.size
|
||||
cx = cy = (w - 1) / 2.0
|
||||
r = w / 2.0
|
||||
px = im.load()
|
||||
viol = 0
|
||||
for y in range(h):
|
||||
dy = y - cy
|
||||
for x in range(w):
|
||||
dx = x - cx
|
||||
if dx * dx + dy * dy > (r + 1.0) ** 2 and px[x, y][3] > ALPHA_EDGE:
|
||||
viol += 1
|
||||
total = w * h
|
||||
if viol:
|
||||
msg = f"{label}: 内切圆外残留 {viol} 个不透明像素({100.0*viol/total:.2f}%)⇒ 圆裁会切掉底板四角,方版语义丢失"
|
||||
if must_fail:
|
||||
expected.append("B 圆角方版负对照: " + msg)
|
||||
ok("预期红(负对照被抓):" + msg)
|
||||
else:
|
||||
bad(msg)
|
||||
else:
|
||||
msg = f"{label}: 圆外零残留,圆即底板"
|
||||
(bad if must_fail else ok)(f"负对照未被抓 ⇒ B 条无约束力:{msg}" if must_fail else msg)
|
||||
|
||||
|
||||
def check_plate(path, label, must_fail=False):
|
||||
"""must_fail=True 用于负对照:判红是**预期红**,登记进 expected 而不是计进失败数
|
||||
(否则"闸抓得越准,退出码越红",正是记忆里那条退出码分档的反例)。"""
|
||||
mask, w, h, px = ink_mask(Image.open(path))
|
||||
bb = bbox(mask, w, h)
|
||||
if not bb:
|
||||
(bad if not must_fail else ok)(f"{label}: 一个墨像素都没有")
|
||||
return
|
||||
x0, y0, x1, y1 = bb
|
||||
l, r, t, b = x0, w - 1 - x1, y0, h - 1 - y1
|
||||
msg = f"{label}: 墨 {x1-x0+1}x{y1-y0+1} 左右差 {l-r}、上下差 {t-b}"
|
||||
if max(l, r) >= w or max(t, b) >= h:
|
||||
(ok if must_fail else bad)("预期红:墨越出板外 —— " + msg if must_fail else "墨越出板外 —— " + msg)
|
||||
return
|
||||
if abs(l - r) > 1 or abs(t - b) > 1:
|
||||
if must_fail:
|
||||
expected.append("E 平移负对照: " + msg)
|
||||
ok("预期红(负对照被抓):" + msg)
|
||||
else:
|
||||
bad("未居中 —— " + msg)
|
||||
else:
|
||||
if must_fail:
|
||||
bad(f"负对照未被抓 ⇒ E 条无约束力:{msg}")
|
||||
else:
|
||||
ok("居中 —— " + msg)
|
||||
|
||||
|
||||
def main():
|
||||
if not os.path.isdir(PKG):
|
||||
print(f"FATAL 资产包缺失:{PKG}")
|
||||
return 2
|
||||
import json
|
||||
|
||||
rp = os.path.join(PKG, "pack-report.json")
|
||||
if not os.path.exists(rp):
|
||||
print(f"FATAL 装配报告缺失:{rp} ⇒ 先跑 wecom-pack.cjs,别拿半套包过闸")
|
||||
return 2
|
||||
report = json.load(open(rp, encoding="utf-8"))
|
||||
files = sorted(f for f in os.listdir(PKG) if f.endswith(".png"))
|
||||
if len(files) < 14:
|
||||
print(f"FATAL 只找到 {len(files)} 张 PNG,少于 14 ⇒ 判据覆盖面不足")
|
||||
return 2
|
||||
print(f"[A] IHDR 尺寸必须等于文件名声明({len(files)} 张)")
|
||||
for f in files:
|
||||
want = name_size(f)
|
||||
got = Image.open(os.path.join(PKG, f)).size
|
||||
(ok if got == want else bad)(f"{f}: 声明 {want[0]}x{want[1]} 实测 {got[0]}x{got[1]}")
|
||||
|
||||
print("\n[A2] 装配报告登记的每张必须真在盘上(防「备好但从未跑成」)")
|
||||
declared, present = set(report.get("files", {})), set(files)
|
||||
missing, extra = sorted(declared - present), sorted(present - declared)
|
||||
(ok if not missing else bad)(f"登记 {len(declared)} 张,盘上缺 {len(missing)} 张" + "".join(f" [{m}]" for m in missing))
|
||||
(ok if not extra else bad)(f"盘上未登记 {len(extra)} 张" + "".join(f" [{e}]" for e in extra))
|
||||
|
||||
print("\n[B] 头像:圆即底板(内切圆外不许有任何不透明像素)")
|
||||
for f in files:
|
||||
if f.startswith("wecom-avatar-"):
|
||||
check_circle_lossless(os.path.join(PKG, f), f)
|
||||
print(" —— 负对照(现网圆角方版,必须被判红)")
|
||||
check_circle_lossless(os.path.join(HERE, "assets-delivery", "icon-512x512.png"), "icon-512x512.png", must_fail=True)
|
||||
|
||||
print("\n[C] 头像:中心是朱砂地(白文印的底不能丢)")
|
||||
for f in files:
|
||||
if f.startswith("wecom-avatar-"):
|
||||
im = Image.open(os.path.join(PKG, f)).convert("RGBA")
|
||||
c = im.load()[im.size[0] // 2, im.size[1] // 2]
|
||||
(ok if is_red(c) else bad)(f"{f}: 中心像素 {c[:3]}")
|
||||
|
||||
print("\n[D] 头像:512 与 144 两档的朱砂占比必须同格(容差按抗锯齿的 1/尺寸律给,不假装它是 0)")
|
||||
for kind in ("full", "ring2"):
|
||||
ratios = {}
|
||||
for px_ in (512, 144):
|
||||
p = os.path.join(PKG, f"wecom-avatar-{kind}-{px_}.png")
|
||||
if os.path.exists(p):
|
||||
ratios[px_] = red_ratio(Image.open(p))
|
||||
if len(ratios) == 2:
|
||||
d = abs(ratios[512] - ratios[144])
|
||||
(ok if d <= 3.0 else bad)(f"{kind}: 512 占 {ratios[512]:.2f}% / 144 占 {ratios[144]:.2f}% 差 {d:.2f}pt(闸 3.0)")
|
||||
print(" —— 负对照(把圆面缩 30%,模拟被咬/缩水,必须被抓)")
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
im = Image.open(os.path.join(PKG, "wecom-avatar-full-512.png")).convert("RGBA")
|
||||
small = im.resize((358, 358), Image.LANCZOS)
|
||||
canvas = Image.new("RGBA", (512, 512), (0, 0, 0, 0))
|
||||
canvas.paste(small, (77, 77), small)
|
||||
p2 = os.path.join(td, "wecom-avatar-shrunk-512.png")
|
||||
canvas.save(p2)
|
||||
base = red_ratio(Image.open(os.path.join(PKG, "wecom-avatar-full-512.png")))
|
||||
shrunk = red_ratio(Image.open(p2))
|
||||
d = abs(base - shrunk)
|
||||
(ok if d > 3.0 else bad)(f"负对照缩水后占比 {base:.2f}%→{shrunk:.2f}% 差 {d:.2f}pt ⇒ " + ("被抓" if d > 3.0 else "未被抓 ⇒ D 条对'面变小'不敏感"))
|
||||
|
||||
print("\n[E] 企业logo 板:居中 + 尺寸")
|
||||
for f in files:
|
||||
if f.startswith("wecom-logo-"):
|
||||
check_plate(os.path.join(PKG, f), f)
|
||||
print(" —— 负对照(故意平移 6px,必须被判红)")
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
src = os.path.join(PKG, "wecom-logo-stacked-702x180-white.png")
|
||||
im = Image.open(src).convert("RGBA")
|
||||
canvas = Image.new("RGBA", im.size, (255, 255, 255, 255))
|
||||
canvas.paste(im.crop((6, 0, im.size[0], im.size[1])), (0, 0))
|
||||
shifted = os.path.join(td, "wecom-logo-shifted-702x180-white.png")
|
||||
canvas.save(shifted)
|
||||
check_plate(shifted, "shifted-6px(负对照)", must_fail=True)
|
||||
|
||||
print("\n[F] 白底板:朱砂面积 —— 有红的版必须落在 0.1%–10%(R6 面积律,两端都要断);"
|
||||
"\n 源字标本身不含红的版(name 只走名、不含号 ⇒ 无 A 可加彩)断言恰为 0,不硬要它出红")
|
||||
src_red = {}
|
||||
for f, meta in report.get("files", {}).items():
|
||||
s = os.path.join(HERE, meta.get("source", ""))
|
||||
src_red[f] = os.path.exists(s) and 'fill="#C41E3A"' in open(s, encoding="utf-8").read()
|
||||
for f in files:
|
||||
if f.endswith("-white.png"):
|
||||
ratio = red_ratio(Image.open(os.path.join(PKG, f)))
|
||||
if src_red.get(f):
|
||||
(ok if 0.1 <= ratio <= 10.0 else bad)(f"{f}: 朱砂 {ratio:.2f}%(源含红)")
|
||||
else:
|
||||
(ok if ratio == 0.0 else bad)(f"{f}: 朱砂 {ratio:.2f}%(源不含红 ⇒ 期望恰 0)")
|
||||
print(" —— 负对照(把红涂满整板,必须被判红)")
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
im = Image.open(os.path.join(PKG, "wecom-logo-stacked-702x180-white.png")).convert("RGBA")
|
||||
px = im.load()
|
||||
for y in range(im.size[1]):
|
||||
for x in range(im.size[0]):
|
||||
if px[x, y][3] > ALPHA_EDGE and not is_red(px[x, y]):
|
||||
px[x, y] = (RED[0], RED[1], RED[2], 255)
|
||||
p2 = os.path.join(td, "wecom-logo-allred-702x180-white.png")
|
||||
im.save(p2)
|
||||
ratio = red_ratio(Image.open(p2))
|
||||
caught = not (0.1 <= ratio <= 10.0)
|
||||
(ok if caught else bad)(f"负对照全红 {ratio:.2f}% ⇒ " + ("被抓" if caught else "未被抓 ⇒ F 条无约束力"))
|
||||
|
||||
print("\n[G] 反白版:0 朱砂(裁定「反白不加彩也不加粗」)")
|
||||
for f in files:
|
||||
if f.endswith("-reversed.png"):
|
||||
ratio = red_ratio(Image.open(os.path.join(PKG, f)))
|
||||
(ok if ratio == 0.0 else bad)(f"{f}: 朱砂 {ratio:.2f}%")
|
||||
print(" —— 负对照(给反白版塞一枚朱砂 A,必须被判红)")
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
im = Image.open(os.path.join(PKG, "wecom-logo-stacked-702x180-reversed.png")).convert("RGBA")
|
||||
px = im.load()
|
||||
n = 0
|
||||
for y in range(im.size[1]):
|
||||
for x in range(im.size[0]):
|
||||
if px[x, y][3] > 128 and n < 400:
|
||||
px[x, y] = (RED[0], RED[1], RED[2], 255)
|
||||
n += 1
|
||||
p2 = os.path.join(td, "wecom-logo-redstain-702x180-reversed.png")
|
||||
im.save(p2)
|
||||
ratio = red_ratio(Image.open(p2))
|
||||
(ok if ratio > 0 else bad)(f"负对照染色 {ratio:.3f}% ⇒ " + ("被抓" if ratio > 0 else "未被抓 ⇒ G 条无约束力"))
|
||||
|
||||
print("\n[H] 透明墨色版:不许出现纯白像素(底板没剥干净会留白块)")
|
||||
for f in files:
|
||||
if f.endswith("-transparent.png"):
|
||||
im = Image.open(os.path.join(PKG, f)).convert("RGBA")
|
||||
px = im.load()
|
||||
w, h = im.size
|
||||
n = sum(
|
||||
1
|
||||
for y in range(h)
|
||||
for x in range(w)
|
||||
if px[x, y][3] > 250 and px[x, y][0] >= 250 and px[x, y][1] >= 250 and px[x, y][2] >= 250
|
||||
)
|
||||
(ok if n == 0 else bad)(f"{f}: 纯白不透明像素 {n}")
|
||||
|
||||
# 预期红必须有条数下限:一条都没有 = 负对照根本没跑成,那上面所有"ok"都失去自证
|
||||
(ok if len(expected) >= 2 else bad)(f"预期红登记 {len(expected)} 条(负对照至少 2 条:B 圆角方版、E 平移)")
|
||||
print("\n预期红明细(负对照,不计失败):")
|
||||
for m in expected:
|
||||
print(" 预期红:", m)
|
||||
print(f"\n{'='*58}\n判红 {len(fails)} 项 / 通过 {len(oks)} 项")
|
||||
for m in fails:
|
||||
print(" RED:", m)
|
||||
return 1 if fails else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
sys.exit(main())
|
||||
except SystemExit:
|
||||
raise
|
||||
except Exception:
|
||||
import traceback
|
||||
|
||||
traceback.print_exc()
|
||||
print("EXIT=2 门禁自身崩溃(与判红不是同一件事,别混)")
|
||||
sys.exit(2)
|
||||
@@ -0,0 +1,184 @@
|
||||
// 企业微信资产包(第五十二刀)
|
||||
// 两类载体,两套判据:
|
||||
// 头像 —— 企业微信显示为圆形裁切 ⇒ 必须为圆设计(avatar-standard / avatar-ceremonial 已是圆面)
|
||||
// 企业logo —— 管理后台固定板 702×180(口径为二手转述,见 WECOM-MANIFEST.md 的存疑条)
|
||||
// 栅格化用仓库自带的 sharp;尺寸一律由 viewBox 反推 density,不靠"看着调"。
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const sharp = require("sharp");
|
||||
|
||||
const HERE = __dirname;
|
||||
const REPO = path.dirname(path.dirname(HERE));
|
||||
const D = path.join(HERE, "assets-delivery");
|
||||
const OUT = path.join(HERE, "assets-wecom");
|
||||
|
||||
const AVATARS = {
|
||||
full: path.join(D, "avatar-standard.svg"),
|
||||
ring2: path.join(D, "avatar-ceremonial.svg"),
|
||||
};
|
||||
const LOGOS = {
|
||||
stacked: { ink: path.join(REPO, "public/logo.svg"), reversed: path.join(REPO, "public/logo-white.svg") },
|
||||
name: { ink: path.join(D, "name-alone.svg"), reversed: path.join(D, "name-alone-reversed.svg") },
|
||||
};
|
||||
|
||||
const PLATE = { w: 702, h: 180 };
|
||||
const PAD = 0.86; // 留白版:板内四周各内缩 7% 板高(13px)后再装墨
|
||||
|
||||
function viewBox(file) {
|
||||
const m = /viewBox="([^"]+)"/.exec(fs.readFileSync(file, "utf8"));
|
||||
if (!m) throw new Error(`${path.basename(file)} 没有 viewBox`);
|
||||
const [, , w, h] = m[1].split(/\s+/).map(Number);
|
||||
if (!(w > 0 && h > 0)) throw new Error(`${path.basename(file)} viewBox 非法: ${m[1]}`);
|
||||
return { w, h };
|
||||
}
|
||||
|
||||
// 纯路径校验:交付件不许有 <text>,不许引外部字体
|
||||
// ⚠ 先剥 XML 注释 —— 这些文件的来源注释里就写着「现网那份用 <text>」,不剥会把判据读成自伤
|
||||
function assertPurePaths(file) {
|
||||
const s = fs.readFileSync(file, "utf8").replace(/<!--[\s\S]*?-->/g, "");
|
||||
if (/<text/.test(s)) throw new Error(`${path.basename(file)} 含 <text>`);
|
||||
if (/https?:\/\//.test(s.replace(/xmlns="[^"]*"/g, ""))) throw new Error(`${path.basename(file)} 含外链`);
|
||||
}
|
||||
|
||||
async function raster(svg, targetH) {
|
||||
const vb = viewBox(svg);
|
||||
const density = (72 * targetH) / vb.h; // 1 用户单位 = targetH/vb.h 设备像素
|
||||
// ⚠ sharp.resize(宽, 高):targetH 是**高**,别把它当宽传进去(上一版就是这么把墨块排成 180×384 的)
|
||||
return sharp(svg, { density }).resize(Math.round((targetH * vb.w) / vb.h), targetH, { fit: "fill" }).png().toBuffer();
|
||||
}
|
||||
|
||||
// 按**墨盒**居中,不按画布盒。实测这些字标的 viewBox 上下留了空盒:
|
||||
// name-alone 画布高 96 而墨只 66 单位,stacked 画布 119.82 而墨 100 上下各空 —— 不裁就直接偏心。
|
||||
async function trimInk(buf) {
|
||||
const { data, info } = await sharp(buf).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
|
||||
const { width: w, height: h } = info;
|
||||
let x0 = w, y0 = h, x1 = -1, y1 = -1;
|
||||
for (let y = 0; y < h; y++) {
|
||||
for (let x = 0; x < w; x++) {
|
||||
if (data[(y * w + x) * 4 + 3] > 8) {
|
||||
if (x < x0) x0 = x;
|
||||
if (x > x1) x1 = x;
|
||||
if (y < y0) y0 = y;
|
||||
if (y > y1) y1 = y;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (x1 < x0) throw new Error("一个不透明像素都没有");
|
||||
const meta = await sharp(buf).metadata();
|
||||
const slack = { top: y0, bottom: meta.height - 1 - y1, left: x0, right: meta.width - 1 - x1 };
|
||||
const cropped = await sharp(buf).extract({ left: x0, top: y0, width: x1 - x0 + 1, height: y1 - y0 + 1 }).png().toBuffer();
|
||||
return { buf: cropped, slack };
|
||||
}
|
||||
|
||||
// 先高倍栅格 + 裁墨,再把**墨盒**装进板内最大缩放 —— 两个理由:
|
||||
// ① 这些字标的 viewBox 上下带空盒(实测 stacked 墨只占画布高 73%、name 52%),按画布排等于缩得不够;
|
||||
// ② name 的墨宽高比实测 4.50,比 702×180 的板(3.90)还扁 ⇒ 它只能按**宽**限死,按高排必溢出。
|
||||
async function inkFit(svg, boxW, boxH) {
|
||||
const probe = 720;
|
||||
const { buf: trimmed } = await trimInk(await raster(svg, probe));
|
||||
const m = await sharp(trimmed).metadata();
|
||||
const sW = boxW / m.width;
|
||||
const sH = boxH / m.height;
|
||||
const s = Math.min(sW, sH);
|
||||
const w = Math.round(m.width * s);
|
||||
const h = Math.round(m.height * s);
|
||||
const buf = await sharp(trimmed).resize(w, h, { fit: "fill" }).png().toBuffer();
|
||||
return { buf, limit: sW < sH ? "width" : "height", inkOverCanvas: m.height / probe, aspect: m.width / m.height };
|
||||
}
|
||||
|
||||
async function plate(inkBuf, bg) {
|
||||
const m = await sharp(inkBuf).metadata();
|
||||
const left = Math.round((PLATE.w - m.width) / 2);
|
||||
const top = Math.round((PLATE.h - m.height) / 2);
|
||||
const buf = await sharp({ create: { width: PLATE.w, height: PLATE.h, channels: 4, background: bg } })
|
||||
.composite([{ input: inkBuf, left, top }])
|
||||
.png()
|
||||
.toBuffer();
|
||||
return { buf, ink: { w: m.width, h: m.height }, pad: { l: left, r: PLATE.w - m.width - left, t: top, b: PLATE.h - m.height - top } };
|
||||
}
|
||||
|
||||
const WHITE_BG = { r: 255, g: 255, b: 255, alpha: 1 };
|
||||
const CLEAR = { r: 0, g: 0, b: 0, alpha: 0 };
|
||||
|
||||
(async () => {
|
||||
fs.mkdirSync(OUT, { recursive: true });
|
||||
const report = { plate: PLATE, pad: PAD, files: {} };
|
||||
|
||||
for (const [kind, svg] of Object.entries(AVATARS)) {
|
||||
assertPurePaths(svg);
|
||||
for (const px of [512, 144]) {
|
||||
const name = `wecom-avatar-${kind}-${px}.png`;
|
||||
const buf = await raster(svg, px);
|
||||
await sharp(buf).resize(px, px, { fit: "fill" }).png().toFile(path.join(OUT, name));
|
||||
report.files[name] = { source: path.relative(HERE, svg), size: `${px}x${px}`, kind: "avatar" };
|
||||
}
|
||||
}
|
||||
|
||||
for (const [variant, src] of Object.entries(LOGOS)) {
|
||||
assertPurePaths(src.ink);
|
||||
assertPurePaths(src.reversed);
|
||||
const padPx = Math.round(PLATE.h * ((1 - PAD) / 2));
|
||||
const boxes = { full: { w: PLATE.w, h: PLATE.h }, pad: { w: PLATE.w - 2 * padPx, h: PLATE.h - 2 * padPx } };
|
||||
for (const [fit, box] of Object.entries(boxes)) {
|
||||
const suffix = fit === "full" ? "" : "-pad";
|
||||
const jobs = [
|
||||
[`wecom-logo-${variant}${suffix}-${PLATE.w}x${PLATE.h}-white.png`, src.ink, WHITE_BG],
|
||||
[`wecom-logo-${variant}${suffix}-${PLATE.w}x${PLATE.h}-transparent.png`, src.ink, CLEAR],
|
||||
[`wecom-logo-${variant}${suffix}-${PLATE.w}x${PLATE.h}-reversed.png`, src.reversed, CLEAR],
|
||||
];
|
||||
for (const [name, svg, bg] of jobs) {
|
||||
const { buf: inkBuf, limit, aspect, inkOverCanvas } = await inkFit(svg, box.w, box.h);
|
||||
const { buf, ink, pad } = await plate(inkBuf, bg);
|
||||
await fs.writeFileSync(path.join(OUT, name), buf);
|
||||
report.files[name] = {
|
||||
source: path.relative(HERE, svg),
|
||||
size: `${PLATE.w}x${PLATE.h}`,
|
||||
kind: "plate",
|
||||
ink,
|
||||
pad,
|
||||
limit,
|
||||
inkAspect: Number(aspect.toFixed(3)),
|
||||
inkOverCanvas: Number(inkOverCanvas.toFixed(3)),
|
||||
};
|
||||
}
|
||||
if (fit === "full") {
|
||||
// @2x 高清备份(只出白底板,上传框按 702×180 用)
|
||||
const big = { w: PLATE.w * 2, h: PLATE.h * 2 };
|
||||
const { buf: trimmed } = await inkFit(src.ink, big.w, big.h);
|
||||
const m = await sharp(trimmed).metadata();
|
||||
const name = `wecom-logo-${variant}-2x-${big.w}x${big.h}-white.png`;
|
||||
const left = Math.floor((big.w - m.width) / 2);
|
||||
const top = Math.floor((big.h - m.height) / 2);
|
||||
const buf = await sharp({ create: { width: big.w, height: big.h, channels: 4, background: WHITE_BG } })
|
||||
.composite([{ input: trimmed, left, top }])
|
||||
.png()
|
||||
.toBuffer();
|
||||
await fs.writeFileSync(path.join(OUT, name), buf);
|
||||
report.files[name] = {
|
||||
source: path.relative(HERE, src.ink),
|
||||
size: `${big.w}x${big.h}`,
|
||||
kind: "plate",
|
||||
ink: { w: m.width, h: m.height },
|
||||
pad: { l: left, r: big.w - m.width - left, t: top, b: big.h - m.height - top },
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
report.avatars = Object.keys(AVATARS);
|
||||
fs.writeFileSync(path.join(OUT, "pack-report.json"), JSON.stringify(report, null, 2));
|
||||
const names = Object.keys(report.files).sort();
|
||||
console.log(`生成 ${names.length} 张 → assets-wecom/`);
|
||||
for (const n of names) {
|
||||
const f = report.files[n];
|
||||
const kb = (fs.statSync(path.join(OUT, n)).size / 1024).toFixed(1);
|
||||
console.log(
|
||||
` ${n} ${f.size} ${kb}KB` +
|
||||
(f.ink ? ` 墨${f.ink.w}x${f.ink.h} 留白 l${f.pad.l}/${f.pad.r} t${f.pad.t}/${f.pad.b}` : "") +
|
||||
(f.inkOverCanvas ? ` 墨/画布 ${f.inkOverCanvas} 墨宽高比 ${f.inkAspect}` : "")+(f.limit ? ` 限${f.limit}` : "")
|
||||
);
|
||||
}
|
||||
})().catch((e) => {
|
||||
console.error("FAIL", e.message);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,936 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Hero 内容方案对照 · 数据驱动决策</title>
|
||||
<style>
|
||||
:root { --ink:#0b0a08; --line:rgba(255,255,255,.12); --amber:#ffb457; }
|
||||
* { box-sizing:border-box; }
|
||||
html, body { height:100%; margin:0; }
|
||||
body {
|
||||
background:var(--ink); color:#fff; overflow:hidden;
|
||||
font-family:-apple-system,BlinkMacSystemFont,'PingFang SC','Helvetica Neue',Arial,sans-serif;
|
||||
-webkit-font-smoothing:antialiased;
|
||||
}
|
||||
#host { position:fixed; inset:0; }
|
||||
#host canvas { display:block; width:100%; height:100%; }
|
||||
#veil { position:fixed; inset:0; background:#07080a; opacity:0; pointer-events:none; }
|
||||
#vignette { position:fixed; inset:0; pointer-events:none;
|
||||
background:radial-gradient(120% 95% at 50% 45%,transparent 48%,rgba(0,0,0,.62) 100%); }
|
||||
|
||||
/* 文案层(默认关,用来最后判断合成后可读性) */
|
||||
#scrim { position:fixed; inset:0; pointer-events:none; opacity:0;
|
||||
background:linear-gradient(90deg,rgba(11,10,8,.94) 0%,rgba(11,10,8,.9) 32%,rgba(11,10,8,.62) 55%,rgba(11,10,8,.16) 100%); }
|
||||
#copy { position:fixed; left:6vw; top:50%; transform:translateY(-50%); width:min(36rem,44vw); pointer-events:none; opacity:0; transition:opacity .2s; }
|
||||
#copy .eyebrow { display:flex; align-items:center; gap:12px; }
|
||||
#copy .eyebrow i { display:block; width:32px; height:1px; background:#c41e3a; }
|
||||
#copy .eyebrow span { font-size:13px; font-weight:500; letter-spacing:.15em; color:rgba(255,255,255,.75); }
|
||||
#copy h1 { margin:24px 0 0; font-size:clamp(26px,2.9vw,42px); line-height:1.14; font-weight:700; }
|
||||
#copy p { margin:16px 0 0; font-size:14.5px; line-height:1.72; color:rgba(255,255,255,.75); max-width:30rem; }
|
||||
#copy .ctas { display:flex; gap:16px; margin-top:28px; }
|
||||
#copy .cta { padding:12px 24px; font-size:14px; font-weight:600; border-radius:2px; }
|
||||
#copy .cta.primary { background:#c41e3a; }
|
||||
#copy .cta.secondary { border:1px solid rgba(255,255,255,.4); }
|
||||
|
||||
#caption { position:fixed; left:6vw; bottom:24px; display:flex; align-items:center; gap:12px; pointer-events:none; font-size:13px; }
|
||||
#caption i { display:block; width:24px; height:1px; background:rgba(255,255,255,.3); }
|
||||
#caption b { font-weight:500; letter-spacing:.08em; color:rgba(255,255,255,.7); }
|
||||
#caption span { color:rgba(255,255,255,.5); }
|
||||
|
||||
#panel {
|
||||
position:fixed; top:16px; right:16px; width:330px; padding:15px 15px 13px;
|
||||
background:rgba(14,13,12,.9); border:1px solid var(--line); border-radius:4px;
|
||||
backdrop-filter:blur(14px); font-size:12px;
|
||||
}
|
||||
#panel h2 { margin:0 0 2px; font-size:12px; font-weight:600; letter-spacing:.06em; }
|
||||
#panel .sub { margin:0 0 11px; font-size:11px; line-height:1.6; color:rgba(255,255,255,.42); }
|
||||
.variants { display:grid; gap:5px; }
|
||||
.vbtn {
|
||||
display:block; width:100%; text-align:left; padding:7px 9px; cursor:pointer;
|
||||
background:transparent; border:1px solid rgba(255,255,255,.1); border-radius:3px;
|
||||
color:rgba(255,255,255,.72); font-size:12px; font-family:inherit; transition:120ms;
|
||||
}
|
||||
.vbtn:hover { border-color:rgba(255,255,255,.28); color:#fff; }
|
||||
.vbtn.on { border-color:rgba(255,255,255,.55); background:rgba(255,255,255,.07); color:#fff; }
|
||||
.vbtn em { display:block; font-style:normal; margin-top:3px; font-size:10.5px; line-height:1.5; color:rgba(255,255,255,.38); }
|
||||
.vbtn.on em { color:rgba(255,255,255,.55); }
|
||||
.vbtn .k { display:inline-block; margin-right:6px; color:rgba(255,255,255,.3); font-variant-numeric:tabular-nums; }
|
||||
.acts { display:flex; gap:5px; margin-top:11px; }
|
||||
.acts button { flex:1; padding:5px 0; cursor:pointer; font-size:10.5px; font-family:inherit;
|
||||
background:transparent; border:1px solid rgba(255,255,255,.1); border-radius:3px; color:rgba(255,255,255,.55); }
|
||||
.acts button:hover { border-color:rgba(255,255,255,.3); color:#fff; }
|
||||
.row { display:flex; gap:6px; margin-top:6px; }
|
||||
.row button { flex:1; padding:6px 0; cursor:pointer; font-size:11px; font-family:inherit;
|
||||
background:transparent; border:1px solid rgba(255,255,255,.1); border-radius:3px; color:rgba(255,255,255,.6); }
|
||||
.row button:hover { border-color:rgba(255,255,255,.3); color:#fff; }
|
||||
#tl { width:100%; margin:11px 0 3px; accent-color:#c41e3a; }
|
||||
.ticks { display:flex; justify-content:space-between; font-size:10px; color:rgba(255,255,255,.28); font-variant-numeric:tabular-nums; }
|
||||
#readout { margin-top:9px; padding-top:9px; border-top:1px solid rgba(255,255,255,.08);
|
||||
display:flex; justify-content:space-between; font-size:10.5px; color:rgba(255,255,255,.42); font-variant-numeric:tabular-nums; }
|
||||
#readout b { color:var(--amber); font-weight:500; }
|
||||
#hint { position:fixed; left:50%; bottom:24px; transform:translateX(-50%); font-size:11px; color:rgba(255,255,255,.25); pointer-events:none; }
|
||||
#err { position:fixed; inset:0; display:none; place-items:center; text-align:center; padding:40px; font-size:13px; color:#ff9b9b; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="host"></div>
|
||||
<div id="vignette"></div>
|
||||
<div id="veil"></div>
|
||||
<div id="scrim"></div>
|
||||
|
||||
<div id="copy">
|
||||
<div class="eyebrow"><i></i><span>企业数字化转型</span></div>
|
||||
<h1>让每一家企业都拥有数据驱动的决策能力</h1>
|
||||
<p>专业核心团队,以结果导向的服务理念,做中国企业数字化转型的同行者与成长伙伴,从战略诊断到系统落地、再到持续陪跑。</p>
|
||||
<div class="ctas"><span class="cta primary">预约咨询</span><span class="cta secondary">看行业实践</span></div>
|
||||
</div>
|
||||
|
||||
<div id="caption"><i></i><b id="cap-label">01 噪声</b><span id="cap-detail">数据尚未被理解</span></div>
|
||||
|
||||
<div id="panel">
|
||||
<h2>Hero 内容方案对照</h2>
|
||||
<p class="sub">三拍等长(16 / 13 / 13s + 压黑),只换「动画讲什么」。</p>
|
||||
<div class="variants" id="variants"></div>
|
||||
<div class="acts">
|
||||
<button data-t="8000">拍一</button>
|
||||
<button data-t="22000">拍二</button>
|
||||
<button data-t="40500">拍三·落定</button>
|
||||
</div>
|
||||
<input id="tl" type="range" min="0" max="43260" step="10" value="0" />
|
||||
<div class="ticks"><span>0s</span><span>16.4s</span><span>29.8s</span><span>42.8s</span></div>
|
||||
<div class="row">
|
||||
<button id="btn-play">暂停</button>
|
||||
<button id="btn-copy">叠文案层</button>
|
||||
</div>
|
||||
<div id="readout"><span>拍 <b id="ro-act">1</b></span><span>k <b id="ro-k">0.00</b></span><span>t <b id="ro-t">0.0s</b></span></div>
|
||||
</div>
|
||||
|
||||
<div id="hint">键盘 1–3 切方案 · 空格播放/暂停</div>
|
||||
<div id="err"></div>
|
||||
|
||||
<script type="importmap">
|
||||
{ "imports": {
|
||||
"three": "./vendor/three.module.js",
|
||||
"three/addons/": "./vendor/addons/"
|
||||
} }
|
||||
</script>
|
||||
|
||||
<script type="module">
|
||||
import * as THREE from 'three';
|
||||
import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
|
||||
import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
|
||||
import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
|
||||
import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';
|
||||
|
||||
const ACTS = [16000, 13000, 13000];
|
||||
const DIP = 420;
|
||||
const CYCLE = ACTS.reduce((a, b) => a + b + DIP, 0);
|
||||
const SETTLE = 0.62;
|
||||
const T2 = ACTS[0] + DIP;
|
||||
const T3 = T2 + ACTS[1] + DIP;
|
||||
|
||||
const CASE_LABEL = {
|
||||
void: [
|
||||
{ label:'01 噪声', detail:'数据尚未被理解' },
|
||||
{ label:'02 增长', detail:'曲线被逐列画出' },
|
||||
{ label:'03 判断', detail:'一点越过判据' },
|
||||
],
|
||||
map: [
|
||||
{ label:'01 流量', detail:'路网正常运转' },
|
||||
{ label:'02 评估', detail:'三条替代被比较' },
|
||||
{ label:'03 改道', detail:'一条新路由生效' },
|
||||
],
|
||||
room: [
|
||||
{ label:'01 数据成形', detail:'散点归成分布' },
|
||||
{ label:'02 三案并置', detail:'候选同框比较' },
|
||||
{ label:'03 选定', detail:'一个方案被点中' },
|
||||
],
|
||||
};
|
||||
|
||||
const CASES = [
|
||||
{ id:'void', name:'1 抽象数据场', desc:'噪声散点 → 从左向右画出上升曲线 → 越过判据的那一点亮起。行业中立、无人、无数字。' },
|
||||
{ id:'map', name:'2 业务场景剖面', desc:'物流路网:某段拥塞 → 三条候选被评估 → 改道执行 → 流量恢复。可指认,但锁定行业。' },
|
||||
{ id:'room', name:'4 决策现场', desc:'人与大屏:数据成形 → 三个方案并置 → 一个被选中。人物是剪影代理,非成品。' },
|
||||
];
|
||||
|
||||
const host = document.getElementById('host');
|
||||
const veil = document.getElementById('veil');
|
||||
const errBox = document.getElementById('err');
|
||||
|
||||
let renderer;
|
||||
try {
|
||||
renderer = new THREE.WebGLRenderer({ antialias:true, alpha:false, powerPreference:'high-performance' });
|
||||
} catch (e) {
|
||||
errBox.style.display='grid'; errBox.textContent='WebGL 不可用:'+e.message; throw e;
|
||||
}
|
||||
renderer.setPixelRatio(Math.min(window.devicePixelRatio||1, 1.5));
|
||||
renderer.setSize(host.clientWidth, host.clientHeight, false);
|
||||
renderer.toneMapping = THREE.ACESFilmicToneMapping;
|
||||
renderer.toneMappingExposure = 1.25;
|
||||
renderer.outputColorSpace = THREE.SRGBColorSpace;
|
||||
host.appendChild(renderer.domElement);
|
||||
|
||||
const smoothstep = (x,a,b) => { const t=Math.min(1,Math.max(0,(x-a)/(b-a))); return t*t*(3-2*t); };
|
||||
const lerp = (a,b,t) => a + (b-a)*t;
|
||||
const BG = 0x07080a;
|
||||
|
||||
/* ═════════════ 1 · 抽象数据场 ═════════════ */
|
||||
function makeVoid() {
|
||||
const scene = new THREE.Scene();
|
||||
scene.background = new THREE.Color(BG);
|
||||
scene.fog = new THREE.Fog(BG, 22, 68);
|
||||
const camera = new THREE.PerspectiveCamera(38, 16/9, .1, 400);
|
||||
|
||||
/* 光斑贴图 —— 方点是"粗糙感"的第一来源。点必须是柔光,不是像素块 */
|
||||
const spriteTex = (() => {
|
||||
const S=128, cv=document.createElement('canvas'); cv.width=cv.height=S;
|
||||
const g=cv.getContext('2d');
|
||||
const rg=g.createRadialGradient(S/2,S/2,0,S/2,S/2,S/2);
|
||||
rg.addColorStop(0,'rgba(255,255,255,1)');
|
||||
rg.addColorStop(.20,'rgba(255,255,255,.66)');
|
||||
rg.addColorStop(.52,'rgba(255,255,255,.15)');
|
||||
rg.addColorStop(1,'rgba(255,255,255,0)');
|
||||
g.fillStyle=rg; g.fillRect(0,0,S,S);
|
||||
const t=new THREE.CanvasTexture(cv); t.colorSpace=THREE.SRGBColorSpace; return t;
|
||||
})();
|
||||
const softPlane = (size, inner, outer, w, h) => {
|
||||
const cv=document.createElement('canvas'); cv.width=cv.height=size;
|
||||
const g=cv.getContext('2d');
|
||||
const rg=g.createRadialGradient(size/2,size/2,0,size/2,size/2,size/2);
|
||||
rg.addColorStop(0,inner); rg.addColorStop(.45,outer); rg.addColorStop(1,'rgba(0,0,0,0)');
|
||||
g.fillStyle=rg; g.fillRect(0,0,size,size);
|
||||
const t=new THREE.CanvasTexture(cv); t.colorSpace=THREE.SRGBColorSpace;
|
||||
return new THREE.MeshBasicMaterial({ map:t, transparent:true, opacity:0,
|
||||
blending:THREE.AdditiveBlending, depthWrite:false, toneMapped:false });
|
||||
};
|
||||
|
||||
/* 背景:纯黑虚空会把一切压成剪贴画。垫一层几乎看不见的冷雾光,空间才成立 */
|
||||
const bgMat = softPlane(256, 'rgba(28,62,104,.30)', 'rgba(16,34,58,.10)');
|
||||
const bgPlane = new THREE.Mesh(new THREE.PlaneGeometry(58, 34), bgMat);
|
||||
bgPlane.position.set(-2, 3.4, -20);
|
||||
scene.add(bgPlane);
|
||||
|
||||
/* 分布形状:对数正态长尾 —— 单一峰 + 右侧拖尾,是一眼可认的「真实分布」。
|
||||
原来的正弦堆叠像随机柱状图,读不出「数据」只读出「图表」。 */
|
||||
const BARS = 42, LAYERS = 132, N = BARS*LAYERS;
|
||||
const BAR_STEP = 0.112; // 42 × 0.112 ≈ 4.6m 宽:让开左侧文字块与右侧面板
|
||||
/* 分布形状 = **增长态势**:单调上升 + 轻微起伏。
|
||||
完全单调会像一根斜坡,加 2~3% 起伏才像真实数据;钟形分布则不表达"增长"。 */
|
||||
const HMAX = 2.9;
|
||||
const BARS_N = BARS;
|
||||
const barH = [];
|
||||
for (let b=0;b<BARS_N;b++) {
|
||||
const tt = b/(BARS_N-1);
|
||||
const base = Math.pow(tt, 1.62); // 前段缓、后段陡 = 增长的形状
|
||||
const ripple = 1 + 0.028*Math.sin(b*0.9) + 0.016*Math.cos(b*2.7);
|
||||
barH.push(0.22 + HMAX*base*ripple);
|
||||
}
|
||||
/* 判据线压在中段偏上 ⇒ 曲线在中右部越过它,结论点正好落在文字块与右侧面板之间 */
|
||||
const thrY = 0.22 + HMAX*0.58;
|
||||
const CROSS = Math.max(0, barH.findIndex(v => v >= thrY));
|
||||
const bxOf = (b) => (b-(BARS-1)/2)*BAR_STEP;
|
||||
|
||||
const noiseP = new Float32Array(N*3);
|
||||
const gridP = new Float32Array(N*3);
|
||||
const pos = new Float32Array(N*3);
|
||||
const col = new Float32Array(N*3);
|
||||
const phase = new Float32Array(N*2);
|
||||
for (let i=0;i<N;i++) {
|
||||
const b = i % BARS, l = Math.floor(i / BARS);
|
||||
const jx = (Math.random()-0.5) * BAR_STEP * 0.78;
|
||||
const jz = (Math.random()-0.5) * 0.62;
|
||||
noiseP[i*3] = (Math.random()-0.5)*9.4;
|
||||
noiseP[i*3+1] = Math.random()*3.6 + 0.2;
|
||||
noiseP[i*3+2] = (Math.random()-0.5)*5.6;
|
||||
gridP[i*3] = bxOf(b) + jx;
|
||||
gridP[i*3+1] = ((l+0.5)/LAYERS) * barH[b];
|
||||
gridP[i*3+2] = jz;
|
||||
pos[i*3]=noiseP[i*3]; pos[i*3+1]=noiseP[i*3+1]; pos[i*3+2]=noiseP[i*3+2];
|
||||
col[i*3]=0.10; col[i*3+1]=0.22; col[i*3+2]=0.46;
|
||||
phase[i*2] = Math.random()*Math.PI*2;
|
||||
phase[i*2+1] = Math.random()*Math.PI*2;
|
||||
}
|
||||
const geo = new THREE.BufferGeometry();
|
||||
geo.setAttribute('position', new THREE.BufferAttribute(pos, 3));
|
||||
geo.setAttribute('color', new THREE.BufferAttribute(col, 3));
|
||||
const dotMat = new THREE.PointsMaterial({
|
||||
size:0.092, sizeAttenuation:true, vertexColors:true, transparent:true,
|
||||
map:spriteTex, blending:THREE.AdditiveBlending, depthWrite:false, toneMapped:false, opacity:.95,
|
||||
});
|
||||
const pts = new THREE.Points(geo, dotMat);
|
||||
scene.add(pts);
|
||||
|
||||
/* 包络:柱顶连成一条平滑曲线(Catmull-Rom),再沿曲线铺一串更亮的小点 ——
|
||||
1px 折线是「Excel 图表」,一条发光曲线才是「被读出来的分布」 */
|
||||
const tops = [];
|
||||
for (let b=0;b<BARS;b++) tops.push(new THREE.Vector3(bxOf(b), barH[b], 0));
|
||||
const curve = new THREE.CatmullRomCurve3(tops);
|
||||
const CS = 420;
|
||||
const cPos = curve.getPoints(CS-1);
|
||||
const cArr = new Float32Array(CS*3), cCol = new Float32Array(CS*3);
|
||||
for (let i=0;i<CS;i++) {
|
||||
cArr[i*3]=cPos[i].x; cArr[i*3+1]=cPos[i].y; cArr[i*3+2]=cPos[i].z;
|
||||
const t = i/(CS-1);
|
||||
cCol[i*3]=0.55; cCol[i*3+1]=0.86; cCol[i*3+2]=1.0;
|
||||
// 两端渐隐
|
||||
const edge = Math.min(1, Math.min(t, 1-t)*7);
|
||||
cCol[i*3]*=edge; cCol[i*3+1]*=edge; cCol[i*3+2]*=edge;
|
||||
}
|
||||
const cGeo = new THREE.BufferGeometry();
|
||||
cGeo.setAttribute('position', new THREE.BufferAttribute(cArr,3));
|
||||
cGeo.setAttribute('color', new THREE.BufferAttribute(cCol,3));
|
||||
const cMat = new THREE.PointsMaterial({
|
||||
size:0.096, sizeAttenuation:true, vertexColors:true, transparent:true, opacity:0,
|
||||
map:spriteTex, blending:THREE.AdditiveBlending, depthWrite:false, toneMapped:false,
|
||||
});
|
||||
const envPts = new THREE.Points(cGeo, cMat);
|
||||
scene.add(envPts);
|
||||
|
||||
/* 每个柱顶对应的曲线高度:收束时点落到「曲线上」而不是折线上 */
|
||||
const curveY = (b) => {
|
||||
const idx = Math.round(b/(BARS-1) * (CS-1));
|
||||
return cArr[idx*3+1];
|
||||
};
|
||||
|
||||
/* 判据线:横向渐变(中间实、两端散)比一条白棒干净得多 */
|
||||
const thrTex = (() => {
|
||||
const W=256, H=16, cv=document.createElement('canvas'); cv.width=W; cv.height=H;
|
||||
const g=cv.getContext('2d');
|
||||
const lg=g.createLinearGradient(0,0,W,0);
|
||||
lg.addColorStop(0,'rgba(255,255,255,0)');
|
||||
lg.addColorStop(.18,'rgba(255,255,255,.55)');
|
||||
lg.addColorStop(.5,'rgba(255,255,255,1)');
|
||||
lg.addColorStop(.82,'rgba(255,255,255,.55)');
|
||||
lg.addColorStop(1,'rgba(255,255,255,0)');
|
||||
g.fillStyle=lg; g.fillRect(0,0,W,H);
|
||||
const t=new THREE.CanvasTexture(cv); t.colorSpace=THREE.SRGBColorSpace; return t;
|
||||
})();
|
||||
const thrMat = new THREE.MeshBasicMaterial({ map:thrTex, transparent:true, opacity:0,
|
||||
blending:THREE.AdditiveBlending, depthWrite:false, toneMapped:false });
|
||||
const thr = new THREE.Mesh(new THREE.PlaneGeometry(5.6, 0.032), thrMat);
|
||||
thr.position.set(0, thrY, 0);
|
||||
scene.add(thr);
|
||||
|
||||
/* 基线:没有基线,投影线就是一根悬空的线;有了基线,整幅才读成"一张图" */
|
||||
const baseMat = new THREE.MeshBasicMaterial({ color:0x9fd8ff, transparent:true, opacity:0,
|
||||
blending:THREE.AdditiveBlending, depthWrite:false, toneMapped:false });
|
||||
const baseLine = new THREE.Mesh(new THREE.PlaneGeometry(5.0, 0.010), baseMat);
|
||||
baseLine.position.set(0, 0.22, 0);
|
||||
scene.add(baseLine);
|
||||
|
||||
/* 结论标记:**不用"放射"**。光晕 + 扩散环读成爆炸特效,不像读数。
|
||||
改用图表注解语法:一个小实心点 + 一圈细目标环 + 一条垂到基线的投影线 + 判据线上的一小段高亮。 */
|
||||
/* 结论点必须精确落在「曲线与判据线的交点」上:按列取第一个越线柱会偏高半个柱宽,
|
||||
近景下一眼就能看出点和线没对上(实测) */
|
||||
let DOT_X = bxOf(CROSS);
|
||||
for (let b=1;b<BARS;b++) {
|
||||
const y0 = barH[b-1], y1 = barH[b];
|
||||
if (y0 < thrY && y1 >= thrY) {
|
||||
const t = (thrY - y0) / (y1 - y0);
|
||||
DOT_X = bxOf(b-1) + (bxOf(b) - bxOf(b-1)) * t;
|
||||
break;
|
||||
}
|
||||
}
|
||||
const DOT_Y = thrY;
|
||||
|
||||
const dotCoreMat = new THREE.MeshBasicMaterial({ color:0xffe0b4, toneMapped:false, transparent:true, opacity:0,
|
||||
blending:THREE.AdditiveBlending, depthWrite:false });
|
||||
const dotCore = new THREE.Mesh(new THREE.CircleGeometry(0.042, 24), dotCoreMat);
|
||||
dotCore.position.set(DOT_X, DOT_Y, 0);
|
||||
scene.add(dotCore);
|
||||
|
||||
const ringMat = new THREE.MeshBasicMaterial({ color:0xffb457, transparent:true, opacity:0,
|
||||
blending:THREE.AdditiveBlending, depthWrite:false, toneMapped:false });
|
||||
const ring = new THREE.Mesh(new THREE.RingGeometry(0.105, 0.118, 56), ringMat);
|
||||
ring.position.set(DOT_X, DOT_Y, 0);
|
||||
scene.add(ring);
|
||||
|
||||
/* 投影线:从结论点垂到基线 —— "读数"的标准注解,比任何光效都可信 */
|
||||
const dropMat = new THREE.MeshBasicMaterial({ color:0xffb457, transparent:true, opacity:0,
|
||||
blending:THREE.AdditiveBlending, depthWrite:false, toneMapped:false });
|
||||
const dropH = Math.max(0.05, DOT_Y - 0.22);
|
||||
const drop = new THREE.Mesh(new THREE.PlaneGeometry(0.006, 1), dropMat);
|
||||
drop.scale.y = dropH;
|
||||
drop.position.set(DOT_X, 0.22 + dropH/2, 0);
|
||||
scene.add(drop);
|
||||
|
||||
/* 判据线在交点处的一小段高亮:让"越过"有落点 */
|
||||
const tickMat = new THREE.MeshBasicMaterial({ color:0xffb457, transparent:true, opacity:0,
|
||||
blending:THREE.AdditiveBlending, depthWrite:false, toneMapped:false });
|
||||
const tick = new THREE.Mesh(new THREE.PlaneGeometry(0.46, 0.020), tickMat);
|
||||
tick.position.set(DOT_X, thrY, 0);
|
||||
scene.add(tick);
|
||||
|
||||
/* 地面冷光:让分布"落"在某个平面上,而不是漂在真空里 */
|
||||
const groundMat = softPlane(256, 'rgba(46,110,180,.34)', 'rgba(24,58,100,.12)');
|
||||
const ground = new THREE.Mesh(new THREE.PlaneGeometry(13, 9), groundMat);
|
||||
ground.rotation.x = -Math.PI/2;
|
||||
ground.position.set(0, -0.02, 0);
|
||||
scene.add(ground);
|
||||
|
||||
const grid = new THREE.GridHelper(22, 44, 0x1a2a3c, 0x101a26);
|
||||
grid.position.y = -0.01;
|
||||
grid.material.transparent = true; grid.material.opacity = 0;
|
||||
scene.add(grid);
|
||||
|
||||
/* 碎片:方向随机、互不相连的短线。让拍一读成「尚未被组织的数据」,
|
||||
而不是均匀星点 —— 均匀星点会读成星空,与数据无关 */
|
||||
const fragMat = new THREE.LineBasicMaterial({ color:0x2f5d92, transparent:true, opacity:.42, toneMapped:false });
|
||||
{
|
||||
const FN = 52;
|
||||
const fpos = new Float32Array(FN*6);
|
||||
for (let i=0;i<FN;i++) {
|
||||
const x=(Math.random()-0.5)*9.4, y=Math.random()*3.6+0.25, z=(Math.random()-0.5)*5.6;
|
||||
const a=Math.random()*Math.PI*2, L=0.22+Math.random()*0.62;
|
||||
fpos[i*6]=x; fpos[i*6+1]=y; fpos[i*6+2]=z;
|
||||
fpos[i*6+3]=x+Math.cos(a)*L; fpos[i*6+4]=y+Math.sin(a)*L*0.55; fpos[i*6+5]=z+Math.sin(a)*L;
|
||||
}
|
||||
const fg = new THREE.BufferGeometry();
|
||||
fg.setAttribute('position', new THREE.BufferAttribute(fpos,3));
|
||||
scene.add(new THREE.LineSegments(fg, fragMat));
|
||||
}
|
||||
|
||||
function update(t, act, k, dt) {
|
||||
const p = geo.attributes.position.array;
|
||||
const setCol = (r,g,b) => { for (let i=0;i<N;i++) { col[i*3]=r; col[i*3+1]=g; col[i*3+2]=b; } };
|
||||
|
||||
if (act === 0) {
|
||||
for (let i=0;i<N;i++) {
|
||||
const i3=i*3, ph=phase[i*2], ph2=phase[i*2+1];
|
||||
p[i3] = noiseP[i3] + Math.sin(t*0.00062 + ph)*0.34;
|
||||
p[i3+1] = noiseP[i3+1] + Math.sin(t*0.00094 + ph2)*0.22;
|
||||
p[i3+2] = noiseP[i3+2] + Math.cos(t*0.00071 + ph)*0.30;
|
||||
const v = 0.55 + 0.45*Math.sin(t*0.0016 + ph2);
|
||||
col[i3]=0.10+0.10*v; col[i3+1]=0.20+0.20*v; col[i3+2]=0.42+0.26*v;
|
||||
}
|
||||
cMat.opacity = 0; thrMat.opacity = 0; dotCoreMat.opacity = 0; ringMat.opacity = 0; dropMat.opacity = 0; tickMat.opacity = 0; baseMat.opacity = 0;
|
||||
grid.material.opacity = 0;
|
||||
groundMat.opacity = 0.10;
|
||||
bgMat.opacity = 0.75;
|
||||
} else if (act === 1) {
|
||||
const g = smoothstep(k, .1, .8);
|
||||
for (let i=0;i<N;i++) {
|
||||
const i3=i*3, ph=phase[i*2], ph2=phase[i*2+1], b=i % BARS;
|
||||
/* 按「列」延迟:从左到右一列一列落位 ⇒ 图是被"画"出来的。
|
||||
配合单调上升的高度,整条曲线读成**增长态势**,而不是一团雾 */
|
||||
const delay = (b / BARS) * 0.52;
|
||||
const e = smoothstep(k, delay, delay + 0.34);
|
||||
/* 起点用拍一的漂移公式现算(闭式),终点是格子 —— 全程无状态累积,
|
||||
所以拖时间轴能精确停在任何一帧,不会因为「跳过去」而错位 */
|
||||
const sx = noiseP[i3] + Math.sin(t*0.00062 + ph)*0.34;
|
||||
const sy = noiseP[i3+1] + Math.sin(t*0.00094 + ph2)*0.22;
|
||||
const sz = noiseP[i3+2] + Math.cos(t*0.00071 + ph)*0.30;
|
||||
const arc = Math.sin(Math.PI*e) * 0.26; // 归位途中抬一点弧线,像被吸过去
|
||||
p[i3] = lerp(sx, gridP[i3], e);
|
||||
p[i3+1] = lerp(sy, gridP[i3+1], e) + arc;
|
||||
p[i3+2] = lerp(sz, gridP[i3+2], e);
|
||||
/* 高度越高的点越亮:分布顶部因此形成一条"密度脊",面积图才有边缘 */
|
||||
const hg = 0.62 + 0.38*Math.min(1, gridP[i3+1]/(HMAX*0.92));
|
||||
col[i3]=lerp(0.10,0.28,g)*hg; col[i3+1]=lerp(0.20,0.74,g)*hg; col[i3+2]=lerp(0.46,1.0,g)*hg;
|
||||
}
|
||||
cMat.opacity = smoothstep(k, .42, .82)*0.95;
|
||||
thrMat.opacity = 0; dotCoreMat.opacity = 0; ringMat.opacity = 0; dropMat.opacity = 0; tickMat.opacity = 0;
|
||||
baseMat.opacity = smoothstep(k, .5, .9)*0.10;
|
||||
grid.material.opacity = smoothstep(k, .25, .9)*0.55;
|
||||
groundMat.opacity = 0.10 + 0.30*smoothstep(k, .2, .9);
|
||||
bgMat.opacity = 0.55;
|
||||
} else {
|
||||
/* ── 拍三:推进(已固化)──
|
||||
镜头收向「曲线 × 判据线」的交点;点云按**到交点的距离**退场,越远越早退。
|
||||
为什么不是统一淡出:统一淡出读成"被关灯",按距离退读成"注意力收窄到这一点"——
|
||||
后者才是「结论」,前者只是「结束」。 */
|
||||
const pushP = smoothstep(k, .08, .72); // 72% 处走完:留 3.6s 让结论态停住再切镜
|
||||
const R = 4.6 - pushP*3.7; // 保留半径从"全覆盖"收到"一个小圈":边缘先退
|
||||
for (let i=0;i<N;i++) {
|
||||
const b = i % BARS, i3 = i*3;
|
||||
p[i3] = gridP[i3];
|
||||
p[i3+1] = gridP[i3+1];
|
||||
p[i3+2] = gridP[i3+2];
|
||||
const dx = bxOf(b) - DOT_X;
|
||||
const dy = (gridP[i3+1] - DOT_Y) * 0.80;
|
||||
const dist = Math.sqrt(dx*dx + dy*dy);
|
||||
const vis = 1 - smoothstep(dist, R*0.72, R*1.06);
|
||||
const hg = 0.62 + 0.38*Math.min(1, gridP[i3+1]/(HMAX*0.92));
|
||||
const f = vis*0.95;
|
||||
col[i3]=0.30*hg*f; col[i3+1]=0.74*hg*f; col[i3+2]=1.0*hg*f;
|
||||
}
|
||||
|
||||
cMat.opacity = lerp(0.95, 1.0, smoothstep(k, 0, .3));
|
||||
|
||||
/* 判据线:到达那一刻"锁一下" —— 极短的一次亮度台阶(~120ms),之后恒定。
|
||||
没有这一下,推近只是镜头运动;有了它,才是"确认"。 */
|
||||
const lock = smoothstep(k, .62, .70);
|
||||
const bump = lock * (1 - smoothstep(k, .72, .82));
|
||||
thrMat.opacity = 0.26 + 0.28*lock + 0.30*bump;
|
||||
|
||||
/* 结论标记 */
|
||||
const q = smoothstep(k, .42, .68);
|
||||
dotCoreMat.opacity = q;
|
||||
ringMat.opacity = q*0.8;
|
||||
dropMat.opacity = 0;
|
||||
tickMat.opacity = smoothstep(k, .26, .52)*0.9;
|
||||
baseMat.opacity = 0;
|
||||
ring.scale.setScalar(1 + 0.06*(1-q));
|
||||
|
||||
grid.material.opacity = 0;
|
||||
groundMat.opacity = lerp(0.40, 0.24, pushP);
|
||||
bgMat.opacity = 0.45;
|
||||
}
|
||||
geo.attributes.position.needsUpdate = true;
|
||||
geo.attributes.color.needsUpdate = true;
|
||||
fragMat.opacity = act === 0 ? .42 : act === 1 ? .42*(1-smoothstep(k,0,.3)) : 0;
|
||||
|
||||
/* 相机:缓慢推近 + 轻微横移。第三拍几乎停住 —— 「停」本身就是结论成立的语法 */
|
||||
const ck = act === 2 ? Math.min(1, k/SETTLE) : k;
|
||||
const z = act === 0 ? lerp(12.8, 11.6, ck) : act === 1 ? lerp(11.6, 10.0, ck) : lerp(10.0, 9.2, ck);
|
||||
const cx = act === 0 ? lerp(-2.6, -1.0, ck) : act === 1 ? lerp(-1.0, 0.45, ck) : lerp(0.45, 0.5, ck);
|
||||
const cy = act === 0 ? lerp(2.15, 1.92, ck) : act === 1 ? lerp(1.92, 1.72, ck) : lerp(1.72, 1.66, ck);
|
||||
if (act === 2) {
|
||||
/* 推进:不加任何新元素,只用镜头把"曲线穿过判据"这一处推到满画幅。
|
||||
这是唯一不受构图限制的收尾 —— 曲线终点本就顶在画面上缘,往外延伸必出画。 */
|
||||
const p = smoothstep(k, .10, .90);
|
||||
camera.position.set(lerp(cx, 1.62, p), lerp(cy, 1.98, p), lerp(z, 5.2, p));
|
||||
// 视线略偏左,把交点推到画面 60% 处 —— 左边是文字块,交点不能落在中线上
|
||||
camera.lookAt(lerp(cx - 0.55, DOT_X - 0.30, p), lerp(1.50, DOT_Y * 0.94, p), 0);
|
||||
} else {
|
||||
camera.position.set(cx, cy, z);
|
||||
camera.lookAt(cx - 0.55, 1.42, 0);
|
||||
}
|
||||
|
||||
/* 判据线 / 结论标记一律朝向相机:它们是「读数」不是「场景里的物体」 */
|
||||
thr.quaternion.copy(camera.quaternion);
|
||||
baseLine.quaternion.copy(camera.quaternion);
|
||||
dotCore.quaternion.copy(camera.quaternion);
|
||||
ring.quaternion.copy(camera.quaternion);
|
||||
drop.quaternion.copy(camera.quaternion);
|
||||
tick.quaternion.copy(camera.quaternion);
|
||||
}
|
||||
|
||||
return { scene, camera, update };
|
||||
}
|
||||
|
||||
/* ═════════════ 2 · 业务场景剖面:物流路网 ═════════════ */
|
||||
function makeMap() {
|
||||
const scene = new THREE.Scene();
|
||||
scene.background = new THREE.Color(BG);
|
||||
scene.fog = new THREE.Fog(BG, 12, 34);
|
||||
const camera = new THREE.PerspectiveCamera(42, 16/9, .1, 120);
|
||||
|
||||
const NODES = [
|
||||
[-3.2,-2.6],[0.1,-3.3],[3.1,-2.4],
|
||||
[-3.6, 0.3],[-1.1, 0.7],[1.5, 0.5],[3.5, 1.1],
|
||||
[-2.9, 2.9],[-0.3, 3.3],[2.7, 3.1],
|
||||
];
|
||||
const EDGES = [
|
||||
[0,1],[1,2],[0,3],[1,4],[2,5],[3,4],[4,5],[5,6],[3,7],[4,8],[5,8],[6,9],[7,8],[8,9],
|
||||
[0,4],[2,6],[7,4],[9,5],
|
||||
];
|
||||
/* 主干道:0→3→4→5→6 ;替代道:0→3→7→8→5→6 */
|
||||
const MAIN = [0,3,4,5,6];
|
||||
const ALT = [0,3,7,8,5,6];
|
||||
const CONGEST = [4,5]; // 拥塞段
|
||||
|
||||
const g = new THREE.Group();
|
||||
g.rotation.x = 0;
|
||||
scene.add(g);
|
||||
|
||||
/* 地面网格 */
|
||||
const grid = new THREE.GridHelper(24, 48, 0x141c26, 0x0c141c);
|
||||
grid.position.y = -0.01;
|
||||
grid.material.transparent = true; grid.material.opacity = .55;
|
||||
g.add(grid);
|
||||
|
||||
/* 节点 */
|
||||
const nodeMat = new THREE.MeshBasicMaterial({ color:0x7fd4ff, toneMapped:false, transparent:true, opacity:.75 });
|
||||
const nodeGeo = new THREE.CircleGeometry(0.085, 20);
|
||||
const nodeMeshes = NODES.map(([x,z]) => {
|
||||
const m = new THREE.Mesh(nodeGeo, nodeMat.clone());
|
||||
m.rotation.x = -Math.PI/2; m.position.set(x, 0.012, z); g.add(m); return m;
|
||||
});
|
||||
|
||||
/* 边:每条一个材质,便于单独改色 */
|
||||
const edgeMeshes = EDGES.map(([a,b]) => {
|
||||
const [x1,z1] = NODES[a], [x2,z2] = NODES[b];
|
||||
const len = Math.hypot(x2-x1, z2-z1);
|
||||
const mat = new THREE.MeshBasicMaterial({ color:0x2f5a80, toneMapped:false, transparent:true, opacity:.9 });
|
||||
const m = new THREE.Mesh(new THREE.BoxGeometry(0.05, 0.01, len), mat);
|
||||
m.position.set((x1+x2)/2, 0.008, (z1+z2)/2);
|
||||
m.rotation.y = Math.atan2(x2-x1, z2-z1);
|
||||
g.add(m);
|
||||
return { mesh:m, mat, a, b };
|
||||
});
|
||||
const edgeOf = (a,b) => edgeMeshes.find(e => (e.a===a&&e.b===b)||(e.a===b&&e.b===a));
|
||||
|
||||
/* 车辆:沿折线匀速前进的光点 */
|
||||
const routePts = (route) => route.map(i => NODES[i]);
|
||||
function pathLen(pts) { let L=0; for (let i=1;i<pts.length;i++) L+=Math.hypot(pts[i][0]-pts[i-1][0], pts[i][1]-pts[i-1][1]); return L; }
|
||||
function pointAt(pts, s) {
|
||||
let acc=0;
|
||||
for (let i=1;i<pts.length;i++) {
|
||||
const d = Math.hypot(pts[i][0]-pts[i-1][0], pts[i][1]-pts[i-1][1]);
|
||||
if (acc + d >= s) {
|
||||
const t = (s-acc)/d;
|
||||
return [lerp(pts[i-1][0],pts[i][0],t), lerp(pts[i-1][1],pts[i][1],t)];
|
||||
}
|
||||
acc += d;
|
||||
}
|
||||
return pts[pts.length-1];
|
||||
}
|
||||
const M = 70, A = 70;
|
||||
const mkDots = (n, color) => {
|
||||
const arr = new Float32Array(n*3), c = new Float32Array(n*3);
|
||||
const cc = new THREE.Color(color);
|
||||
for (let i=0;i<n;i++) { c[i*3]=cc.r; c[i*3+1]=cc.g; c[i*3+2]=cc.b; }
|
||||
const geo = new THREE.BufferGeometry();
|
||||
geo.setAttribute('position', new THREE.BufferAttribute(arr,3));
|
||||
geo.setAttribute('color', new THREE.BufferAttribute(c,3));
|
||||
const pts = new THREE.Points(geo, new THREE.PointsMaterial({
|
||||
size:0.105, sizeAttenuation:true, vertexColors:true, transparent:true,
|
||||
blending:THREE.AdditiveBlending, depthWrite:false, toneMapped:false, opacity:1,
|
||||
}));
|
||||
g.add(pts);
|
||||
return { pts, arr, geo };
|
||||
};
|
||||
const mainDots = mkDots(M, 0x9fdcff);
|
||||
const altDots = mkDots(A, 0x9fdcff);
|
||||
const mainPts = routePts(MAIN), altPts = routePts(ALT);
|
||||
const mainLen = pathLen(mainPts), altLen = pathLen(altPts);
|
||||
|
||||
function update(t, act, k, dt) {
|
||||
const cg = edgeOf(CONGEST[0], CONGEST[1]);
|
||||
const cAlt = [edgeOf(3,7), edgeOf(7,8), edgeOf(8,5)];
|
||||
|
||||
if (act === 0) {
|
||||
/* 正常流量;末段主干道那段开始变慢变亮(拥塞正在形成) */
|
||||
const load = smoothstep(k, .55, 1);
|
||||
cg.mat.color.setHex(0x2f5a80).lerp(new THREE.Color(0xffb457), load);
|
||||
cg.mat.opacity = 0.9;
|
||||
for (const e of cAlt) { e.mat.color.setHex(0x2f5a80); e.mat.opacity = .9; }
|
||||
nodeMeshes.forEach(m => m.material.color.setHex(0x7fd4ff));
|
||||
} else if (act === 1) {
|
||||
/* 三条候选替代段依次被评估(闪一下),随后一条被选定 */
|
||||
cg.mat.color.setHex(0xffb457); cg.mat.opacity = .95;
|
||||
cAlt.forEach((e,i) => {
|
||||
const scan = smoothstep(k, i*0.16, i*0.16 + 0.14) * (1 - smoothstep(k, i*0.16+0.2, i*0.16+0.34));
|
||||
e.mat.color.setHex(0x2f5a80).lerp(new THREE.Color(0xffffff), scan*0.9).lerp(new THREE.Color(0x63d2ff), smoothstep(k, .55, .8)*0.85);
|
||||
e.mat.opacity = .9;
|
||||
});
|
||||
nodeMeshes[8].material.color.setHex(0xffd39a);
|
||||
nodeMeshes.forEach((m,i) => { if (i!==8) m.material.color.setHex(0x7fd4ff); });
|
||||
} else {
|
||||
/* 执行改道:主干清空、替代道满流、拥塞段回落到常态 */
|
||||
const done = smoothstep(k, .1, .75);
|
||||
cg.mat.color.setHex(0xffb457).lerp(new THREE.Color(0x3a2a18), done*0.75);
|
||||
for (const e of cAlt) { e.mat.color.setHex(0x63d2ff); e.mat.opacity = .95; }
|
||||
nodeMeshes[8].material.color.setHex(0xffb457);
|
||||
nodeMeshes.forEach((m,i) => { if (i!==8) m.material.color.setHex(0x7fd4ff); });
|
||||
}
|
||||
|
||||
/* 车辆位置:主干速度在拍一末段下降(拥塞),拍二后逐步消失 */
|
||||
const mainVisible = act === 0 ? 1 : act === 1 ? 1 - smoothstep(k, .45, .95) : 0;
|
||||
const altVisible = act === 0 ? 0 : act === 1 ? smoothstep(k, .55, .95) : 1;
|
||||
for (let i=0;i<M;i++) {
|
||||
const s = ((i/M)*mainLen + t*0.0016*(act===0? 1 - 0.45*smoothstep(k,.55,1) : 1)) % mainLen;
|
||||
const [x,z] = pointAt(mainPts, s);
|
||||
mainDots.arr[i*3]=x; mainDots.arr[i*3+1]=0.026; mainDots.arr[i*3+2]=z;
|
||||
}
|
||||
for (let i=0;i<A;i++) {
|
||||
const s = ((i/A)*altLen + t*0.0019) % altLen;
|
||||
const [x,z] = pointAt(altPts, s);
|
||||
altDots.arr[i*3]=x; altDots.arr[i*3+1]=0.026; altDots.arr[i*3+2]=z;
|
||||
}
|
||||
mainDots.geo.attributes.position.needsUpdate = true;
|
||||
altDots.geo.attributes.position.needsUpdate = true;
|
||||
mainDots.pts.material.opacity = mainVisible;
|
||||
altDots.pts.material.opacity = altVisible;
|
||||
|
||||
/* 俯视缓推 + 轻旋:R 必须装得下整张路网(7.2 × 6.6),否则四边被裁 */
|
||||
const ck = act === 2 ? Math.min(1, k/SETTLE) : k;
|
||||
const ang = -0.34 + ck*0.04 + act*0.02;
|
||||
const R = act === 0 ? lerp(12.8, 11.8, ck) : act === 1 ? 11.8 : lerp(11.8, 11.0, ck);
|
||||
camera.position.set(Math.sin(ang)*R*0.55, R*0.95, Math.cos(ang)*R*0.62);
|
||||
camera.lookAt(0.9, 0, 0.1);
|
||||
}
|
||||
|
||||
return { scene, camera, update };
|
||||
}
|
||||
|
||||
/* ═════════════ 4 · 决策现场:人与大屏 ═════════════ */
|
||||
function makeRoom() {
|
||||
const scene = new THREE.Scene();
|
||||
scene.background = new THREE.Color(BG);
|
||||
scene.fog = new THREE.Fog(BG, 5, 16);
|
||||
const camera = new THREE.PerspectiveCamera(40, 16/9, .1, 60);
|
||||
|
||||
scene.add(new THREE.AmbientLight(0x223044, 0.55));
|
||||
const screenLight = new THREE.PointLight(0x9fd8ff, 16, 14, 2);
|
||||
screenLight.position.set(0, 1.6, -3.5);
|
||||
scene.add(screenLight);
|
||||
|
||||
/* 房间:地板 + 后墙(墙要够大,否则画面里会露出墙的硬边) */
|
||||
const floor = new THREE.Mesh(new THREE.PlaneGeometry(20,20),
|
||||
new THREE.MeshStandardMaterial({ color:0x0a0c10, roughness:.55, metalness:.25 }));
|
||||
floor.rotation.x = -Math.PI/2; scene.add(floor);
|
||||
const wall = new THREE.Mesh(new THREE.PlaneGeometry(26,12),
|
||||
new THREE.MeshStandardMaterial({ color:0x0b0e13, roughness:.95 }));
|
||||
wall.position.set(0, 4, -4.7); scene.add(wall);
|
||||
|
||||
/* 大屏:CanvasTexture,内容按拍次重画 */
|
||||
const SC = document.createElement('canvas');
|
||||
SC.width = 1024; SC.height = 320;
|
||||
const ctx = SC.getContext('2d');
|
||||
const sTex = new THREE.CanvasTexture(SC);
|
||||
sTex.colorSpace = THREE.SRGBColorSpace;
|
||||
const screen = new THREE.Mesh(new THREE.PlaneGeometry(2.62, 0.82),
|
||||
new THREE.MeshBasicMaterial({ map:sTex, toneMapped:false }));
|
||||
screen.position.set(0, 1.72, -4.56);
|
||||
scene.add(screen);
|
||||
|
||||
/* 桌子:压到接近黑 —— 桌面反光会把整块画面拉成一块白板(实测首版) */
|
||||
const deskMat = new THREE.MeshStandardMaterial({ color:0x080a0d, roughness:.98, metalness:0 });
|
||||
const desk = new THREE.Mesh(new THREE.BoxGeometry(1.7, 0.05, 0.72), deskMat);
|
||||
desk.position.set(0.15, 0.74, -2.55); scene.add(desk);
|
||||
for (const [dx,dz] of [[-0.7,-0.28],[0.7,-0.28]]) {
|
||||
const leg = new THREE.Mesh(new THREE.BoxGeometry(0.05,0.74,0.05), deskMat);
|
||||
leg.position.set(0.15+dx, 0.37, -2.55+dz); scene.add(leg);
|
||||
}
|
||||
|
||||
/* 人:剪影几何(头 / 肩 / 躯干 / 腿 / 臂)。刻意不写实 —— 3D 写实人脸必假 */
|
||||
const skin = new THREE.MeshStandardMaterial({ color:0x1a1d22, roughness:.85, metalness:.05 });
|
||||
const person = new THREE.Group();
|
||||
person.position.set(0.02, 0, -2.05);
|
||||
|
||||
const head = new THREE.Mesh(new THREE.SphereGeometry(0.108, 20, 16), skin);
|
||||
head.position.set(0, 1.66, 0); head.scale.set(0.94, 1.1, 0.98); person.add(head);
|
||||
const neck = new THREE.Mesh(new THREE.CylinderGeometry(0.045,0.055,0.09,12), skin);
|
||||
neck.position.set(0,1.565,0); person.add(neck);
|
||||
const torso = new THREE.Mesh(new THREE.CylinderGeometry(0.175,0.145,0.56,16), skin);
|
||||
torso.position.set(0,1.28,0); torso.scale.set(1,1,0.62); person.add(torso);
|
||||
/* 肩:没有肩,圆柱躯干会读成一根管子 */
|
||||
const shoulders = new THREE.Mesh(new THREE.SphereGeometry(0.2,16,12), skin);
|
||||
shoulders.position.set(0,1.5,0); shoulders.scale.set(1.26,0.52,0.72); person.add(shoulders);
|
||||
const hip = new THREE.Mesh(new THREE.CylinderGeometry(0.145,0.13,0.22,16), skin);
|
||||
hip.position.set(0,0.95,0); hip.scale.set(1,1,0.7); person.add(hip);
|
||||
for (const sx of [-0.085, 0.085]) {
|
||||
const leg = new THREE.Mesh(new THREE.CylinderGeometry(0.062,0.052,0.86,12), skin);
|
||||
leg.position.set(sx, 0.44, 0); person.add(leg);
|
||||
const foot = new THREE.Mesh(new THREE.BoxGeometry(0.09,0.05,0.22), skin);
|
||||
foot.position.set(sx, 0.03, 0.05); person.add(foot);
|
||||
}
|
||||
/* 右臂:可抬起 —— 拍三的「他做了选择」由这个动作承担 */
|
||||
const armPivot = new THREE.Group();
|
||||
armPivot.position.set(0.185, 1.5, 0);
|
||||
const upper = new THREE.Mesh(new THREE.CylinderGeometry(0.05,0.045,0.34,10), skin);
|
||||
upper.position.set(0,-0.17,0); armPivot.add(upper);
|
||||
const forePivot = new THREE.Group();
|
||||
forePivot.position.set(0,-0.34,0);
|
||||
const fore = new THREE.Mesh(new THREE.CylinderGeometry(0.043,0.038,0.3,10), skin);
|
||||
fore.position.set(0,-0.15,0); forePivot.add(fore);
|
||||
const hand = new THREE.Mesh(new THREE.SphereGeometry(0.047, 14, 12), skin);
|
||||
hand.position.set(0,-0.315,0); forePivot.add(hand);
|
||||
armPivot.add(forePivot);
|
||||
person.add(armPivot);
|
||||
const armL = new THREE.Mesh(new THREE.CylinderGeometry(0.05,0.045,0.62,10), skin);
|
||||
armL.position.set(-0.19, 1.2, 0); person.add(armL);
|
||||
scene.add(person);
|
||||
|
||||
/* 屏幕内容的分帧绘制 */
|
||||
const dots = [];
|
||||
for (let i=0;i<260;i++) dots.push({ x:Math.random(), y:Math.random(), b:Math.floor(Math.random()*14), h: Math.random() });
|
||||
|
||||
function drawScreen(act, k, t) {
|
||||
const w = SC.width, h = SC.height;
|
||||
ctx.fillStyle = '#080c12'; ctx.fillRect(0,0,w,h);
|
||||
ctx.strokeStyle = 'rgba(120,190,255,.10)'; ctx.lineWidth = 2;
|
||||
ctx.strokeRect(1,1,w-2,h-2);
|
||||
|
||||
if (act <= 1) {
|
||||
/* 标题条 */
|
||||
ctx.fillStyle = 'rgba(130,205,255,.30)'; ctx.fillRect(48, 34, 168, 7);
|
||||
ctx.fillStyle = 'rgba(130,205,255,.16)'; ctx.fillRect(48, 52, 96, 5);
|
||||
|
||||
const sep = act === 0 ? 0 : smoothstep(k, 0.1, 0.75);
|
||||
const barW = (w-120)/14;
|
||||
for (const d of dots) {
|
||||
let x, y;
|
||||
if (sep < 0.02) {
|
||||
x = 48 + d.x*(w-96) + Math.sin(t*0.001 + d.x*20)*6;
|
||||
y = 96 + d.y*(h-150) + Math.cos(t*0.0013 + d.y*17)*5;
|
||||
} else {
|
||||
const targetX = 48 + (d.b+0.5)*barW + (d.h-0.5)*2;
|
||||
const targetY = h-58 - (0.25+0.75*d.h) * (h-180) * (0.4 + 0.6*Math.abs(Math.sin(d.b*0.6)));
|
||||
x = lerp(48 + d.x*(w-96), targetX, sep);
|
||||
y = lerp(96 + d.y*(h-150), targetY, sep);
|
||||
}
|
||||
ctx.fillStyle = sep > 0.5 ? 'rgba(150,215,255,.85)' : 'rgba(120,180,255,.5)';
|
||||
ctx.fillRect(x, y, 2.6, 2.6);
|
||||
}
|
||||
if (sep > 0.4) {
|
||||
ctx.strokeStyle = 'rgba(120,190,255,.28)'; ctx.lineWidth = 1.5;
|
||||
ctx.beginPath(); ctx.moveTo(48, h-56); ctx.lineTo(w-48, h-56); ctx.stroke();
|
||||
}
|
||||
} else {
|
||||
/* 三个方案并置 → 一个被选中 */
|
||||
ctx.fillStyle = 'rgba(130,205,255,.30)'; ctx.fillRect(48, 34, 210, 7);
|
||||
const sel = smoothstep(k, 0.45, 0.7);
|
||||
for (let i=0;i<3;i++) {
|
||||
const bx = 48 + i*(w-96)/3 + 8;
|
||||
const bw = (w-96)/3 - 26;
|
||||
const on = i === 1;
|
||||
const alpha = on ? 0.16 + 0.24*sel : 0.10 - 0.04*sel;
|
||||
ctx.fillStyle = on ? `rgba(255,180,87,${alpha})` : `rgba(120,190,255,${alpha})`;
|
||||
ctx.fillRect(bx, 92, bw, h-190);
|
||||
ctx.strokeStyle = on ? `rgba(255,180,87,${0.3+0.55*sel})` : 'rgba(120,190,255,.22)';
|
||||
ctx.lineWidth = on ? 3 : 1.5;
|
||||
ctx.strokeRect(bx, 92, bw, h-190);
|
||||
/* 方案内的抽象条 */
|
||||
for (let b=0;b<5;b++) {
|
||||
const bh = (0.25 + 0.6*Math.abs(Math.sin(i*2.1+b*1.3))) * (h-250);
|
||||
ctx.fillStyle = on ? `rgba(255,200,130,${0.35+0.4*sel})` : 'rgba(120,190,255,.28)';
|
||||
ctx.fillRect(bx+14+b*((bw-28)/5), h-98-bh, (bw-28)/5-8, bh);
|
||||
}
|
||||
ctx.fillStyle = on ? 'rgba(255,215,160,.85)' : 'rgba(150,205,255,.45)';
|
||||
ctx.fillRect(bx+14, 110, 34, 6);
|
||||
}
|
||||
}
|
||||
sTex.needsUpdate = true;
|
||||
}
|
||||
|
||||
let lastDraw = -1;
|
||||
function update(t, act, k, dt) {
|
||||
if (Math.abs(t - lastDraw) > 60) { drawScreen(act, k, t); lastDraw = t; }
|
||||
|
||||
/* 拍三:手抬起指向屏幕(决策落定的身体动作) */
|
||||
const raise = act === 2 ? smoothstep(Math.min(1,k/SETTLE), .25, .62) : 0;
|
||||
armPivot.rotation.x = -raise * 1.05;
|
||||
armPivot.rotation.z = raise * 0.16;
|
||||
forePivot.rotation.x = -raise * 0.55;
|
||||
person.rotation.y = act === 2 ? lerp(0, -0.06, raise) : 0;
|
||||
|
||||
/* 屏幕亮度随拍次升高:拍一是暗噪,拍三最亮 */
|
||||
const bright = act === 0 ? 1.0 : act === 1 ? 1.25 : 1.45;
|
||||
sTex.colorSpace = THREE.SRGBColorSpace;
|
||||
screenLight.intensity = (18 + 10*bright) * (act===2 ? 0.85 + 0.15*Math.min(1,k/SETTLE) : 1);
|
||||
|
||||
/* 相机:侧后方推近,第三拍更低更近(像站在他身后) */
|
||||
const ck = act === 2 ? Math.min(1, k/SETTLE) : k;
|
||||
const x = act === 0 ? lerp(2.5, 2.05, ck) : act === 1 ? lerp(2.05, 1.72, ck) : lerp(1.72, 1.45, ck);
|
||||
const y = act === 0 ? lerp(1.62, 1.56, ck) : act === 1 ? lerp(1.56, 1.5, ck) : lerp(1.5, 1.62, ck);
|
||||
const z = act === 0 ? lerp(1.05, 0.5, ck) : act === 1 ? lerp(0.5, 0.05, ck) : lerp(0.05, -0.25, ck);
|
||||
camera.position.set(x, y, z);
|
||||
camera.lookAt(lerp(-0.12, -0.05, ck), 1.44, -4.4);
|
||||
}
|
||||
|
||||
return { scene, camera, update };
|
||||
}
|
||||
|
||||
/* ═════════════ 播放器 ═════════════ */
|
||||
const built = { void: makeVoid(), map: makeMap(), room: makeRoom() };
|
||||
let current = 'void';
|
||||
let playing = true, clockT = 0, lastNow = performance.now();
|
||||
|
||||
/* 后处理:只给「抽象数据场」开 bloom。
|
||||
点阵的柔光靠它才成立 —— 没有 bloom,加色混合的点在暗底上永远是"灰点"。 */
|
||||
const composer = new EffectComposer(renderer);
|
||||
composer.addPass(new RenderPass(built.void.scene, built.void.camera));
|
||||
const bloom = new UnrealBloomPass(
|
||||
new THREE.Vector2(host.clientWidth, host.clientHeight), 0.72, 0.62, 0.35,
|
||||
);
|
||||
composer.addPass(bloom);
|
||||
// ?bloom=0 可关后处理;键盘 B 亦可切换,用来分离"点阵更新"与"后处理"两笔成本
|
||||
if (new URLSearchParams(location.search).get("bloom") === "0") bloom.enabled = false;
|
||||
// 初始也按半分辨率构建
|
||||
bloom.setSize(Math.round(host.clientWidth*0.5), Math.round(host.clientHeight*0.5));
|
||||
composer.addPass(new OutputPass());
|
||||
|
||||
function beatAt(t) {
|
||||
let acc = 0;
|
||||
for (let i=0;i<ACTS.length;i++) {
|
||||
if (t < acc + ACTS[i]) return { act:i, k:(t-acc)/ACTS[i], dip:-1, prev:-1 };
|
||||
acc += ACTS[i];
|
||||
if (t < acc + DIP) return { act:(i+1)%3, k:0, dip:(t-acc)/DIP, prev:i };
|
||||
acc += DIP;
|
||||
}
|
||||
return { act:0, k:0, dip:-1, prev:-1 };
|
||||
}
|
||||
|
||||
function setCase(id) {
|
||||
current = id;
|
||||
for (const b of document.querySelectorAll('.vbtn')) b.classList.toggle('on', b.dataset.id === id);
|
||||
const b = built[id];
|
||||
b.camera.aspect = host.clientWidth/host.clientHeight;
|
||||
b.camera.updateProjectionMatrix();
|
||||
}
|
||||
function setCopy(on) {
|
||||
document.getElementById('copy').style.opacity = on ? '1' : '0';
|
||||
document.getElementById('scrim').style.opacity = on ? '1' : '0';
|
||||
}
|
||||
|
||||
const roAct=document.getElementById('ro-act'), roK=document.getElementById('ro-k'), roT=document.getElementById('ro-t');
|
||||
function frame(now) {
|
||||
const dt = Math.min(0.05, (now-lastNow)/1000); lastNow = now;
|
||||
if (playing) clockT = (clockT + dt*1000) % CYCLE;
|
||||
|
||||
const beat = beatAt(clockT);
|
||||
const b = built[current];
|
||||
b.update(clockT, beat.act, beat.k, dt);
|
||||
|
||||
if (beat.dip >= 0) {
|
||||
veil.style.opacity = String(beat.dip < .5 ? Math.min(1, beat.dip*2) : Math.max(0, (1-beat.dip)*2));
|
||||
} else veil.style.opacity = '0';
|
||||
|
||||
if (current === 'void') composer.render();
|
||||
else renderer.render(b.scene, b.camera);
|
||||
|
||||
const cap = CASE_LABEL[current][beat.act];
|
||||
const cl = document.getElementById('cap-label'), cd = document.getElementById('cap-detail');
|
||||
if (cl.textContent !== cap.label) { cl.textContent = cap.label; cd.textContent = cap.detail; }
|
||||
roAct.textContent = String(beat.act+1);
|
||||
roK.textContent = (beat.act===2 ? Math.min(1, beat.k/SETTLE) : beat.k).toFixed(2);
|
||||
roT.textContent = (clockT/1000).toFixed(1)+'s';
|
||||
document.getElementById('tl').value = String(Math.round(clockT));
|
||||
requestAnimationFrame(frame);
|
||||
}
|
||||
|
||||
const wrap = document.getElementById('variants');
|
||||
CASES.forEach((v,i) => {
|
||||
const el = document.createElement('button');
|
||||
el.className='vbtn'; el.dataset.id=v.id;
|
||||
el.innerHTML = `<b><span class="k">${i+1}</span>${v.name}</b><em>${v.desc}</em>`;
|
||||
el.onclick = () => setCase(v.id);
|
||||
wrap.appendChild(el);
|
||||
});
|
||||
for (const btn of document.querySelectorAll('.acts button[data-t]')) {
|
||||
btn.onclick = () => { clockT = Number(btn.dataset.t); playing = false; syncPlay(); };
|
||||
}
|
||||
const tl = document.getElementById('tl');
|
||||
tl.addEventListener('input', () => { clockT = Number(tl.value); playing = false; syncPlay(); });
|
||||
const btnPlay = document.getElementById('btn-play');
|
||||
function syncPlay(){ btnPlay.textContent = playing ? '暂停' : '播放'; }
|
||||
btnPlay.onclick = () => { playing = !playing; syncPlay(); };
|
||||
document.getElementById('btn-copy').onclick = () => {
|
||||
const on = document.getElementById('copy').style.opacity !== '1';
|
||||
setCopy(on);
|
||||
};
|
||||
window.addEventListener('keydown', (e) => {
|
||||
const n = Number(e.key);
|
||||
if (n>=1 && n<=CASES.length) setCase(CASES[n-1].id);
|
||||
if (e.code === 'Space') { e.preventDefault(); playing = !playing; syncPlay(); }
|
||||
if (e.key === "b" || e.key === "B") bloom.enabled = !bloom.enabled;
|
||||
});
|
||||
window.addEventListener('resize', () => {
|
||||
const w=host.clientWidth, h=host.clientHeight; if (!w||!h) return;
|
||||
renderer.setSize(w,h,false);
|
||||
composer.setSize(w,h);
|
||||
// bloom 半分辨率:软件渲染实测全分辨率 60fps→11fps,半分辨率回到可用区间
|
||||
bloom.setSize(Math.round(w*0.5), Math.round(h*0.5));
|
||||
for (const k of Object.keys(built)) { built[k].camera.aspect = w/h; built[k].camera.updateProjectionMatrix(); }
|
||||
});
|
||||
|
||||
setCase('void');
|
||||
setCopy(true); // 默认叠文案:交付判断的是"合成后"是否成立,不是裸画面
|
||||
requestAnimationFrame(frame);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,187 @@
|
||||
import {
|
||||
HalfFloatType,
|
||||
NearestFilter,
|
||||
NoBlending,
|
||||
ShaderMaterial,
|
||||
UniformsUtils,
|
||||
WebGLRenderTarget
|
||||
} from 'three';
|
||||
import { Pass, FullScreenQuad } from './Pass.js';
|
||||
import { CopyShader } from '../shaders/CopyShader.js';
|
||||
import { AfterimageShader } from '../shaders/AfterimageShader.js';
|
||||
|
||||
/**
|
||||
* Pass for a basic after image effect.
|
||||
*
|
||||
* ```js
|
||||
* const afterimagePass = new AfterimagePass( 0.9 );
|
||||
* composer.addPass( afterimagePass );
|
||||
* ```
|
||||
*
|
||||
* @augments Pass
|
||||
* @three_import import { AfterimagePass } from 'three/addons/postprocessing/AfterimagePass.js';
|
||||
*/
|
||||
class AfterimagePass extends Pass {
|
||||
|
||||
/**
|
||||
* Constructs a new after image pass.
|
||||
*
|
||||
* @param {number} [damp=0.96] - The damping intensity. A higher value means a stronger after image effect.
|
||||
*/
|
||||
constructor( damp = 0.96 ) {
|
||||
|
||||
super();
|
||||
|
||||
/**
|
||||
* The pass uniforms. Use this object if you want to update the
|
||||
* `damp` value at runtime.
|
||||
* ```js
|
||||
* pass.uniforms.damp.value = 0.9;
|
||||
* ```
|
||||
*
|
||||
* @type {Object}
|
||||
*/
|
||||
this.uniforms = UniformsUtils.clone( AfterimageShader.uniforms );
|
||||
|
||||
this.damp = damp;
|
||||
|
||||
/**
|
||||
* The composition material.
|
||||
*
|
||||
* @type {ShaderMaterial}
|
||||
*/
|
||||
this.compFsMaterial = new ShaderMaterial( {
|
||||
|
||||
uniforms: this.uniforms,
|
||||
vertexShader: AfterimageShader.vertexShader,
|
||||
fragmentShader: AfterimageShader.fragmentShader
|
||||
|
||||
} );
|
||||
|
||||
/**
|
||||
* The copy material.
|
||||
*
|
||||
* @type {ShaderMaterial}
|
||||
*/
|
||||
this.copyFsMaterial = new ShaderMaterial( {
|
||||
uniforms: UniformsUtils.clone( CopyShader.uniforms ),
|
||||
vertexShader: CopyShader.vertexShader,
|
||||
fragmentShader: CopyShader.fragmentShader,
|
||||
blending: NoBlending,
|
||||
depthTest: false,
|
||||
depthWrite: false
|
||||
} );
|
||||
|
||||
// internals
|
||||
|
||||
this._textureComp = new WebGLRenderTarget( window.innerWidth, window.innerHeight, {
|
||||
magFilter: NearestFilter,
|
||||
type: HalfFloatType,
|
||||
depthBuffer: false
|
||||
} );
|
||||
|
||||
this._textureOld = new WebGLRenderTarget( window.innerWidth, window.innerHeight, {
|
||||
magFilter: NearestFilter,
|
||||
type: HalfFloatType,
|
||||
depthBuffer: false
|
||||
} );
|
||||
|
||||
this._compFsQuad = new FullScreenQuad( this.compFsMaterial );
|
||||
this._copyFsQuad = new FullScreenQuad( this.copyFsMaterial );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* The damping intensity, from 0.0 to 1.0. A higher value means a stronger after image effect.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get damp() {
|
||||
|
||||
return this.uniforms[ 'damp' ].value;
|
||||
|
||||
}
|
||||
|
||||
set damp( value ) {
|
||||
|
||||
this.uniforms[ 'damp' ].value = value;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs the after image pass.
|
||||
*
|
||||
* @param {WebGLRenderer} renderer - The renderer.
|
||||
* @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
|
||||
* destination for the pass.
|
||||
* @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
|
||||
* previous pass from this buffer.
|
||||
* @param {number} deltaTime - The delta time in seconds.
|
||||
* @param {boolean} maskActive - Whether masking is active or not.
|
||||
*/
|
||||
render( renderer, writeBuffer, readBuffer/*, deltaTime, maskActive*/ ) {
|
||||
|
||||
this.uniforms[ 'tOld' ].value = this._textureOld.texture;
|
||||
this.uniforms[ 'tNew' ].value = readBuffer.texture;
|
||||
|
||||
renderer.setRenderTarget( this._textureComp );
|
||||
this._compFsQuad.render( renderer );
|
||||
|
||||
this._copyFsQuad.material.uniforms.tDiffuse.value = this._textureComp.texture;
|
||||
|
||||
if ( this.renderToScreen ) {
|
||||
|
||||
renderer.setRenderTarget( null );
|
||||
this._copyFsQuad.render( renderer );
|
||||
|
||||
} else {
|
||||
|
||||
renderer.setRenderTarget( writeBuffer );
|
||||
|
||||
if ( this.clear ) renderer.clear();
|
||||
|
||||
this._copyFsQuad.render( renderer );
|
||||
|
||||
}
|
||||
|
||||
// Swap buffers.
|
||||
const temp = this._textureOld;
|
||||
this._textureOld = this._textureComp;
|
||||
this._textureComp = temp;
|
||||
// Now textureOld contains the latest image, ready for the next frame.
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the size of the pass.
|
||||
*
|
||||
* @param {number} width - The width to set.
|
||||
* @param {number} height - The height to set.
|
||||
*/
|
||||
setSize( width, height ) {
|
||||
|
||||
this._textureComp.setSize( width, height );
|
||||
this._textureOld.setSize( width, height );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Frees the GPU-related resources allocated by this instance. Call this
|
||||
* method whenever the pass is no longer used in your app.
|
||||
*/
|
||||
dispose() {
|
||||
|
||||
this._textureComp.dispose();
|
||||
this._textureOld.dispose();
|
||||
|
||||
this.compFsMaterial.dispose();
|
||||
this.copyFsMaterial.dispose();
|
||||
|
||||
this._compFsQuad.dispose();
|
||||
this._copyFsQuad.dispose();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export { AfterimagePass };
|
||||
@@ -0,0 +1,274 @@
|
||||
import {
|
||||
AdditiveBlending,
|
||||
HalfFloatType,
|
||||
ShaderMaterial,
|
||||
UniformsUtils,
|
||||
Vector2,
|
||||
WebGLRenderTarget
|
||||
} from 'three';
|
||||
import { Pass, FullScreenQuad } from './Pass.js';
|
||||
import { ConvolutionShader } from '../shaders/ConvolutionShader.js';
|
||||
|
||||
/**
|
||||
* A pass for a basic Bloom effect.
|
||||
*
|
||||
* {@link UnrealBloomPass} produces a more advanced Bloom but is also
|
||||
* more expensive.
|
||||
*
|
||||
* ```js
|
||||
* const effectBloom = new BloomPass( 0.75 );
|
||||
* composer.addPass( effectBloom );
|
||||
* ```
|
||||
*
|
||||
* @augments Pass
|
||||
* @three_import import { BloomPass } from 'three/addons/postprocessing/BloomPass.js';
|
||||
*/
|
||||
class BloomPass extends Pass {
|
||||
|
||||
/**
|
||||
* Constructs a new Bloom pass.
|
||||
*
|
||||
* @param {number} [strength=1] - The Bloom strength.
|
||||
* @param {number} [kernelSize=25] - The kernel size.
|
||||
* @param {number} [sigma=4] - The sigma.
|
||||
*/
|
||||
constructor( strength = 1, kernelSize = 25, sigma = 4 ) {
|
||||
|
||||
super();
|
||||
|
||||
// combine material
|
||||
|
||||
/**
|
||||
* The combine pass uniforms.
|
||||
*
|
||||
* @type {Object}
|
||||
*/
|
||||
this.combineUniforms = UniformsUtils.clone( CombineShader.uniforms );
|
||||
this.combineUniforms[ 'strength' ].value = strength;
|
||||
|
||||
/**
|
||||
* The combine pass material.
|
||||
*
|
||||
* @type {ShaderMaterial}
|
||||
*/
|
||||
this.materialCombine = new ShaderMaterial( {
|
||||
|
||||
name: CombineShader.name,
|
||||
uniforms: this.combineUniforms,
|
||||
vertexShader: CombineShader.vertexShader,
|
||||
fragmentShader: CombineShader.fragmentShader,
|
||||
blending: AdditiveBlending,
|
||||
transparent: true
|
||||
|
||||
} );
|
||||
|
||||
// convolution material
|
||||
|
||||
const convolutionShader = ConvolutionShader;
|
||||
|
||||
/**
|
||||
* The convolution pass uniforms.
|
||||
*
|
||||
* @type {Object}
|
||||
*/
|
||||
this.convolutionUniforms = UniformsUtils.clone( convolutionShader.uniforms );
|
||||
|
||||
this.convolutionUniforms[ 'uImageIncrement' ].value = BloomPass.blurX;
|
||||
this.convolutionUniforms[ 'cKernel' ].value = buildKernel( sigma );
|
||||
|
||||
/**
|
||||
* The convolution pass material.
|
||||
*
|
||||
* @type {ShaderMaterial}
|
||||
*/
|
||||
this.materialConvolution = new ShaderMaterial( {
|
||||
|
||||
name: convolutionShader.name,
|
||||
uniforms: this.convolutionUniforms,
|
||||
vertexShader: convolutionShader.vertexShader,
|
||||
fragmentShader: convolutionShader.fragmentShader,
|
||||
defines: {
|
||||
'KERNEL_SIZE_FLOAT': kernelSize.toFixed( 1 ),
|
||||
'KERNEL_SIZE_INT': kernelSize.toFixed( 0 )
|
||||
}
|
||||
|
||||
} );
|
||||
|
||||
/**
|
||||
* Overwritten to disable the swap.
|
||||
*
|
||||
* @type {boolean}
|
||||
* @default false
|
||||
*/
|
||||
this.needsSwap = false;
|
||||
|
||||
// internals
|
||||
|
||||
this._renderTargetX = new WebGLRenderTarget( 1, 1, { type: HalfFloatType, depthBuffer: false } ); // will be resized later
|
||||
this._renderTargetX.texture.name = 'BloomPass.x';
|
||||
this._renderTargetY = new WebGLRenderTarget( 1, 1, { type: HalfFloatType, depthBuffer: false } ); // will be resized later
|
||||
this._renderTargetY.texture.name = 'BloomPass.y';
|
||||
|
||||
this._fsQuad = new FullScreenQuad( null );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs the Bloom pass.
|
||||
*
|
||||
* @param {WebGLRenderer} renderer - The renderer.
|
||||
* @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
|
||||
* destination for the pass.
|
||||
* @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
|
||||
* previous pass from this buffer.
|
||||
* @param {number} deltaTime - The delta time in seconds.
|
||||
* @param {boolean} maskActive - Whether masking is active or not.
|
||||
*/
|
||||
render( renderer, writeBuffer, readBuffer, deltaTime, maskActive ) {
|
||||
|
||||
if ( maskActive ) renderer.state.buffers.stencil.setTest( false );
|
||||
|
||||
// Render quad with blurred scene into texture (convolution pass 1)
|
||||
|
||||
this._fsQuad.material = this.materialConvolution;
|
||||
|
||||
this.convolutionUniforms[ 'tDiffuse' ].value = readBuffer.texture;
|
||||
this.convolutionUniforms[ 'uImageIncrement' ].value = BloomPass.blurX;
|
||||
|
||||
renderer.setRenderTarget( this._renderTargetX );
|
||||
renderer.clear();
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
|
||||
// Render quad with blurred scene into texture (convolution pass 2)
|
||||
|
||||
this.convolutionUniforms[ 'tDiffuse' ].value = this._renderTargetX.texture;
|
||||
this.convolutionUniforms[ 'uImageIncrement' ].value = BloomPass.blurY;
|
||||
|
||||
renderer.setRenderTarget( this._renderTargetY );
|
||||
renderer.clear();
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
// Render original scene with superimposed blur to texture
|
||||
|
||||
this._fsQuad.material = this.materialCombine;
|
||||
|
||||
this.combineUniforms[ 'tDiffuse' ].value = this._renderTargetY.texture;
|
||||
|
||||
if ( maskActive ) renderer.state.buffers.stencil.setTest( true );
|
||||
|
||||
renderer.setRenderTarget( readBuffer );
|
||||
if ( this.clear ) renderer.clear();
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the size of the pass.
|
||||
*
|
||||
* @param {number} width - The width to set.
|
||||
* @param {number} height - The height to set.
|
||||
*/
|
||||
setSize( width, height ) {
|
||||
|
||||
this._renderTargetX.setSize( width, height );
|
||||
this._renderTargetY.setSize( width, height );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Frees the GPU-related resources allocated by this instance. Call this
|
||||
* method whenever the pass is no longer used in your app.
|
||||
*/
|
||||
dispose() {
|
||||
|
||||
this._renderTargetX.dispose();
|
||||
this._renderTargetY.dispose();
|
||||
|
||||
this.materialCombine.dispose();
|
||||
this.materialConvolution.dispose();
|
||||
|
||||
this._fsQuad.dispose();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
const CombineShader = {
|
||||
|
||||
name: 'CombineShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDiffuse': { value: null },
|
||||
'strength': { value: 1.0 }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform float strength;
|
||||
|
||||
uniform sampler2D tDiffuse;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vec4 texel = texture2D( tDiffuse, vUv );
|
||||
gl_FragColor = strength * texel;
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
BloomPass.blurX = new Vector2( 0.001953125, 0.0 );
|
||||
BloomPass.blurY = new Vector2( 0.0, 0.001953125 );
|
||||
|
||||
|
||||
function gauss( x, sigma ) {
|
||||
|
||||
return Math.exp( - ( x * x ) / ( 2.0 * sigma * sigma ) );
|
||||
|
||||
}
|
||||
|
||||
function buildKernel( sigma ) {
|
||||
|
||||
// We loop off the sqrt(2 * pi) * sigma term, since we're going to normalize anyway.
|
||||
|
||||
const kMaxKernelSize = 25;
|
||||
let kernelSize = 2 * Math.ceil( sigma * 3.0 ) + 1;
|
||||
|
||||
if ( kernelSize > kMaxKernelSize ) kernelSize = kMaxKernelSize;
|
||||
|
||||
const halfWidth = ( kernelSize - 1 ) * 0.5;
|
||||
|
||||
const values = new Array( kernelSize );
|
||||
let sum = 0.0;
|
||||
for ( let i = 0; i < kernelSize; ++ i ) {
|
||||
|
||||
values[ i ] = gauss( i - halfWidth, sigma );
|
||||
sum += values[ i ];
|
||||
|
||||
}
|
||||
|
||||
// normalize the kernel
|
||||
|
||||
for ( let i = 0; i < kernelSize; ++ i ) values[ i ] /= sum;
|
||||
|
||||
return values;
|
||||
|
||||
}
|
||||
|
||||
export { BloomPass };
|
||||
@@ -0,0 +1,218 @@
|
||||
import {
|
||||
Color,
|
||||
HalfFloatType,
|
||||
MeshDepthMaterial,
|
||||
NearestFilter,
|
||||
NoBlending,
|
||||
RGBADepthPacking,
|
||||
ShaderMaterial,
|
||||
UniformsUtils,
|
||||
WebGLRenderTarget
|
||||
} from 'three';
|
||||
import { Pass, FullScreenQuad } from './Pass.js';
|
||||
import { BokehShader } from '../shaders/BokehShader.js';
|
||||
|
||||
/**
|
||||
* Pass for creating depth of field (DOF) effect.
|
||||
*
|
||||
* ```js
|
||||
* const bokehPass = new BokehPass( scene, camera, {
|
||||
* focus: 500,
|
||||
* aperture: 5,
|
||||
* maxblur: 0.01
|
||||
* } );
|
||||
* composer.addPass( bokehPass );
|
||||
* ```
|
||||
*
|
||||
* @augments Pass
|
||||
* @three_import import { BokehPass } from 'three/addons/postprocessing/BokehPass.js';
|
||||
*/
|
||||
class BokehPass extends Pass {
|
||||
|
||||
/**
|
||||
* Constructs a new Bokeh pass.
|
||||
*
|
||||
* @param {Scene} scene - The scene to render the DOF for.
|
||||
* @param {Camera} camera - The camera.
|
||||
* @param {BokehPass~Options} params - The pass options.
|
||||
*/
|
||||
constructor( scene, camera, params ) {
|
||||
|
||||
super();
|
||||
|
||||
/**
|
||||
* The scene to render the DOF for.
|
||||
*
|
||||
* @type {Scene}
|
||||
*/
|
||||
this.scene = scene;
|
||||
|
||||
/**
|
||||
* The camera.
|
||||
*
|
||||
* @type {Camera}
|
||||
*/
|
||||
this.camera = camera;
|
||||
|
||||
const focus = ( params.focus !== undefined ) ? params.focus : 1.0;
|
||||
const aperture = ( params.aperture !== undefined ) ? params.aperture : 0.025;
|
||||
const maxblur = ( params.maxblur !== undefined ) ? params.maxblur : 1.0;
|
||||
|
||||
// render targets
|
||||
|
||||
this._renderTargetDepth = new WebGLRenderTarget( 1, 1, { // will be resized later
|
||||
minFilter: NearestFilter,
|
||||
magFilter: NearestFilter,
|
||||
type: HalfFloatType
|
||||
} );
|
||||
|
||||
this._renderTargetDepth.texture.name = 'BokehPass.depth';
|
||||
|
||||
// depth material
|
||||
|
||||
this._materialDepth = new MeshDepthMaterial();
|
||||
this._materialDepth.depthPacking = RGBADepthPacking;
|
||||
this._materialDepth.blending = NoBlending;
|
||||
|
||||
// bokeh material
|
||||
|
||||
const bokehUniforms = UniformsUtils.clone( BokehShader.uniforms );
|
||||
|
||||
bokehUniforms[ 'tDepth' ].value = this._renderTargetDepth.texture;
|
||||
|
||||
bokehUniforms[ 'focus' ].value = focus;
|
||||
bokehUniforms[ 'aspect' ].value = camera.aspect;
|
||||
bokehUniforms[ 'aperture' ].value = aperture;
|
||||
bokehUniforms[ 'maxblur' ].value = maxblur;
|
||||
bokehUniforms[ 'nearClip' ].value = camera.near;
|
||||
bokehUniforms[ 'farClip' ].value = camera.far;
|
||||
|
||||
/**
|
||||
* The pass bokeh material.
|
||||
*
|
||||
* @type {ShaderMaterial}
|
||||
*/
|
||||
this.materialBokeh = new ShaderMaterial( {
|
||||
defines: Object.assign( {}, BokehShader.defines ),
|
||||
uniforms: bokehUniforms,
|
||||
vertexShader: BokehShader.vertexShader,
|
||||
fragmentShader: BokehShader.fragmentShader
|
||||
} );
|
||||
|
||||
/**
|
||||
* The pass uniforms. Use this object if you want to update the
|
||||
* `focus`, `aperture` or `maxblur` values at runtime.
|
||||
*
|
||||
* ```js
|
||||
* pass.uniforms.focus.value = focus;
|
||||
* pass.uniforms.aperture.value = aperture;
|
||||
* pass.uniforms.maxblur.value = maxblur;
|
||||
* ```
|
||||
*
|
||||
* @type {Object}
|
||||
*/
|
||||
this.uniforms = bokehUniforms;
|
||||
|
||||
// internals
|
||||
|
||||
this._fsQuad = new FullScreenQuad( this.materialBokeh );
|
||||
|
||||
this._oldClearColor = new Color();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs the Bokeh pass.
|
||||
*
|
||||
* @param {WebGLRenderer} renderer - The renderer.
|
||||
* @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
|
||||
* destination for the pass.
|
||||
* @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
|
||||
* previous pass from this buffer.
|
||||
* @param {number} deltaTime - The delta time in seconds.
|
||||
* @param {boolean} maskActive - Whether masking is active or not.
|
||||
*/
|
||||
render( renderer, writeBuffer, readBuffer/*, deltaTime, maskActive*/ ) {
|
||||
|
||||
// Render depth into texture
|
||||
|
||||
this.scene.overrideMaterial = this._materialDepth;
|
||||
|
||||
renderer.getClearColor( this._oldClearColor );
|
||||
const oldClearAlpha = renderer.getClearAlpha();
|
||||
const oldAutoClear = renderer.autoClear;
|
||||
renderer.autoClear = false;
|
||||
|
||||
renderer.setClearColor( 0xffffff );
|
||||
renderer.setClearAlpha( 1.0 );
|
||||
renderer.setRenderTarget( this._renderTargetDepth );
|
||||
renderer.clear();
|
||||
renderer.render( this.scene, this.camera );
|
||||
|
||||
// Render bokeh composite
|
||||
|
||||
this.uniforms[ 'tColor' ].value = readBuffer.texture;
|
||||
this.uniforms[ 'nearClip' ].value = this.camera.near;
|
||||
this.uniforms[ 'farClip' ].value = this.camera.far;
|
||||
|
||||
if ( this.renderToScreen ) {
|
||||
|
||||
renderer.setRenderTarget( null );
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
} else {
|
||||
|
||||
renderer.setRenderTarget( writeBuffer );
|
||||
renderer.clear();
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
}
|
||||
|
||||
this.scene.overrideMaterial = null;
|
||||
renderer.setClearColor( this._oldClearColor );
|
||||
renderer.setClearAlpha( oldClearAlpha );
|
||||
renderer.autoClear = oldAutoClear;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the size of the pass.
|
||||
*
|
||||
* @param {number} width - The width to set.
|
||||
* @param {number} height - The height to set.
|
||||
*/
|
||||
setSize( width, height ) {
|
||||
|
||||
this.materialBokeh.uniforms[ 'aspect' ].value = width / height;
|
||||
|
||||
this._renderTargetDepth.setSize( width, height );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Frees the GPU-related resources allocated by this instance. Call this
|
||||
* method whenever the pass is no longer used in your app.
|
||||
*/
|
||||
dispose() {
|
||||
|
||||
this._renderTargetDepth.dispose();
|
||||
|
||||
this._materialDepth.dispose();
|
||||
this.materialBokeh.dispose();
|
||||
|
||||
this._fsQuad.dispose();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructor options of `BokehPass`.
|
||||
*
|
||||
* @typedef {Object} BokehPass~Options
|
||||
* @property {number} [focus=1] - Defines the effect's focus which is the distance along the camera's look direction in world units.
|
||||
* @property {number} [aperture=0.025] - Defines the effect's aperture.
|
||||
* @property {number} [maxblur=1] - Defines the effect's maximum blur.
|
||||
**/
|
||||
|
||||
export { BokehPass };
|
||||
@@ -0,0 +1,97 @@
|
||||
import {
|
||||
Color
|
||||
} from 'three';
|
||||
import { Pass } from './Pass.js';
|
||||
|
||||
/**
|
||||
* This class can be used to force a clear operation for the current read or
|
||||
* default framebuffer (when rendering to screen).
|
||||
*
|
||||
* ```js
|
||||
* const clearPass = new ClearPass();
|
||||
* composer.addPass( clearPass );
|
||||
* ```
|
||||
*
|
||||
* @augments Pass
|
||||
* @three_import import { ClearPass } from 'three/addons/postprocessing/ClearPass.js';
|
||||
*/
|
||||
class ClearPass extends Pass {
|
||||
|
||||
/**
|
||||
* Constructs a new clear pass.
|
||||
*
|
||||
* @param {(number|Color|string)} [clearColor=0x000000] - The clear color.
|
||||
* @param {number} [clearAlpha=0] - The clear alpha.
|
||||
*/
|
||||
constructor( clearColor = 0x000000, clearAlpha = 0 ) {
|
||||
|
||||
super();
|
||||
|
||||
/**
|
||||
* Overwritten to disable the swap.
|
||||
*
|
||||
* @type {boolean}
|
||||
* @default false
|
||||
*/
|
||||
this.needsSwap = false;
|
||||
|
||||
/**
|
||||
* The clear color.
|
||||
*
|
||||
* @type {(number|Color|string)}
|
||||
* @default 0x000000
|
||||
*/
|
||||
this.clearColor = clearColor;
|
||||
|
||||
/**
|
||||
* The clear alpha.
|
||||
*
|
||||
* @type {number}
|
||||
* @default 0
|
||||
*/
|
||||
this.clearAlpha = clearAlpha;
|
||||
|
||||
// internals
|
||||
|
||||
this._oldClearColor = new Color();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs the clear operation. This affects the current read or the default framebuffer.
|
||||
*
|
||||
* @param {WebGLRenderer} renderer - The renderer.
|
||||
* @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
|
||||
* destination for the pass.
|
||||
* @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
|
||||
* previous pass from this buffer.
|
||||
* @param {number} deltaTime - The delta time in seconds.
|
||||
* @param {boolean} maskActive - Whether masking is active or not.
|
||||
*/
|
||||
render( renderer, writeBuffer, readBuffer /*, deltaTime, maskActive */ ) {
|
||||
|
||||
let oldClearAlpha;
|
||||
|
||||
if ( this.clearColor ) {
|
||||
|
||||
renderer.getClearColor( this._oldClearColor );
|
||||
oldClearAlpha = renderer.getClearAlpha();
|
||||
|
||||
renderer.setClearColor( this.clearColor, this.clearAlpha );
|
||||
|
||||
}
|
||||
|
||||
renderer.setRenderTarget( this.renderToScreen ? null : readBuffer );
|
||||
renderer.clear();
|
||||
|
||||
if ( this.clearColor ) {
|
||||
|
||||
renderer.setClearColor( this._oldClearColor, oldClearAlpha );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export { ClearPass };
|
||||
@@ -0,0 +1,146 @@
|
||||
import {
|
||||
BackSide,
|
||||
BoxGeometry,
|
||||
Mesh,
|
||||
PerspectiveCamera,
|
||||
Scene,
|
||||
ShaderLib,
|
||||
ShaderMaterial,
|
||||
UniformsUtils
|
||||
} from 'three';
|
||||
import { Pass } from './Pass.js';
|
||||
|
||||
/**
|
||||
* This pass can be used to render a cube texture over the entire screen.
|
||||
*
|
||||
* ```js
|
||||
* const cubeMap = new THREE.CubeTextureLoader().load( urls );
|
||||
*
|
||||
* const cubeTexturePass = new CubeTexturePass( camera, cubemap );
|
||||
* composer.addPass( cubeTexturePass );
|
||||
* ```
|
||||
*
|
||||
* @augments Pass
|
||||
* @three_import import { CubeTexturePass } from 'three/addons/postprocessing/CubeTexturePass.js';
|
||||
*/
|
||||
class CubeTexturePass extends Pass {
|
||||
|
||||
/**
|
||||
* Constructs a new cube texture pass.
|
||||
*
|
||||
* @param {PerspectiveCamera} camera - The camera.
|
||||
* @param {CubeTexture} tCube - The cube texture to render.
|
||||
* @param {number} [opacity=1] - The opacity.
|
||||
*/
|
||||
constructor( camera, tCube, opacity = 1 ) {
|
||||
|
||||
super();
|
||||
|
||||
/**
|
||||
* The camera.
|
||||
*
|
||||
* @type {PerspectiveCamera}
|
||||
*/
|
||||
this.camera = camera;
|
||||
|
||||
/**
|
||||
* The cube texture to render.
|
||||
*
|
||||
* @type {CubeTexture}
|
||||
*/
|
||||
this.tCube = tCube;
|
||||
|
||||
/**
|
||||
* The opacity.
|
||||
*
|
||||
* @type {number}
|
||||
* @default 1
|
||||
*/
|
||||
this.opacity = opacity;
|
||||
|
||||
/**
|
||||
* Overwritten to disable the swap.
|
||||
*
|
||||
* @type {boolean}
|
||||
* @default false
|
||||
*/
|
||||
this.needsSwap = false;
|
||||
|
||||
// internals
|
||||
|
||||
const cubeShader = ShaderLib[ 'cube' ];
|
||||
|
||||
this._cubeMesh = new Mesh(
|
||||
new BoxGeometry( 10, 10, 10 ),
|
||||
new ShaderMaterial( {
|
||||
uniforms: UniformsUtils.clone( cubeShader.uniforms ),
|
||||
vertexShader: cubeShader.vertexShader,
|
||||
fragmentShader: cubeShader.fragmentShader,
|
||||
depthTest: false,
|
||||
depthWrite: false,
|
||||
side: BackSide
|
||||
} )
|
||||
);
|
||||
|
||||
Object.defineProperty( this._cubeMesh.material, 'envMap', {
|
||||
|
||||
get: function () {
|
||||
|
||||
return this.uniforms.tCube.value;
|
||||
|
||||
}
|
||||
|
||||
} );
|
||||
|
||||
this._cubeScene = new Scene();
|
||||
this._cubeCamera = new PerspectiveCamera();
|
||||
this._cubeScene.add( this._cubeMesh );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs the cube texture pass.
|
||||
*
|
||||
* @param {WebGLRenderer} renderer - The renderer.
|
||||
* @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
|
||||
* destination for the pass.
|
||||
* @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
|
||||
* previous pass from this buffer.
|
||||
* @param {number} deltaTime - The delta time in seconds.
|
||||
* @param {boolean} maskActive - Whether masking is active or not.
|
||||
*/
|
||||
render( renderer, writeBuffer, readBuffer/*, deltaTime, maskActive*/ ) {
|
||||
|
||||
const oldAutoClear = renderer.autoClear;
|
||||
renderer.autoClear = false;
|
||||
|
||||
this._cubeCamera.projectionMatrix.copy( this.camera.projectionMatrix );
|
||||
this._cubeCamera.quaternion.setFromRotationMatrix( this.camera.matrixWorld );
|
||||
|
||||
this._cubeMesh.material.uniforms.tCube.value = this.tCube;
|
||||
this._cubeMesh.material.uniforms.tFlip.value = ( this.tCube.isCubeTexture && this.tCube.isRenderTargetTexture === false ) ? - 1 : 1;
|
||||
this._cubeMesh.material.uniforms.opacity.value = this.opacity;
|
||||
this._cubeMesh.material.transparent = ( this.opacity < 1.0 );
|
||||
|
||||
renderer.setRenderTarget( this.renderToScreen ? null : readBuffer );
|
||||
if ( this.clear ) renderer.clear();
|
||||
renderer.render( this._cubeScene, this._cubeCamera );
|
||||
|
||||
renderer.autoClear = oldAutoClear;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Frees the GPU-related resources allocated by this instance. Call this
|
||||
* method whenever the pass is no longer used in your app.
|
||||
*/
|
||||
dispose() {
|
||||
|
||||
this._cubeMesh.geometry.dispose();
|
||||
this._cubeMesh.material.dispose();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export { CubeTexturePass };
|
||||
@@ -0,0 +1,114 @@
|
||||
import {
|
||||
ShaderMaterial,
|
||||
UniformsUtils
|
||||
} from 'three';
|
||||
import { Pass, FullScreenQuad } from './Pass.js';
|
||||
import { DotScreenShader } from '../shaders/DotScreenShader.js';
|
||||
|
||||
/**
|
||||
* Pass for creating a dot-screen effect.
|
||||
*
|
||||
* ```js
|
||||
* const pass = new DotScreenPass( new THREE.Vector2( 0, 0 ), 0.5, 0.8 );
|
||||
* composer.addPass( pass );
|
||||
* ```
|
||||
*
|
||||
* @augments Pass
|
||||
* @three_import import { DotScreenPass } from 'three/addons/postprocessing/DotScreenPass.js';
|
||||
*/
|
||||
class DotScreenPass extends Pass {
|
||||
|
||||
/**
|
||||
* Constructs a new dot screen pass.
|
||||
*
|
||||
* @param {Vector2} center - The center point.
|
||||
* @param {number} angle - The rotation of the effect in radians.
|
||||
* @param {number} scale - The scale of the effect. A higher value means smaller dots.
|
||||
*/
|
||||
constructor( center, angle, scale ) {
|
||||
|
||||
super();
|
||||
|
||||
/**
|
||||
* The pass uniforms. Use this object if you want to update the
|
||||
* `center`, `angle` or `scale` values at runtime.
|
||||
* ```js
|
||||
* pass.uniforms.center.value.copy( center );
|
||||
* pass.uniforms.angle.value = 0;
|
||||
* pass.uniforms.scale.value = 0.5;
|
||||
* ```
|
||||
*
|
||||
* @type {Object}
|
||||
*/
|
||||
this.uniforms = UniformsUtils.clone( DotScreenShader.uniforms );
|
||||
|
||||
if ( center !== undefined ) this.uniforms[ 'center' ].value.copy( center );
|
||||
if ( angle !== undefined ) this.uniforms[ 'angle' ].value = angle;
|
||||
if ( scale !== undefined ) this.uniforms[ 'scale' ].value = scale;
|
||||
|
||||
/**
|
||||
* The pass material.
|
||||
*
|
||||
* @type {ShaderMaterial}
|
||||
*/
|
||||
this.material = new ShaderMaterial( {
|
||||
|
||||
name: DotScreenShader.name,
|
||||
uniforms: this.uniforms,
|
||||
vertexShader: DotScreenShader.vertexShader,
|
||||
fragmentShader: DotScreenShader.fragmentShader
|
||||
|
||||
} );
|
||||
|
||||
// internals
|
||||
|
||||
this._fsQuad = new FullScreenQuad( this.material );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs the dot screen pass.
|
||||
*
|
||||
* @param {WebGLRenderer} renderer - The renderer.
|
||||
* @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
|
||||
* destination for the pass.
|
||||
* @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
|
||||
* previous pass from this buffer.
|
||||
* @param {number} deltaTime - The delta time in seconds.
|
||||
* @param {boolean} maskActive - Whether masking is active or not.
|
||||
*/
|
||||
render( renderer, writeBuffer, readBuffer /*, deltaTime, maskActive */ ) {
|
||||
|
||||
this.uniforms[ 'tDiffuse' ].value = readBuffer.texture;
|
||||
this.uniforms[ 'tSize' ].value.set( readBuffer.width, readBuffer.height );
|
||||
|
||||
if ( this.renderToScreen ) {
|
||||
|
||||
renderer.setRenderTarget( null );
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
} else {
|
||||
|
||||
renderer.setRenderTarget( writeBuffer );
|
||||
if ( this.clear ) renderer.clear();
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Frees the GPU-related resources allocated by this instance. Call this
|
||||
* method whenever the pass is no longer used in your app.
|
||||
*/
|
||||
dispose() {
|
||||
|
||||
this.material.dispose();
|
||||
|
||||
this._fsQuad.dispose();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export { DotScreenPass };
|
||||
@@ -0,0 +1,365 @@
|
||||
import {
|
||||
HalfFloatType,
|
||||
NoBlending,
|
||||
Timer,
|
||||
Vector2,
|
||||
WebGLRenderTarget
|
||||
} from 'three';
|
||||
import { CopyShader } from '../shaders/CopyShader.js';
|
||||
import { ShaderPass } from './ShaderPass.js';
|
||||
import { ClearMaskPass, MaskPass } from './MaskPass.js';
|
||||
|
||||
/**
|
||||
* Used to implement post-processing effects in three.js.
|
||||
* The class manages a chain of post-processing passes to produce the final visual result.
|
||||
* Post-processing passes are executed in order of their addition/insertion.
|
||||
* The last pass is automatically rendered to screen.
|
||||
*
|
||||
* This module can only be used with {@link WebGLRenderer}.
|
||||
*
|
||||
* ```js
|
||||
* const composer = new EffectComposer( renderer );
|
||||
*
|
||||
* // adding some passes
|
||||
* const renderPass = new RenderPass( scene, camera );
|
||||
* composer.addPass( renderPass );
|
||||
*
|
||||
* const glitchPass = new GlitchPass();
|
||||
* composer.addPass( glitchPass );
|
||||
*
|
||||
* const outputPass = new OutputPass()
|
||||
* composer.addPass( outputPass );
|
||||
*
|
||||
* function animate() {
|
||||
*
|
||||
* composer.render(); // instead of renderer.render()
|
||||
*
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @three_import import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
|
||||
*/
|
||||
class EffectComposer {
|
||||
|
||||
/**
|
||||
* Constructs a new effect composer.
|
||||
*
|
||||
* @param {WebGLRenderer} renderer - The renderer.
|
||||
* @param {WebGLRenderTarget} [renderTarget] - This render target and a clone will
|
||||
* be used as the internal read and write buffers. If not given, the composer creates
|
||||
* the buffers automatically.
|
||||
*/
|
||||
constructor( renderer, renderTarget ) {
|
||||
|
||||
/**
|
||||
* The renderer.
|
||||
*
|
||||
* @type {WebGLRenderer}
|
||||
*/
|
||||
this.renderer = renderer;
|
||||
|
||||
this._pixelRatio = renderer.getPixelRatio();
|
||||
|
||||
if ( renderTarget === undefined ) {
|
||||
|
||||
const size = renderer.getSize( new Vector2() );
|
||||
this._width = size.width;
|
||||
this._height = size.height;
|
||||
|
||||
renderTarget = new WebGLRenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType } );
|
||||
renderTarget.texture.name = 'EffectComposer.rt1';
|
||||
|
||||
} else {
|
||||
|
||||
this._width = renderTarget.width;
|
||||
this._height = renderTarget.height;
|
||||
|
||||
}
|
||||
|
||||
this.renderTarget1 = renderTarget;
|
||||
this.renderTarget2 = renderTarget.clone();
|
||||
this.renderTarget2.texture.name = 'EffectComposer.rt2';
|
||||
|
||||
/**
|
||||
* A reference to the internal write buffer. Passes usually write
|
||||
* their result into this buffer.
|
||||
*
|
||||
* @type {WebGLRenderTarget}
|
||||
*/
|
||||
this.writeBuffer = this.renderTarget1;
|
||||
|
||||
/**
|
||||
* A reference to the internal read buffer. Passes usually read
|
||||
* the previous render result from this buffer.
|
||||
*
|
||||
* @type {WebGLRenderTarget}
|
||||
*/
|
||||
this.readBuffer = this.renderTarget2;
|
||||
|
||||
/**
|
||||
* Whether the final pass is rendered to the screen (default framebuffer) or not.
|
||||
*
|
||||
* @type {boolean}
|
||||
* @default true
|
||||
*/
|
||||
this.renderToScreen = true;
|
||||
|
||||
/**
|
||||
* An array representing the (ordered) chain of post-processing passes.
|
||||
*
|
||||
* @type {Array<Pass>}
|
||||
*/
|
||||
this.passes = [];
|
||||
|
||||
/**
|
||||
* A copy pass used for internal swap operations.
|
||||
*
|
||||
* @private
|
||||
* @type {ShaderPass}
|
||||
*/
|
||||
this.copyPass = new ShaderPass( CopyShader );
|
||||
this.copyPass.material.blending = NoBlending;
|
||||
|
||||
/**
|
||||
* The internal timer for managing time data.
|
||||
*
|
||||
* @private
|
||||
* @type {Timer}
|
||||
*/
|
||||
this.timer = new Timer();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Swaps the internal read/write buffers.
|
||||
*/
|
||||
swapBuffers() {
|
||||
|
||||
const tmp = this.readBuffer;
|
||||
this.readBuffer = this.writeBuffer;
|
||||
this.writeBuffer = tmp;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the given pass to the pass chain.
|
||||
*
|
||||
* @param {Pass} pass - The pass to add.
|
||||
*/
|
||||
addPass( pass ) {
|
||||
|
||||
this.passes.push( pass );
|
||||
pass.setSize( this._width * this._pixelRatio, this._height * this._pixelRatio );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts the given pass at a given index.
|
||||
*
|
||||
* @param {Pass} pass - The pass to insert.
|
||||
* @param {number} index - The index into the pass chain.
|
||||
*/
|
||||
insertPass( pass, index ) {
|
||||
|
||||
this.passes.splice( index, 0, pass );
|
||||
pass.setSize( this._width * this._pixelRatio, this._height * this._pixelRatio );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the given pass from the pass chain.
|
||||
*
|
||||
* @param {Pass} pass - The pass to remove.
|
||||
*/
|
||||
removePass( pass ) {
|
||||
|
||||
const index = this.passes.indexOf( pass );
|
||||
|
||||
if ( index !== - 1 ) {
|
||||
|
||||
this.passes.splice( index, 1 );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns `true` if the pass for the given index is the last enabled pass in the pass chain.
|
||||
*
|
||||
* @param {number} passIndex - The pass index.
|
||||
* @return {boolean} Whether the pass for the given index is the last pass in the pass chain.
|
||||
*/
|
||||
isLastEnabledPass( passIndex ) {
|
||||
|
||||
for ( let i = passIndex + 1; i < this.passes.length; i ++ ) {
|
||||
|
||||
if ( this.passes[ i ].enabled ) {
|
||||
|
||||
return false;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return true;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes all enabled post-processing passes in order to produce the final frame.
|
||||
*
|
||||
* @param {number} deltaTime - The delta time in seconds. If not given, the composer computes
|
||||
* its own time delta value.
|
||||
*/
|
||||
render( deltaTime ) {
|
||||
|
||||
// deltaTime value is in seconds
|
||||
|
||||
this.timer.update();
|
||||
|
||||
if ( deltaTime === undefined ) {
|
||||
|
||||
deltaTime = this.timer.getDelta();
|
||||
|
||||
}
|
||||
|
||||
const currentRenderTarget = this.renderer.getRenderTarget();
|
||||
|
||||
let maskActive = false;
|
||||
|
||||
for ( let i = 0, il = this.passes.length; i < il; i ++ ) {
|
||||
|
||||
const pass = this.passes[ i ];
|
||||
|
||||
if ( pass.enabled === false ) continue;
|
||||
|
||||
pass.renderToScreen = ( this.renderToScreen && this.isLastEnabledPass( i ) );
|
||||
pass.render( this.renderer, this.writeBuffer, this.readBuffer, deltaTime, maskActive );
|
||||
|
||||
if ( pass.needsSwap ) {
|
||||
|
||||
if ( maskActive ) {
|
||||
|
||||
const context = this.renderer.getContext();
|
||||
const stencil = this.renderer.state.buffers.stencil;
|
||||
|
||||
//context.stencilFunc( context.NOTEQUAL, 1, 0xffffffff );
|
||||
stencil.setFunc( context.NOTEQUAL, 1, 0xffffffff );
|
||||
|
||||
this.copyPass.render( this.renderer, this.writeBuffer, this.readBuffer, deltaTime );
|
||||
|
||||
//context.stencilFunc( context.EQUAL, 1, 0xffffffff );
|
||||
stencil.setFunc( context.EQUAL, 1, 0xffffffff );
|
||||
|
||||
}
|
||||
|
||||
this.swapBuffers();
|
||||
|
||||
}
|
||||
|
||||
if ( MaskPass !== undefined ) {
|
||||
|
||||
if ( pass instanceof MaskPass ) {
|
||||
|
||||
maskActive = true;
|
||||
|
||||
} else if ( pass instanceof ClearMaskPass ) {
|
||||
|
||||
maskActive = false;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
this.renderer.setRenderTarget( currentRenderTarget );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets the internal state of the EffectComposer.
|
||||
*
|
||||
* @param {WebGLRenderTarget} [renderTarget] - This render target has the same purpose like
|
||||
* the one from the constructor. If set, it is used to setup the read and write buffers.
|
||||
*/
|
||||
reset( renderTarget ) {
|
||||
|
||||
if ( renderTarget === undefined ) {
|
||||
|
||||
const size = this.renderer.getSize( new Vector2() );
|
||||
this._pixelRatio = this.renderer.getPixelRatio();
|
||||
this._width = size.width;
|
||||
this._height = size.height;
|
||||
|
||||
renderTarget = this.renderTarget1.clone();
|
||||
renderTarget.setSize( this._width * this._pixelRatio, this._height * this._pixelRatio );
|
||||
|
||||
}
|
||||
|
||||
this.renderTarget1.dispose();
|
||||
this.renderTarget2.dispose();
|
||||
this.renderTarget1 = renderTarget;
|
||||
this.renderTarget2 = renderTarget.clone();
|
||||
|
||||
this.writeBuffer = this.renderTarget1;
|
||||
this.readBuffer = this.renderTarget2;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Resizes the internal read and write buffers as well as all passes. Similar to {@link WebGLRenderer#setSize},
|
||||
* this method honors the current pixel ration.
|
||||
*
|
||||
* @param {number} width - The width in logical pixels.
|
||||
* @param {number} height - The height in logical pixels.
|
||||
*/
|
||||
setSize( width, height ) {
|
||||
|
||||
this._width = width;
|
||||
this._height = height;
|
||||
|
||||
const effectiveWidth = this._width * this._pixelRatio;
|
||||
const effectiveHeight = this._height * this._pixelRatio;
|
||||
|
||||
this.renderTarget1.setSize( effectiveWidth, effectiveHeight );
|
||||
this.renderTarget2.setSize( effectiveWidth, effectiveHeight );
|
||||
|
||||
for ( let i = 0; i < this.passes.length; i ++ ) {
|
||||
|
||||
this.passes[ i ].setSize( effectiveWidth, effectiveHeight );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets device pixel ratio. This is usually used for HiDPI device to prevent blurring output.
|
||||
* Setting the pixel ratio will automatically resize the composer.
|
||||
*
|
||||
* @param {number} pixelRatio - The pixel ratio to set.
|
||||
*/
|
||||
setPixelRatio( pixelRatio ) {
|
||||
|
||||
this._pixelRatio = pixelRatio;
|
||||
|
||||
this.setSize( this._width, this._height );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Frees the GPU-related resources allocated by this instance. Call this
|
||||
* method whenever the composer is no longer used in your app.
|
||||
*/
|
||||
dispose() {
|
||||
|
||||
this.renderTarget1.dispose();
|
||||
this.renderTarget2.dispose();
|
||||
|
||||
this.copyPass.dispose();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export { EffectComposer };
|
||||
@@ -0,0 +1,40 @@
|
||||
import { FXAAShader } from '../shaders/FXAAShader.js';
|
||||
import { ShaderPass } from './ShaderPass.js';
|
||||
|
||||
/**
|
||||
* A pass for applying FXAA.
|
||||
*
|
||||
* ```js
|
||||
* const fxaaPass = new FXAAPass();
|
||||
* composer.addPass( fxaaPass );
|
||||
* ```
|
||||
*
|
||||
* @augments ShaderPass
|
||||
* @three_import import { FXAAPass } from 'three/addons/postprocessing/FXAAPass.js';
|
||||
*/
|
||||
class FXAAPass extends ShaderPass {
|
||||
|
||||
/**
|
||||
* Constructs a new FXAA pass.
|
||||
*/
|
||||
constructor() {
|
||||
|
||||
super( FXAAShader );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the size of the pass.
|
||||
*
|
||||
* @param {number} width - The width to set.
|
||||
* @param {number} height - The height to set.
|
||||
*/
|
||||
setSize( width, height ) {
|
||||
|
||||
this.material.uniforms[ 'resolution' ].value.set( 1 / width, 1 / height );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export { FXAAPass };
|
||||
@@ -0,0 +1,113 @@
|
||||
import {
|
||||
ShaderMaterial,
|
||||
UniformsUtils
|
||||
} from 'three';
|
||||
import { Pass, FullScreenQuad } from './Pass.js';
|
||||
import { FilmShader } from '../shaders/FilmShader.js';
|
||||
|
||||
/**
|
||||
* This pass can be used to create a film grain effect.
|
||||
*
|
||||
* ```js
|
||||
* const filmPass = new FilmPass();
|
||||
* composer.addPass( filmPass );
|
||||
* ```
|
||||
*
|
||||
* @augments Pass
|
||||
* @three_import import { FilmPass } from 'three/addons/postprocessing/FilmPass.js';
|
||||
*/
|
||||
class FilmPass extends Pass {
|
||||
|
||||
/**
|
||||
* Constructs a new film pass.
|
||||
*
|
||||
* @param {number} [intensity=0.5] - The grain intensity in the range `[0,1]` (0 = no effect, 1 = full effect).
|
||||
* @param {boolean} [grayscale=false] - Whether to apply a grayscale effect or not.
|
||||
*/
|
||||
constructor( intensity = 0.5, grayscale = false ) {
|
||||
|
||||
super();
|
||||
|
||||
const shader = FilmShader;
|
||||
|
||||
/**
|
||||
* The pass uniforms. Use this object if you want to update the
|
||||
* `intensity` or `grayscale` values at runtime.
|
||||
* ```js
|
||||
* pass.uniforms.intensity.value = 1;
|
||||
* pass.uniforms.grayscale.value = true;
|
||||
* ```
|
||||
*
|
||||
* @type {Object}
|
||||
*/
|
||||
this.uniforms = UniformsUtils.clone( shader.uniforms );
|
||||
|
||||
/**
|
||||
* The pass material.
|
||||
*
|
||||
* @type {ShaderMaterial}
|
||||
*/
|
||||
this.material = new ShaderMaterial( {
|
||||
|
||||
name: shader.name,
|
||||
uniforms: this.uniforms,
|
||||
vertexShader: shader.vertexShader,
|
||||
fragmentShader: shader.fragmentShader
|
||||
|
||||
} );
|
||||
|
||||
this.uniforms.intensity.value = intensity;
|
||||
this.uniforms.grayscale.value = grayscale;
|
||||
|
||||
// internals
|
||||
|
||||
this._fsQuad = new FullScreenQuad( this.material );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs the film pass.
|
||||
*
|
||||
* @param {WebGLRenderer} renderer - The renderer.
|
||||
* @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
|
||||
* destination for the pass.
|
||||
* @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
|
||||
* previous pass from this buffer.
|
||||
* @param {number} deltaTime - The delta time in seconds.
|
||||
* @param {boolean} maskActive - Whether masking is active or not.
|
||||
*/
|
||||
render( renderer, writeBuffer, readBuffer, deltaTime /*, maskActive */ ) {
|
||||
|
||||
this.uniforms[ 'tDiffuse' ].value = readBuffer.texture;
|
||||
this.uniforms[ 'time' ].value += deltaTime;
|
||||
|
||||
if ( this.renderToScreen ) {
|
||||
|
||||
renderer.setRenderTarget( null );
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
} else {
|
||||
|
||||
renderer.setRenderTarget( writeBuffer );
|
||||
if ( this.clear ) renderer.clear();
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Frees the GPU-related resources allocated by this instance. Call this
|
||||
* method whenever the pass is no longer used in your app.
|
||||
*/
|
||||
dispose() {
|
||||
|
||||
this.material.dispose();
|
||||
|
||||
this._fsQuad.dispose();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export { FilmPass };
|
||||
@@ -0,0 +1,735 @@
|
||||
import {
|
||||
AddEquation,
|
||||
Color,
|
||||
CustomBlending,
|
||||
DataTexture,
|
||||
DepthTexture,
|
||||
DepthStencilFormat,
|
||||
DstAlphaFactor,
|
||||
DstColorFactor,
|
||||
HalfFloatType,
|
||||
MeshNormalMaterial,
|
||||
NearestFilter,
|
||||
NoBlending,
|
||||
RepeatWrapping,
|
||||
RGBAFormat,
|
||||
ShaderMaterial,
|
||||
UniformsUtils,
|
||||
UnsignedByteType,
|
||||
UnsignedInt248Type,
|
||||
WebGLRenderTarget,
|
||||
ZeroFactor
|
||||
} from 'three';
|
||||
import { Pass, FullScreenQuad } from './Pass.js';
|
||||
import { generateMagicSquareNoise, GTAOShader, GTAODepthShader, GTAOBlendShader } from '../shaders/GTAOShader.js';
|
||||
import { generatePdSamplePointInitializer, PoissonDenoiseShader } from '../shaders/PoissonDenoiseShader.js';
|
||||
import { CopyShader } from '../shaders/CopyShader.js';
|
||||
import { SimplexNoise } from '../math/SimplexNoise.js';
|
||||
|
||||
/**
|
||||
* A pass for an GTAO effect.
|
||||
*
|
||||
* `GTAOPass` provides better quality than {@link SSAOPass} but is also more expensive.
|
||||
*
|
||||
* ```js
|
||||
* const gtaoPass = new GTAOPass( scene, camera, width, height );
|
||||
* gtaoPass.output = GTAOPass.OUTPUT.Denoise;
|
||||
* composer.addPass( gtaoPass );
|
||||
* ```
|
||||
*
|
||||
* @augments Pass
|
||||
* @three_import import { GTAOPass } from 'three/addons/postprocessing/GTAOPass.js';
|
||||
*/
|
||||
class GTAOPass extends Pass {
|
||||
|
||||
/**
|
||||
* Constructs a new GTAO pass.
|
||||
*
|
||||
* @param {Scene} scene - The scene to compute the AO for.
|
||||
* @param {Camera} camera - The camera.
|
||||
* @param {number} [width=512] - The width of the effect.
|
||||
* @param {number} [height=512] - The height of the effect.
|
||||
* @param {Object} [parameters] - The pass parameters.
|
||||
* @param {Object} [aoParameters] - The AO parameters.
|
||||
* @param {Object} [pdParameters] - The denoise parameters.
|
||||
*/
|
||||
constructor( scene, camera, width = 512, height = 512, parameters, aoParameters, pdParameters ) {
|
||||
|
||||
super();
|
||||
|
||||
/**
|
||||
* The width of the effect.
|
||||
*
|
||||
* @type {number}
|
||||
* @default 512
|
||||
*/
|
||||
this.width = width;
|
||||
|
||||
/**
|
||||
* The height of the effect.
|
||||
*
|
||||
* @type {number}
|
||||
* @default 512
|
||||
*/
|
||||
this.height = height;
|
||||
|
||||
/**
|
||||
* Overwritten to perform a clear operation by default.
|
||||
*
|
||||
* @type {boolean}
|
||||
* @default true
|
||||
*/
|
||||
this.clear = true;
|
||||
|
||||
/**
|
||||
* The camera.
|
||||
*
|
||||
* @type {Camera}
|
||||
*/
|
||||
this.camera = camera;
|
||||
|
||||
/**
|
||||
* The scene to render the AO for.
|
||||
*
|
||||
* @type {Scene}
|
||||
*/
|
||||
this.scene = scene;
|
||||
|
||||
/**
|
||||
* The output configuration.
|
||||
*
|
||||
* @type {number}
|
||||
* @default 0
|
||||
*/
|
||||
this.output = 0;
|
||||
this._renderGBuffer = true;
|
||||
this._visibilityCache = [];
|
||||
|
||||
/**
|
||||
* The AO blend intensity.
|
||||
*
|
||||
* @type {number}
|
||||
* @default 1
|
||||
*/
|
||||
this.blendIntensity = 1.;
|
||||
|
||||
/**
|
||||
* The number of Poisson Denoise rings.
|
||||
*
|
||||
* @type {number}
|
||||
* @default 2
|
||||
*/
|
||||
this.pdRings = 2.;
|
||||
|
||||
/**
|
||||
* The Poisson Denoise radius exponent.
|
||||
*
|
||||
* @type {number}
|
||||
* @default 2
|
||||
*/
|
||||
this.pdRadiusExponent = 2.;
|
||||
|
||||
/**
|
||||
* The Poisson Denoise sample count.
|
||||
*
|
||||
* @type {number}
|
||||
* @default 16
|
||||
*/
|
||||
this.pdSamples = 16;
|
||||
|
||||
this.gtaoNoiseTexture = generateMagicSquareNoise();
|
||||
this.pdNoiseTexture = this._generateNoise();
|
||||
|
||||
this.gtaoRenderTarget = new WebGLRenderTarget( this.width, this.height, { type: HalfFloatType, depthBuffer: false } );
|
||||
this.pdRenderTarget = this.gtaoRenderTarget.clone();
|
||||
|
||||
this.gtaoMaterial = new ShaderMaterial( {
|
||||
defines: Object.assign( {}, GTAOShader.defines ),
|
||||
uniforms: UniformsUtils.clone( GTAOShader.uniforms ),
|
||||
vertexShader: GTAOShader.vertexShader,
|
||||
fragmentShader: GTAOShader.fragmentShader,
|
||||
blending: NoBlending,
|
||||
depthTest: false,
|
||||
depthWrite: false,
|
||||
} );
|
||||
this.gtaoMaterial.defines.PERSPECTIVE_CAMERA = this.camera.isPerspectiveCamera ? 1 : 0;
|
||||
this.gtaoMaterial.uniforms.tNoise.value = this.gtaoNoiseTexture;
|
||||
this.gtaoMaterial.uniforms.resolution.value.set( this.width, this.height );
|
||||
this.gtaoMaterial.uniforms.cameraNear.value = this.camera.near;
|
||||
this.gtaoMaterial.uniforms.cameraFar.value = this.camera.far;
|
||||
|
||||
this.normalMaterial = new MeshNormalMaterial();
|
||||
this.normalMaterial.blending = NoBlending;
|
||||
|
||||
this.pdMaterial = new ShaderMaterial( {
|
||||
defines: Object.assign( {}, PoissonDenoiseShader.defines ),
|
||||
uniforms: UniformsUtils.clone( PoissonDenoiseShader.uniforms ),
|
||||
vertexShader: PoissonDenoiseShader.vertexShader,
|
||||
fragmentShader: PoissonDenoiseShader.fragmentShader,
|
||||
depthTest: false,
|
||||
depthWrite: false,
|
||||
} );
|
||||
this.pdMaterial.uniforms.tDiffuse.value = this.gtaoRenderTarget.texture;
|
||||
this.pdMaterial.uniforms.tNoise.value = this.pdNoiseTexture;
|
||||
this.pdMaterial.uniforms.resolution.value.set( this.width, this.height );
|
||||
this.pdMaterial.uniforms.lumaPhi.value = 10;
|
||||
this.pdMaterial.uniforms.depthPhi.value = 2;
|
||||
this.pdMaterial.uniforms.normalPhi.value = 3;
|
||||
this.pdMaterial.uniforms.radius.value = 8;
|
||||
|
||||
this.depthRenderMaterial = new ShaderMaterial( {
|
||||
defines: Object.assign( {}, GTAODepthShader.defines ),
|
||||
uniforms: UniformsUtils.clone( GTAODepthShader.uniforms ),
|
||||
vertexShader: GTAODepthShader.vertexShader,
|
||||
fragmentShader: GTAODepthShader.fragmentShader,
|
||||
blending: NoBlending
|
||||
} );
|
||||
this.depthRenderMaterial.uniforms.cameraNear.value = this.camera.near;
|
||||
this.depthRenderMaterial.uniforms.cameraFar.value = this.camera.far;
|
||||
|
||||
this.copyMaterial = new ShaderMaterial( {
|
||||
uniforms: UniformsUtils.clone( CopyShader.uniforms ),
|
||||
vertexShader: CopyShader.vertexShader,
|
||||
fragmentShader: CopyShader.fragmentShader,
|
||||
transparent: true,
|
||||
depthTest: false,
|
||||
depthWrite: false,
|
||||
blendSrc: DstColorFactor,
|
||||
blendDst: ZeroFactor,
|
||||
blendEquation: AddEquation,
|
||||
blendSrcAlpha: DstAlphaFactor,
|
||||
blendDstAlpha: ZeroFactor,
|
||||
blendEquationAlpha: AddEquation
|
||||
} );
|
||||
|
||||
this.blendMaterial = new ShaderMaterial( {
|
||||
uniforms: UniformsUtils.clone( GTAOBlendShader.uniforms ),
|
||||
vertexShader: GTAOBlendShader.vertexShader,
|
||||
fragmentShader: GTAOBlendShader.fragmentShader,
|
||||
transparent: true,
|
||||
depthTest: false,
|
||||
depthWrite: false,
|
||||
blending: CustomBlending,
|
||||
blendSrc: DstColorFactor,
|
||||
blendDst: ZeroFactor,
|
||||
blendEquation: AddEquation,
|
||||
blendSrcAlpha: DstAlphaFactor,
|
||||
blendDstAlpha: ZeroFactor,
|
||||
blendEquationAlpha: AddEquation
|
||||
} );
|
||||
|
||||
this._fsQuad = new FullScreenQuad( null );
|
||||
|
||||
this._originalClearColor = new Color();
|
||||
|
||||
this.setGBuffer( parameters ? parameters.depthTexture : undefined, parameters ? parameters.normalTexture : undefined );
|
||||
|
||||
if ( aoParameters !== undefined ) {
|
||||
|
||||
this.updateGtaoMaterial( aoParameters );
|
||||
|
||||
}
|
||||
|
||||
if ( pdParameters !== undefined ) {
|
||||
|
||||
this.updatePdMaterial( pdParameters );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the size of the pass.
|
||||
*
|
||||
* @param {number} width - The width to set.
|
||||
* @param {number} height - The height to set.
|
||||
*/
|
||||
setSize( width, height ) {
|
||||
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
|
||||
this.gtaoRenderTarget.setSize( width, height );
|
||||
if ( this.normalRenderTarget ) this.normalRenderTarget.setSize( width, height );
|
||||
this.pdRenderTarget.setSize( width, height );
|
||||
|
||||
this.gtaoMaterial.uniforms.resolution.value.set( width, height );
|
||||
this.gtaoMaterial.uniforms.cameraProjectionMatrix.value.copy( this.camera.projectionMatrix );
|
||||
this.gtaoMaterial.uniforms.cameraProjectionMatrixInverse.value.copy( this.camera.projectionMatrixInverse );
|
||||
|
||||
this.pdMaterial.uniforms.resolution.value.set( width, height );
|
||||
this.pdMaterial.uniforms.cameraProjectionMatrixInverse.value.copy( this.camera.projectionMatrixInverse );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Frees the GPU-related resources allocated by this instance. Call this
|
||||
* method whenever the pass is no longer used in your app.
|
||||
*/
|
||||
dispose() {
|
||||
|
||||
this.gtaoNoiseTexture.dispose();
|
||||
this.pdNoiseTexture.dispose();
|
||||
if ( this.normalRenderTarget ) this.normalRenderTarget.dispose();
|
||||
this.gtaoRenderTarget.dispose();
|
||||
this.pdRenderTarget.dispose();
|
||||
this.normalMaterial.dispose();
|
||||
this.pdMaterial.dispose();
|
||||
this.copyMaterial.dispose();
|
||||
this.depthRenderMaterial.dispose();
|
||||
this._fsQuad.dispose();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* A texture holding the computed AO.
|
||||
*
|
||||
* @type {Texture}
|
||||
* @readonly
|
||||
*/
|
||||
get gtaoMap() {
|
||||
|
||||
return this.pdRenderTarget.texture;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures the GBuffer of this pass. If no arguments are passed,
|
||||
* the pass creates an internal render target for holding depth
|
||||
* and normal data. External depth and normal data must use separate
|
||||
* textures and remain owned by the caller.
|
||||
* If no normal texture is supplied, normals are reconstructed from depth
|
||||
* for AO and denoising, and the normal output displays black.
|
||||
*
|
||||
* @param {DepthTexture} [depthTexture] - The depth texture.
|
||||
* @param {Texture} [normalTexture] - The normal texture.
|
||||
*/
|
||||
setGBuffer( depthTexture, normalTexture ) {
|
||||
|
||||
if ( depthTexture !== undefined ) {
|
||||
|
||||
this.depthTexture = depthTexture;
|
||||
this.normalTexture = normalTexture;
|
||||
this._renderGBuffer = false;
|
||||
|
||||
} else {
|
||||
|
||||
if ( this.normalRenderTarget === undefined ) {
|
||||
|
||||
const depthTexture = new DepthTexture();
|
||||
depthTexture.format = DepthStencilFormat;
|
||||
depthTexture.type = UnsignedInt248Type;
|
||||
this.normalRenderTarget = new WebGLRenderTarget( this.width, this.height, {
|
||||
minFilter: NearestFilter,
|
||||
magFilter: NearestFilter,
|
||||
type: HalfFloatType,
|
||||
depthTexture: depthTexture
|
||||
} );
|
||||
|
||||
}
|
||||
|
||||
this.depthTexture = this.normalRenderTarget.depthTexture;
|
||||
this.normalTexture = this.normalRenderTarget.texture;
|
||||
this._renderGBuffer = true;
|
||||
|
||||
}
|
||||
|
||||
const normalVectorType = ( this.normalTexture ) ? 1 : 0;
|
||||
|
||||
this.gtaoMaterial.defines.NORMAL_VECTOR_TYPE = normalVectorType;
|
||||
this.gtaoMaterial.needsUpdate = true;
|
||||
this.gtaoMaterial.uniforms.tNormal.value = this.normalTexture;
|
||||
this.gtaoMaterial.uniforms.tDepth.value = this.depthTexture;
|
||||
|
||||
this.pdMaterial.defines.NORMAL_VECTOR_TYPE = normalVectorType;
|
||||
this.pdMaterial.needsUpdate = true;
|
||||
this.pdMaterial.uniforms.tNormal.value = this.normalTexture;
|
||||
this.pdMaterial.uniforms.tDepth.value = this.depthTexture;
|
||||
|
||||
this.depthRenderMaterial.uniforms.tDepth.value = this.depthTexture;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures the clip box of the GTAO shader with the given AABB.
|
||||
*
|
||||
* @param {?Box3} box - The AABB enclosing the scene that should receive AO. When passing
|
||||
* `null`, to clip box is used.
|
||||
*/
|
||||
setSceneClipBox( box ) {
|
||||
|
||||
if ( box ) {
|
||||
|
||||
this.gtaoMaterial.needsUpdate = this.gtaoMaterial.defines.SCENE_CLIP_BOX !== 1;
|
||||
this.gtaoMaterial.defines.SCENE_CLIP_BOX = 1;
|
||||
this.gtaoMaterial.uniforms.sceneBoxMin.value.copy( box.min );
|
||||
this.gtaoMaterial.uniforms.sceneBoxMax.value.copy( box.max );
|
||||
|
||||
} else {
|
||||
|
||||
this.gtaoMaterial.needsUpdate = this.gtaoMaterial.defines.SCENE_CLIP_BOX === 0;
|
||||
this.gtaoMaterial.defines.SCENE_CLIP_BOX = 0;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the GTAO material from the given parameter object.
|
||||
*
|
||||
* @param {Object} parameters - The GTAO material parameters.
|
||||
*/
|
||||
updateGtaoMaterial( parameters ) {
|
||||
|
||||
if ( parameters.radius !== undefined ) {
|
||||
|
||||
this.gtaoMaterial.uniforms.radius.value = parameters.radius;
|
||||
|
||||
}
|
||||
|
||||
if ( parameters.distanceExponent !== undefined ) {
|
||||
|
||||
this.gtaoMaterial.uniforms.distanceExponent.value = parameters.distanceExponent;
|
||||
|
||||
}
|
||||
|
||||
if ( parameters.thickness !== undefined ) {
|
||||
|
||||
this.gtaoMaterial.uniforms.thickness.value = parameters.thickness;
|
||||
|
||||
}
|
||||
|
||||
if ( parameters.distanceFallOff !== undefined ) {
|
||||
|
||||
this.gtaoMaterial.uniforms.distanceFallOff.value = parameters.distanceFallOff;
|
||||
this.gtaoMaterial.needsUpdate = true;
|
||||
|
||||
}
|
||||
|
||||
if ( parameters.scale !== undefined ) {
|
||||
|
||||
this.gtaoMaterial.uniforms.scale.value = parameters.scale;
|
||||
|
||||
}
|
||||
|
||||
if ( parameters.samples !== undefined && parameters.samples !== this.gtaoMaterial.defines.SAMPLES ) {
|
||||
|
||||
this.gtaoMaterial.defines.SAMPLES = parameters.samples;
|
||||
this.gtaoMaterial.needsUpdate = true;
|
||||
|
||||
}
|
||||
|
||||
if ( parameters.screenSpaceRadius !== undefined && ( parameters.screenSpaceRadius ? 1 : 0 ) !== this.gtaoMaterial.defines.SCREEN_SPACE_RADIUS ) {
|
||||
|
||||
this.gtaoMaterial.defines.SCREEN_SPACE_RADIUS = parameters.screenSpaceRadius ? 1 : 0;
|
||||
this.gtaoMaterial.needsUpdate = true;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the Denoise material from the given parameter object.
|
||||
*
|
||||
* @param {Object} parameters - The denoise parameters.
|
||||
*/
|
||||
updatePdMaterial( parameters ) {
|
||||
|
||||
let updateShader = false;
|
||||
|
||||
if ( parameters.lumaPhi !== undefined ) {
|
||||
|
||||
this.pdMaterial.uniforms.lumaPhi.value = parameters.lumaPhi;
|
||||
|
||||
}
|
||||
|
||||
if ( parameters.depthPhi !== undefined ) {
|
||||
|
||||
this.pdMaterial.uniforms.depthPhi.value = parameters.depthPhi;
|
||||
|
||||
}
|
||||
|
||||
if ( parameters.normalPhi !== undefined ) {
|
||||
|
||||
this.pdMaterial.uniforms.normalPhi.value = parameters.normalPhi;
|
||||
|
||||
}
|
||||
|
||||
if ( parameters.radius !== undefined && parameters.radius !== this.radius ) {
|
||||
|
||||
this.pdMaterial.uniforms.radius.value = parameters.radius;
|
||||
|
||||
}
|
||||
|
||||
if ( parameters.radiusExponent !== undefined && parameters.radiusExponent !== this.pdRadiusExponent ) {
|
||||
|
||||
this.pdRadiusExponent = parameters.radiusExponent;
|
||||
updateShader = true;
|
||||
|
||||
}
|
||||
|
||||
if ( parameters.rings !== undefined && parameters.rings !== this.pdRings ) {
|
||||
|
||||
this.pdRings = parameters.rings;
|
||||
updateShader = true;
|
||||
|
||||
}
|
||||
|
||||
if ( parameters.samples !== undefined && parameters.samples !== this.pdSamples ) {
|
||||
|
||||
this.pdSamples = parameters.samples;
|
||||
updateShader = true;
|
||||
|
||||
}
|
||||
|
||||
if ( updateShader ) {
|
||||
|
||||
this.pdMaterial.defines.SAMPLES = this.pdSamples;
|
||||
this.pdMaterial.defines.SAMPLE_VECTORS = generatePdSamplePointInitializer( this.pdSamples, this.pdRings, this.pdRadiusExponent );
|
||||
this.pdMaterial.needsUpdate = true;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs the GTAO pass.
|
||||
*
|
||||
* @param {WebGLRenderer} renderer - The renderer.
|
||||
* @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
|
||||
* destination for the pass.
|
||||
* @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
|
||||
* previous pass from this buffer.
|
||||
* @param {number} deltaTime - The delta time in seconds.
|
||||
* @param {boolean} maskActive - Whether masking is active or not.
|
||||
*/
|
||||
render( renderer, writeBuffer, readBuffer /*, deltaTime, maskActive */ ) {
|
||||
|
||||
// render normals and depth (honor only meshes, points and lines do not contribute to AO)
|
||||
|
||||
if ( this._renderGBuffer ) {
|
||||
|
||||
this._overrideVisibility();
|
||||
this._renderOverride( renderer, this.normalMaterial, this.normalRenderTarget, 0x7777ff, 1.0 );
|
||||
this._restoreVisibility();
|
||||
|
||||
}
|
||||
|
||||
// render AO
|
||||
|
||||
this.gtaoMaterial.uniforms.cameraNear.value = this.camera.near;
|
||||
this.gtaoMaterial.uniforms.cameraFar.value = this.camera.far;
|
||||
this.gtaoMaterial.uniforms.cameraProjectionMatrix.value.copy( this.camera.projectionMatrix );
|
||||
this.gtaoMaterial.uniforms.cameraProjectionMatrixInverse.value.copy( this.camera.projectionMatrixInverse );
|
||||
this.gtaoMaterial.uniforms.cameraWorldMatrix.value.copy( this.camera.matrixWorld );
|
||||
this._renderPass( renderer, this.gtaoMaterial, this.gtaoRenderTarget, 0xffffff, 1.0 );
|
||||
|
||||
// render poisson denoise
|
||||
|
||||
this.pdMaterial.uniforms.cameraProjectionMatrixInverse.value.copy( this.camera.projectionMatrixInverse );
|
||||
this._renderPass( renderer, this.pdMaterial, this.pdRenderTarget, 0xffffff, 1.0 );
|
||||
|
||||
// output result to screen
|
||||
|
||||
switch ( this.output ) {
|
||||
|
||||
case GTAOPass.OUTPUT.Off:
|
||||
break;
|
||||
|
||||
case GTAOPass.OUTPUT.Diffuse:
|
||||
|
||||
this.copyMaterial.uniforms.tDiffuse.value = readBuffer.texture;
|
||||
this.copyMaterial.blending = NoBlending;
|
||||
this._renderPass( renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer );
|
||||
|
||||
break;
|
||||
|
||||
case GTAOPass.OUTPUT.AO:
|
||||
|
||||
this.copyMaterial.uniforms.tDiffuse.value = this.gtaoRenderTarget.texture;
|
||||
this.copyMaterial.blending = NoBlending;
|
||||
this._renderPass( renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer );
|
||||
|
||||
break;
|
||||
|
||||
case GTAOPass.OUTPUT.Denoise:
|
||||
|
||||
this.copyMaterial.uniforms.tDiffuse.value = this.pdRenderTarget.texture;
|
||||
this.copyMaterial.blending = NoBlending;
|
||||
this._renderPass( renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer );
|
||||
|
||||
break;
|
||||
|
||||
case GTAOPass.OUTPUT.Depth:
|
||||
|
||||
this.depthRenderMaterial.uniforms.cameraNear.value = this.camera.near;
|
||||
this.depthRenderMaterial.uniforms.cameraFar.value = this.camera.far;
|
||||
this._renderPass( renderer, this.depthRenderMaterial, this.renderToScreen ? null : writeBuffer );
|
||||
|
||||
break;
|
||||
|
||||
case GTAOPass.OUTPUT.Normal:
|
||||
|
||||
this.copyMaterial.uniforms.tDiffuse.value = this.normalTexture || null;
|
||||
this.copyMaterial.blending = NoBlending;
|
||||
this._renderPass( renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer );
|
||||
|
||||
break;
|
||||
|
||||
case GTAOPass.OUTPUT.Default:
|
||||
|
||||
this.copyMaterial.uniforms.tDiffuse.value = readBuffer.texture;
|
||||
this.copyMaterial.blending = NoBlending;
|
||||
this._renderPass( renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer );
|
||||
|
||||
this.blendMaterial.uniforms.intensity.value = this.blendIntensity;
|
||||
this.blendMaterial.uniforms.tDiffuse.value = this.pdRenderTarget.texture;
|
||||
this._renderPass( renderer, this.blendMaterial, this.renderToScreen ? null : writeBuffer );
|
||||
|
||||
break;
|
||||
|
||||
default:
|
||||
console.warn( 'THREE.GTAOPass: Unknown output type.' );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// internals
|
||||
|
||||
_renderPass( renderer, passMaterial, renderTarget, clearColor, clearAlpha ) {
|
||||
|
||||
// save original state
|
||||
renderer.getClearColor( this._originalClearColor );
|
||||
const originalClearAlpha = renderer.getClearAlpha();
|
||||
const originalAutoClear = renderer.autoClear;
|
||||
|
||||
renderer.setRenderTarget( renderTarget );
|
||||
|
||||
// setup pass state
|
||||
renderer.autoClear = false;
|
||||
if ( ( clearColor !== undefined ) && ( clearColor !== null ) ) {
|
||||
|
||||
renderer.setClearColor( clearColor );
|
||||
renderer.setClearAlpha( clearAlpha || 0.0 );
|
||||
renderer.clear();
|
||||
|
||||
}
|
||||
|
||||
this._fsQuad.material = passMaterial;
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
// restore original state
|
||||
renderer.autoClear = originalAutoClear;
|
||||
renderer.setClearColor( this._originalClearColor );
|
||||
renderer.setClearAlpha( originalClearAlpha );
|
||||
|
||||
}
|
||||
|
||||
_renderOverride( renderer, overrideMaterial, renderTarget, clearColor, clearAlpha ) {
|
||||
|
||||
renderer.getClearColor( this._originalClearColor );
|
||||
const originalClearAlpha = renderer.getClearAlpha();
|
||||
const originalAutoClear = renderer.autoClear;
|
||||
|
||||
renderer.setRenderTarget( renderTarget );
|
||||
renderer.autoClear = false;
|
||||
|
||||
clearColor = overrideMaterial.clearColor || clearColor;
|
||||
clearAlpha = overrideMaterial.clearAlpha || clearAlpha;
|
||||
|
||||
if ( ( clearColor !== undefined ) && ( clearColor !== null ) ) {
|
||||
|
||||
renderer.setClearColor( clearColor );
|
||||
renderer.setClearAlpha( clearAlpha || 0.0 );
|
||||
renderer.clear();
|
||||
|
||||
}
|
||||
|
||||
this.scene.overrideMaterial = overrideMaterial;
|
||||
renderer.render( this.scene, this.camera );
|
||||
this.scene.overrideMaterial = null;
|
||||
|
||||
renderer.autoClear = originalAutoClear;
|
||||
renderer.setClearColor( this._originalClearColor );
|
||||
renderer.setClearAlpha( originalClearAlpha );
|
||||
|
||||
}
|
||||
|
||||
_overrideVisibility() {
|
||||
|
||||
const scene = this.scene;
|
||||
const cache = this._visibilityCache;
|
||||
|
||||
scene.traverse( function ( object ) {
|
||||
|
||||
if ( ( object.isPoints || object.isLine || object.isLine2 ) && object.visible ) {
|
||||
|
||||
object.visible = false;
|
||||
cache.push( object );
|
||||
|
||||
}
|
||||
|
||||
} );
|
||||
|
||||
}
|
||||
|
||||
_restoreVisibility() {
|
||||
|
||||
const cache = this._visibilityCache;
|
||||
|
||||
for ( let i = 0; i < cache.length; i ++ ) {
|
||||
|
||||
cache[ i ].visible = true;
|
||||
|
||||
}
|
||||
|
||||
cache.length = 0;
|
||||
|
||||
}
|
||||
|
||||
_generateNoise( size = 64 ) {
|
||||
|
||||
const simplex = new SimplexNoise();
|
||||
|
||||
const arraySize = size * size * 4;
|
||||
const data = new Uint8Array( arraySize );
|
||||
|
||||
for ( let i = 0; i < size; i ++ ) {
|
||||
|
||||
for ( let j = 0; j < size; j ++ ) {
|
||||
|
||||
const x = i;
|
||||
const y = j;
|
||||
|
||||
data[ ( i * size + j ) * 4 ] = ( simplex.noise( x, y ) * 0.5 + 0.5 ) * 255;
|
||||
data[ ( i * size + j ) * 4 + 1 ] = ( simplex.noise( x + size, y ) * 0.5 + 0.5 ) * 255;
|
||||
data[ ( i * size + j ) * 4 + 2 ] = ( simplex.noise( x, y + size ) * 0.5 + 0.5 ) * 255;
|
||||
data[ ( i * size + j ) * 4 + 3 ] = ( simplex.noise( x + size, y + size ) * 0.5 + 0.5 ) * 255;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
const noiseTexture = new DataTexture( data, size, size, RGBAFormat, UnsignedByteType );
|
||||
noiseTexture.wrapS = RepeatWrapping;
|
||||
noiseTexture.wrapT = RepeatWrapping;
|
||||
noiseTexture.needsUpdate = true;
|
||||
|
||||
return noiseTexture;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
GTAOPass.OUTPUT = {
|
||||
'Off': - 1,
|
||||
'Default': 0,
|
||||
'Diffuse': 1,
|
||||
'Depth': 2,
|
||||
'Normal': 3,
|
||||
'AO': 4,
|
||||
'Denoise': 5,
|
||||
};
|
||||
|
||||
export { GTAOPass };
|
||||
@@ -0,0 +1,177 @@
|
||||
import {
|
||||
DataTexture,
|
||||
FloatType,
|
||||
MathUtils,
|
||||
RedFormat,
|
||||
ShaderMaterial,
|
||||
UniformsUtils
|
||||
} from 'three';
|
||||
import { Pass, FullScreenQuad } from './Pass.js';
|
||||
import { DigitalGlitch } from '../shaders/DigitalGlitch.js';
|
||||
|
||||
/**
|
||||
* Pass for creating a glitch effect.
|
||||
*
|
||||
* ```js
|
||||
* const glitchPass = new GlitchPass();
|
||||
* composer.addPass( glitchPass );
|
||||
* ```
|
||||
*
|
||||
* @augments Pass
|
||||
* @three_import import { GlitchPass } from 'three/addons/postprocessing/GlitchPass.js';
|
||||
*/
|
||||
class GlitchPass extends Pass {
|
||||
|
||||
/**
|
||||
* Constructs a new glitch pass.
|
||||
*
|
||||
* @param {number} [dt_size=64] - The size of the displacement texture
|
||||
* for digital glitch squares.
|
||||
*/
|
||||
constructor( dt_size = 64 ) {
|
||||
|
||||
super();
|
||||
|
||||
/**
|
||||
* The pass uniforms.
|
||||
*
|
||||
* @type {Object}
|
||||
*/
|
||||
this.uniforms = UniformsUtils.clone( DigitalGlitch.uniforms );
|
||||
|
||||
/**
|
||||
* The pass material.
|
||||
*
|
||||
* @type {ShaderMaterial}
|
||||
*/
|
||||
this.material = new ShaderMaterial( {
|
||||
uniforms: this.uniforms,
|
||||
vertexShader: DigitalGlitch.vertexShader,
|
||||
fragmentShader: DigitalGlitch.fragmentShader
|
||||
} );
|
||||
|
||||
/**
|
||||
* Whether to noticeably increase the effect intensity or not.
|
||||
*
|
||||
* @type {boolean}
|
||||
* @default false
|
||||
*/
|
||||
this.goWild = false;
|
||||
|
||||
// internals
|
||||
|
||||
this._heightMap = this._generateHeightmap( dt_size );
|
||||
this.uniforms[ 'tDisp' ].value = this._heightMap;
|
||||
|
||||
this._fsQuad = new FullScreenQuad( this.material );
|
||||
|
||||
this._curF = 0;
|
||||
this._randX = 0;
|
||||
|
||||
this._generateTrigger();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs the glitch pass.
|
||||
*
|
||||
* @param {WebGLRenderer} renderer - The renderer.
|
||||
* @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
|
||||
* destination for the pass.
|
||||
* @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
|
||||
* previous pass from this buffer.
|
||||
* @param {number} deltaTime - The delta time in seconds.
|
||||
* @param {boolean} maskActive - Whether masking is active or not.
|
||||
*/
|
||||
render( renderer, writeBuffer, readBuffer /*, deltaTime, maskActive */ ) {
|
||||
|
||||
this.uniforms[ 'tDiffuse' ].value = readBuffer.texture;
|
||||
this.uniforms[ 'seed' ].value = Math.random(); // default seeding
|
||||
this.uniforms[ 'byp' ].value = 0;
|
||||
|
||||
if ( this._curF % this._randX == 0 || this.goWild == true ) {
|
||||
|
||||
this.uniforms[ 'amount' ].value = Math.random() / 30;
|
||||
this.uniforms[ 'angle' ].value = MathUtils.randFloat( - Math.PI, Math.PI );
|
||||
this.uniforms[ 'seed_x' ].value = MathUtils.randFloat( - 1, 1 );
|
||||
this.uniforms[ 'seed_y' ].value = MathUtils.randFloat( - 1, 1 );
|
||||
this.uniforms[ 'distortion_x' ].value = MathUtils.randFloat( 0, 1 );
|
||||
this.uniforms[ 'distortion_y' ].value = MathUtils.randFloat( 0, 1 );
|
||||
this._curF = 0;
|
||||
this._generateTrigger();
|
||||
|
||||
} else if ( this._curF % this._randX < this._randX / 5 ) {
|
||||
|
||||
this.uniforms[ 'amount' ].value = Math.random() / 90;
|
||||
this.uniforms[ 'angle' ].value = MathUtils.randFloat( - Math.PI, Math.PI );
|
||||
this.uniforms[ 'distortion_x' ].value = MathUtils.randFloat( 0, 1 );
|
||||
this.uniforms[ 'distortion_y' ].value = MathUtils.randFloat( 0, 1 );
|
||||
this.uniforms[ 'seed_x' ].value = MathUtils.randFloat( - 0.3, 0.3 );
|
||||
this.uniforms[ 'seed_y' ].value = MathUtils.randFloat( - 0.3, 0.3 );
|
||||
|
||||
} else if ( this.goWild == false ) {
|
||||
|
||||
this.uniforms[ 'byp' ].value = 1;
|
||||
|
||||
}
|
||||
|
||||
this._curF ++;
|
||||
|
||||
if ( this.renderToScreen ) {
|
||||
|
||||
renderer.setRenderTarget( null );
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
} else {
|
||||
|
||||
renderer.setRenderTarget( writeBuffer );
|
||||
if ( this.clear ) renderer.clear();
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Frees the GPU-related resources allocated by this instance. Call this
|
||||
* method whenever the pass is no longer used in your app.
|
||||
*/
|
||||
dispose() {
|
||||
|
||||
this.material.dispose();
|
||||
|
||||
this._heightMap.dispose();
|
||||
|
||||
this._fsQuad.dispose();
|
||||
|
||||
}
|
||||
|
||||
// internals
|
||||
|
||||
_generateTrigger() {
|
||||
|
||||
this._randX = MathUtils.randInt( 120, 240 );
|
||||
|
||||
}
|
||||
|
||||
_generateHeightmap( dt_size ) {
|
||||
|
||||
const data_arr = new Float32Array( dt_size * dt_size );
|
||||
const length = dt_size * dt_size;
|
||||
|
||||
for ( let i = 0; i < length; i ++ ) {
|
||||
|
||||
const val = MathUtils.randFloat( 0, 1 );
|
||||
data_arr[ i ] = val;
|
||||
|
||||
}
|
||||
|
||||
const texture = new DataTexture( data_arr, dt_size, dt_size, RedFormat, FloatType );
|
||||
texture.needsUpdate = true;
|
||||
return texture;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export { GlitchPass };
|
||||
@@ -0,0 +1,134 @@
|
||||
import {
|
||||
ShaderMaterial,
|
||||
UniformsUtils
|
||||
} from 'three';
|
||||
import { Pass, FullScreenQuad } from './Pass.js';
|
||||
import { HalftoneShader } from '../shaders/HalftoneShader.js';
|
||||
|
||||
/**
|
||||
* Pass for creating a RGB halftone effect.
|
||||
*
|
||||
* ```js
|
||||
* const params = {
|
||||
* shape: 1,
|
||||
* radius: 4,
|
||||
* rotateR: Math.PI / 12,
|
||||
* rotateB: Math.PI / 12 * 2,
|
||||
* rotateG: Math.PI / 12 * 3,
|
||||
* scatter: 0,
|
||||
* blending: 1,
|
||||
* blendingMode: 1,
|
||||
* greyscale: false,
|
||||
* disable: false
|
||||
* };
|
||||
* const halftonePass = new HalftonePass( params );
|
||||
* composer.addPass( halftonePass );
|
||||
* ```
|
||||
*
|
||||
* @augments Pass
|
||||
* @three_import import { HalftonePass } from 'three/addons/postprocessing/HalftonePass.js';
|
||||
*/
|
||||
class HalftonePass extends Pass {
|
||||
|
||||
/**
|
||||
* Constructs a new halftone pass.
|
||||
*
|
||||
* @param {Object} params - The halftone shader parameter.
|
||||
*/
|
||||
constructor( params ) {
|
||||
|
||||
super();
|
||||
|
||||
/**
|
||||
* The pass uniforms.
|
||||
*
|
||||
* @type {Object}
|
||||
*/
|
||||
this.uniforms = UniformsUtils.clone( HalftoneShader.uniforms );
|
||||
|
||||
/**
|
||||
* The pass material.
|
||||
*
|
||||
* @type {ShaderMaterial}
|
||||
*/
|
||||
this.material = new ShaderMaterial( {
|
||||
uniforms: this.uniforms,
|
||||
fragmentShader: HalftoneShader.fragmentShader,
|
||||
vertexShader: HalftoneShader.vertexShader
|
||||
} );
|
||||
|
||||
|
||||
for ( const key in params ) {
|
||||
|
||||
if ( params.hasOwnProperty( key ) && this.uniforms.hasOwnProperty( key ) ) {
|
||||
|
||||
this.uniforms[ key ].value = params[ key ];
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// internals
|
||||
|
||||
this._fsQuad = new FullScreenQuad( this.material );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs the halftone pass.
|
||||
*
|
||||
* @param {WebGLRenderer} renderer - The renderer.
|
||||
* @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
|
||||
* destination for the pass.
|
||||
* @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
|
||||
* previous pass from this buffer.
|
||||
* @param {number} deltaTime - The delta time in seconds.
|
||||
* @param {boolean} maskActive - Whether masking is active or not.
|
||||
*/
|
||||
render( renderer, writeBuffer, readBuffer/*, deltaTime, maskActive*/ ) {
|
||||
|
||||
this.material.uniforms[ 'tDiffuse' ].value = readBuffer.texture;
|
||||
|
||||
if ( this.renderToScreen ) {
|
||||
|
||||
renderer.setRenderTarget( null );
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
} else {
|
||||
|
||||
renderer.setRenderTarget( writeBuffer );
|
||||
if ( this.clear ) renderer.clear();
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the size of the pass.
|
||||
*
|
||||
* @param {number} width - The width to set.
|
||||
* @param {number} height - The height to set.
|
||||
*/
|
||||
setSize( width, height ) {
|
||||
|
||||
this.uniforms.width.value = width;
|
||||
this.uniforms.height.value = height;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Frees the GPU-related resources allocated by this instance. Call this
|
||||
* method whenever the pass is no longer used in your app.
|
||||
*/
|
||||
dispose() {
|
||||
|
||||
this.material.dispose();
|
||||
|
||||
this._fsQuad.dispose();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export { HalftonePass };
|
||||
@@ -0,0 +1,138 @@
|
||||
import { ShaderPass } from './ShaderPass.js';
|
||||
|
||||
const LUTShader = {
|
||||
|
||||
name: 'LUTShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
lut: { value: null },
|
||||
lutSize: { value: 0 },
|
||||
|
||||
tDiffuse: { value: null },
|
||||
intensity: { value: 1.0 },
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}
|
||||
|
||||
`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform float lutSize;
|
||||
uniform sampler3D lut;
|
||||
|
||||
varying vec2 vUv;
|
||||
uniform float intensity;
|
||||
uniform sampler2D tDiffuse;
|
||||
void main() {
|
||||
|
||||
vec4 val = texture2D( tDiffuse, vUv );
|
||||
vec4 lutVal;
|
||||
|
||||
// pull the sample in by half a pixel so the sample begins
|
||||
// at the center of the edge pixels.
|
||||
float pixelWidth = 1.0 / lutSize;
|
||||
float halfPixelWidth = 0.5 / lutSize;
|
||||
vec3 uvw = vec3( halfPixelWidth ) + val.rgb * ( 1.0 - pixelWidth );
|
||||
|
||||
|
||||
lutVal = vec4( texture( lut, uvw ).rgb, val.a );
|
||||
|
||||
gl_FragColor = vec4( mix( val, lutVal, intensity ) );
|
||||
|
||||
}
|
||||
|
||||
`,
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Pass for color grading via lookup tables.
|
||||
*
|
||||
* ```js
|
||||
* const lutPass = new LUTPass( { lut: lut.texture3D } );
|
||||
* composer.addPass( lutPass );
|
||||
* ```
|
||||
*
|
||||
* @augments ShaderPass
|
||||
* @three_import import { LUTPass } from 'three/addons/postprocessing/LUTPass.js';
|
||||
*/
|
||||
class LUTPass extends ShaderPass {
|
||||
|
||||
/**
|
||||
* Constructs a LUT pass.
|
||||
*
|
||||
* @param {{lut:Data3DTexture,intensity:number}} [options={}] - The pass options.
|
||||
*/
|
||||
constructor( options = {} ) {
|
||||
|
||||
super( LUTShader );
|
||||
|
||||
/**
|
||||
* The LUT as a 3D texture.
|
||||
*
|
||||
* @type {?Data3DTexture}
|
||||
* @default null
|
||||
*/
|
||||
this.lut = options.lut || null;
|
||||
|
||||
/**
|
||||
* The intensity.
|
||||
*
|
||||
* @type {?number}
|
||||
* @default 1
|
||||
*/
|
||||
this.intensity = 'intensity' in options ? options.intensity : 1;
|
||||
|
||||
}
|
||||
|
||||
set lut( v ) {
|
||||
|
||||
const material = this.material;
|
||||
|
||||
if ( v !== this.lut ) {
|
||||
|
||||
material.uniforms.lut.value = null;
|
||||
|
||||
if ( v ) {
|
||||
|
||||
material.uniforms.lutSize.value = v.image.width;
|
||||
material.uniforms.lut.value = v;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
get lut() {
|
||||
|
||||
return this.material.uniforms.lut.value;
|
||||
|
||||
}
|
||||
|
||||
set intensity( v ) {
|
||||
|
||||
this.material.uniforms.intensity.value = v;
|
||||
|
||||
}
|
||||
|
||||
get intensity() {
|
||||
|
||||
return this.material.uniforms.intensity.value;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export { LUTPass };
|
||||
@@ -0,0 +1,195 @@
|
||||
import { Pass } from './Pass.js';
|
||||
|
||||
/**
|
||||
* This pass can be used to define a mask during post processing.
|
||||
* Meaning only areas of subsequent post processing are affected
|
||||
* which lie in the masking area of this pass. Internally, the masking
|
||||
* is implemented with the stencil buffer.
|
||||
*
|
||||
* ```js
|
||||
* const maskPass = new MaskPass( scene, camera );
|
||||
* composer.addPass( maskPass );
|
||||
* ```
|
||||
*
|
||||
* @augments Pass
|
||||
* @three_import import { MaskPass } from 'three/addons/postprocessing/MaskPass.js';
|
||||
*/
|
||||
class MaskPass extends Pass {
|
||||
|
||||
/**
|
||||
* Constructs a new mask pass.
|
||||
*
|
||||
* @param {Scene} scene - The 3D objects in this scene will define the mask.
|
||||
* @param {Camera} camera - The camera.
|
||||
*/
|
||||
constructor( scene, camera ) {
|
||||
|
||||
super();
|
||||
|
||||
/**
|
||||
* The scene that defines the mask.
|
||||
*
|
||||
* @type {Scene}
|
||||
*/
|
||||
this.scene = scene;
|
||||
|
||||
/**
|
||||
* The camera.
|
||||
*
|
||||
* @type {Camera}
|
||||
*/
|
||||
this.camera = camera;
|
||||
|
||||
/**
|
||||
* Overwritten to perform a clear operation by default.
|
||||
*
|
||||
* @type {boolean}
|
||||
* @default true
|
||||
*/
|
||||
this.clear = true;
|
||||
|
||||
/**
|
||||
* Overwritten to disable the swap.
|
||||
*
|
||||
* @type {boolean}
|
||||
* @default false
|
||||
*/
|
||||
this.needsSwap = false;
|
||||
|
||||
/**
|
||||
* Whether to inverse the mask or not.
|
||||
*
|
||||
* @type {boolean}
|
||||
* @default false
|
||||
*/
|
||||
this.inverse = false;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs a mask pass with the configured scene and camera.
|
||||
*
|
||||
* @param {WebGLRenderer} renderer - The renderer.
|
||||
* @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
|
||||
* destination for the pass.
|
||||
* @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
|
||||
* previous pass from this buffer.
|
||||
* @param {number} deltaTime - The delta time in seconds.
|
||||
* @param {boolean} maskActive - Whether masking is active or not.
|
||||
*/
|
||||
render( renderer, writeBuffer, readBuffer /*, deltaTime, maskActive */ ) {
|
||||
|
||||
const context = renderer.getContext();
|
||||
const state = renderer.state;
|
||||
|
||||
// don't update color or depth
|
||||
|
||||
state.buffers.color.setMask( false );
|
||||
state.buffers.depth.setMask( false );
|
||||
|
||||
// lock buffers
|
||||
|
||||
state.buffers.color.setLocked( true );
|
||||
state.buffers.depth.setLocked( true );
|
||||
|
||||
// set up stencil
|
||||
|
||||
let writeValue, clearValue;
|
||||
|
||||
if ( this.inverse ) {
|
||||
|
||||
writeValue = 0;
|
||||
clearValue = 1;
|
||||
|
||||
} else {
|
||||
|
||||
writeValue = 1;
|
||||
clearValue = 0;
|
||||
|
||||
}
|
||||
|
||||
state.buffers.stencil.setTest( true );
|
||||
state.buffers.stencil.setOp( context.REPLACE, context.REPLACE, context.REPLACE );
|
||||
state.buffers.stencil.setFunc( context.ALWAYS, writeValue, 0xffffffff );
|
||||
state.buffers.stencil.setClear( clearValue );
|
||||
state.buffers.stencil.setLocked( true );
|
||||
|
||||
// draw into the stencil buffer
|
||||
|
||||
renderer.setRenderTarget( readBuffer );
|
||||
if ( this.clear ) renderer.clear();
|
||||
renderer.render( this.scene, this.camera );
|
||||
|
||||
renderer.setRenderTarget( writeBuffer );
|
||||
if ( this.clear ) renderer.clear();
|
||||
renderer.render( this.scene, this.camera );
|
||||
|
||||
// unlock color and depth buffer and make them writable for subsequent rendering/clearing
|
||||
|
||||
state.buffers.color.setLocked( false );
|
||||
state.buffers.depth.setLocked( false );
|
||||
|
||||
state.buffers.color.setMask( true );
|
||||
state.buffers.depth.setMask( true );
|
||||
|
||||
// only render where stencil is set to 1
|
||||
|
||||
state.buffers.stencil.setLocked( false );
|
||||
state.buffers.stencil.setFunc( context.EQUAL, 1, 0xffffffff ); // draw if == 1
|
||||
state.buffers.stencil.setOp( context.KEEP, context.KEEP, context.KEEP );
|
||||
state.buffers.stencil.setLocked( true );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* This pass can be used to clear a mask previously defined with {@link MaskPass}.
|
||||
*
|
||||
* ```js
|
||||
* const clearPass = new ClearMaskPass();
|
||||
* composer.addPass( clearPass );
|
||||
* ```
|
||||
*
|
||||
* @augments Pass
|
||||
*/
|
||||
class ClearMaskPass extends Pass {
|
||||
|
||||
/**
|
||||
* Constructs a new clear mask pass.
|
||||
*/
|
||||
constructor() {
|
||||
|
||||
super();
|
||||
|
||||
/**
|
||||
* Overwritten to disable the swap.
|
||||
*
|
||||
* @type {boolean}
|
||||
* @default false
|
||||
*/
|
||||
this.needsSwap = false;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs the clear of the currently defined mask.
|
||||
*
|
||||
* @param {WebGLRenderer} renderer - The renderer.
|
||||
* @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
|
||||
* destination for the pass.
|
||||
* @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
|
||||
* previous pass from this buffer.
|
||||
* @param {number} deltaTime - The delta time in seconds.
|
||||
* @param {boolean} maskActive - Whether masking is active or not.
|
||||
*/
|
||||
render( renderer /*, writeBuffer, readBuffer, deltaTime, maskActive */ ) {
|
||||
|
||||
renderer.state.buffers.stencil.setLocked( false );
|
||||
renderer.state.buffers.stencil.setTest( false );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export { MaskPass, ClearMaskPass };
|
||||
@@ -0,0 +1,776 @@
|
||||
import {
|
||||
AdditiveBlending,
|
||||
Color,
|
||||
DoubleSide,
|
||||
HalfFloatType,
|
||||
Matrix4,
|
||||
MeshDepthMaterial,
|
||||
NoBlending,
|
||||
RGBADepthPacking,
|
||||
ShaderMaterial,
|
||||
UniformsUtils,
|
||||
Vector2,
|
||||
Vector3,
|
||||
WebGLRenderTarget
|
||||
} from 'three';
|
||||
import { Pass, FullScreenQuad } from './Pass.js';
|
||||
import { CopyShader } from '../shaders/CopyShader.js';
|
||||
|
||||
/**
|
||||
* A pass for rendering outlines around selected objects.
|
||||
*
|
||||
* ```js
|
||||
* const resolution = new THREE.Vector2( window.innerWidth, window.innerHeight );
|
||||
* const outlinePass = new OutlinePass( resolution, scene, camera );
|
||||
* composer.addPass( outlinePass );
|
||||
* ```
|
||||
*
|
||||
* @augments Pass
|
||||
* @three_import import { OutlinePass } from 'three/addons/postprocessing/OutlinePass.js';
|
||||
*/
|
||||
class OutlinePass extends Pass {
|
||||
|
||||
/**
|
||||
* Constructs a new outline pass.
|
||||
*
|
||||
* @param {Vector2} [resolution] - The effect's resolution.
|
||||
* @param {Scene} scene - The scene to render.
|
||||
* @param {Camera} camera - The camera.
|
||||
* @param {Array<Object3D>} [selectedObjects] - The selected 3D objects that should receive an outline.
|
||||
*
|
||||
*/
|
||||
constructor( resolution, scene, camera, selectedObjects ) {
|
||||
|
||||
super();
|
||||
|
||||
/**
|
||||
* The scene to render.
|
||||
*
|
||||
* @type {Object}
|
||||
*/
|
||||
this.renderScene = scene;
|
||||
|
||||
/**
|
||||
* The camera.
|
||||
*
|
||||
* @type {Object}
|
||||
*/
|
||||
this.renderCamera = camera;
|
||||
|
||||
/**
|
||||
* The selected 3D objects that should receive an outline.
|
||||
*
|
||||
* @type {Array<Object3D>}
|
||||
*/
|
||||
this.selectedObjects = selectedObjects !== undefined ? selectedObjects : [];
|
||||
|
||||
/**
|
||||
* The visible edge color.
|
||||
*
|
||||
* @type {Color}
|
||||
* @default (1,1,1)
|
||||
*/
|
||||
this.visibleEdgeColor = new Color( 1, 1, 1 );
|
||||
|
||||
/**
|
||||
* The hidden edge color.
|
||||
*
|
||||
* @type {Color}
|
||||
* @default (0.1,0.04,0.02)
|
||||
*/
|
||||
this.hiddenEdgeColor = new Color( 0.1, 0.04, 0.02 );
|
||||
|
||||
/**
|
||||
* Can be used for an animated glow/pulse effect.
|
||||
*
|
||||
* @type {number}
|
||||
* @default 0
|
||||
*/
|
||||
this.edgeGlow = 0.0;
|
||||
|
||||
/**
|
||||
* Whether to use a pattern texture for to highlight selected
|
||||
* 3D objects or not.
|
||||
*
|
||||
* @type {boolean}
|
||||
* @default false
|
||||
*/
|
||||
this.usePatternTexture = false;
|
||||
|
||||
/**
|
||||
* Can be used to highlight selected 3D objects. Requires to set
|
||||
* {@link OutlinePass#usePatternTexture} to `true`.
|
||||
*
|
||||
* @type {?Texture}
|
||||
* @default null
|
||||
*/
|
||||
this.patternTexture = null;
|
||||
|
||||
/**
|
||||
* The edge thickness.
|
||||
*
|
||||
* @type {number}
|
||||
* @default 1
|
||||
*/
|
||||
this.edgeThickness = 1.0;
|
||||
|
||||
/**
|
||||
* The edge strength.
|
||||
*
|
||||
* @type {number}
|
||||
* @default 3
|
||||
*/
|
||||
this.edgeStrength = 3.0;
|
||||
|
||||
/**
|
||||
* The downsample ratio. The effect can be rendered in a much
|
||||
* lower resolution than the beauty pass.
|
||||
*
|
||||
* @type {number}
|
||||
* @default 2
|
||||
*/
|
||||
this.downSampleRatio = 2;
|
||||
|
||||
/**
|
||||
* The pulse period.
|
||||
*
|
||||
* @type {number}
|
||||
* @default 0
|
||||
*/
|
||||
this.pulsePeriod = 0;
|
||||
|
||||
this._visibilityCache = new Map();
|
||||
this._selectionCache = new Set();
|
||||
|
||||
/**
|
||||
* The effect's resolution.
|
||||
*
|
||||
* @type {Vector2}
|
||||
* @default (256,256)
|
||||
*/
|
||||
this.resolution = ( resolution !== undefined ) ? new Vector2( resolution.x, resolution.y ) : new Vector2( 256, 256 );
|
||||
|
||||
const resx = Math.round( this.resolution.x / this.downSampleRatio );
|
||||
const resy = Math.round( this.resolution.y / this.downSampleRatio );
|
||||
|
||||
this.renderTargetMaskBuffer = new WebGLRenderTarget( this.resolution.x, this.resolution.y );
|
||||
this.renderTargetMaskBuffer.texture.name = 'OutlinePass.mask';
|
||||
this.renderTargetMaskBuffer.texture.generateMipmaps = false;
|
||||
|
||||
this.depthMaterial = new MeshDepthMaterial();
|
||||
this.depthMaterial.side = DoubleSide;
|
||||
this.depthMaterial.depthPacking = RGBADepthPacking;
|
||||
this.depthMaterial.blending = NoBlending;
|
||||
|
||||
this.prepareMaskMaterial = this._getPrepareMaskMaterial();
|
||||
this.prepareMaskMaterial.side = DoubleSide;
|
||||
this.prepareMaskMaterial.fragmentShader = replaceDepthToViewZ( this.prepareMaskMaterial.fragmentShader, this.renderCamera );
|
||||
|
||||
this.renderTargetDepthBuffer = new WebGLRenderTarget( this.resolution.x, this.resolution.y, { type: HalfFloatType } );
|
||||
this.renderTargetDepthBuffer.texture.name = 'OutlinePass.depth';
|
||||
this.renderTargetDepthBuffer.texture.generateMipmaps = false;
|
||||
|
||||
this.renderTargetMaskDownSampleBuffer = new WebGLRenderTarget( resx, resy, { type: HalfFloatType, depthBuffer: false } );
|
||||
this.renderTargetMaskDownSampleBuffer.texture.name = 'OutlinePass.depthDownSample';
|
||||
this.renderTargetMaskDownSampleBuffer.texture.generateMipmaps = false;
|
||||
|
||||
this.renderTargetBlurBuffer1 = new WebGLRenderTarget( resx, resy, { type: HalfFloatType, depthBuffer: false } );
|
||||
this.renderTargetBlurBuffer1.texture.name = 'OutlinePass.blur1';
|
||||
this.renderTargetBlurBuffer1.texture.generateMipmaps = false;
|
||||
this.renderTargetBlurBuffer2 = new WebGLRenderTarget( Math.round( resx / 2 ), Math.round( resy / 2 ), { type: HalfFloatType, depthBuffer: false } );
|
||||
this.renderTargetBlurBuffer2.texture.name = 'OutlinePass.blur2';
|
||||
this.renderTargetBlurBuffer2.texture.generateMipmaps = false;
|
||||
|
||||
this.edgeDetectionMaterial = this._getEdgeDetectionMaterial();
|
||||
this.renderTargetEdgeBuffer1 = new WebGLRenderTarget( resx, resy, { type: HalfFloatType, depthBuffer: false } );
|
||||
this.renderTargetEdgeBuffer1.texture.name = 'OutlinePass.edge1';
|
||||
this.renderTargetEdgeBuffer1.texture.generateMipmaps = false;
|
||||
this.renderTargetEdgeBuffer2 = new WebGLRenderTarget( Math.round( resx / 2 ), Math.round( resy / 2 ), { type: HalfFloatType, depthBuffer: false } );
|
||||
this.renderTargetEdgeBuffer2.texture.name = 'OutlinePass.edge2';
|
||||
this.renderTargetEdgeBuffer2.texture.generateMipmaps = false;
|
||||
|
||||
const MAX_EDGE_THICKNESS = 4;
|
||||
const MAX_EDGE_GLOW = 4;
|
||||
|
||||
this.separableBlurMaterial1 = this._getSeparableBlurMaterial( MAX_EDGE_THICKNESS );
|
||||
this.separableBlurMaterial1.uniforms[ 'texSize' ].value.set( resx, resy );
|
||||
this.separableBlurMaterial1.uniforms[ 'kernelRadius' ].value = 1;
|
||||
this.separableBlurMaterial2 = this._getSeparableBlurMaterial( MAX_EDGE_GLOW );
|
||||
this.separableBlurMaterial2.uniforms[ 'texSize' ].value.set( Math.round( resx / 2 ), Math.round( resy / 2 ) );
|
||||
this.separableBlurMaterial2.uniforms[ 'kernelRadius' ].value = MAX_EDGE_GLOW;
|
||||
|
||||
// Overlay material
|
||||
this.overlayMaterial = this._getOverlayMaterial();
|
||||
|
||||
// copy material
|
||||
|
||||
const copyShader = CopyShader;
|
||||
|
||||
this.copyUniforms = UniformsUtils.clone( copyShader.uniforms );
|
||||
|
||||
this.materialCopy = new ShaderMaterial( {
|
||||
uniforms: this.copyUniforms,
|
||||
vertexShader: copyShader.vertexShader,
|
||||
fragmentShader: copyShader.fragmentShader,
|
||||
blending: NoBlending,
|
||||
depthTest: false,
|
||||
depthWrite: false
|
||||
} );
|
||||
|
||||
this.enabled = true;
|
||||
this.needsSwap = false;
|
||||
|
||||
this._oldClearColor = new Color();
|
||||
this.oldClearAlpha = 1;
|
||||
|
||||
this._fsQuad = new FullScreenQuad( null );
|
||||
|
||||
this.tempPulseColor1 = new Color();
|
||||
this.tempPulseColor2 = new Color();
|
||||
this.textureMatrix = new Matrix4();
|
||||
|
||||
function replaceDepthToViewZ( string, camera ) {
|
||||
|
||||
const type = camera.isPerspectiveCamera ? 'perspective' : 'orthographic';
|
||||
|
||||
return string.replace( /DEPTH_TO_VIEW_Z/g, type + 'DepthToViewZ' );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Frees the GPU-related resources allocated by this instance. Call this
|
||||
* method whenever the pass is no longer used in your app.
|
||||
*/
|
||||
dispose() {
|
||||
|
||||
this.renderTargetMaskBuffer.dispose();
|
||||
this.renderTargetDepthBuffer.dispose();
|
||||
this.renderTargetMaskDownSampleBuffer.dispose();
|
||||
this.renderTargetBlurBuffer1.dispose();
|
||||
this.renderTargetBlurBuffer2.dispose();
|
||||
this.renderTargetEdgeBuffer1.dispose();
|
||||
this.renderTargetEdgeBuffer2.dispose();
|
||||
|
||||
this.depthMaterial.dispose();
|
||||
this.prepareMaskMaterial.dispose();
|
||||
this.edgeDetectionMaterial.dispose();
|
||||
this.separableBlurMaterial1.dispose();
|
||||
this.separableBlurMaterial2.dispose();
|
||||
this.overlayMaterial.dispose();
|
||||
this.materialCopy.dispose();
|
||||
|
||||
this._fsQuad.dispose();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the size of the pass.
|
||||
*
|
||||
* @param {number} width - The width to set.
|
||||
* @param {number} height - The height to set.
|
||||
*/
|
||||
setSize( width, height ) {
|
||||
|
||||
this.renderTargetMaskBuffer.setSize( width, height );
|
||||
this.renderTargetDepthBuffer.setSize( width, height );
|
||||
|
||||
let resx = Math.round( width / this.downSampleRatio );
|
||||
let resy = Math.round( height / this.downSampleRatio );
|
||||
this.renderTargetMaskDownSampleBuffer.setSize( resx, resy );
|
||||
this.renderTargetBlurBuffer1.setSize( resx, resy );
|
||||
this.renderTargetEdgeBuffer1.setSize( resx, resy );
|
||||
this.separableBlurMaterial1.uniforms[ 'texSize' ].value.set( resx, resy );
|
||||
|
||||
resx = Math.round( resx / 2 );
|
||||
resy = Math.round( resy / 2 );
|
||||
|
||||
this.renderTargetBlurBuffer2.setSize( resx, resy );
|
||||
this.renderTargetEdgeBuffer2.setSize( resx, resy );
|
||||
|
||||
this.separableBlurMaterial2.uniforms[ 'texSize' ].value.set( resx, resy );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs the Outline pass.
|
||||
*
|
||||
* @param {WebGLRenderer} renderer - The renderer.
|
||||
* @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
|
||||
* destination for the pass.
|
||||
* @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
|
||||
* previous pass from this buffer.
|
||||
* @param {number} deltaTime - The delta time in seconds.
|
||||
* @param {boolean} maskActive - Whether masking is active or not.
|
||||
*/
|
||||
render( renderer, writeBuffer, readBuffer, deltaTime, maskActive ) {
|
||||
|
||||
if ( this.selectedObjects.length > 0 ) {
|
||||
|
||||
renderer.getClearColor( this._oldClearColor );
|
||||
this.oldClearAlpha = renderer.getClearAlpha();
|
||||
const oldAutoClear = renderer.autoClear;
|
||||
|
||||
renderer.autoClear = false;
|
||||
|
||||
if ( maskActive ) renderer.state.buffers.stencil.setTest( false );
|
||||
|
||||
renderer.setClearColor( 0xffffff, 1 );
|
||||
|
||||
this._updateSelectionCache();
|
||||
|
||||
// Make selected objects invisible
|
||||
this._changeVisibilityOfSelectedObjects( false );
|
||||
|
||||
const currentBackground = this.renderScene.background;
|
||||
const currentOverrideMaterial = this.renderScene.overrideMaterial;
|
||||
this.renderScene.background = null;
|
||||
|
||||
// 1. Draw Non Selected objects in the depth buffer
|
||||
this.renderScene.overrideMaterial = this.depthMaterial;
|
||||
renderer.setRenderTarget( this.renderTargetDepthBuffer );
|
||||
renderer.clear();
|
||||
renderer.render( this.renderScene, this.renderCamera );
|
||||
|
||||
// Make selected objects visible
|
||||
this._changeVisibilityOfSelectedObjects( true );
|
||||
this._visibilityCache.clear();
|
||||
|
||||
// Update Texture Matrix for Depth compare
|
||||
this._updateTextureMatrix();
|
||||
|
||||
// Make non selected objects invisible, and draw only the selected objects, by comparing the depth buffer of non selected objects
|
||||
this._changeVisibilityOfNonSelectedObjects( false );
|
||||
this.renderScene.overrideMaterial = this.prepareMaskMaterial;
|
||||
this.prepareMaskMaterial.uniforms[ 'cameraNearFar' ].value.set( this.renderCamera.near, this.renderCamera.far );
|
||||
this.prepareMaskMaterial.uniforms[ 'depthTexture' ].value = this.renderTargetDepthBuffer.texture;
|
||||
this.prepareMaskMaterial.uniforms[ 'textureMatrix' ].value = this.textureMatrix;
|
||||
renderer.setRenderTarget( this.renderTargetMaskBuffer );
|
||||
renderer.clear();
|
||||
renderer.render( this.renderScene, this.renderCamera );
|
||||
this._changeVisibilityOfNonSelectedObjects( true );
|
||||
this._visibilityCache.clear();
|
||||
this._selectionCache.clear();
|
||||
|
||||
this.renderScene.background = currentBackground;
|
||||
this.renderScene.overrideMaterial = currentOverrideMaterial;
|
||||
|
||||
// 2. Downsample to Half resolution
|
||||
this._fsQuad.material = this.materialCopy;
|
||||
this.copyUniforms[ 'tDiffuse' ].value = this.renderTargetMaskBuffer.texture;
|
||||
renderer.setRenderTarget( this.renderTargetMaskDownSampleBuffer );
|
||||
renderer.clear();
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
this.tempPulseColor1.copy( this.visibleEdgeColor );
|
||||
this.tempPulseColor2.copy( this.hiddenEdgeColor );
|
||||
|
||||
if ( this.pulsePeriod > 0 ) {
|
||||
|
||||
const scalar = ( 1 + 0.25 ) / 2 + Math.cos( performance.now() * 0.01 / this.pulsePeriod ) * ( 1.0 - 0.25 ) / 2;
|
||||
this.tempPulseColor1.multiplyScalar( scalar );
|
||||
this.tempPulseColor2.multiplyScalar( scalar );
|
||||
|
||||
}
|
||||
|
||||
// 3. Apply Edge Detection Pass
|
||||
this._fsQuad.material = this.edgeDetectionMaterial;
|
||||
this.edgeDetectionMaterial.uniforms[ 'maskTexture' ].value = this.renderTargetMaskDownSampleBuffer.texture;
|
||||
this.edgeDetectionMaterial.uniforms[ 'texSize' ].value.set( this.renderTargetMaskDownSampleBuffer.width, this.renderTargetMaskDownSampleBuffer.height );
|
||||
this.edgeDetectionMaterial.uniforms[ 'visibleEdgeColor' ].value = this.tempPulseColor1;
|
||||
this.edgeDetectionMaterial.uniforms[ 'hiddenEdgeColor' ].value = this.tempPulseColor2;
|
||||
renderer.setRenderTarget( this.renderTargetEdgeBuffer1 );
|
||||
renderer.clear();
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
// 4. Apply Blur on Half res
|
||||
this._fsQuad.material = this.separableBlurMaterial1;
|
||||
this.separableBlurMaterial1.uniforms[ 'colorTexture' ].value = this.renderTargetEdgeBuffer1.texture;
|
||||
this.separableBlurMaterial1.uniforms[ 'direction' ].value = OutlinePass.BlurDirectionX;
|
||||
this.separableBlurMaterial1.uniforms[ 'kernelRadius' ].value = this.edgeThickness;
|
||||
renderer.setRenderTarget( this.renderTargetBlurBuffer1 );
|
||||
renderer.clear();
|
||||
this._fsQuad.render( renderer );
|
||||
this.separableBlurMaterial1.uniforms[ 'colorTexture' ].value = this.renderTargetBlurBuffer1.texture;
|
||||
this.separableBlurMaterial1.uniforms[ 'direction' ].value = OutlinePass.BlurDirectionY;
|
||||
renderer.setRenderTarget( this.renderTargetEdgeBuffer1 );
|
||||
renderer.clear();
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
// Apply Blur on quarter res
|
||||
this._fsQuad.material = this.separableBlurMaterial2;
|
||||
this.separableBlurMaterial2.uniforms[ 'colorTexture' ].value = this.renderTargetEdgeBuffer1.texture;
|
||||
this.separableBlurMaterial2.uniforms[ 'direction' ].value = OutlinePass.BlurDirectionX;
|
||||
renderer.setRenderTarget( this.renderTargetBlurBuffer2 );
|
||||
renderer.clear();
|
||||
this._fsQuad.render( renderer );
|
||||
this.separableBlurMaterial2.uniforms[ 'colorTexture' ].value = this.renderTargetBlurBuffer2.texture;
|
||||
this.separableBlurMaterial2.uniforms[ 'direction' ].value = OutlinePass.BlurDirectionY;
|
||||
renderer.setRenderTarget( this.renderTargetEdgeBuffer2 );
|
||||
renderer.clear();
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
// Blend it additively over the input texture
|
||||
this._fsQuad.material = this.overlayMaterial;
|
||||
this.overlayMaterial.uniforms[ 'maskTexture' ].value = this.renderTargetMaskBuffer.texture;
|
||||
this.overlayMaterial.uniforms[ 'edgeTexture1' ].value = this.renderTargetEdgeBuffer1.texture;
|
||||
this.overlayMaterial.uniforms[ 'edgeTexture2' ].value = this.renderTargetEdgeBuffer2.texture;
|
||||
this.overlayMaterial.uniforms[ 'patternTexture' ].value = this.patternTexture;
|
||||
this.overlayMaterial.uniforms[ 'edgeStrength' ].value = this.edgeStrength;
|
||||
this.overlayMaterial.uniforms[ 'edgeGlow' ].value = this.edgeGlow;
|
||||
this.overlayMaterial.uniforms[ 'usePatternTexture' ].value = this.usePatternTexture;
|
||||
|
||||
|
||||
if ( maskActive ) renderer.state.buffers.stencil.setTest( true );
|
||||
|
||||
renderer.setRenderTarget( readBuffer );
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
renderer.setClearColor( this._oldClearColor, this.oldClearAlpha );
|
||||
renderer.autoClear = oldAutoClear;
|
||||
|
||||
}
|
||||
|
||||
if ( this.renderToScreen ) {
|
||||
|
||||
this._fsQuad.material = this.materialCopy;
|
||||
this.copyUniforms[ 'tDiffuse' ].value = readBuffer.texture;
|
||||
renderer.setRenderTarget( null );
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// internals
|
||||
|
||||
_updateSelectionCache() {
|
||||
|
||||
const cache = this._selectionCache;
|
||||
|
||||
function gatherSelectedMeshesCallBack( object ) {
|
||||
|
||||
if ( object.isMesh ) cache.add( object );
|
||||
|
||||
}
|
||||
|
||||
cache.clear();
|
||||
|
||||
for ( let i = 0; i < this.selectedObjects.length; i ++ ) {
|
||||
|
||||
const selectedObject = this.selectedObjects[ i ];
|
||||
selectedObject.traverse( gatherSelectedMeshesCallBack );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
_changeVisibilityOfSelectedObjects( bVisible ) {
|
||||
|
||||
const cache = this._visibilityCache;
|
||||
|
||||
for ( const mesh of this._selectionCache ) {
|
||||
|
||||
if ( bVisible === true ) {
|
||||
|
||||
mesh.visible = cache.get( mesh );
|
||||
|
||||
} else {
|
||||
|
||||
cache.set( mesh, mesh.visible );
|
||||
mesh.visible = bVisible;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
_changeVisibilityOfNonSelectedObjects( bVisible ) {
|
||||
|
||||
const visibilityCache = this._visibilityCache;
|
||||
const selectionCache = this._selectionCache;
|
||||
|
||||
function VisibilityChangeCallBack( object ) {
|
||||
|
||||
if ( object.isPoints || object.isLine || object.isLine2 ) {
|
||||
|
||||
// the visibility of points and lines is always set to false in order to
|
||||
// not affect the outline computation
|
||||
|
||||
if ( bVisible === true ) {
|
||||
|
||||
object.visible = visibilityCache.get( object ); // restore
|
||||
|
||||
} else {
|
||||
|
||||
visibilityCache.set( object, object.visible );
|
||||
object.visible = bVisible;
|
||||
|
||||
}
|
||||
|
||||
} else if ( object.isMesh || object.isSprite ) {
|
||||
|
||||
// only meshes and sprites are supported by OutlinePass
|
||||
|
||||
if ( ! selectionCache.has( object ) ) {
|
||||
|
||||
const visibility = object.visible;
|
||||
|
||||
if ( bVisible === false || visibilityCache.get( object ) === true ) {
|
||||
|
||||
object.visible = bVisible;
|
||||
|
||||
}
|
||||
|
||||
visibilityCache.set( object, visibility );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
this.renderScene.traverse( VisibilityChangeCallBack );
|
||||
|
||||
}
|
||||
|
||||
_updateTextureMatrix() {
|
||||
|
||||
this.textureMatrix.set( 0.5, 0.0, 0.0, 0.5,
|
||||
0.0, 0.5, 0.0, 0.5,
|
||||
0.0, 0.0, 0.5, 0.5,
|
||||
0.0, 0.0, 0.0, 1.0 );
|
||||
this.textureMatrix.multiply( this.renderCamera.projectionMatrix );
|
||||
this.textureMatrix.multiply( this.renderCamera.matrixWorldInverse );
|
||||
|
||||
}
|
||||
|
||||
_getPrepareMaskMaterial() {
|
||||
|
||||
return new ShaderMaterial( {
|
||||
|
||||
uniforms: {
|
||||
'depthTexture': { value: null },
|
||||
'cameraNearFar': { value: new Vector2( 0.5, 0.5 ) },
|
||||
'textureMatrix': { value: null }
|
||||
},
|
||||
|
||||
vertexShader:
|
||||
`#include <batching_pars_vertex>
|
||||
#include <morphtarget_pars_vertex>
|
||||
#include <skinning_pars_vertex>
|
||||
|
||||
varying vec4 projTexCoord;
|
||||
varying vec4 vPosition;
|
||||
uniform mat4 textureMatrix;
|
||||
|
||||
void main() {
|
||||
|
||||
#include <batching_vertex>
|
||||
#include <skinbase_vertex>
|
||||
#include <begin_vertex>
|
||||
#include <morphtarget_vertex>
|
||||
#include <skinning_vertex>
|
||||
#include <project_vertex>
|
||||
|
||||
vPosition = mvPosition;
|
||||
|
||||
vec4 worldPosition = vec4( transformed, 1.0 );
|
||||
|
||||
#ifdef USE_INSTANCING
|
||||
|
||||
worldPosition = instanceMatrix * worldPosition;
|
||||
|
||||
#endif
|
||||
|
||||
worldPosition = modelMatrix * worldPosition;
|
||||
|
||||
projTexCoord = textureMatrix * worldPosition;
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader:
|
||||
`#include <packing>
|
||||
varying vec4 vPosition;
|
||||
varying vec4 projTexCoord;
|
||||
uniform sampler2D depthTexture;
|
||||
uniform vec2 cameraNearFar;
|
||||
|
||||
void main() {
|
||||
|
||||
float depth = unpackRGBAToDepth(texture2DProj( depthTexture, projTexCoord ));
|
||||
float viewZ = - DEPTH_TO_VIEW_Z( depth, cameraNearFar.x, cameraNearFar.y );
|
||||
float depthTest = (-vPosition.z > viewZ) ? 1.0 : 0.0;
|
||||
gl_FragColor = vec4(0.0, depthTest, 1.0, 1.0);
|
||||
|
||||
}`
|
||||
|
||||
} );
|
||||
|
||||
}
|
||||
|
||||
_getEdgeDetectionMaterial() {
|
||||
|
||||
return new ShaderMaterial( {
|
||||
|
||||
uniforms: {
|
||||
'maskTexture': { value: null },
|
||||
'texSize': { value: new Vector2( 0.5, 0.5 ) },
|
||||
'visibleEdgeColor': { value: new Vector3( 1.0, 1.0, 1.0 ) },
|
||||
'hiddenEdgeColor': { value: new Vector3( 1.0, 1.0, 1.0 ) },
|
||||
},
|
||||
|
||||
vertexShader:
|
||||
`varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
}`,
|
||||
|
||||
fragmentShader:
|
||||
`varying vec2 vUv;
|
||||
|
||||
uniform sampler2D maskTexture;
|
||||
uniform vec2 texSize;
|
||||
uniform vec3 visibleEdgeColor;
|
||||
uniform vec3 hiddenEdgeColor;
|
||||
|
||||
void main() {
|
||||
vec2 invSize = 1.0 / texSize;
|
||||
vec4 uvOffset = vec4(1.0, 0.0, 0.0, 1.0) * vec4(invSize, invSize);
|
||||
vec4 c1 = texture2D( maskTexture, vUv + uvOffset.xy);
|
||||
vec4 c2 = texture2D( maskTexture, vUv - uvOffset.xy);
|
||||
vec4 c3 = texture2D( maskTexture, vUv + uvOffset.yw);
|
||||
vec4 c4 = texture2D( maskTexture, vUv - uvOffset.yw);
|
||||
float diff1 = (c1.r - c2.r)*0.5;
|
||||
float diff2 = (c3.r - c4.r)*0.5;
|
||||
float d = length( vec2(diff1, diff2) );
|
||||
float a1 = min(c1.g, c2.g);
|
||||
float a2 = min(c3.g, c4.g);
|
||||
float visibilityFactor = min(a1, a2);
|
||||
vec3 edgeColor = 1.0 - visibilityFactor > 0.001 ? visibleEdgeColor : hiddenEdgeColor;
|
||||
gl_FragColor = vec4(edgeColor, 1.0) * vec4(d);
|
||||
}`
|
||||
} );
|
||||
|
||||
}
|
||||
|
||||
_getSeparableBlurMaterial( maxRadius ) {
|
||||
|
||||
return new ShaderMaterial( {
|
||||
|
||||
defines: {
|
||||
'MAX_RADIUS': maxRadius,
|
||||
},
|
||||
|
||||
uniforms: {
|
||||
'colorTexture': { value: null },
|
||||
'texSize': { value: new Vector2( 0.5, 0.5 ) },
|
||||
'direction': { value: new Vector2( 0.5, 0.5 ) },
|
||||
'kernelRadius': { value: 1.0 }
|
||||
},
|
||||
|
||||
vertexShader:
|
||||
`varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
}`,
|
||||
|
||||
fragmentShader:
|
||||
`#include <common>
|
||||
varying vec2 vUv;
|
||||
uniform sampler2D colorTexture;
|
||||
uniform vec2 texSize;
|
||||
uniform vec2 direction;
|
||||
uniform float kernelRadius;
|
||||
|
||||
float gaussianPdf(in float x, in float sigma) {
|
||||
return 0.39894 * exp( -0.5 * x * x/( sigma * sigma))/sigma;
|
||||
}
|
||||
|
||||
void main() {
|
||||
vec2 invSize = 1.0 / texSize;
|
||||
float sigma = kernelRadius/2.0;
|
||||
float weightSum = gaussianPdf(0.0, sigma);
|
||||
vec4 diffuseSum = texture2D( colorTexture, vUv) * weightSum;
|
||||
vec2 delta = direction * invSize * kernelRadius/float(MAX_RADIUS);
|
||||
vec2 uvOffset = delta;
|
||||
for( int i = 1; i <= MAX_RADIUS; i ++ ) {
|
||||
float x = kernelRadius * float(i) / float(MAX_RADIUS);
|
||||
float w = gaussianPdf(x, sigma);
|
||||
vec4 sample1 = texture2D( colorTexture, vUv + uvOffset);
|
||||
vec4 sample2 = texture2D( colorTexture, vUv - uvOffset);
|
||||
diffuseSum += ((sample1 + sample2) * w);
|
||||
weightSum += (2.0 * w);
|
||||
uvOffset += delta;
|
||||
}
|
||||
gl_FragColor = diffuseSum/weightSum;
|
||||
}`
|
||||
} );
|
||||
|
||||
}
|
||||
|
||||
_getOverlayMaterial() {
|
||||
|
||||
return new ShaderMaterial( {
|
||||
|
||||
uniforms: {
|
||||
'maskTexture': { value: null },
|
||||
'edgeTexture1': { value: null },
|
||||
'edgeTexture2': { value: null },
|
||||
'patternTexture': { value: null },
|
||||
'edgeStrength': { value: 1.0 },
|
||||
'edgeGlow': { value: 1.0 },
|
||||
'usePatternTexture': { value: 0.0 }
|
||||
},
|
||||
|
||||
vertexShader:
|
||||
`varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
}`,
|
||||
|
||||
fragmentShader:
|
||||
`varying vec2 vUv;
|
||||
|
||||
uniform sampler2D maskTexture;
|
||||
uniform sampler2D edgeTexture1;
|
||||
uniform sampler2D edgeTexture2;
|
||||
uniform sampler2D patternTexture;
|
||||
uniform float edgeStrength;
|
||||
uniform float edgeGlow;
|
||||
uniform bool usePatternTexture;
|
||||
|
||||
void main() {
|
||||
vec4 edgeValue1 = texture2D(edgeTexture1, vUv);
|
||||
vec4 edgeValue2 = texture2D(edgeTexture2, vUv);
|
||||
vec4 maskColor = texture2D(maskTexture, vUv);
|
||||
vec4 patternColor = texture2D(patternTexture, 6.0 * vUv);
|
||||
float visibilityFactor = 1.0 - maskColor.g > 0.0 ? 1.0 : 0.5;
|
||||
vec4 edgeValue = edgeValue1 + edgeValue2 * edgeGlow;
|
||||
vec4 finalColor = edgeStrength * maskColor.r * edgeValue;
|
||||
if(usePatternTexture)
|
||||
finalColor += + visibilityFactor * (1.0 - maskColor.r) * (1.0 - patternColor.r);
|
||||
gl_FragColor = finalColor;
|
||||
}`,
|
||||
blending: AdditiveBlending,
|
||||
depthTest: false,
|
||||
depthWrite: false,
|
||||
transparent: true
|
||||
} );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
OutlinePass.BlurDirectionX = new Vector2( 1.0, 0.0 );
|
||||
OutlinePass.BlurDirectionY = new Vector2( 0.0, 1.0 );
|
||||
|
||||
export { OutlinePass };
|
||||
@@ -0,0 +1,148 @@
|
||||
import {
|
||||
ColorManagement,
|
||||
RawShaderMaterial,
|
||||
UniformsUtils,
|
||||
LinearToneMapping,
|
||||
ReinhardToneMapping,
|
||||
CineonToneMapping,
|
||||
AgXToneMapping,
|
||||
ACESFilmicToneMapping,
|
||||
NeutralToneMapping,
|
||||
CustomToneMapping,
|
||||
SRGBTransfer
|
||||
} from 'three';
|
||||
import { Pass, FullScreenQuad } from './Pass.js';
|
||||
import { OutputShader } from '../shaders/OutputShader.js';
|
||||
|
||||
/**
|
||||
* This pass is responsible for including tone mapping and color space conversion
|
||||
* into your pass chain. In most cases, this pass should be included at the end
|
||||
* of each pass chain. If a pass requires sRGB input (e.g. like FXAA), the pass
|
||||
* must follow `OutputPass` in the pass chain.
|
||||
*
|
||||
* The tone mapping and color space settings are extracted from the renderer.
|
||||
*
|
||||
* ```js
|
||||
* const outputPass = new OutputPass();
|
||||
* composer.addPass( outputPass );
|
||||
* ```
|
||||
*
|
||||
* @augments Pass
|
||||
* @three_import import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';
|
||||
*/
|
||||
class OutputPass extends Pass {
|
||||
|
||||
/**
|
||||
* Constructs a new output pass.
|
||||
*/
|
||||
constructor() {
|
||||
|
||||
super();
|
||||
|
||||
/**
|
||||
* This flag indicates that this is an output pass.
|
||||
*
|
||||
* @type {boolean}
|
||||
* @readonly
|
||||
* @default true
|
||||
*/
|
||||
this.isOutputPass = true;
|
||||
|
||||
/**
|
||||
* The pass uniforms.
|
||||
*
|
||||
* @type {Object}
|
||||
*/
|
||||
this.uniforms = UniformsUtils.clone( OutputShader.uniforms );
|
||||
|
||||
/**
|
||||
* The pass material.
|
||||
*
|
||||
* @type {RawShaderMaterial}
|
||||
*/
|
||||
this.material = new RawShaderMaterial( {
|
||||
name: OutputShader.name,
|
||||
uniforms: this.uniforms,
|
||||
vertexShader: OutputShader.vertexShader,
|
||||
fragmentShader: OutputShader.fragmentShader
|
||||
} );
|
||||
|
||||
// internals
|
||||
|
||||
this._fsQuad = new FullScreenQuad( this.material );
|
||||
|
||||
this._outputColorSpace = null;
|
||||
this._toneMapping = null;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs the output pass.
|
||||
*
|
||||
* @param {WebGLRenderer} renderer - The renderer.
|
||||
* @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
|
||||
* destination for the pass.
|
||||
* @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
|
||||
* previous pass from this buffer.
|
||||
* @param {number} deltaTime - The delta time in seconds.
|
||||
* @param {boolean} maskActive - Whether masking is active or not.
|
||||
*/
|
||||
render( renderer, writeBuffer, readBuffer/*, deltaTime, maskActive */ ) {
|
||||
|
||||
this.uniforms[ 'tDiffuse' ].value = readBuffer.texture;
|
||||
this.uniforms[ 'toneMappingExposure' ].value = renderer.toneMappingExposure;
|
||||
|
||||
// rebuild defines if required
|
||||
|
||||
if ( this._outputColorSpace !== renderer.outputColorSpace || this._toneMapping !== renderer.toneMapping ) {
|
||||
|
||||
this._outputColorSpace = renderer.outputColorSpace;
|
||||
this._toneMapping = renderer.toneMapping;
|
||||
|
||||
this.material.defines = {};
|
||||
|
||||
if ( ColorManagement.getTransfer( this._outputColorSpace ) === SRGBTransfer ) this.material.defines.SRGB_TRANSFER = '';
|
||||
|
||||
if ( this._toneMapping === LinearToneMapping ) this.material.defines.LINEAR_TONE_MAPPING = '';
|
||||
else if ( this._toneMapping === ReinhardToneMapping ) this.material.defines.REINHARD_TONE_MAPPING = '';
|
||||
else if ( this._toneMapping === CineonToneMapping ) this.material.defines.CINEON_TONE_MAPPING = '';
|
||||
else if ( this._toneMapping === ACESFilmicToneMapping ) this.material.defines.ACES_FILMIC_TONE_MAPPING = '';
|
||||
else if ( this._toneMapping === AgXToneMapping ) this.material.defines.AGX_TONE_MAPPING = '';
|
||||
else if ( this._toneMapping === NeutralToneMapping ) this.material.defines.NEUTRAL_TONE_MAPPING = '';
|
||||
else if ( this._toneMapping === CustomToneMapping ) this.material.defines.CUSTOM_TONE_MAPPING = '';
|
||||
|
||||
this.material.needsUpdate = true;
|
||||
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
if ( this.renderToScreen === true ) {
|
||||
|
||||
renderer.setRenderTarget( null );
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
} else {
|
||||
|
||||
renderer.setRenderTarget( writeBuffer );
|
||||
if ( this.clear ) renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Frees the GPU-related resources allocated by this instance. Call this
|
||||
* method whenever the pass is no longer used in your app.
|
||||
*/
|
||||
dispose() {
|
||||
|
||||
this.material.dispose();
|
||||
this._fsQuad.dispose();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export { OutputPass };
|
||||
@@ -0,0 +1,191 @@
|
||||
import {
|
||||
BufferGeometry,
|
||||
Float32BufferAttribute,
|
||||
OrthographicCamera,
|
||||
Mesh
|
||||
} from 'three';
|
||||
|
||||
/**
|
||||
* Abstract base class for all post processing passes.
|
||||
*
|
||||
* This module is only relevant for post processing with {@link WebGLRenderer}.
|
||||
*
|
||||
* @abstract
|
||||
* @three_import import { Pass } from 'three/addons/postprocessing/Pass.js';
|
||||
*/
|
||||
class Pass {
|
||||
|
||||
/**
|
||||
* Constructs a new pass.
|
||||
*/
|
||||
constructor() {
|
||||
|
||||
/**
|
||||
* This flag can be used for type testing.
|
||||
*
|
||||
* @type {boolean}
|
||||
* @readonly
|
||||
* @default true
|
||||
*/
|
||||
this.isPass = true;
|
||||
|
||||
/**
|
||||
* If set to `true`, the pass is processed by the composer.
|
||||
*
|
||||
* @type {boolean}
|
||||
* @default true
|
||||
*/
|
||||
this.enabled = true;
|
||||
|
||||
/**
|
||||
* If set to `true`, the pass indicates to swap read and write buffer after rendering.
|
||||
*
|
||||
* @type {boolean}
|
||||
* @default true
|
||||
*/
|
||||
this.needsSwap = true;
|
||||
|
||||
/**
|
||||
* If set to `true`, the pass clears its buffer before rendering
|
||||
*
|
||||
* @type {boolean}
|
||||
* @default false
|
||||
*/
|
||||
this.clear = false;
|
||||
|
||||
/**
|
||||
* If set to `true`, the result of the pass is rendered to screen. The last pass in the composers
|
||||
* pass chain gets automatically rendered to screen, no matter how this property is configured.
|
||||
*
|
||||
* @type {boolean}
|
||||
* @default false
|
||||
*/
|
||||
this.renderToScreen = false;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the size of the pass.
|
||||
*
|
||||
* @abstract
|
||||
* @param {number} width - The width to set.
|
||||
* @param {number} height - The height to set.
|
||||
*/
|
||||
setSize( /* width, height */ ) {}
|
||||
|
||||
/**
|
||||
* This method holds the render logic of a pass. It must be implemented in all derived classes.
|
||||
*
|
||||
* @abstract
|
||||
* @param {WebGLRenderer} renderer - The renderer.
|
||||
* @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
|
||||
* destination for the pass.
|
||||
* @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
|
||||
* previous pass from this buffer.
|
||||
* @param {number} deltaTime - The delta time in seconds.
|
||||
* @param {boolean} maskActive - Whether masking is active or not.
|
||||
*/
|
||||
render( /* renderer, writeBuffer, readBuffer, deltaTime, maskActive */ ) {
|
||||
|
||||
console.error( 'THREE.Pass: .render() must be implemented in derived pass.' );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Frees the GPU-related resources allocated by this instance. Call this
|
||||
* method whenever the pass is no longer used in your app.
|
||||
*
|
||||
* @abstract
|
||||
*/
|
||||
dispose() {}
|
||||
|
||||
}
|
||||
|
||||
// Helper for passes that need to fill the viewport with a single quad.
|
||||
|
||||
const _camera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
|
||||
|
||||
// https://github.com/mrdoob/three.js/pull/21358
|
||||
|
||||
class FullscreenTriangleGeometry extends BufferGeometry {
|
||||
|
||||
constructor() {
|
||||
|
||||
super();
|
||||
|
||||
this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
|
||||
this.setAttribute( 'uv', new Float32BufferAttribute( [ 0, 2, 0, 0, 2, 0 ], 2 ) );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
const _geometry = new FullscreenTriangleGeometry();
|
||||
|
||||
|
||||
/**
|
||||
* This module is a helper for passes which need to render a full
|
||||
* screen effect which is quite common in context of post processing.
|
||||
*
|
||||
* The intended usage is to reuse a single full screen quad for rendering
|
||||
* subsequent passes by just reassigning the `material` reference.
|
||||
*
|
||||
* This module can only be used with {@link WebGLRenderer}.
|
||||
*
|
||||
* @augments Mesh
|
||||
* @three_import import { FullScreenQuad } from 'three/addons/postprocessing/Pass.js';
|
||||
*/
|
||||
class FullScreenQuad {
|
||||
|
||||
/**
|
||||
* Constructs a new full screen quad.
|
||||
*
|
||||
* @param {?Material} material - The material to render te full screen quad with.
|
||||
*/
|
||||
constructor( material ) {
|
||||
|
||||
this._mesh = new Mesh( _geometry, material );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Frees the GPU-related resources allocated by this instance. Call this
|
||||
* method whenever the instance is no longer used in your app.
|
||||
*/
|
||||
dispose() {
|
||||
|
||||
this._mesh.geometry.dispose();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the full screen quad.
|
||||
*
|
||||
* @param {WebGLRenderer} renderer - The renderer.
|
||||
*/
|
||||
render( renderer ) {
|
||||
|
||||
renderer.render( this._mesh, _camera );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* The quad's material.
|
||||
*
|
||||
* @type {?Material}
|
||||
*/
|
||||
get material() {
|
||||
|
||||
return this._mesh.material;
|
||||
|
||||
}
|
||||
|
||||
set material( value ) {
|
||||
|
||||
this._mesh.material = value;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export { Pass, FullScreenQuad };
|
||||
@@ -0,0 +1,193 @@
|
||||
import {
|
||||
Color
|
||||
} from 'three';
|
||||
import { Pass } from './Pass.js';
|
||||
|
||||
/**
|
||||
* This class represents a render pass. It takes a camera and a scene and produces
|
||||
* a beauty pass for subsequent post processing effects.
|
||||
*
|
||||
* ```js
|
||||
* const renderPass = new RenderPass( scene, camera );
|
||||
* composer.addPass( renderPass );
|
||||
* ```
|
||||
*
|
||||
* @augments Pass
|
||||
* @three_import import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
|
||||
*/
|
||||
class RenderPass extends Pass {
|
||||
|
||||
/**
|
||||
* Constructs a new render pass.
|
||||
*
|
||||
* @param {Scene} scene - The scene to render.
|
||||
* @param {Camera} camera - The camera.
|
||||
* @param {?Material} [overrideMaterial=null] - The override material. If set, this material is used
|
||||
* for all objects in the scene.
|
||||
* @param {?(number|Color|string)} [clearColor=null] - The clear color of the render pass.
|
||||
* @param {?number} [clearAlpha=null] - The clear alpha of the render pass.
|
||||
*/
|
||||
constructor( scene, camera, overrideMaterial = null, clearColor = null, clearAlpha = null ) {
|
||||
|
||||
super();
|
||||
|
||||
/**
|
||||
* The scene to render.
|
||||
*
|
||||
* @type {Scene}
|
||||
*/
|
||||
this.scene = scene;
|
||||
|
||||
/**
|
||||
* The camera.
|
||||
*
|
||||
* @type {Camera}
|
||||
*/
|
||||
this.camera = camera;
|
||||
|
||||
/**
|
||||
* The override material. If set, this material is used
|
||||
* for all objects in the scene.
|
||||
*
|
||||
* @type {?Material}
|
||||
* @default null
|
||||
*/
|
||||
this.overrideMaterial = overrideMaterial;
|
||||
|
||||
/**
|
||||
* The clear color of the render pass.
|
||||
*
|
||||
* @type {?(number|Color|string)}
|
||||
* @default null
|
||||
*/
|
||||
this.clearColor = clearColor;
|
||||
|
||||
/**
|
||||
* The clear alpha of the render pass.
|
||||
*
|
||||
* @type {?number}
|
||||
* @default null
|
||||
*/
|
||||
this.clearAlpha = clearAlpha;
|
||||
|
||||
/**
|
||||
* Overwritten to perform a clear operation by default.
|
||||
*
|
||||
* @type {boolean}
|
||||
* @default true
|
||||
*/
|
||||
this.clear = true;
|
||||
|
||||
/**
|
||||
* If set to `true`, only the depth can be cleared when `clear` is to `false`.
|
||||
*
|
||||
* @type {boolean}
|
||||
* @default false
|
||||
*/
|
||||
this.clearDepth = false;
|
||||
|
||||
/**
|
||||
* Overwritten to disable the swap.
|
||||
*
|
||||
* @type {boolean}
|
||||
* @default false
|
||||
*/
|
||||
this.needsSwap = false;
|
||||
|
||||
/**
|
||||
* This flag indicates that this pass renders the scene itself.
|
||||
*
|
||||
* @type {boolean}
|
||||
* @readonly
|
||||
* @default true
|
||||
*/
|
||||
this.isRenderPass = true;
|
||||
|
||||
this._oldClearColor = new Color();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs a beauty pass with the configured scene and camera.
|
||||
*
|
||||
* @param {WebGLRenderer} renderer - The renderer.
|
||||
* @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
|
||||
* destination for the pass.
|
||||
* @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
|
||||
* previous pass from this buffer.
|
||||
* @param {number} deltaTime - The delta time in seconds.
|
||||
* @param {boolean} maskActive - Whether masking is active or not.
|
||||
*/
|
||||
render( renderer, writeBuffer, readBuffer /*, deltaTime, maskActive */ ) {
|
||||
|
||||
const oldAutoClear = renderer.autoClear;
|
||||
renderer.autoClear = false;
|
||||
|
||||
let oldClearAlpha, oldOverrideMaterial;
|
||||
|
||||
if ( this.overrideMaterial !== null ) {
|
||||
|
||||
oldOverrideMaterial = this.scene.overrideMaterial;
|
||||
|
||||
this.scene.overrideMaterial = this.overrideMaterial;
|
||||
|
||||
}
|
||||
|
||||
if ( this.clearColor !== null ) {
|
||||
|
||||
renderer.getClearColor( this._oldClearColor );
|
||||
renderer.setClearColor( this.clearColor, renderer.getClearAlpha() );
|
||||
|
||||
}
|
||||
|
||||
if ( this.clearAlpha !== null ) {
|
||||
|
||||
oldClearAlpha = renderer.getClearAlpha();
|
||||
renderer.setClearAlpha( this.clearAlpha );
|
||||
|
||||
}
|
||||
|
||||
if ( this.clearDepth == true ) {
|
||||
|
||||
renderer.clearDepth();
|
||||
|
||||
}
|
||||
|
||||
renderer.setRenderTarget( this.renderToScreen ? null : readBuffer );
|
||||
|
||||
if ( this.clear === true ) {
|
||||
|
||||
// TODO: Avoid using autoClear properties, see https://github.com/mrdoob/three.js/pull/15571#issuecomment-465669600
|
||||
renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
|
||||
|
||||
}
|
||||
|
||||
renderer.render( this.scene, this.camera );
|
||||
|
||||
// restore
|
||||
|
||||
if ( this.clearColor !== null ) {
|
||||
|
||||
renderer.setClearColor( this._oldClearColor );
|
||||
|
||||
}
|
||||
|
||||
if ( this.clearAlpha !== null ) {
|
||||
|
||||
renderer.setClearAlpha( oldClearAlpha );
|
||||
|
||||
}
|
||||
|
||||
if ( this.overrideMaterial !== null ) {
|
||||
|
||||
this.scene.overrideMaterial = oldOverrideMaterial;
|
||||
|
||||
}
|
||||
|
||||
renderer.autoClear = oldAutoClear;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export { RenderPass };
|
||||
@@ -0,0 +1,314 @@
|
||||
import {
|
||||
WebGLRenderTarget,
|
||||
MeshNormalMaterial,
|
||||
ShaderMaterial,
|
||||
Vector2,
|
||||
Vector4,
|
||||
DepthTexture,
|
||||
NearestFilter,
|
||||
HalfFloatType
|
||||
} from 'three';
|
||||
import { Pass, FullScreenQuad } from './Pass.js';
|
||||
|
||||
/**
|
||||
* A special type of render pass that produces a pixelated beauty pass.
|
||||
*
|
||||
* ```js
|
||||
* const renderPixelatedPass = new RenderPixelatedPass( 6, scene, camera );
|
||||
* composer.addPass( renderPixelatedPass );
|
||||
* ```
|
||||
*
|
||||
* @augments Pass
|
||||
* @three_import import { RenderPixelatedPass } from 'three/addons/postprocessing/RenderPixelatedPass.js';
|
||||
*/
|
||||
class RenderPixelatedPass extends Pass {
|
||||
|
||||
/**
|
||||
* Constructs a new render pixelated pass.
|
||||
*
|
||||
* @param {number} pixelSize - The effect's pixel size.
|
||||
* @param {Scene} scene - The scene to render.
|
||||
* @param {Camera} camera - The camera.
|
||||
* @param {{normalEdgeStrength:number,depthEdgeStrength:number}} options - The pass options.
|
||||
*/
|
||||
constructor( pixelSize, scene, camera, options = {} ) {
|
||||
|
||||
super();
|
||||
|
||||
/**
|
||||
* The effect's pixel size.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
this.pixelSize = pixelSize;
|
||||
|
||||
/**
|
||||
* The scene to render.
|
||||
*
|
||||
* @type {Scene}
|
||||
*/
|
||||
this.scene = scene;
|
||||
|
||||
/**
|
||||
* The camera.
|
||||
*
|
||||
* @type {Camera}
|
||||
*/
|
||||
this.camera = camera;
|
||||
|
||||
/**
|
||||
* The normal edge strength.
|
||||
*
|
||||
* @type {number}
|
||||
* @default 0.3
|
||||
*/
|
||||
this.normalEdgeStrength = options.normalEdgeStrength || 0.3;
|
||||
|
||||
/**
|
||||
* The normal edge strength.
|
||||
*
|
||||
* @type {number}
|
||||
* @default 0.4
|
||||
*/
|
||||
this.depthEdgeStrength = options.depthEdgeStrength || 0.4;
|
||||
|
||||
/**
|
||||
* The pixelated material.
|
||||
*
|
||||
* @type {ShaderMaterial}
|
||||
*/
|
||||
this.pixelatedMaterial = this._createPixelatedMaterial();
|
||||
|
||||
// internals
|
||||
|
||||
this._resolution = new Vector2();
|
||||
this._renderResolution = new Vector2();
|
||||
|
||||
this._normalMaterial = new MeshNormalMaterial();
|
||||
|
||||
this._beautyRenderTarget = new WebGLRenderTarget();
|
||||
this._beautyRenderTarget.texture.minFilter = NearestFilter;
|
||||
this._beautyRenderTarget.texture.magFilter = NearestFilter;
|
||||
this._beautyRenderTarget.texture.type = HalfFloatType;
|
||||
this._beautyRenderTarget.depthTexture = new DepthTexture();
|
||||
|
||||
this._normalRenderTarget = new WebGLRenderTarget();
|
||||
this._normalRenderTarget.texture.minFilter = NearestFilter;
|
||||
this._normalRenderTarget.texture.magFilter = NearestFilter;
|
||||
this._normalRenderTarget.texture.type = HalfFloatType;
|
||||
|
||||
this._fsQuad = new FullScreenQuad( this.pixelatedMaterial );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Frees the GPU-related resources allocated by this instance. Call this
|
||||
* method whenever the pass is no longer used in your app.
|
||||
*/
|
||||
dispose() {
|
||||
|
||||
this._beautyRenderTarget.dispose();
|
||||
this._normalRenderTarget.dispose();
|
||||
|
||||
this.pixelatedMaterial.dispose();
|
||||
this._normalMaterial.dispose();
|
||||
|
||||
this._fsQuad.dispose();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the size of the pass.
|
||||
*
|
||||
* @param {number} width - The width to set.
|
||||
* @param {number} height - The height to set.
|
||||
*/
|
||||
setSize( width, height ) {
|
||||
|
||||
this._resolution.set( width, height );
|
||||
this._renderResolution.set( ( width / this.pixelSize ) | 0, ( height / this.pixelSize ) | 0 );
|
||||
const { x, y } = this._renderResolution;
|
||||
this._beautyRenderTarget.setSize( x, y );
|
||||
this._normalRenderTarget.setSize( x, y );
|
||||
this._fsQuad.material.uniforms.resolution.value.set( x, y, 1 / x, 1 / y );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the effect's pixel size.
|
||||
*
|
||||
* @param {number} pixelSize - The pixel size to set.
|
||||
*/
|
||||
setPixelSize( pixelSize ) {
|
||||
|
||||
this.pixelSize = pixelSize;
|
||||
this.setSize( this._resolution.x, this._resolution.y );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs the pixelation pass.
|
||||
*
|
||||
* @param {WebGLRenderer} renderer - The renderer.
|
||||
* @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
|
||||
* destination for the pass.
|
||||
* @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
|
||||
* previous pass from this buffer.
|
||||
* @param {number} deltaTime - The delta time in seconds.
|
||||
* @param {boolean} maskActive - Whether masking is active or not.
|
||||
*/
|
||||
render( renderer, writeBuffer/*, readBuffer , deltaTime, maskActive */ ) {
|
||||
|
||||
const uniforms = this._fsQuad.material.uniforms;
|
||||
uniforms.normalEdgeStrength.value = this.normalEdgeStrength;
|
||||
uniforms.depthEdgeStrength.value = this.depthEdgeStrength;
|
||||
|
||||
renderer.setRenderTarget( this._beautyRenderTarget );
|
||||
renderer.render( this.scene, this.camera );
|
||||
|
||||
const overrideMaterial_old = this.scene.overrideMaterial;
|
||||
renderer.setRenderTarget( this._normalRenderTarget );
|
||||
this.scene.overrideMaterial = this._normalMaterial;
|
||||
renderer.render( this.scene, this.camera );
|
||||
this.scene.overrideMaterial = overrideMaterial_old;
|
||||
|
||||
uniforms.tDiffuse.value = this._beautyRenderTarget.texture;
|
||||
uniforms.tDepth.value = this._beautyRenderTarget.depthTexture;
|
||||
uniforms.tNormal.value = this._normalRenderTarget.texture;
|
||||
|
||||
if ( this.renderToScreen ) {
|
||||
|
||||
renderer.setRenderTarget( null );
|
||||
|
||||
} else {
|
||||
|
||||
renderer.setRenderTarget( writeBuffer );
|
||||
|
||||
if ( this.clear ) renderer.clear();
|
||||
|
||||
}
|
||||
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
}
|
||||
|
||||
// internals
|
||||
|
||||
_createPixelatedMaterial() {
|
||||
|
||||
return new ShaderMaterial( {
|
||||
uniforms: {
|
||||
tDiffuse: { value: null },
|
||||
tDepth: { value: null },
|
||||
tNormal: { value: null },
|
||||
resolution: { value: new Vector4() },
|
||||
normalEdgeStrength: { value: 0 },
|
||||
depthEdgeStrength: { value: 0 }
|
||||
},
|
||||
vertexShader: /* glsl */`
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}
|
||||
`,
|
||||
fragmentShader: /* glsl */`
|
||||
uniform sampler2D tDiffuse;
|
||||
uniform sampler2D tDepth;
|
||||
uniform sampler2D tNormal;
|
||||
uniform vec4 resolution;
|
||||
uniform float normalEdgeStrength;
|
||||
uniform float depthEdgeStrength;
|
||||
varying vec2 vUv;
|
||||
|
||||
float getDepth(int x, int y) {
|
||||
|
||||
return texture2D( tDepth, vUv + vec2(x, y) * resolution.zw ).r;
|
||||
|
||||
}
|
||||
|
||||
vec3 getNormal(int x, int y) {
|
||||
|
||||
return texture2D( tNormal, vUv + vec2(x, y) * resolution.zw ).rgb * 2.0 - 1.0;
|
||||
|
||||
}
|
||||
|
||||
float depthEdgeIndicator(float depth, vec3 normal) {
|
||||
|
||||
float diff = 0.0;
|
||||
diff += clamp(getDepth(1, 0) - depth, 0.0, 1.0);
|
||||
diff += clamp(getDepth(-1, 0) - depth, 0.0, 1.0);
|
||||
diff += clamp(getDepth(0, 1) - depth, 0.0, 1.0);
|
||||
diff += clamp(getDepth(0, -1) - depth, 0.0, 1.0);
|
||||
return floor(smoothstep(0.01, 0.02, diff) * 2.) / 2.;
|
||||
|
||||
}
|
||||
|
||||
float neighborNormalEdgeIndicator(int x, int y, float depth, vec3 normal) {
|
||||
|
||||
float depthDiff = getDepth(x, y) - depth;
|
||||
vec3 neighborNormal = getNormal(x, y);
|
||||
|
||||
// Edge pixels should yield to faces who's normals are closer to the bias normal.
|
||||
vec3 normalEdgeBias = vec3(1., 1., 1.); // This should probably be a parameter.
|
||||
float normalDiff = dot(normal - neighborNormal, normalEdgeBias);
|
||||
float normalIndicator = clamp(smoothstep(-.01, .01, normalDiff), 0.0, 1.0);
|
||||
|
||||
// Only the shallower pixel should detect the normal edge.
|
||||
float depthIndicator = clamp(sign(depthDiff * .25 + .0025), 0.0, 1.0);
|
||||
|
||||
return (1.0 - dot(normal, neighborNormal)) * depthIndicator * normalIndicator;
|
||||
|
||||
}
|
||||
|
||||
float normalEdgeIndicator(float depth, vec3 normal) {
|
||||
|
||||
float indicator = 0.0;
|
||||
|
||||
indicator += neighborNormalEdgeIndicator(0, -1, depth, normal);
|
||||
indicator += neighborNormalEdgeIndicator(0, 1, depth, normal);
|
||||
indicator += neighborNormalEdgeIndicator(-1, 0, depth, normal);
|
||||
indicator += neighborNormalEdgeIndicator(1, 0, depth, normal);
|
||||
|
||||
return step(0.1, indicator);
|
||||
|
||||
}
|
||||
|
||||
void main() {
|
||||
|
||||
vec4 texel = texture2D( tDiffuse, vUv );
|
||||
|
||||
float depth = 0.0;
|
||||
vec3 normal = vec3(0.0);
|
||||
|
||||
if (depthEdgeStrength > 0.0 || normalEdgeStrength > 0.0) {
|
||||
|
||||
depth = getDepth(0, 0);
|
||||
normal = getNormal(0, 0);
|
||||
|
||||
}
|
||||
|
||||
float dei = 0.0;
|
||||
if (depthEdgeStrength > 0.0)
|
||||
dei = depthEdgeIndicator(depth, normal);
|
||||
|
||||
float nei = 0.0;
|
||||
if (normalEdgeStrength > 0.0)
|
||||
nei = normalEdgeIndicator(depth, normal);
|
||||
|
||||
float Strength = dei > 0.0 ? (1.0 - depthEdgeStrength * dei) : (1.0 + normalEdgeStrength * nei);
|
||||
|
||||
gl_FragColor = texel * Strength;
|
||||
|
||||
}
|
||||
`
|
||||
} );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export { RenderPixelatedPass };
|
||||
@@ -0,0 +1,267 @@
|
||||
import {
|
||||
HalfFloatType,
|
||||
ShaderMaterial,
|
||||
WebGLRenderTarget
|
||||
} from 'three';
|
||||
import { FullScreenQuad, Pass } from './Pass.js';
|
||||
|
||||
/**
|
||||
* A special type of render pass for implementing transition effects.
|
||||
* When active, the pass will transition from scene A to scene B.
|
||||
*
|
||||
* ```js
|
||||
* const renderTransitionPass = new RenderTransitionPass( fxSceneA.scene, fxSceneA.camera, fxSceneB.scene, fxSceneB.camera );
|
||||
* renderTransitionPass.setTexture( textures[ 0 ] );
|
||||
* composer.addPass( renderTransitionPass );
|
||||
* ```
|
||||
*
|
||||
* @augments Pass
|
||||
* @three_import import { RenderTransitionPass } from 'three/addons/postprocessing/RenderTransitionPass.js';
|
||||
*/
|
||||
class RenderTransitionPass extends Pass {
|
||||
|
||||
/**
|
||||
* Constructs a render transition pass.
|
||||
*
|
||||
* @param {Scene} sceneA - The first scene.
|
||||
* @param {Camera} cameraA - The camera of the first scene.
|
||||
* @param {Scene} sceneB - The second scene.
|
||||
* @param {Camera} cameraB - The camera of the second scene.
|
||||
*/
|
||||
constructor( sceneA, cameraA, sceneB, cameraB ) {
|
||||
|
||||
super();
|
||||
|
||||
/**
|
||||
* The first scene.
|
||||
*
|
||||
* @type {Scene}
|
||||
*/
|
||||
this.sceneA = sceneA;
|
||||
|
||||
|
||||
/**
|
||||
* The camera of the first scene.
|
||||
*
|
||||
* @type {Camera}
|
||||
*/
|
||||
this.cameraA = cameraA;
|
||||
|
||||
/**
|
||||
* The second scene.
|
||||
*
|
||||
* @type {Scene}
|
||||
*/
|
||||
this.sceneB = sceneB;
|
||||
|
||||
/**
|
||||
* The camera of the second scene.
|
||||
*
|
||||
* @type {Camera}
|
||||
*/
|
||||
this.cameraB = cameraB;
|
||||
|
||||
/**
|
||||
* The pass material.
|
||||
*
|
||||
* @type {ShaderMaterial}
|
||||
*/
|
||||
this.material = this._createMaterial();
|
||||
|
||||
// internals
|
||||
|
||||
this._renderTargetA = new WebGLRenderTarget();
|
||||
this._renderTargetA.texture.type = HalfFloatType;
|
||||
this._renderTargetB = new WebGLRenderTarget();
|
||||
this._renderTargetB.texture.type = HalfFloatType;
|
||||
|
||||
this._fsQuad = new FullScreenQuad( this.material );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the transition factor. Must be in the range `[0,1]`.
|
||||
* This value determines to what degree both scenes are mixed.
|
||||
*
|
||||
* @param {boolean|number} value - The transition factor.
|
||||
*/
|
||||
setTransition( value ) {
|
||||
|
||||
this.material.uniforms.mixRatio.value = value;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggles the usage of a texture for the effect.
|
||||
*
|
||||
* @param {boolean} value - Whether to use a texture for the transition effect or not.
|
||||
*/
|
||||
useTexture( value ) {
|
||||
|
||||
this.material.uniforms.useTexture.value = value ? 1 : 0;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the effect texture.
|
||||
*
|
||||
* @param {Texture} value - The effect texture.
|
||||
*/
|
||||
setTexture( value ) {
|
||||
|
||||
this.material.uniforms.tMixTexture.value = value;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the texture threshold. This value defines how strong the texture effects
|
||||
* the transition. Must be in the range `[0,1]` (0 means full effect, 1 means no effect).
|
||||
*
|
||||
* @param {boolean|number} value - The threshold value.
|
||||
*/
|
||||
setTextureThreshold( value ) {
|
||||
|
||||
this.material.uniforms.threshold.value = value;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the size of the pass.
|
||||
*
|
||||
* @param {number} width - The width to set.
|
||||
* @param {number} height - The height to set.
|
||||
*/
|
||||
setSize( width, height ) {
|
||||
|
||||
this._renderTargetA.setSize( width, height );
|
||||
this._renderTargetB.setSize( width, height );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs the transition pass.
|
||||
*
|
||||
* @param {WebGLRenderer} renderer - The renderer.
|
||||
* @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
|
||||
* destination for the pass.
|
||||
* @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
|
||||
* previous pass from this buffer.
|
||||
* @param {number} deltaTime - The delta time in seconds.
|
||||
* @param {boolean} maskActive - Whether masking is active or not.
|
||||
*/
|
||||
render( renderer, writeBuffer/*, readBuffer , deltaTime, maskActive */ ) {
|
||||
|
||||
renderer.setRenderTarget( this._renderTargetA );
|
||||
renderer.render( this.sceneA, this.cameraA );
|
||||
renderer.setRenderTarget( this._renderTargetB );
|
||||
renderer.render( this.sceneB, this.cameraB );
|
||||
|
||||
const uniforms = this._fsQuad.material.uniforms;
|
||||
uniforms.tDiffuse1.value = this._renderTargetA.texture;
|
||||
uniforms.tDiffuse2.value = this._renderTargetB.texture;
|
||||
|
||||
if ( this.renderToScreen ) {
|
||||
|
||||
renderer.setRenderTarget( null );
|
||||
renderer.clear();
|
||||
|
||||
} else {
|
||||
|
||||
renderer.setRenderTarget( writeBuffer );
|
||||
if ( this.clear ) renderer.clear();
|
||||
|
||||
}
|
||||
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Frees the GPU-related resources allocated by this instance. Call this
|
||||
* method whenever the pass is no longer used in your app.
|
||||
*/
|
||||
dispose() {
|
||||
|
||||
this.material.dispose();
|
||||
|
||||
this._renderTargetA.dispose();
|
||||
this._renderTargetB.dispose();
|
||||
this._fsQuad.dispose();
|
||||
|
||||
}
|
||||
|
||||
// internals
|
||||
|
||||
_createMaterial() {
|
||||
|
||||
return new ShaderMaterial( {
|
||||
uniforms: {
|
||||
tDiffuse1: {
|
||||
value: null
|
||||
},
|
||||
tDiffuse2: {
|
||||
value: null
|
||||
},
|
||||
mixRatio: {
|
||||
value: 0.0
|
||||
},
|
||||
threshold: {
|
||||
value: 0.1
|
||||
},
|
||||
useTexture: {
|
||||
value: 1
|
||||
},
|
||||
tMixTexture: {
|
||||
value: null
|
||||
}
|
||||
},
|
||||
vertexShader: /* glsl */`
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = vec2( uv.x, uv.y );
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}
|
||||
`,
|
||||
fragmentShader: /* glsl */`
|
||||
uniform float mixRatio;
|
||||
|
||||
uniform sampler2D tDiffuse1;
|
||||
uniform sampler2D tDiffuse2;
|
||||
uniform sampler2D tMixTexture;
|
||||
|
||||
uniform int useTexture;
|
||||
uniform float threshold;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vec4 texel1 = texture2D( tDiffuse1, vUv );
|
||||
vec4 texel2 = texture2D( tDiffuse2, vUv );
|
||||
|
||||
if (useTexture == 1) {
|
||||
|
||||
vec4 transitionTexel = texture2D( tMixTexture, vUv );
|
||||
float r = mixRatio * ( 1.0 + threshold * 2.0 ) - threshold;
|
||||
float mixf = clamp( ( transitionTexel.r - r ) * ( 1.0 / threshold ), 0.0, 1.0 );
|
||||
|
||||
gl_FragColor = mix( texel1, texel2, mixf );
|
||||
|
||||
} else {
|
||||
|
||||
gl_FragColor = mix( texel2, texel1, mixRatio );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
`
|
||||
} );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export { RenderTransitionPass };
|
||||
@@ -0,0 +1,407 @@
|
||||
import {
|
||||
AddEquation,
|
||||
Color,
|
||||
CustomBlending,
|
||||
DepthTexture,
|
||||
DstAlphaFactor,
|
||||
DstColorFactor,
|
||||
HalfFloatType,
|
||||
MeshNormalMaterial,
|
||||
NearestFilter,
|
||||
NoBlending,
|
||||
ShaderMaterial,
|
||||
UniformsUtils,
|
||||
DepthStencilFormat,
|
||||
UnsignedInt248Type,
|
||||
Vector2,
|
||||
WebGLRenderTarget,
|
||||
ZeroFactor
|
||||
} from 'three';
|
||||
import { Pass, FullScreenQuad } from './Pass.js';
|
||||
import { SAOShader } from '../shaders/SAOShader.js';
|
||||
import { BlurShaderUtils, DepthLimitedBlurShader } from '../shaders/DepthLimitedBlurShader.js';
|
||||
import { CopyShader } from '../shaders/CopyShader.js';
|
||||
|
||||
/**
|
||||
* A SAO implementation inspired from @bhouston previous SAO work.
|
||||
*
|
||||
* `SAOPass` provides better quality than {@link SSAOPass} but is also more expensive.
|
||||
*
|
||||
* ```js
|
||||
* const saoPass = new SAOPass( scene, camera );
|
||||
* composer.addPass( saoPass );
|
||||
* ```
|
||||
*
|
||||
* @augments Pass
|
||||
* @three_import import { SAOPass } from 'three/addons/postprocessing/SAOPass.js';
|
||||
*/
|
||||
class SAOPass extends Pass {
|
||||
|
||||
/**
|
||||
* Constructs a new SAO pass.
|
||||
*
|
||||
* @param {Scene} scene - The scene to compute the AO for.
|
||||
* @param {Camera} camera - The camera.
|
||||
* @param {Vector2} [resolution] - The effect's resolution.
|
||||
*/
|
||||
constructor( scene, camera, resolution = new Vector2( 256, 256 ) ) {
|
||||
|
||||
super();
|
||||
|
||||
/**
|
||||
* The scene to render the AO for.
|
||||
*
|
||||
* @type {Scene}
|
||||
*/
|
||||
this.scene = scene;
|
||||
|
||||
/**
|
||||
* The camera.
|
||||
*
|
||||
* @type {Camera}
|
||||
*/
|
||||
this.camera = camera;
|
||||
|
||||
/**
|
||||
* Overwritten to perform a clear operation by default.
|
||||
*
|
||||
* @type {boolean}
|
||||
* @default true
|
||||
*/
|
||||
this.clear = true;
|
||||
|
||||
/**
|
||||
* Overwritten to disable the swap.
|
||||
*
|
||||
* @type {boolean}
|
||||
* @default false
|
||||
*/
|
||||
this.needsSwap = false;
|
||||
|
||||
this._originalClearColor = new Color();
|
||||
this._oldClearColor = new Color();
|
||||
this._oldClearAlpha = 1;
|
||||
|
||||
/**
|
||||
* The SAO parameter.
|
||||
*
|
||||
* @type {Object}
|
||||
*/
|
||||
this.params = {
|
||||
output: 0,
|
||||
saoBias: 0.5,
|
||||
saoIntensity: 0.18,
|
||||
saoScale: 1,
|
||||
saoKernelRadius: 100,
|
||||
saoMinResolution: 0,
|
||||
saoBlur: true,
|
||||
saoBlurRadius: 8,
|
||||
saoBlurStdDev: 4,
|
||||
saoBlurDepthCutoff: 0.01
|
||||
};
|
||||
|
||||
/**
|
||||
* The effect's resolution.
|
||||
*
|
||||
* @type {Vector2}
|
||||
* @default (256,256)
|
||||
*/
|
||||
this.resolution = new Vector2( resolution.x, resolution.y );
|
||||
|
||||
this.saoRenderTarget = new WebGLRenderTarget( this.resolution.x, this.resolution.y, { type: HalfFloatType, depthBuffer: false } );
|
||||
this.blurIntermediateRenderTarget = this.saoRenderTarget.clone();
|
||||
|
||||
const depthTexture = new DepthTexture();
|
||||
depthTexture.format = DepthStencilFormat;
|
||||
depthTexture.type = UnsignedInt248Type;
|
||||
|
||||
this.normalRenderTarget = new WebGLRenderTarget( this.resolution.x, this.resolution.y, {
|
||||
minFilter: NearestFilter,
|
||||
magFilter: NearestFilter,
|
||||
type: HalfFloatType,
|
||||
depthTexture: depthTexture
|
||||
} );
|
||||
|
||||
this.normalMaterial = new MeshNormalMaterial();
|
||||
this.normalMaterial.blending = NoBlending;
|
||||
|
||||
this.saoMaterial = new ShaderMaterial( {
|
||||
defines: Object.assign( {}, SAOShader.defines ),
|
||||
fragmentShader: SAOShader.fragmentShader,
|
||||
vertexShader: SAOShader.vertexShader,
|
||||
uniforms: UniformsUtils.clone( SAOShader.uniforms )
|
||||
} );
|
||||
this.saoMaterial.defines[ 'PERSPECTIVE_CAMERA' ] = this.camera.isPerspectiveCamera ? 1 : 0;
|
||||
this.saoMaterial.uniforms[ 'tDepth' ].value = depthTexture;
|
||||
this.saoMaterial.uniforms[ 'tNormal' ].value = this.normalRenderTarget.texture;
|
||||
this.saoMaterial.uniforms[ 'size' ].value.set( this.resolution.x, this.resolution.y );
|
||||
this.saoMaterial.uniforms[ 'cameraInverseProjectionMatrix' ].value.copy( this.camera.projectionMatrixInverse );
|
||||
this.saoMaterial.uniforms[ 'cameraProjectionMatrix' ].value = this.camera.projectionMatrix;
|
||||
this.saoMaterial.blending = NoBlending;
|
||||
|
||||
this.vBlurMaterial = new ShaderMaterial( {
|
||||
uniforms: UniformsUtils.clone( DepthLimitedBlurShader.uniforms ),
|
||||
defines: Object.assign( {}, DepthLimitedBlurShader.defines ),
|
||||
vertexShader: DepthLimitedBlurShader.vertexShader,
|
||||
fragmentShader: DepthLimitedBlurShader.fragmentShader
|
||||
} );
|
||||
this.vBlurMaterial.defines[ 'DEPTH_PACKING' ] = 0;
|
||||
this.vBlurMaterial.defines[ 'PERSPECTIVE_CAMERA' ] = this.camera.isPerspectiveCamera ? 1 : 0;
|
||||
this.vBlurMaterial.uniforms[ 'tDiffuse' ].value = this.saoRenderTarget.texture;
|
||||
this.vBlurMaterial.uniforms[ 'tDepth' ].value = depthTexture;
|
||||
this.vBlurMaterial.uniforms[ 'size' ].value.set( this.resolution.x, this.resolution.y );
|
||||
this.vBlurMaterial.blending = NoBlending;
|
||||
|
||||
this.hBlurMaterial = new ShaderMaterial( {
|
||||
uniforms: UniformsUtils.clone( DepthLimitedBlurShader.uniforms ),
|
||||
defines: Object.assign( {}, DepthLimitedBlurShader.defines ),
|
||||
vertexShader: DepthLimitedBlurShader.vertexShader,
|
||||
fragmentShader: DepthLimitedBlurShader.fragmentShader
|
||||
} );
|
||||
this.hBlurMaterial.defines[ 'DEPTH_PACKING' ] = 0;
|
||||
this.hBlurMaterial.defines[ 'PERSPECTIVE_CAMERA' ] = this.camera.isPerspectiveCamera ? 1 : 0;
|
||||
this.hBlurMaterial.uniforms[ 'tDiffuse' ].value = this.blurIntermediateRenderTarget.texture;
|
||||
this.hBlurMaterial.uniforms[ 'tDepth' ].value = depthTexture;
|
||||
this.hBlurMaterial.uniforms[ 'size' ].value.set( this.resolution.x, this.resolution.y );
|
||||
this.hBlurMaterial.blending = NoBlending;
|
||||
|
||||
this.materialCopy = new ShaderMaterial( {
|
||||
uniforms: UniformsUtils.clone( CopyShader.uniforms ),
|
||||
vertexShader: CopyShader.vertexShader,
|
||||
fragmentShader: CopyShader.fragmentShader,
|
||||
blending: NoBlending
|
||||
} );
|
||||
this.materialCopy.transparent = true;
|
||||
this.materialCopy.depthTest = false;
|
||||
this.materialCopy.depthWrite = false;
|
||||
this.materialCopy.blending = CustomBlending;
|
||||
this.materialCopy.blendSrc = DstColorFactor;
|
||||
this.materialCopy.blendDst = ZeroFactor;
|
||||
this.materialCopy.blendEquation = AddEquation;
|
||||
this.materialCopy.blendSrcAlpha = DstAlphaFactor;
|
||||
this.materialCopy.blendDstAlpha = ZeroFactor;
|
||||
this.materialCopy.blendEquationAlpha = AddEquation;
|
||||
|
||||
this.fsQuad = new FullScreenQuad( null );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs the SAO pass.
|
||||
*
|
||||
* @param {WebGLRenderer} renderer - The renderer.
|
||||
* @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
|
||||
* destination for the pass.
|
||||
* @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
|
||||
* previous pass from this buffer.
|
||||
* @param {number} deltaTime - The delta time in seconds.
|
||||
* @param {boolean} maskActive - Whether masking is active or not.
|
||||
*/
|
||||
render( renderer, writeBuffer, readBuffer/*, deltaTime, maskActive*/ ) {
|
||||
|
||||
// Rendering readBuffer first when rendering to screen
|
||||
if ( this.renderToScreen ) {
|
||||
|
||||
this.materialCopy.blending = NoBlending;
|
||||
this.materialCopy.uniforms[ 'tDiffuse' ].value = readBuffer.texture;
|
||||
this.materialCopy.needsUpdate = true;
|
||||
this._renderPass( renderer, this.materialCopy, null );
|
||||
|
||||
}
|
||||
|
||||
renderer.getClearColor( this._oldClearColor );
|
||||
this._oldClearAlpha = renderer.getClearAlpha();
|
||||
const oldAutoClear = renderer.autoClear;
|
||||
renderer.autoClear = false;
|
||||
|
||||
this.saoMaterial.uniforms[ 'bias' ].value = this.params.saoBias;
|
||||
this.saoMaterial.uniforms[ 'intensity' ].value = this.params.saoIntensity;
|
||||
this.saoMaterial.uniforms[ 'scale' ].value = this.params.saoScale;
|
||||
this.saoMaterial.uniforms[ 'kernelRadius' ].value = this.params.saoKernelRadius;
|
||||
this.saoMaterial.uniforms[ 'minResolution' ].value = this.params.saoMinResolution;
|
||||
this.saoMaterial.uniforms[ 'cameraNear' ].value = this.camera.near;
|
||||
this.saoMaterial.uniforms[ 'cameraFar' ].value = this.camera.far;
|
||||
// this.saoMaterial.uniforms['randomSeed'].value = Math.random();
|
||||
|
||||
const depthCutoff = this.params.saoBlurDepthCutoff * ( this.camera.far - this.camera.near );
|
||||
this.vBlurMaterial.uniforms[ 'depthCutoff' ].value = depthCutoff;
|
||||
this.hBlurMaterial.uniforms[ 'depthCutoff' ].value = depthCutoff;
|
||||
|
||||
this.vBlurMaterial.uniforms[ 'cameraNear' ].value = this.camera.near;
|
||||
this.vBlurMaterial.uniforms[ 'cameraFar' ].value = this.camera.far;
|
||||
this.hBlurMaterial.uniforms[ 'cameraNear' ].value = this.camera.near;
|
||||
this.hBlurMaterial.uniforms[ 'cameraFar' ].value = this.camera.far;
|
||||
|
||||
this.params.saoBlurRadius = Math.floor( this.params.saoBlurRadius );
|
||||
if ( ( this.prevStdDev !== this.params.saoBlurStdDev ) || ( this.prevNumSamples !== this.params.saoBlurRadius ) ) {
|
||||
|
||||
BlurShaderUtils.configure( this.vBlurMaterial, this.params.saoBlurRadius, this.params.saoBlurStdDev, new Vector2( 0, 1 ) );
|
||||
BlurShaderUtils.configure( this.hBlurMaterial, this.params.saoBlurRadius, this.params.saoBlurStdDev, new Vector2( 1, 0 ) );
|
||||
this.prevStdDev = this.params.saoBlurStdDev;
|
||||
this.prevNumSamples = this.params.saoBlurRadius;
|
||||
|
||||
}
|
||||
|
||||
// render normal and depth
|
||||
this._renderOverride( renderer, this.normalMaterial, this.normalRenderTarget, 0x7777ff, 1.0 );
|
||||
|
||||
// Rendering SAO texture
|
||||
this._renderPass( renderer, this.saoMaterial, this.saoRenderTarget, 0xffffff, 1.0 );
|
||||
|
||||
// Blurring SAO texture
|
||||
if ( this.params.saoBlur ) {
|
||||
|
||||
this._renderPass( renderer, this.vBlurMaterial, this.blurIntermediateRenderTarget, 0xffffff, 1.0 );
|
||||
this._renderPass( renderer, this.hBlurMaterial, this.saoRenderTarget, 0xffffff, 1.0 );
|
||||
|
||||
}
|
||||
|
||||
const outputMaterial = this.materialCopy;
|
||||
|
||||
// Setting up SAO rendering
|
||||
if ( this.params.output === SAOPass.OUTPUT.Normal ) {
|
||||
|
||||
this.materialCopy.uniforms[ 'tDiffuse' ].value = this.normalRenderTarget.texture;
|
||||
this.materialCopy.needsUpdate = true;
|
||||
|
||||
} else {
|
||||
|
||||
this.materialCopy.uniforms[ 'tDiffuse' ].value = this.saoRenderTarget.texture;
|
||||
this.materialCopy.needsUpdate = true;
|
||||
|
||||
}
|
||||
|
||||
// Blending depends on output
|
||||
if ( this.params.output === SAOPass.OUTPUT.Default ) {
|
||||
|
||||
outputMaterial.blending = CustomBlending;
|
||||
|
||||
} else {
|
||||
|
||||
outputMaterial.blending = NoBlending;
|
||||
|
||||
}
|
||||
|
||||
// Rendering SAOPass result on top of previous pass
|
||||
this._renderPass( renderer, outputMaterial, this.renderToScreen ? null : readBuffer );
|
||||
|
||||
renderer.setClearColor( this._oldClearColor, this._oldClearAlpha );
|
||||
renderer.autoClear = oldAutoClear;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the size of the pass.
|
||||
*
|
||||
* @param {number} width - The width to set.
|
||||
* @param {number} height - The height to set.
|
||||
*/
|
||||
setSize( width, height ) {
|
||||
|
||||
this.saoRenderTarget.setSize( width, height );
|
||||
this.blurIntermediateRenderTarget.setSize( width, height );
|
||||
this.normalRenderTarget.setSize( width, height );
|
||||
|
||||
this.saoMaterial.uniforms[ 'size' ].value.set( width, height );
|
||||
this.saoMaterial.uniforms[ 'cameraInverseProjectionMatrix' ].value.copy( this.camera.projectionMatrixInverse );
|
||||
this.saoMaterial.uniforms[ 'cameraProjectionMatrix' ].value = this.camera.projectionMatrix;
|
||||
this.saoMaterial.needsUpdate = true;
|
||||
|
||||
this.vBlurMaterial.uniforms[ 'size' ].value.set( width, height );
|
||||
this.vBlurMaterial.needsUpdate = true;
|
||||
|
||||
this.hBlurMaterial.uniforms[ 'size' ].value.set( width, height );
|
||||
this.hBlurMaterial.needsUpdate = true;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Frees the GPU-related resources allocated by this instance. Call this
|
||||
* method whenever the pass is no longer used in your app.
|
||||
*/
|
||||
dispose() {
|
||||
|
||||
this.saoRenderTarget.dispose();
|
||||
this.blurIntermediateRenderTarget.dispose();
|
||||
this.normalRenderTarget.dispose();
|
||||
|
||||
this.normalMaterial.dispose();
|
||||
this.saoMaterial.dispose();
|
||||
this.vBlurMaterial.dispose();
|
||||
this.hBlurMaterial.dispose();
|
||||
this.materialCopy.dispose();
|
||||
|
||||
this.fsQuad.dispose();
|
||||
|
||||
}
|
||||
|
||||
// internal
|
||||
|
||||
_renderPass( renderer, passMaterial, renderTarget, clearColor, clearAlpha ) {
|
||||
|
||||
// save original state
|
||||
renderer.getClearColor( this._originalClearColor );
|
||||
const originalClearAlpha = renderer.getClearAlpha();
|
||||
const originalAutoClear = renderer.autoClear;
|
||||
|
||||
renderer.setRenderTarget( renderTarget );
|
||||
|
||||
// setup pass state
|
||||
renderer.autoClear = false;
|
||||
if ( ( clearColor !== undefined ) && ( clearColor !== null ) ) {
|
||||
|
||||
renderer.setClearColor( clearColor );
|
||||
renderer.setClearAlpha( clearAlpha || 0.0 );
|
||||
renderer.clear();
|
||||
|
||||
}
|
||||
|
||||
this.fsQuad.material = passMaterial;
|
||||
this.fsQuad.render( renderer );
|
||||
|
||||
// restore original state
|
||||
renderer.autoClear = originalAutoClear;
|
||||
renderer.setClearColor( this._originalClearColor );
|
||||
renderer.setClearAlpha( originalClearAlpha );
|
||||
|
||||
}
|
||||
|
||||
_renderOverride( renderer, overrideMaterial, renderTarget, clearColor, clearAlpha ) {
|
||||
|
||||
renderer.getClearColor( this._originalClearColor );
|
||||
const originalClearAlpha = renderer.getClearAlpha();
|
||||
const originalAutoClear = renderer.autoClear;
|
||||
|
||||
renderer.setRenderTarget( renderTarget );
|
||||
renderer.autoClear = false;
|
||||
|
||||
clearColor = overrideMaterial.clearColor || clearColor;
|
||||
clearAlpha = overrideMaterial.clearAlpha || clearAlpha;
|
||||
if ( ( clearColor !== undefined ) && ( clearColor !== null ) ) {
|
||||
|
||||
renderer.setClearColor( clearColor );
|
||||
renderer.setClearAlpha( clearAlpha || 0.0 );
|
||||
renderer.clear();
|
||||
|
||||
}
|
||||
|
||||
this.scene.overrideMaterial = overrideMaterial;
|
||||
renderer.render( this.scene, this.camera );
|
||||
this.scene.overrideMaterial = null;
|
||||
|
||||
// restore original state
|
||||
renderer.autoClear = originalAutoClear;
|
||||
renderer.setClearColor( this._originalClearColor );
|
||||
renderer.setClearAlpha( originalClearAlpha );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
SAOPass.OUTPUT = {
|
||||
'Default': 0,
|
||||
'SAO': 1,
|
||||
'Normal': 2
|
||||
};
|
||||
|
||||
export { SAOPass };
|
||||
@@ -0,0 +1,230 @@
|
||||
import {
|
||||
HalfFloatType,
|
||||
LinearFilter,
|
||||
NearestFilter,
|
||||
ShaderMaterial,
|
||||
Texture,
|
||||
UniformsUtils,
|
||||
WebGLRenderTarget
|
||||
} from 'three';
|
||||
import { Pass, FullScreenQuad } from './Pass.js';
|
||||
import { SMAABlendShader, SMAAEdgesShader, SMAAWeightsShader } from '../shaders/SMAAShader.js';
|
||||
|
||||
/**
|
||||
* A pass for applying SMAA. Unlike {@link FXAAPass}, `SMAAPass` operates in
|
||||
* `linear-srgb` so this pass must be executed before {@link OutputPass}.
|
||||
*
|
||||
* ```js
|
||||
* const smaaPass = new SMAAPass();
|
||||
* composer.addPass( smaaPass );
|
||||
* ```
|
||||
*
|
||||
* @augments Pass
|
||||
* @three_import import { SMAAPass } from 'three/addons/postprocessing/SMAAPass.js';
|
||||
*/
|
||||
class SMAAPass extends Pass {
|
||||
|
||||
/**
|
||||
* Constructs a new SMAA pass.
|
||||
*/
|
||||
constructor( ) {
|
||||
|
||||
super();
|
||||
|
||||
// render targets
|
||||
|
||||
this._edgesRT = new WebGLRenderTarget( 1, 1, {
|
||||
depthBuffer: false,
|
||||
type: HalfFloatType
|
||||
} );
|
||||
this._edgesRT.texture.name = 'SMAAPass.edges';
|
||||
|
||||
this._weightsRT = new WebGLRenderTarget( 1, 1, {
|
||||
depthBuffer: false,
|
||||
type: HalfFloatType
|
||||
} );
|
||||
this._weightsRT.texture.name = 'SMAAPass.weights';
|
||||
|
||||
// textures
|
||||
const scope = this;
|
||||
|
||||
const areaTextureImage = new Image();
|
||||
areaTextureImage.src = this._getAreaTexture();
|
||||
areaTextureImage.onload = function () {
|
||||
|
||||
// assigning data to HTMLImageElement.src is asynchronous (see #15162)
|
||||
scope._areaTexture.needsUpdate = true;
|
||||
|
||||
};
|
||||
|
||||
this._areaTexture = new Texture();
|
||||
this._areaTexture.name = 'SMAAPass.area';
|
||||
this._areaTexture.image = areaTextureImage;
|
||||
this._areaTexture.minFilter = LinearFilter;
|
||||
this._areaTexture.generateMipmaps = false;
|
||||
this._areaTexture.flipY = false;
|
||||
|
||||
const searchTextureImage = new Image();
|
||||
searchTextureImage.src = this._getSearchTexture();
|
||||
searchTextureImage.onload = function () {
|
||||
|
||||
// assigning data to HTMLImageElement.src is asynchronous (see #15162)
|
||||
scope._searchTexture.needsUpdate = true;
|
||||
|
||||
};
|
||||
|
||||
this._searchTexture = new Texture();
|
||||
this._searchTexture.name = 'SMAAPass.search';
|
||||
this._searchTexture.image = searchTextureImage;
|
||||
this._searchTexture.magFilter = NearestFilter;
|
||||
this._searchTexture.minFilter = NearestFilter;
|
||||
this._searchTexture.generateMipmaps = false;
|
||||
this._searchTexture.flipY = false;
|
||||
|
||||
// materials - pass 1
|
||||
|
||||
this._uniformsEdges = UniformsUtils.clone( SMAAEdgesShader.uniforms );
|
||||
|
||||
this._materialEdges = new ShaderMaterial( {
|
||||
defines: Object.assign( {}, SMAAEdgesShader.defines ),
|
||||
uniforms: this._uniformsEdges,
|
||||
vertexShader: SMAAEdgesShader.vertexShader,
|
||||
fragmentShader: SMAAEdgesShader.fragmentShader
|
||||
} );
|
||||
|
||||
// materials - pass 2
|
||||
|
||||
this._uniformsWeights = UniformsUtils.clone( SMAAWeightsShader.uniforms );
|
||||
|
||||
this._uniformsWeights[ 'tDiffuse' ].value = this._edgesRT.texture;
|
||||
this._uniformsWeights[ 'tArea' ].value = this._areaTexture;
|
||||
this._uniformsWeights[ 'tSearch' ].value = this._searchTexture;
|
||||
|
||||
this._materialWeights = new ShaderMaterial( {
|
||||
defines: Object.assign( {}, SMAAWeightsShader.defines ),
|
||||
uniforms: this._uniformsWeights,
|
||||
vertexShader: SMAAWeightsShader.vertexShader,
|
||||
fragmentShader: SMAAWeightsShader.fragmentShader
|
||||
} );
|
||||
|
||||
// materials - pass 3
|
||||
|
||||
this._uniformsBlend = UniformsUtils.clone( SMAABlendShader.uniforms );
|
||||
this._uniformsBlend[ 'tDiffuse' ].value = this._weightsRT.texture;
|
||||
|
||||
this._materialBlend = new ShaderMaterial( {
|
||||
uniforms: this._uniformsBlend,
|
||||
vertexShader: SMAABlendShader.vertexShader,
|
||||
fragmentShader: SMAABlendShader.fragmentShader
|
||||
} );
|
||||
|
||||
this._fsQuad = new FullScreenQuad( null );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs the SMAA pass.
|
||||
*
|
||||
* @param {WebGLRenderer} renderer - The renderer.
|
||||
* @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
|
||||
* destination for the pass.
|
||||
* @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
|
||||
* previous pass from this buffer.
|
||||
* @param {number} deltaTime - The delta time in seconds.
|
||||
* @param {boolean} maskActive - Whether masking is active or not.
|
||||
*/
|
||||
render( renderer, writeBuffer, readBuffer/*, deltaTime, maskActive*/ ) {
|
||||
|
||||
// pass 1
|
||||
|
||||
this._uniformsEdges[ 'tDiffuse' ].value = readBuffer.texture;
|
||||
|
||||
this._fsQuad.material = this._materialEdges;
|
||||
|
||||
renderer.setRenderTarget( this._edgesRT );
|
||||
if ( this.clear ) renderer.clear();
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
// pass 2
|
||||
|
||||
this._fsQuad.material = this._materialWeights;
|
||||
|
||||
renderer.setRenderTarget( this._weightsRT );
|
||||
if ( this.clear ) renderer.clear();
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
// pass 3
|
||||
|
||||
this._uniformsBlend[ 'tColor' ].value = readBuffer.texture;
|
||||
|
||||
this._fsQuad.material = this._materialBlend;
|
||||
|
||||
if ( this.renderToScreen ) {
|
||||
|
||||
renderer.setRenderTarget( null );
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
} else {
|
||||
|
||||
renderer.setRenderTarget( writeBuffer );
|
||||
if ( this.clear ) renderer.clear();
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the size of the pass.
|
||||
*
|
||||
* @param {number} width - The width to set.
|
||||
* @param {number} height - The height to set.
|
||||
*/
|
||||
setSize( width, height ) {
|
||||
|
||||
this._edgesRT.setSize( width, height );
|
||||
this._weightsRT.setSize( width, height );
|
||||
|
||||
this._materialEdges.uniforms[ 'resolution' ].value.set( 1 / width, 1 / height );
|
||||
this._materialWeights.uniforms[ 'resolution' ].value.set( 1 / width, 1 / height );
|
||||
this._materialBlend.uniforms[ 'resolution' ].value.set( 1 / width, 1 / height );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Frees the GPU-related resources allocated by this instance. Call this
|
||||
* method whenever the pass is no longer used in your app.
|
||||
*/
|
||||
dispose() {
|
||||
|
||||
this._edgesRT.dispose();
|
||||
this._weightsRT.dispose();
|
||||
|
||||
this._areaTexture.dispose();
|
||||
this._searchTexture.dispose();
|
||||
|
||||
this._materialEdges.dispose();
|
||||
this._materialWeights.dispose();
|
||||
this._materialBlend.dispose();
|
||||
|
||||
this._fsQuad.dispose();
|
||||
|
||||
}
|
||||
|
||||
// internals
|
||||
|
||||
_getAreaTexture() {
|
||||
|
||||
return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKAAAAIwCAIAAACOVPcQAACBeklEQVR42u39W4xlWXrnh/3WWvuciIzMrKxrV8/0rWbY0+SQFKcb4owIkSIFCjY9AC1BT/LYBozRi+EX+cV+8IMsYAaCwRcBwjzMiw2jAWtgwC8WR5Q8mDFHZLNHTarZGrLJJllt1W2qKrsumZWZcTvn7L3W54e1vrXX3vuciLPPORFR1XE2EomorB0nVuz//r71re/y/1eMvb4Cb3N11xV/PP/2v4UBAwJG/7H8urx6/25/Gf8O5hypMQ0EEEQwAqLfoN/Z+97f/SW+/NvcgQk4sGBJK6H7N4PFVL+K+e0N11yNfkKvwUdwdlUAXPHHL38oa15f/i/46Ih6SuMSPmLAYAwyRKn7dfMGH97jaMFBYCJUgotIC2YAdu+LyW9vvubxAP8kAL8H/koAuOKP3+q6+xGnd5kdYCeECnGIJViwGJMAkQKfDvB3WZxjLKGh8VSCCzhwEWBpMc5/kBbjawT4HnwJfhr+pPBIu7uu+OOTo9vsmtQcniMBGkKFd4jDWMSCRUpLjJYNJkM+IRzQ+PQvIeAMTrBS2LEiaiR9b/5PuT6Ap/AcfAFO4Y3dA3DFH7/VS+M8k4baEAQfMI4QfbVDDGIRg7GKaIY52qAjTAgTvGBAPGIIghOCYAUrGFNgzA7Q3QhgCwfwAnwe5vDejgG44o/fbm1C5ZlYQvQDARPAIQGxCWBM+wWl37ZQESb4gImexGMDouhGLx1Cst0Saa4b4AqO4Hk4gxo+3DHAV/nx27p3JziPM2pVgoiia5MdEzCGULprIN7gEEeQ5IQxEBBBQnxhsDb5auGmAAYcHMA9eAAz8PBol8/xij9+C4Djlim4gJjWcwZBhCBgMIIYxGAVIkH3ZtcBuLdtRFMWsPGoY9rN+HoBji9VBYdwD2ZQg4cnO7OSq/z4rU5KKdwVbFAjNojCQzTlCLPFSxtamwh2jMUcEgg2Wm/6XgErIBhBckQtGN3CzbVacERgCnfgLswhnvqf7QyAq/z4rRZm1YglYE3affGITaZsdIe2FmMIpnOCap25I6jt2kCwCW0D1uAD9sZctNGXcQIHCkINDQgc78aCr+zjtw3BU/ijdpw3zhCwcaONwBvdeS2YZKkJNJsMPf2JKEvC28RXxxI0ASJyzQCjCEQrO4Q7sFArEzjZhaFc4cdv+/JFdKULM4px0DfUBI2hIsy06BqLhGTQEVdbfAIZXYMPesq6VoCHICzUyjwInO4Y411//LYLs6TDa9wvg2CC2rElgAnpTBziThxaL22MYhzfkghz6GAs2VHbbdM91VZu1MEEpupMMwKyVTb5ij9+u4VJG/5EgEMMmFF01cFai3isRbKbzb+YaU/MQbAm2XSMoUPAmvZzbuKYRIFApbtlrfFuUGd6vq2hXNnH78ZLh/iFhsQG3T4D1ib7k5CC6vY0DCbtrohgLEIClXiGtl10zc0CnEGIhhatLBva7NP58Tvw0qE8yWhARLQ8h4+AhQSP+I4F5xoU+VilGRJs6wnS7ruti/4KvAY/CfdgqjsMy4pf8fodQO8/gnuX3f/3xi3om1/h7THr+co3x93PP9+FBUfbNUjcjEmhcrkT+8K7ml7V10Jo05mpIEFy1NmCJWx9SIKKt+EjAL4Ez8EBVOB6havuT/rByPvHXK+9zUcfcbb254+9fydJknYnRr1oGfdaiAgpxu1Rx/Rek8KISftx3L+DfsLWAANn8Hvw0/AFeAGO9DFV3c6D+CcWbL8Dj9e7f+T1k8AZv/d7+PXWM/Z+VvdCrIvuAKO09RpEEQJM0Ci6+B4xhTWr4cZNOvhktabw0ta0rSJmqz3Yw5/AKXwenod7cAhTmBSPKf6JBdvH8IP17h95pXqw50/+BFnj88fev4NchyaK47OPhhtI8RFSvAfDSNh0Ck0p2gLxGkib5NJj/JWCr90EWQJvwBzO4AHcgztwAFN1evHPUVGwfXON+0debT1YeGON9Yy9/63X+OguiwmhIhQhD7l4sMqlG3D86Suc3qWZ4rWjI1X7u0Ytw6x3rIMeIOPDprfe2XzNgyj6PahhBjO4C3e6puDgXrdg+/5l948vF3bqwZetZ+z9Rx9zdIY5pInPK4Nk0t+l52xdK2B45Qd87nM8fsD5EfUhIcJcERw4RdqqH7Yde5V7m1vhNmtedkz6EDzUMF/2jJYWbC+4fzzA/Y+/8PPH3j9dcBAPIRP8JLXd5BpAu03aziOL3VVHZzz3CXWDPWd+SH2AnxIqQoTZpo9Ckc6HIrFbAbzNmlcg8Ag8NFDDAhbJvTBZXbC94P7t68EXfv6o+21gUtPETU7bbkLxvNKRFG2+KXzvtObonPP4rBvsgmaKj404DlshFole1Glfh02fE7bYR7dZ82oTewIBGn1Md6CG6YUF26X376oevOLzx95vhUmgblI6LBZwTCDY7vMq0op5WVXgsObOXJ+1x3qaBl9j1FeLxbhU9w1F+Wiba6s1X/TBz1LnUfuYDi4r2C69f1f14BWfP+p+W2GFKuC9phcELMYRRLur9DEZTUdEH+iEqWdaM7X4WOoPGI+ZYD2+wcQ+y+ioHUZ9dTDbArzxmi/bJI9BND0Ynd6lBdve/butBw8+f/T9D3ABa3AG8W3VPX4hBin+bj8dMMmSpp5pg7fJ6xrBFE2WQQEWnV8Qg3FbAWzYfM1rREEnmvkN2o1+acG2d/9u68GDzx91v3mAjb1zkpqT21OipPKO0b9TO5W0nTdOmAQm0TObts3aBKgwARtoPDiCT0gHgwnbArzxmtcLc08HgF1asN0C4Ms/fvD5I+7PhfqyXE/b7RbbrGyRQRT9ARZcwAUmgdoz0ehJ9Fn7QAhUjhDAQSw0bV3T3WbNa59jzmiP6GsWbGXDX2ytjy8+f9T97fiBPq9YeLdBmyuizZHaqXITnXiMUEEVcJ7K4j3BFPurtB4bixW8wTpweL8DC95szWMOqucFYGsWbGU7p3TxxxefP+r+oTVktxY0v5hbq3KiOKYnY8ddJVSBxuMMVffNbxwIOERShst73HZ78DZrHpmJmH3K6sGz0fe3UUj0eyRrSCGTTc+rjVNoGzNSv05srAxUBh8IhqChiQgVNIIBH3AVPnrsnXQZbLTm8ammv8eVXn/vWpaTem5IXRlt+U/LA21zhSb9cye6jcOfCnOwhIAYXAMVTUNV0QhVha9xjgA27ODJbLbmitt3tRN80lqG6N/khgot4ZVlOyO4WNg3OIMzhIZQpUEHieg2im6F91hB3I2tubql6BYNN9Hj5S7G0G2tahslBWKDnOiIvuAEDzakDQKDNFQT6gbn8E2y4BBubM230YIpBnDbMa+y3dx0n1S0BtuG62lCCXwcY0F72T1VRR3t2ONcsmDjbmzNt9RFs2LO2hQNyb022JisaI8rAWuw4HI3FuAIhZdOGIcdjLJvvObqlpqvWTJnnQbyi/1M9O8UxWhBs//H42I0q1Yb/XPGONzcmm+ri172mHKvZBpHkJaNJz6v9jxqiklDj3U4CA2ugpAaYMWqNXsdXbmJNd9egCnJEsphXNM+MnK3m0FCJ5S1kmJpa3DgPVbnQnPGWIDspW9ozbcO4K/9LkfaQO2KHuqlfFXSbdNzcEcwoqNEFE9zcIXu9/6n/ym/BC/C3aJLzEKPuYVlbFnfhZ8kcWxV3dbv4bKl28566wD+8C53aw49lTABp9PWbsB+knfc/Li3eVizf5vv/xmvnPKg5ihwKEwlrcHqucuVcVOxEv8aH37E3ZqpZypUulrHEtIWKUr+txHg+ojZDGlwnqmkGlzcVi1dLiNSJiHjfbRNOPwKpx9TVdTn3K05DBx4psIk4Ei8aCkJahRgffk4YnEXe07T4H2RR1u27E6wfQsBDofUgjFUFnwC2AiVtA+05J2zpiDK2Oa0c5fmAecN1iJzmpqFZxqYBCYhFTCsUNEmUnIcZ6aEA5rQVhEywG6w7HSW02XfOoBlQmjwulOFQAg66SvJblrTEX1YtJ3uG15T/BH1OfOQeuR8g/c0gdpT5fx2SKbs9EfHTKdM8A1GaJRHLVIwhcGyydZsbifAFVKl5EMKNU2Hryo+06BeTgqnxzYjThVySDikbtJPieco75lYfKAJOMEZBTjoITuWHXXZVhcUDIS2hpiXHV9Ku4u44bN5OYLDOkJo8w+xJSMbhBRHEdEs9JZUCkQrPMAvaHyLkxgkEHxiNkx/x2YB0mGsQ8EUWj/stW5YLhtS5SMu+/YBbNPDCkGTUybN8krRLBGPlZkVOA0j+a1+rkyQKWGaPHPLZOkJhioQYnVZ2hS3zVxMtgC46KuRwbJNd9nV2PHgb36F194ecf/Yeu2vAFe5nm/bRBFrnY4BauE8ERmZRFUn0k8hbftiVYSKMEme2dJCJSCGYAlNqh87bXOPdUkGy24P6d1ll21MBqqx48Fvv8ZHH8HZFY7j/uAq1xMJUFqCSUlJPmNbIiNsmwuMs/q9CMtsZsFO6SprzCS1Z7QL8xCQClEelpjTduDMsmWD8S1PT152BtvmIGvUeDA/yRn83u/x0/4qxoPHjx+PXY9pqX9bgMvh/Nz9kpP4pOe1/fYf3axUiMdHLlPpZCNjgtNFAhcHEDxTumNONhHrBduW+vOyY++70WWnPXj98eA4kOt/mj/5E05l9+O4o8ePx67HFqyC+qSSnyselqjZGaVK2TadbFLPWAQ4NBhHqDCCV7OTpo34AlSSylPtIdd2AJZlyzYQrDJ5lcWGNceD80CunPLGGzsfD+7wRb95NevJI5docQ3tgCyr5bGnyaPRlmwNsFELViOOx9loebGNq2moDOKpHLVP5al2cymWHbkfzGXL7kfRl44H9wZy33tvt+PB/Xnf93e+nh5ZlU18wCiRUa9m7kib9LYuOk+hudQNbxwm0AQqbfloimaB2lM5fChex+ylMwuTbfmXQtmWlenZljb
Line truncated
|
||||
|
||||
}
|
||||
|
||||
_getSearchTexture() {
|
||||
|
||||
return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEIAAAAhCAAAAABIXyLAAAAAOElEQVRIx2NgGAWjYBSMglEwEICREYRgFBZBqDCSLA2MGPUIVQETE9iNUAqLR5gIeoQKRgwXjwAAGn4AtaFeYLEAAAAASUVORK5CYII=';
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export { SMAAPass };
|
||||
@@ -0,0 +1,313 @@
|
||||
import {
|
||||
AdditiveBlending,
|
||||
Color,
|
||||
HalfFloatType,
|
||||
ShaderMaterial,
|
||||
UniformsUtils,
|
||||
WebGLRenderTarget
|
||||
} from 'three';
|
||||
import { Pass, FullScreenQuad } from './Pass.js';
|
||||
import { CopyShader } from '../shaders/CopyShader.js';
|
||||
|
||||
/**
|
||||
* Supersample Anti-Aliasing Render Pass.
|
||||
*
|
||||
* This manual approach to SSAA re-renders the scene ones for each sample with camera jitter and accumulates the results.
|
||||
*
|
||||
* ```js
|
||||
* const ssaaRenderPass = new SSAARenderPass( scene, camera );
|
||||
* ssaaRenderPass.sampleLevel = 3;
|
||||
* composer.addPass( ssaaRenderPass );
|
||||
* ```
|
||||
*
|
||||
* @augments Pass
|
||||
* @three_import import { SSAARenderPass } from 'three/addons/postprocessing/SSAARenderPass.js';
|
||||
*/
|
||||
class SSAARenderPass extends Pass {
|
||||
|
||||
/**
|
||||
* Constructs a new SSAA render pass.
|
||||
*
|
||||
* @param {Scene} scene - The scene to render.
|
||||
* @param {Camera} camera - The camera.
|
||||
* @param {?(number|Color|string)} [clearColor=0x000000] - The clear color of the render pass.
|
||||
* @param {?number} [clearAlpha=0] - The clear alpha of the render pass.
|
||||
*/
|
||||
constructor( scene, camera, clearColor = 0x000000, clearAlpha = 0 ) {
|
||||
|
||||
super();
|
||||
|
||||
/**
|
||||
* The scene to render.
|
||||
*
|
||||
* @type {Scene}
|
||||
*/
|
||||
this.scene = scene;
|
||||
|
||||
/**
|
||||
* The camera.
|
||||
*
|
||||
* @type {Camera}
|
||||
*/
|
||||
this.camera = camera;
|
||||
|
||||
/**
|
||||
* The sample level. Specified as n, where the number of
|
||||
* samples is 2^n, so sampleLevel = 4, is 2^4 samples, 16.
|
||||
*
|
||||
* @type {number}
|
||||
* @default 4
|
||||
*/
|
||||
this.sampleLevel = 4;
|
||||
|
||||
/**
|
||||
* Whether the pass should be unbiased or not. This property has the most
|
||||
* visible effect when rendering to a RGBA8 buffer because it mitigates
|
||||
* rounding errors. By default RGBA16F is used.
|
||||
*
|
||||
* @type {boolean}
|
||||
* @default true
|
||||
*/
|
||||
this.unbiased = true;
|
||||
|
||||
/**
|
||||
* Whether to use a stencil buffer or not. This property can't
|
||||
* be changed after the first render.
|
||||
*
|
||||
* @type {boolean}
|
||||
* @default false
|
||||
*/
|
||||
this.stencilBuffer = false;
|
||||
|
||||
/**
|
||||
* The clear color of the render pass.
|
||||
*
|
||||
* @type {?(number|Color|string)}
|
||||
* @default 0x000000
|
||||
*/
|
||||
this.clearColor = clearColor;
|
||||
|
||||
/**
|
||||
* The clear alpha of the render pass.
|
||||
*
|
||||
* @type {?number}
|
||||
* @default 0
|
||||
*/
|
||||
this.clearAlpha = clearAlpha;
|
||||
|
||||
// internals
|
||||
|
||||
this._sampleRenderTarget = null;
|
||||
|
||||
this._oldClearColor = new Color();
|
||||
|
||||
this._copyUniforms = UniformsUtils.clone( CopyShader.uniforms );
|
||||
|
||||
this._copyMaterial = new ShaderMaterial( {
|
||||
uniforms: this._copyUniforms,
|
||||
vertexShader: CopyShader.vertexShader,
|
||||
fragmentShader: CopyShader.fragmentShader,
|
||||
transparent: true,
|
||||
depthTest: false,
|
||||
depthWrite: false,
|
||||
premultipliedAlpha: true,
|
||||
blending: AdditiveBlending
|
||||
} );
|
||||
|
||||
this._fsQuad = new FullScreenQuad( this._copyMaterial );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Frees the GPU-related resources allocated by this instance. Call this
|
||||
* method whenever the pass is no longer used in your app.
|
||||
*/
|
||||
dispose() {
|
||||
|
||||
if ( this._sampleRenderTarget ) {
|
||||
|
||||
this._sampleRenderTarget.dispose();
|
||||
this._sampleRenderTarget = null;
|
||||
|
||||
}
|
||||
|
||||
this._copyMaterial.dispose();
|
||||
|
||||
this._fsQuad.dispose();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the size of the pass.
|
||||
*
|
||||
* @param {number} width - The width to set.
|
||||
* @param {number} height - The height to set.
|
||||
*/
|
||||
setSize( width, height ) {
|
||||
|
||||
if ( this._sampleRenderTarget ) this._sampleRenderTarget.setSize( width, height );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs the SSAA render pass.
|
||||
*
|
||||
* @param {WebGLRenderer} renderer - The renderer.
|
||||
* @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
|
||||
* destination for the pass.
|
||||
* @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
|
||||
* previous pass from this buffer.
|
||||
* @param {number} deltaTime - The delta time in seconds.
|
||||
* @param {boolean} maskActive - Whether masking is active or not.
|
||||
*/
|
||||
render( renderer, writeBuffer, readBuffer/*, deltaTime, maskActive */ ) {
|
||||
|
||||
if ( ! this._sampleRenderTarget ) {
|
||||
|
||||
this._sampleRenderTarget = new WebGLRenderTarget( readBuffer.width, readBuffer.height, { type: HalfFloatType, stencilBuffer: this.stencilBuffer } );
|
||||
this._sampleRenderTarget.texture.name = 'SSAARenderPass.sample';
|
||||
|
||||
}
|
||||
|
||||
const jitterOffsets = _JitterVectors[ Math.max( 0, Math.min( this.sampleLevel, 5 ) ) ];
|
||||
|
||||
const autoClear = renderer.autoClear;
|
||||
renderer.autoClear = false;
|
||||
|
||||
renderer.getClearColor( this._oldClearColor );
|
||||
const oldClearAlpha = renderer.getClearAlpha();
|
||||
|
||||
const baseSampleWeight = 1.0 / jitterOffsets.length;
|
||||
const roundingRange = 1 / 32;
|
||||
this._copyUniforms[ 'tDiffuse' ].value = this._sampleRenderTarget.texture;
|
||||
|
||||
const viewOffset = {
|
||||
|
||||
fullWidth: readBuffer.width,
|
||||
fullHeight: readBuffer.height,
|
||||
offsetX: 0,
|
||||
offsetY: 0,
|
||||
width: readBuffer.width,
|
||||
height: readBuffer.height
|
||||
|
||||
};
|
||||
|
||||
const originalViewOffset = Object.assign( {}, this.camera.view );
|
||||
|
||||
if ( originalViewOffset.enabled ) Object.assign( viewOffset, originalViewOffset );
|
||||
|
||||
// render the scene multiple times, each slightly jitter offset from the last and accumulate the results.
|
||||
for ( let i = 0; i < jitterOffsets.length; i ++ ) {
|
||||
|
||||
const jitterOffset = jitterOffsets[ i ];
|
||||
|
||||
if ( this.camera.setViewOffset ) {
|
||||
|
||||
this.camera.setViewOffset(
|
||||
|
||||
viewOffset.fullWidth, viewOffset.fullHeight,
|
||||
|
||||
viewOffset.offsetX + jitterOffset[ 0 ] * 0.0625, viewOffset.offsetY + jitterOffset[ 1 ] * 0.0625, // 0.0625 = 1 / 16
|
||||
|
||||
viewOffset.width, viewOffset.height
|
||||
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
let sampleWeight = baseSampleWeight;
|
||||
|
||||
if ( this.unbiased ) {
|
||||
|
||||
// the theory is that equal weights for each sample lead to an accumulation of rounding errors.
|
||||
// The following equation varies the sampleWeight per sample so that it is uniformly distributed
|
||||
// across a range of values whose rounding errors cancel each other out.
|
||||
|
||||
const uniformCenteredDistribution = ( - 0.5 + ( i + 0.5 ) / jitterOffsets.length );
|
||||
sampleWeight += roundingRange * uniformCenteredDistribution;
|
||||
|
||||
}
|
||||
|
||||
this._copyUniforms[ 'opacity' ].value = sampleWeight;
|
||||
renderer.setClearColor( this.clearColor, this.clearAlpha );
|
||||
renderer.setRenderTarget( this._sampleRenderTarget );
|
||||
renderer.clear();
|
||||
renderer.render( this.scene, this.camera );
|
||||
|
||||
renderer.setRenderTarget( this.renderToScreen ? null : writeBuffer );
|
||||
|
||||
if ( i === 0 ) {
|
||||
|
||||
renderer.setClearColor( 0x000000, 0.0 );
|
||||
renderer.clear();
|
||||
|
||||
}
|
||||
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
}
|
||||
|
||||
if ( this.camera.setViewOffset && originalViewOffset.enabled ) {
|
||||
|
||||
this.camera.setViewOffset(
|
||||
|
||||
originalViewOffset.fullWidth, originalViewOffset.fullHeight,
|
||||
|
||||
originalViewOffset.offsetX, originalViewOffset.offsetY,
|
||||
|
||||
originalViewOffset.width, originalViewOffset.height
|
||||
|
||||
);
|
||||
|
||||
} else if ( this.camera.clearViewOffset ) {
|
||||
|
||||
this.camera.clearViewOffset();
|
||||
|
||||
}
|
||||
|
||||
renderer.autoClear = autoClear;
|
||||
renderer.setClearColor( this._oldClearColor, oldClearAlpha );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
// These jitter vectors are specified in integers because it is easier.
|
||||
// I am assuming a [-8,8) integer grid, but it needs to be mapped onto [-0.5,0.5)
|
||||
// before being used, thus these integers need to be scaled by 1/16.
|
||||
//
|
||||
// Sample patterns reference: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476218%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396
|
||||
const _JitterVectors = [
|
||||
[
|
||||
[ 0, 0 ]
|
||||
],
|
||||
[
|
||||
[ 4, 4 ], [ - 4, - 4 ]
|
||||
],
|
||||
[
|
||||
[ - 2, - 6 ], [ 6, - 2 ], [ - 6, 2 ], [ 2, 6 ]
|
||||
],
|
||||
[
|
||||
[ 1, - 3 ], [ - 1, 3 ], [ 5, 1 ], [ - 3, - 5 ],
|
||||
[ - 5, 5 ], [ - 7, - 1 ], [ 3, 7 ], [ 7, - 7 ]
|
||||
],
|
||||
[
|
||||
[ 1, 1 ], [ - 1, - 3 ], [ - 3, 2 ], [ 4, - 1 ],
|
||||
[ - 5, - 2 ], [ 2, 5 ], [ 5, 3 ], [ 3, - 5 ],
|
||||
[ - 2, 6 ], [ 0, - 7 ], [ - 4, - 6 ], [ - 6, 4 ],
|
||||
[ - 8, 0 ], [ 7, - 4 ], [ 6, 7 ], [ - 7, - 8 ]
|
||||
],
|
||||
[
|
||||
[ - 4, - 7 ], [ - 7, - 5 ], [ - 3, - 5 ], [ - 5, - 4 ],
|
||||
[ - 1, - 4 ], [ - 2, - 2 ], [ - 6, - 1 ], [ - 4, 0 ],
|
||||
[ - 7, 1 ], [ - 1, 2 ], [ - 6, 3 ], [ - 3, 3 ],
|
||||
[ - 7, 6 ], [ - 3, 6 ], [ - 5, 7 ], [ - 1, 7 ],
|
||||
[ 5, - 7 ], [ 1, - 6 ], [ 6, - 5 ], [ 4, - 4 ],
|
||||
[ 2, - 3 ], [ 7, - 2 ], [ 1, - 1 ], [ 4, - 1 ],
|
||||
[ 2, 1 ], [ 6, 2 ], [ 0, 4 ], [ 4, 4 ],
|
||||
[ 2, 5 ], [ 7, 5 ], [ 5, 6 ], [ 3, 7 ]
|
||||
]
|
||||
];
|
||||
|
||||
export { SSAARenderPass };
|
||||
@@ -0,0 +1,527 @@
|
||||
import {
|
||||
AddEquation,
|
||||
Color,
|
||||
CustomBlending,
|
||||
DataTexture,
|
||||
DepthTexture,
|
||||
DstAlphaFactor,
|
||||
DstColorFactor,
|
||||
FloatType,
|
||||
HalfFloatType,
|
||||
MathUtils,
|
||||
MeshNormalMaterial,
|
||||
NearestFilter,
|
||||
NoBlending,
|
||||
RedFormat,
|
||||
DepthStencilFormat,
|
||||
UnsignedInt248Type,
|
||||
RepeatWrapping,
|
||||
ShaderMaterial,
|
||||
UniformsUtils,
|
||||
Vector3,
|
||||
WebGLRenderTarget,
|
||||
ZeroFactor
|
||||
} from 'three';
|
||||
import { Pass, FullScreenQuad } from './Pass.js';
|
||||
import { SimplexNoise } from '../math/SimplexNoise.js';
|
||||
import { SSAOBlurShader, SSAODepthShader, SSAOShader } from '../shaders/SSAOShader.js';
|
||||
import { CopyShader } from '../shaders/CopyShader.js';
|
||||
|
||||
/**
|
||||
* A pass for a basic SSAO effect.
|
||||
*
|
||||
* {@link SAOPass} and {@link GTAPass} produce a more advanced AO but are also
|
||||
* more expensive.
|
||||
*
|
||||
* ```js
|
||||
* const ssaoPass = new SSAOPass( scene, camera, width, height );
|
||||
* composer.addPass( ssaoPass );
|
||||
* ```
|
||||
*
|
||||
* @augments Pass
|
||||
* @three_import import { SSAOPass } from 'three/addons/postprocessing/SSAOPass.js';
|
||||
*/
|
||||
class SSAOPass extends Pass {
|
||||
|
||||
/**
|
||||
* Constructs a new SSAO pass.
|
||||
*
|
||||
* @param {Scene} scene - The scene to compute the AO for.
|
||||
* @param {Camera} camera - The camera.
|
||||
* @param {number} [width=512] - The width of the effect.
|
||||
* @param {number} [height=512] - The height of the effect.
|
||||
* @param {number} [kernelSize=32] - The kernel size.
|
||||
*/
|
||||
constructor( scene, camera, width = 512, height = 512, kernelSize = 32 ) {
|
||||
|
||||
super();
|
||||
|
||||
/**
|
||||
* The width of the effect.
|
||||
*
|
||||
* @type {number}
|
||||
* @default 512
|
||||
*/
|
||||
this.width = width;
|
||||
|
||||
/**
|
||||
* The height of the effect.
|
||||
*
|
||||
* @type {number}
|
||||
* @default 512
|
||||
*/
|
||||
this.height = height;
|
||||
|
||||
/**
|
||||
* Overwritten to perform a clear operation by default.
|
||||
*
|
||||
* @type {boolean}
|
||||
* @default true
|
||||
*/
|
||||
this.clear = true;
|
||||
|
||||
/**
|
||||
* Overwritten to disable the swap.
|
||||
*
|
||||
* @type {boolean}
|
||||
* @default false
|
||||
*/
|
||||
this.needsSwap = false;
|
||||
|
||||
/**
|
||||
* The camera.
|
||||
*
|
||||
* @type {Camera}
|
||||
*/
|
||||
this.camera = camera;
|
||||
|
||||
/**
|
||||
* The scene to render the AO for.
|
||||
*
|
||||
* @type {Scene}
|
||||
*/
|
||||
this.scene = scene;
|
||||
|
||||
/**
|
||||
* The kernel radius controls how wide the
|
||||
* AO spreads.
|
||||
*
|
||||
* @type {number}
|
||||
* @default 8
|
||||
*/
|
||||
this.kernelRadius = 8;
|
||||
this.kernel = [];
|
||||
this.noiseTexture = null;
|
||||
|
||||
/**
|
||||
* The output configuration.
|
||||
*
|
||||
* @type {number}
|
||||
* @default 0
|
||||
*/
|
||||
this.output = 0;
|
||||
|
||||
/**
|
||||
* Defines the minimum distance that should be
|
||||
* affected by the AO.
|
||||
*
|
||||
* @type {number}
|
||||
* @default 0.005
|
||||
*/
|
||||
this.minDistance = 0.005;
|
||||
|
||||
/**
|
||||
* Defines the maximum distance that should be
|
||||
* affected by the AO.
|
||||
*
|
||||
* @type {number}
|
||||
* @default 0.1
|
||||
*/
|
||||
this.maxDistance = 0.1;
|
||||
|
||||
this._visibilityCache = [];
|
||||
|
||||
//
|
||||
|
||||
this._generateSampleKernel( kernelSize );
|
||||
this._generateRandomKernelRotations();
|
||||
|
||||
// depth texture
|
||||
|
||||
const depthTexture = new DepthTexture();
|
||||
depthTexture.format = DepthStencilFormat;
|
||||
depthTexture.type = UnsignedInt248Type;
|
||||
|
||||
// normal render target with depth buffer
|
||||
|
||||
this.normalRenderTarget = new WebGLRenderTarget( this.width, this.height, {
|
||||
minFilter: NearestFilter,
|
||||
magFilter: NearestFilter,
|
||||
type: HalfFloatType,
|
||||
depthTexture: depthTexture
|
||||
} );
|
||||
|
||||
// ssao render target
|
||||
|
||||
this.ssaoRenderTarget = new WebGLRenderTarget( this.width, this.height, { type: HalfFloatType, depthBuffer: false } );
|
||||
|
||||
this.blurRenderTarget = this.ssaoRenderTarget.clone();
|
||||
|
||||
// ssao material
|
||||
|
||||
this.ssaoMaterial = new ShaderMaterial( {
|
||||
defines: Object.assign( {}, SSAOShader.defines ),
|
||||
uniforms: UniformsUtils.clone( SSAOShader.uniforms ),
|
||||
vertexShader: SSAOShader.vertexShader,
|
||||
fragmentShader: SSAOShader.fragmentShader,
|
||||
blending: NoBlending
|
||||
} );
|
||||
|
||||
this.ssaoMaterial.defines[ 'KERNEL_SIZE' ] = kernelSize;
|
||||
|
||||
this.ssaoMaterial.uniforms[ 'tNormal' ].value = this.normalRenderTarget.texture;
|
||||
this.ssaoMaterial.uniforms[ 'tDepth' ].value = this.normalRenderTarget.depthTexture;
|
||||
this.ssaoMaterial.uniforms[ 'tNoise' ].value = this.noiseTexture;
|
||||
this.ssaoMaterial.uniforms[ 'kernel' ].value = this.kernel;
|
||||
this.ssaoMaterial.uniforms[ 'cameraNear' ].value = this.camera.near;
|
||||
this.ssaoMaterial.uniforms[ 'cameraFar' ].value = this.camera.far;
|
||||
this.ssaoMaterial.uniforms[ 'resolution' ].value.set( this.width, this.height );
|
||||
this.ssaoMaterial.uniforms[ 'cameraProjectionMatrix' ].value.copy( this.camera.projectionMatrix );
|
||||
this.ssaoMaterial.uniforms[ 'cameraInverseProjectionMatrix' ].value.copy( this.camera.projectionMatrixInverse );
|
||||
|
||||
// normal material
|
||||
|
||||
this.normalMaterial = new MeshNormalMaterial();
|
||||
this.normalMaterial.blending = NoBlending;
|
||||
|
||||
// blur material
|
||||
|
||||
this.blurMaterial = new ShaderMaterial( {
|
||||
defines: Object.assign( {}, SSAOBlurShader.defines ),
|
||||
uniforms: UniformsUtils.clone( SSAOBlurShader.uniforms ),
|
||||
vertexShader: SSAOBlurShader.vertexShader,
|
||||
fragmentShader: SSAOBlurShader.fragmentShader
|
||||
} );
|
||||
this.blurMaterial.uniforms[ 'tDiffuse' ].value = this.ssaoRenderTarget.texture;
|
||||
this.blurMaterial.uniforms[ 'resolution' ].value.set( this.width, this.height );
|
||||
|
||||
// material for rendering the depth
|
||||
|
||||
this.depthRenderMaterial = new ShaderMaterial( {
|
||||
defines: Object.assign( {}, SSAODepthShader.defines ),
|
||||
uniforms: UniformsUtils.clone( SSAODepthShader.uniforms ),
|
||||
vertexShader: SSAODepthShader.vertexShader,
|
||||
fragmentShader: SSAODepthShader.fragmentShader,
|
||||
blending: NoBlending
|
||||
} );
|
||||
this.depthRenderMaterial.uniforms[ 'tDepth' ].value = this.normalRenderTarget.depthTexture;
|
||||
this.depthRenderMaterial.uniforms[ 'cameraNear' ].value = this.camera.near;
|
||||
this.depthRenderMaterial.uniforms[ 'cameraFar' ].value = this.camera.far;
|
||||
|
||||
// material for rendering the content of a render target
|
||||
|
||||
this.copyMaterial = new ShaderMaterial( {
|
||||
uniforms: UniformsUtils.clone( CopyShader.uniforms ),
|
||||
vertexShader: CopyShader.vertexShader,
|
||||
fragmentShader: CopyShader.fragmentShader,
|
||||
transparent: true,
|
||||
depthTest: false,
|
||||
depthWrite: false,
|
||||
blendSrc: DstColorFactor,
|
||||
blendDst: ZeroFactor,
|
||||
blendEquation: AddEquation,
|
||||
blendSrcAlpha: DstAlphaFactor,
|
||||
blendDstAlpha: ZeroFactor,
|
||||
blendEquationAlpha: AddEquation
|
||||
} );
|
||||
|
||||
// internals
|
||||
|
||||
this._fsQuad = new FullScreenQuad( null );
|
||||
|
||||
this._originalClearColor = new Color();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Frees the GPU-related resources allocated by this instance. Call this
|
||||
* method whenever the pass is no longer used in your app.
|
||||
*/
|
||||
dispose() {
|
||||
|
||||
// dispose render targets
|
||||
|
||||
this.normalRenderTarget.dispose();
|
||||
this.ssaoRenderTarget.dispose();
|
||||
this.blurRenderTarget.dispose();
|
||||
|
||||
// dispose materials
|
||||
|
||||
this.normalMaterial.dispose();
|
||||
this.blurMaterial.dispose();
|
||||
this.copyMaterial.dispose();
|
||||
this.depthRenderMaterial.dispose();
|
||||
|
||||
// dispose full screen quad
|
||||
|
||||
this._fsQuad.dispose();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs the SSAO pass.
|
||||
*
|
||||
* @param {WebGLRenderer} renderer - The renderer.
|
||||
* @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
|
||||
* destination for the pass.
|
||||
* @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
|
||||
* previous pass from this buffer.
|
||||
* @param {number} deltaTime - The delta time in seconds.
|
||||
* @param {boolean} maskActive - Whether masking is active or not.
|
||||
*/
|
||||
render( renderer, writeBuffer, readBuffer /*, deltaTime, maskActive */ ) {
|
||||
|
||||
// render normals and depth (honor only meshes, points and lines do not contribute to SSAO)
|
||||
|
||||
this._overrideVisibility();
|
||||
this._renderOverride( renderer, this.normalMaterial, this.normalRenderTarget, 0x7777ff, 1.0 );
|
||||
this._restoreVisibility();
|
||||
|
||||
// render SSAO
|
||||
|
||||
this.ssaoMaterial.uniforms[ 'kernelRadius' ].value = this.kernelRadius;
|
||||
this.ssaoMaterial.uniforms[ 'minDistance' ].value = this.minDistance;
|
||||
this.ssaoMaterial.uniforms[ 'maxDistance' ].value = this.maxDistance;
|
||||
this._renderPass( renderer, this.ssaoMaterial, this.ssaoRenderTarget );
|
||||
|
||||
// render blur
|
||||
|
||||
this._renderPass( renderer, this.blurMaterial, this.blurRenderTarget );
|
||||
|
||||
// output result to screen
|
||||
|
||||
switch ( this.output ) {
|
||||
|
||||
case SSAOPass.OUTPUT.SSAO:
|
||||
|
||||
this.copyMaterial.uniforms[ 'tDiffuse' ].value = this.ssaoRenderTarget.texture;
|
||||
this.copyMaterial.blending = NoBlending;
|
||||
this._renderPass( renderer, this.copyMaterial, this.renderToScreen ? null : readBuffer );
|
||||
|
||||
break;
|
||||
|
||||
case SSAOPass.OUTPUT.Blur:
|
||||
|
||||
this.copyMaterial.uniforms[ 'tDiffuse' ].value = this.blurRenderTarget.texture;
|
||||
this.copyMaterial.blending = NoBlending;
|
||||
this._renderPass( renderer, this.copyMaterial, this.renderToScreen ? null : readBuffer );
|
||||
|
||||
break;
|
||||
|
||||
case SSAOPass.OUTPUT.Depth:
|
||||
|
||||
this._renderPass( renderer, this.depthRenderMaterial, this.renderToScreen ? null : readBuffer );
|
||||
|
||||
break;
|
||||
|
||||
case SSAOPass.OUTPUT.Normal:
|
||||
|
||||
this.copyMaterial.uniforms[ 'tDiffuse' ].value = this.normalRenderTarget.texture;
|
||||
this.copyMaterial.blending = NoBlending;
|
||||
this._renderPass( renderer, this.copyMaterial, this.renderToScreen ? null : readBuffer );
|
||||
|
||||
break;
|
||||
|
||||
case SSAOPass.OUTPUT.Default:
|
||||
|
||||
this.copyMaterial.uniforms[ 'tDiffuse' ].value = this.blurRenderTarget.texture;
|
||||
this.copyMaterial.blending = CustomBlending;
|
||||
this._renderPass( renderer, this.copyMaterial, this.renderToScreen ? null : readBuffer );
|
||||
|
||||
break;
|
||||
|
||||
default:
|
||||
console.warn( 'THREE.SSAOPass: Unknown output type.' );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the size of the pass.
|
||||
*
|
||||
* @param {number} width - The width to set.
|
||||
* @param {number} height - The height to set.
|
||||
*/
|
||||
setSize( width, height ) {
|
||||
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
|
||||
this.ssaoRenderTarget.setSize( width, height );
|
||||
this.normalRenderTarget.setSize( width, height );
|
||||
this.blurRenderTarget.setSize( width, height );
|
||||
|
||||
this.ssaoMaterial.uniforms[ 'resolution' ].value.set( width, height );
|
||||
this.ssaoMaterial.uniforms[ 'cameraProjectionMatrix' ].value.copy( this.camera.projectionMatrix );
|
||||
this.ssaoMaterial.uniforms[ 'cameraInverseProjectionMatrix' ].value.copy( this.camera.projectionMatrixInverse );
|
||||
|
||||
this.blurMaterial.uniforms[ 'resolution' ].value.set( width, height );
|
||||
|
||||
}
|
||||
|
||||
// internals
|
||||
|
||||
_renderPass( renderer, passMaterial, renderTarget, clearColor, clearAlpha ) {
|
||||
|
||||
// save original state
|
||||
renderer.getClearColor( this._originalClearColor );
|
||||
const originalClearAlpha = renderer.getClearAlpha();
|
||||
const originalAutoClear = renderer.autoClear;
|
||||
|
||||
renderer.setRenderTarget( renderTarget );
|
||||
|
||||
// setup pass state
|
||||
renderer.autoClear = false;
|
||||
if ( ( clearColor !== undefined ) && ( clearColor !== null ) ) {
|
||||
|
||||
renderer.setClearColor( clearColor );
|
||||
renderer.setClearAlpha( clearAlpha || 0.0 );
|
||||
renderer.clear();
|
||||
|
||||
}
|
||||
|
||||
this._fsQuad.material = passMaterial;
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
// restore original state
|
||||
renderer.autoClear = originalAutoClear;
|
||||
renderer.setClearColor( this._originalClearColor );
|
||||
renderer.setClearAlpha( originalClearAlpha );
|
||||
|
||||
}
|
||||
|
||||
_renderOverride( renderer, overrideMaterial, renderTarget, clearColor, clearAlpha ) {
|
||||
|
||||
renderer.getClearColor( this._originalClearColor );
|
||||
const originalClearAlpha = renderer.getClearAlpha();
|
||||
const originalAutoClear = renderer.autoClear;
|
||||
|
||||
renderer.setRenderTarget( renderTarget );
|
||||
renderer.autoClear = false;
|
||||
|
||||
clearColor = overrideMaterial.clearColor || clearColor;
|
||||
clearAlpha = overrideMaterial.clearAlpha || clearAlpha;
|
||||
|
||||
if ( ( clearColor !== undefined ) && ( clearColor !== null ) ) {
|
||||
|
||||
renderer.setClearColor( clearColor );
|
||||
renderer.setClearAlpha( clearAlpha || 0.0 );
|
||||
renderer.clear();
|
||||
|
||||
}
|
||||
|
||||
this.scene.overrideMaterial = overrideMaterial;
|
||||
renderer.render( this.scene, this.camera );
|
||||
this.scene.overrideMaterial = null;
|
||||
|
||||
// restore original state
|
||||
|
||||
renderer.autoClear = originalAutoClear;
|
||||
renderer.setClearColor( this._originalClearColor );
|
||||
renderer.setClearAlpha( originalClearAlpha );
|
||||
|
||||
}
|
||||
|
||||
_generateSampleKernel( kernelSize ) {
|
||||
|
||||
const kernel = this.kernel;
|
||||
|
||||
for ( let i = 0; i < kernelSize; i ++ ) {
|
||||
|
||||
const sample = new Vector3();
|
||||
sample.x = ( Math.random() * 2 ) - 1;
|
||||
sample.y = ( Math.random() * 2 ) - 1;
|
||||
sample.z = Math.random();
|
||||
|
||||
sample.normalize();
|
||||
|
||||
let scale = i / kernelSize;
|
||||
scale = MathUtils.lerp( 0.1, 1, scale * scale );
|
||||
sample.multiplyScalar( scale );
|
||||
|
||||
kernel.push( sample );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
_generateRandomKernelRotations() {
|
||||
|
||||
const width = 4, height = 4;
|
||||
|
||||
const simplex = new SimplexNoise();
|
||||
|
||||
const size = width * height;
|
||||
const data = new Float32Array( size );
|
||||
|
||||
for ( let i = 0; i < size; i ++ ) {
|
||||
|
||||
const x = ( Math.random() * 2 ) - 1;
|
||||
const y = ( Math.random() * 2 ) - 1;
|
||||
const z = 0;
|
||||
|
||||
data[ i ] = simplex.noise3d( x, y, z );
|
||||
|
||||
}
|
||||
|
||||
this.noiseTexture = new DataTexture( data, width, height, RedFormat, FloatType );
|
||||
this.noiseTexture.wrapS = RepeatWrapping;
|
||||
this.noiseTexture.wrapT = RepeatWrapping;
|
||||
this.noiseTexture.needsUpdate = true;
|
||||
|
||||
}
|
||||
|
||||
_overrideVisibility() {
|
||||
|
||||
const scene = this.scene;
|
||||
const cache = this._visibilityCache;
|
||||
|
||||
scene.traverse( function ( object ) {
|
||||
|
||||
if ( ( object.isPoints || object.isLine || object.isLine2 ) && object.visible ) {
|
||||
|
||||
object.visible = false;
|
||||
cache.push( object );
|
||||
|
||||
}
|
||||
|
||||
} );
|
||||
|
||||
}
|
||||
|
||||
_restoreVisibility() {
|
||||
|
||||
const cache = this._visibilityCache;
|
||||
|
||||
for ( let i = 0; i < cache.length; i ++ ) {
|
||||
|
||||
cache[ i ].visible = true;
|
||||
|
||||
}
|
||||
|
||||
cache.length = 0;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
SSAOPass.OUTPUT = {
|
||||
'Default': 0,
|
||||
'SSAO': 1,
|
||||
'Blur': 2,
|
||||
'Depth': 3,
|
||||
'Normal': 4
|
||||
};
|
||||
|
||||
export { SSAOPass };
|
||||
@@ -0,0 +1,858 @@
|
||||
import {
|
||||
AddEquation,
|
||||
Color,
|
||||
NormalBlending,
|
||||
DepthTexture,
|
||||
SrcAlphaFactor,
|
||||
OneMinusSrcAlphaFactor,
|
||||
MeshNormalMaterial,
|
||||
MeshBasicMaterial,
|
||||
NearestFilter,
|
||||
NoBlending,
|
||||
ShaderMaterial,
|
||||
UniformsUtils,
|
||||
UnsignedShortType,
|
||||
WebGLRenderTarget,
|
||||
HalfFloatType,
|
||||
} from 'three';
|
||||
import { Pass, FullScreenQuad } from './Pass.js';
|
||||
import { SSRBlurShader, SSRDepthShader, SSRShader } from '../shaders/SSRShader.js';
|
||||
import { CopyShader } from '../shaders/CopyShader.js';
|
||||
|
||||
/**
|
||||
* A pass for a basic SSR effect.
|
||||
*
|
||||
* ```js
|
||||
* const ssrPass = new SSRPass( {
|
||||
* renderer,
|
||||
* scene,
|
||||
* camera,
|
||||
* width: innerWidth,
|
||||
* height: innerHeight
|
||||
* } );
|
||||
* composer.addPass( ssrPass );
|
||||
* ```
|
||||
*
|
||||
* @augments Pass
|
||||
* @three_import import { SSRPass } from 'three/addons/postprocessing/SSRPass.js';
|
||||
*/
|
||||
class SSRPass extends Pass {
|
||||
|
||||
/**
|
||||
* Constructs a new SSR pass.
|
||||
*
|
||||
* @param {SSRPass~Options} options - The pass options.
|
||||
*/
|
||||
constructor( { renderer, scene, camera, width = 512, height = 512, selects = null, bouncing = false, groundReflector = null } ) {
|
||||
|
||||
super();
|
||||
|
||||
/**
|
||||
* The width of the effect.
|
||||
*
|
||||
* @type {number}
|
||||
* @default 512
|
||||
*/
|
||||
this.width = width;
|
||||
|
||||
/**
|
||||
* The height of the effect.
|
||||
*
|
||||
* @type {number}
|
||||
* @default 512
|
||||
*/
|
||||
this.height = height;
|
||||
|
||||
/**
|
||||
* Overwritten to perform a clear operation by default.
|
||||
*
|
||||
* @type {boolean}
|
||||
* @default true
|
||||
*/
|
||||
this.clear = true;
|
||||
|
||||
/**
|
||||
* The renderer.
|
||||
*
|
||||
* @type {WebGLRenderer}
|
||||
*/
|
||||
this.renderer = renderer;
|
||||
|
||||
/**
|
||||
* The scene to render.
|
||||
*
|
||||
* @type {Scene}
|
||||
*/
|
||||
this.scene = scene;
|
||||
|
||||
/**
|
||||
* The camera.
|
||||
*
|
||||
* @type {Camera}
|
||||
*/
|
||||
this.camera = camera;
|
||||
|
||||
/**
|
||||
* The ground reflector.
|
||||
*
|
||||
* @type {?ReflectorForSSRPass}
|
||||
* @default 0
|
||||
*/
|
||||
this.groundReflector = groundReflector;
|
||||
|
||||
/**
|
||||
* The opacity.
|
||||
*
|
||||
* @type {number}
|
||||
* @default 0.5
|
||||
*/
|
||||
this.opacity = SSRShader.uniforms.opacity.value;
|
||||
|
||||
/**
|
||||
* The output configuration.
|
||||
*
|
||||
* @type {number}
|
||||
* @default 0
|
||||
*/
|
||||
this.output = 0;
|
||||
|
||||
/**
|
||||
* Controls how far a fragment can reflect.
|
||||
*
|
||||
* @type {number}
|
||||
* @default 180
|
||||
*/
|
||||
this.maxDistance = SSRShader.uniforms.maxDistance.value;
|
||||
|
||||
/**
|
||||
* Controls the cutoff between what counts as a
|
||||
* possible reflection hit and what does not.
|
||||
*
|
||||
* @type {number}
|
||||
* @default .018
|
||||
*/
|
||||
this.thickness = SSRShader.uniforms.thickness.value;
|
||||
|
||||
this.tempColor = new Color();
|
||||
|
||||
this._selects = selects;
|
||||
|
||||
this._resolutionScale = 1;
|
||||
|
||||
/**
|
||||
* Whether the pass is selective or not.
|
||||
*
|
||||
* @type {boolean}
|
||||
* @default false
|
||||
*/
|
||||
this.selective = Array.isArray( this._selects );
|
||||
|
||||
/**
|
||||
* Which 3D objects should be affected by SSR. If not set, the entire scene is affected.
|
||||
*
|
||||
* @name SSRPass#selects
|
||||
* @type {?Array<Object3D>}
|
||||
* @default null
|
||||
*/
|
||||
Object.defineProperty( this, 'selects', {
|
||||
get() {
|
||||
|
||||
return this._selects;
|
||||
|
||||
},
|
||||
set( val ) {
|
||||
|
||||
if ( this._selects === val ) return;
|
||||
this._selects = val;
|
||||
if ( Array.isArray( val ) ) {
|
||||
|
||||
this.selective = true;
|
||||
this.ssrMaterial.defines.SELECTIVE = true;
|
||||
this.ssrMaterial.needsUpdate = true;
|
||||
|
||||
} else {
|
||||
|
||||
this.selective = false;
|
||||
this.ssrMaterial.defines.SELECTIVE = false;
|
||||
this.ssrMaterial.needsUpdate = true;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
} );
|
||||
|
||||
this._bouncing = bouncing;
|
||||
|
||||
/**
|
||||
* Whether bouncing is enabled or not.
|
||||
*
|
||||
* @name SSRPass#bouncing
|
||||
* @type {boolean}
|
||||
* @default false
|
||||
*/
|
||||
Object.defineProperty( this, 'bouncing', {
|
||||
get() {
|
||||
|
||||
return this._bouncing;
|
||||
|
||||
},
|
||||
set( val ) {
|
||||
|
||||
if ( this._bouncing === val ) return;
|
||||
this._bouncing = val;
|
||||
if ( val ) {
|
||||
|
||||
this.ssrMaterial.uniforms[ 'tDiffuse' ].value = this.prevRenderTarget.texture;
|
||||
|
||||
} else {
|
||||
|
||||
this.ssrMaterial.uniforms[ 'tDiffuse' ].value = this.beautyRenderTarget.texture;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
} );
|
||||
|
||||
/**
|
||||
* Whether to blur reflections or not.
|
||||
*
|
||||
* @type {boolean}
|
||||
* @default true
|
||||
*/
|
||||
this.blur = true;
|
||||
|
||||
this._distanceAttenuation = SSRShader.defines.DISTANCE_ATTENUATION;
|
||||
|
||||
/**
|
||||
* Whether to use distance attenuation or not.
|
||||
*
|
||||
* @name SSRPass#distanceAttenuation
|
||||
* @type {boolean}
|
||||
* @default true
|
||||
*/
|
||||
Object.defineProperty( this, 'distanceAttenuation', {
|
||||
get() {
|
||||
|
||||
return this._distanceAttenuation;
|
||||
|
||||
},
|
||||
set( val ) {
|
||||
|
||||
if ( this._distanceAttenuation === val ) return;
|
||||
this._distanceAttenuation = val;
|
||||
this.ssrMaterial.defines.DISTANCE_ATTENUATION = val;
|
||||
this.ssrMaterial.needsUpdate = true;
|
||||
|
||||
}
|
||||
} );
|
||||
|
||||
|
||||
this._fresnel = SSRShader.defines.FRESNEL;
|
||||
|
||||
/**
|
||||
* Whether to use fresnel or not.
|
||||
*
|
||||
* @name SSRPass#fresnel
|
||||
* @type {boolean}
|
||||
* @default true
|
||||
*/
|
||||
Object.defineProperty( this, 'fresnel', {
|
||||
get() {
|
||||
|
||||
return this._fresnel;
|
||||
|
||||
},
|
||||
set( val ) {
|
||||
|
||||
if ( this._fresnel === val ) return;
|
||||
this._fresnel = val;
|
||||
this.ssrMaterial.defines.FRESNEL = val;
|
||||
this.ssrMaterial.needsUpdate = true;
|
||||
|
||||
}
|
||||
} );
|
||||
|
||||
this._infiniteThick = SSRShader.defines.INFINITE_THICK;
|
||||
|
||||
/**
|
||||
* Whether to use infinite thickness or not.
|
||||
*
|
||||
* @name SSRPass#infiniteThick
|
||||
* @type {boolean}
|
||||
* @default false
|
||||
*/
|
||||
Object.defineProperty( this, 'infiniteThick', {
|
||||
get() {
|
||||
|
||||
return this._infiniteThick;
|
||||
|
||||
},
|
||||
set( val ) {
|
||||
|
||||
if ( this._infiniteThick === val ) return;
|
||||
this._infiniteThick = val;
|
||||
this.ssrMaterial.defines.INFINITE_THICK = val;
|
||||
this.ssrMaterial.needsUpdate = true;
|
||||
|
||||
}
|
||||
} );
|
||||
|
||||
// beauty render target with depth buffer
|
||||
|
||||
const depthTexture = new DepthTexture();
|
||||
depthTexture.type = UnsignedShortType;
|
||||
depthTexture.minFilter = NearestFilter;
|
||||
depthTexture.magFilter = NearestFilter;
|
||||
|
||||
this.beautyRenderTarget = new WebGLRenderTarget( this.width, this.height, {
|
||||
minFilter: NearestFilter,
|
||||
magFilter: NearestFilter,
|
||||
type: HalfFloatType,
|
||||
depthTexture: depthTexture,
|
||||
depthBuffer: true
|
||||
} );
|
||||
|
||||
//for bouncing
|
||||
this.prevRenderTarget = new WebGLRenderTarget( this.width, this.height, {
|
||||
minFilter: NearestFilter,
|
||||
magFilter: NearestFilter,
|
||||
depthBuffer: false
|
||||
} );
|
||||
|
||||
// normal render target
|
||||
|
||||
this.normalRenderTarget = new WebGLRenderTarget( this.width, this.height, {
|
||||
minFilter: NearestFilter,
|
||||
magFilter: NearestFilter,
|
||||
type: HalfFloatType,
|
||||
} );
|
||||
|
||||
// metalness render target
|
||||
|
||||
this.metalnessRenderTarget = new WebGLRenderTarget( this.width, this.height, {
|
||||
minFilter: NearestFilter,
|
||||
magFilter: NearestFilter,
|
||||
type: HalfFloatType,
|
||||
} );
|
||||
|
||||
|
||||
|
||||
// ssr render target
|
||||
|
||||
this.ssrRenderTarget = new WebGLRenderTarget( this.width, this.height, {
|
||||
minFilter: NearestFilter,
|
||||
magFilter: NearestFilter,
|
||||
depthBuffer: false
|
||||
} );
|
||||
|
||||
this.blurRenderTarget = this.ssrRenderTarget.clone();
|
||||
this.blurRenderTarget2 = this.ssrRenderTarget.clone();
|
||||
// this.blurRenderTarget3 = this.ssrRenderTarget.clone();
|
||||
|
||||
// ssr material
|
||||
|
||||
this.ssrMaterial = new ShaderMaterial( {
|
||||
defines: Object.assign( {}, SSRShader.defines, {
|
||||
MAX_STEP: Math.sqrt( this.width * this.width + this.height * this.height )
|
||||
} ),
|
||||
uniforms: UniformsUtils.clone( SSRShader.uniforms ),
|
||||
vertexShader: SSRShader.vertexShader,
|
||||
fragmentShader: SSRShader.fragmentShader,
|
||||
blending: NoBlending
|
||||
} );
|
||||
|
||||
this.ssrMaterial.uniforms[ 'tDiffuse' ].value = this.beautyRenderTarget.texture;
|
||||
this.ssrMaterial.uniforms[ 'tNormal' ].value = this.normalRenderTarget.texture;
|
||||
this.ssrMaterial.defines.SELECTIVE = this.selective;
|
||||
this.ssrMaterial.needsUpdate = true;
|
||||
this.ssrMaterial.uniforms[ 'tMetalness' ].value = this.metalnessRenderTarget.texture;
|
||||
this.ssrMaterial.uniforms[ 'tDepth' ].value = this.beautyRenderTarget.depthTexture;
|
||||
this.ssrMaterial.uniforms[ 'cameraNear' ].value = this.camera.near;
|
||||
this.ssrMaterial.uniforms[ 'cameraFar' ].value = this.camera.far;
|
||||
this.ssrMaterial.uniforms[ 'thickness' ].value = this.thickness;
|
||||
this.ssrMaterial.uniforms[ 'resolution' ].value.set( this.width, this.height );
|
||||
this.ssrMaterial.uniforms[ 'cameraProjectionMatrix' ].value.copy( this.camera.projectionMatrix );
|
||||
this.ssrMaterial.uniforms[ 'cameraInverseProjectionMatrix' ].value.copy( this.camera.projectionMatrixInverse );
|
||||
|
||||
// normal material
|
||||
|
||||
this.normalMaterial = new MeshNormalMaterial();
|
||||
this.normalMaterial.blending = NoBlending;
|
||||
|
||||
// metalnessOn material
|
||||
|
||||
this.metalnessOnMaterial = new MeshBasicMaterial( {
|
||||
color: 'white'
|
||||
} );
|
||||
|
||||
// metalnessOff material
|
||||
|
||||
this.metalnessOffMaterial = new MeshBasicMaterial( {
|
||||
color: 'black'
|
||||
} );
|
||||
|
||||
// blur material
|
||||
|
||||
this.blurMaterial = new ShaderMaterial( {
|
||||
defines: Object.assign( {}, SSRBlurShader.defines ),
|
||||
uniforms: UniformsUtils.clone( SSRBlurShader.uniforms ),
|
||||
vertexShader: SSRBlurShader.vertexShader,
|
||||
fragmentShader: SSRBlurShader.fragmentShader
|
||||
} );
|
||||
this.blurMaterial.uniforms[ 'tDiffuse' ].value = this.ssrRenderTarget.texture;
|
||||
this.blurMaterial.uniforms[ 'resolution' ].value.set( this.width, this.height );
|
||||
|
||||
// blur material 2
|
||||
|
||||
this.blurMaterial2 = new ShaderMaterial( {
|
||||
defines: Object.assign( {}, SSRBlurShader.defines ),
|
||||
uniforms: UniformsUtils.clone( SSRBlurShader.uniforms ),
|
||||
vertexShader: SSRBlurShader.vertexShader,
|
||||
fragmentShader: SSRBlurShader.fragmentShader
|
||||
} );
|
||||
this.blurMaterial2.uniforms[ 'tDiffuse' ].value = this.blurRenderTarget.texture;
|
||||
this.blurMaterial2.uniforms[ 'resolution' ].value.set( this.width, this.height );
|
||||
|
||||
// // blur material 3
|
||||
|
||||
// this.blurMaterial3 = new ShaderMaterial({
|
||||
// defines: Object.assign({}, SSRBlurShader.defines),
|
||||
// uniforms: UniformsUtils.clone(SSRBlurShader.uniforms),
|
||||
// vertexShader: SSRBlurShader.vertexShader,
|
||||
// fragmentShader: SSRBlurShader.fragmentShader
|
||||
// });
|
||||
// this.blurMaterial3.uniforms['tDiffuse'].value = this.blurRenderTarget2.texture;
|
||||
// this.blurMaterial3.uniforms['resolution'].value.set(this.width, this.height);
|
||||
|
||||
// material for rendering the depth
|
||||
|
||||
this.depthRenderMaterial = new ShaderMaterial( {
|
||||
defines: Object.assign( {}, SSRDepthShader.defines ),
|
||||
uniforms: UniformsUtils.clone( SSRDepthShader.uniforms ),
|
||||
vertexShader: SSRDepthShader.vertexShader,
|
||||
fragmentShader: SSRDepthShader.fragmentShader,
|
||||
blending: NoBlending
|
||||
} );
|
||||
this.depthRenderMaterial.uniforms[ 'tDepth' ].value = this.beautyRenderTarget.depthTexture;
|
||||
this.depthRenderMaterial.uniforms[ 'cameraNear' ].value = this.camera.near;
|
||||
this.depthRenderMaterial.uniforms[ 'cameraFar' ].value = this.camera.far;
|
||||
|
||||
// material for rendering the content of a render target
|
||||
|
||||
this.copyMaterial = new ShaderMaterial( {
|
||||
uniforms: UniformsUtils.clone( CopyShader.uniforms ),
|
||||
vertexShader: CopyShader.vertexShader,
|
||||
fragmentShader: CopyShader.fragmentShader,
|
||||
transparent: true,
|
||||
depthTest: false,
|
||||
depthWrite: false,
|
||||
blendSrc: SrcAlphaFactor,
|
||||
blendDst: OneMinusSrcAlphaFactor,
|
||||
blendEquation: AddEquation,
|
||||
blendSrcAlpha: SrcAlphaFactor,
|
||||
blendDstAlpha: OneMinusSrcAlphaFactor,
|
||||
blendEquationAlpha: AddEquation,
|
||||
// premultipliedAlpha:true,
|
||||
} );
|
||||
|
||||
this.fsQuad = new FullScreenQuad( null );
|
||||
|
||||
this.originalClearColor = new Color();
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* The resolution scale. Valid values are in the range
|
||||
* `[0,1]`. `1` means best quality but also results in
|
||||
* more computational overhead. Setting to `0.5` means
|
||||
* the effect is computed in half-resolution.
|
||||
*
|
||||
* @type {number}
|
||||
* @default 1
|
||||
*/
|
||||
get resolutionScale() {
|
||||
|
||||
return this._resolutionScale;
|
||||
|
||||
}
|
||||
|
||||
set resolutionScale( value ) {
|
||||
|
||||
this._resolutionScale = value;
|
||||
this.setSize( this.width, this.height ); // force a resize when resolution scaling changes
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Frees the GPU-related resources allocated by this instance. Call this
|
||||
* method whenever the pass is no longer used in your app.
|
||||
*/
|
||||
dispose() {
|
||||
|
||||
// dispose render targets
|
||||
|
||||
this.beautyRenderTarget.dispose();
|
||||
this.prevRenderTarget.dispose();
|
||||
this.normalRenderTarget.dispose();
|
||||
this.metalnessRenderTarget.dispose();
|
||||
this.ssrRenderTarget.dispose();
|
||||
this.blurRenderTarget.dispose();
|
||||
this.blurRenderTarget2.dispose();
|
||||
// this.blurRenderTarget3.dispose();
|
||||
|
||||
// dispose materials
|
||||
|
||||
this.normalMaterial.dispose();
|
||||
this.metalnessOnMaterial.dispose();
|
||||
this.metalnessOffMaterial.dispose();
|
||||
this.blurMaterial.dispose();
|
||||
this.blurMaterial2.dispose();
|
||||
this.copyMaterial.dispose();
|
||||
this.depthRenderMaterial.dispose();
|
||||
|
||||
// dispose full screen quad
|
||||
|
||||
this.fsQuad.dispose();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs the SSR pass.
|
||||
*
|
||||
* @param {WebGLRenderer} renderer - The renderer.
|
||||
* @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
|
||||
* destination for the pass.
|
||||
* @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
|
||||
* previous pass from this buffer.
|
||||
* @param {number} deltaTime - The delta time in seconds.
|
||||
* @param {boolean} maskActive - Whether masking is active or not.
|
||||
*/
|
||||
render( renderer, writeBuffer /*, readBuffer, deltaTime, maskActive */ ) {
|
||||
|
||||
// render beauty and depth
|
||||
|
||||
renderer.setRenderTarget( this.beautyRenderTarget );
|
||||
renderer.clear();
|
||||
if ( this.groundReflector ) {
|
||||
|
||||
this.groundReflector.visible = false;
|
||||
this.groundReflector.doRender( this.renderer, this.scene, this.camera );
|
||||
this.groundReflector.visible = true;
|
||||
|
||||
}
|
||||
|
||||
renderer.render( this.scene, this.camera );
|
||||
if ( this.groundReflector ) this.groundReflector.visible = false;
|
||||
|
||||
// render normals
|
||||
|
||||
this._renderOverride( renderer, this.normalMaterial, this.normalRenderTarget, 0, 0 );
|
||||
|
||||
// render metalnesses
|
||||
|
||||
if ( this.selective ) {
|
||||
|
||||
this._renderMetalness( renderer, this.metalnessOnMaterial, this.metalnessRenderTarget, 0, 0 );
|
||||
|
||||
}
|
||||
|
||||
// render SSR
|
||||
|
||||
this.ssrMaterial.uniforms[ 'opacity' ].value = this.opacity;
|
||||
this.ssrMaterial.uniforms[ 'maxDistance' ].value = this.maxDistance;
|
||||
this.ssrMaterial.uniforms[ 'thickness' ].value = this.thickness;
|
||||
this._renderPass( renderer, this.ssrMaterial, this.ssrRenderTarget );
|
||||
|
||||
|
||||
// render blur
|
||||
|
||||
if ( this.blur ) {
|
||||
|
||||
this._renderPass( renderer, this.blurMaterial, this.blurRenderTarget );
|
||||
this._renderPass( renderer, this.blurMaterial2, this.blurRenderTarget2 );
|
||||
// this._renderPass(renderer, this.blurMaterial3, this.blurRenderTarget3);
|
||||
|
||||
}
|
||||
|
||||
// output result to screen
|
||||
|
||||
switch ( this.output ) {
|
||||
|
||||
case SSRPass.OUTPUT.Default:
|
||||
|
||||
if ( this.bouncing ) {
|
||||
|
||||
this.copyMaterial.uniforms[ 'tDiffuse' ].value = this.beautyRenderTarget.texture;
|
||||
this.copyMaterial.blending = NoBlending;
|
||||
this._renderPass( renderer, this.copyMaterial, this.prevRenderTarget );
|
||||
|
||||
if ( this.blur )
|
||||
this.copyMaterial.uniforms[ 'tDiffuse' ].value = this.blurRenderTarget2.texture;
|
||||
else
|
||||
this.copyMaterial.uniforms[ 'tDiffuse' ].value = this.ssrRenderTarget.texture;
|
||||
this.copyMaterial.blending = NormalBlending;
|
||||
this._renderPass( renderer, this.copyMaterial, this.prevRenderTarget );
|
||||
|
||||
this.copyMaterial.uniforms[ 'tDiffuse' ].value = this.prevRenderTarget.texture;
|
||||
this.copyMaterial.blending = NoBlending;
|
||||
this._renderPass( renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer );
|
||||
|
||||
} else {
|
||||
|
||||
this.copyMaterial.uniforms[ 'tDiffuse' ].value = this.beautyRenderTarget.texture;
|
||||
this.copyMaterial.blending = NoBlending;
|
||||
this._renderPass( renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer );
|
||||
|
||||
if ( this.blur )
|
||||
this.copyMaterial.uniforms[ 'tDiffuse' ].value = this.blurRenderTarget2.texture;
|
||||
else
|
||||
this.copyMaterial.uniforms[ 'tDiffuse' ].value = this.ssrRenderTarget.texture;
|
||||
this.copyMaterial.blending = NormalBlending;
|
||||
this._renderPass( renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer );
|
||||
|
||||
}
|
||||
|
||||
break;
|
||||
case SSRPass.OUTPUT.SSR:
|
||||
|
||||
if ( this.blur )
|
||||
this.copyMaterial.uniforms[ 'tDiffuse' ].value = this.blurRenderTarget2.texture;
|
||||
else
|
||||
this.copyMaterial.uniforms[ 'tDiffuse' ].value = this.ssrRenderTarget.texture;
|
||||
this.copyMaterial.blending = NoBlending;
|
||||
this._renderPass( renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer );
|
||||
|
||||
if ( this.bouncing ) {
|
||||
|
||||
if ( this.blur )
|
||||
this.copyMaterial.uniforms[ 'tDiffuse' ].value = this.blurRenderTarget2.texture;
|
||||
else
|
||||
this.copyMaterial.uniforms[ 'tDiffuse' ].value = this.beautyRenderTarget.texture;
|
||||
this.copyMaterial.blending = NoBlending;
|
||||
this._renderPass( renderer, this.copyMaterial, this.prevRenderTarget );
|
||||
|
||||
this.copyMaterial.uniforms[ 'tDiffuse' ].value = this.ssrRenderTarget.texture;
|
||||
this.copyMaterial.blending = NormalBlending;
|
||||
this._renderPass( renderer, this.copyMaterial, this.prevRenderTarget );
|
||||
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case SSRPass.OUTPUT.Beauty:
|
||||
|
||||
this.copyMaterial.uniforms[ 'tDiffuse' ].value = this.beautyRenderTarget.texture;
|
||||
this.copyMaterial.blending = NoBlending;
|
||||
this._renderPass( renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer );
|
||||
|
||||
break;
|
||||
|
||||
case SSRPass.OUTPUT.Depth:
|
||||
|
||||
this._renderPass( renderer, this.depthRenderMaterial, this.renderToScreen ? null : writeBuffer );
|
||||
|
||||
break;
|
||||
|
||||
case SSRPass.OUTPUT.Normal:
|
||||
|
||||
this.copyMaterial.uniforms[ 'tDiffuse' ].value = this.normalRenderTarget.texture;
|
||||
this.copyMaterial.blending = NoBlending;
|
||||
this._renderPass( renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer );
|
||||
|
||||
break;
|
||||
|
||||
case SSRPass.OUTPUT.Metalness:
|
||||
|
||||
this.copyMaterial.uniforms[ 'tDiffuse' ].value = this.metalnessRenderTarget.texture;
|
||||
this.copyMaterial.blending = NoBlending;
|
||||
this._renderPass( renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer );
|
||||
|
||||
break;
|
||||
|
||||
default:
|
||||
console.warn( 'THREE.SSRPass: Unknown output type.' );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the size of the pass.
|
||||
*
|
||||
* @param {number} width - The width to set.
|
||||
* @param {number} height - The height to set.
|
||||
*/
|
||||
setSize( width, height ) {
|
||||
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
|
||||
const effectiveWidth = Math.round( this.resolutionScale * width );
|
||||
const effectiveHeight = Math.round( this.resolutionScale * height );
|
||||
|
||||
this.ssrMaterial.defines.MAX_STEP = Math.sqrt( effectiveWidth * effectiveWidth + effectiveHeight * effectiveHeight );
|
||||
this.ssrMaterial.needsUpdate = true;
|
||||
|
||||
this.beautyRenderTarget.setSize( width, height );
|
||||
this.normalRenderTarget.setSize( width, height );
|
||||
this.metalnessRenderTarget.setSize( width, height );
|
||||
this.ssrRenderTarget.setSize( effectiveWidth, effectiveHeight );
|
||||
this.prevRenderTarget.setSize( effectiveWidth, effectiveHeight );
|
||||
this.blurRenderTarget.setSize( effectiveWidth, effectiveHeight );
|
||||
this.blurRenderTarget2.setSize( effectiveWidth, effectiveHeight );
|
||||
// this.blurRenderTarget3.setSize(width, height);
|
||||
|
||||
this.ssrMaterial.uniforms[ 'resolution' ].value.set( effectiveWidth, effectiveHeight );
|
||||
this.ssrMaterial.uniforms[ 'cameraProjectionMatrix' ].value.copy( this.camera.projectionMatrix );
|
||||
this.ssrMaterial.uniforms[ 'cameraInverseProjectionMatrix' ].value.copy( this.camera.projectionMatrixInverse );
|
||||
|
||||
this.blurMaterial.uniforms[ 'resolution' ].value.set( effectiveWidth, effectiveHeight );
|
||||
this.blurMaterial2.uniforms[ 'resolution' ].value.set( effectiveWidth, effectiveHeight );
|
||||
|
||||
}
|
||||
|
||||
// internals
|
||||
|
||||
_renderPass( renderer, passMaterial, renderTarget, clearColor, clearAlpha ) {
|
||||
|
||||
// save original state
|
||||
this.originalClearColor.copy( renderer.getClearColor( this.tempColor ) );
|
||||
const originalClearAlpha = renderer.getClearAlpha( this.tempColor );
|
||||
const originalAutoClear = renderer.autoClear;
|
||||
|
||||
renderer.setRenderTarget( renderTarget );
|
||||
|
||||
// setup pass state
|
||||
renderer.autoClear = false;
|
||||
if ( ( clearColor !== undefined ) && ( clearColor !== null ) ) {
|
||||
|
||||
renderer.setClearColor( clearColor );
|
||||
renderer.setClearAlpha( clearAlpha || 0.0 );
|
||||
renderer.clear();
|
||||
|
||||
}
|
||||
|
||||
this.fsQuad.material = passMaterial;
|
||||
this.fsQuad.render( renderer );
|
||||
|
||||
// restore original state
|
||||
renderer.autoClear = originalAutoClear;
|
||||
renderer.setClearColor( this.originalClearColor );
|
||||
renderer.setClearAlpha( originalClearAlpha );
|
||||
|
||||
}
|
||||
|
||||
_renderOverride( renderer, overrideMaterial, renderTarget, clearColor, clearAlpha ) {
|
||||
|
||||
this.originalClearColor.copy( renderer.getClearColor( this.tempColor ) );
|
||||
const originalClearAlpha = renderer.getClearAlpha( this.tempColor );
|
||||
const originalAutoClear = renderer.autoClear;
|
||||
|
||||
renderer.setRenderTarget( renderTarget );
|
||||
renderer.autoClear = false;
|
||||
|
||||
clearColor = overrideMaterial.clearColor || clearColor;
|
||||
clearAlpha = overrideMaterial.clearAlpha || clearAlpha;
|
||||
|
||||
if ( ( clearColor !== undefined ) && ( clearColor !== null ) ) {
|
||||
|
||||
renderer.setClearColor( clearColor );
|
||||
renderer.setClearAlpha( clearAlpha || 0.0 );
|
||||
renderer.clear();
|
||||
|
||||
}
|
||||
|
||||
this.scene.overrideMaterial = overrideMaterial;
|
||||
renderer.render( this.scene, this.camera );
|
||||
this.scene.overrideMaterial = null;
|
||||
|
||||
// restore original state
|
||||
|
||||
renderer.autoClear = originalAutoClear;
|
||||
renderer.setClearColor( this.originalClearColor );
|
||||
renderer.setClearAlpha( originalClearAlpha );
|
||||
|
||||
}
|
||||
|
||||
_renderMetalness( renderer, overrideMaterial, renderTarget, clearColor, clearAlpha ) {
|
||||
|
||||
this.originalClearColor.copy( renderer.getClearColor( this.tempColor ) );
|
||||
const originalClearAlpha = renderer.getClearAlpha( this.tempColor );
|
||||
const originalAutoClear = renderer.autoClear;
|
||||
const originalBackground = this.scene.background;
|
||||
const originalFog = this.scene.fog;
|
||||
|
||||
renderer.setRenderTarget( renderTarget );
|
||||
renderer.autoClear = false;
|
||||
this.scene.background = null;
|
||||
this.scene.fog = null;
|
||||
|
||||
clearColor = overrideMaterial.clearColor || clearColor;
|
||||
clearAlpha = overrideMaterial.clearAlpha || clearAlpha;
|
||||
|
||||
if ( ( clearColor !== undefined ) && ( clearColor !== null ) ) {
|
||||
|
||||
renderer.setClearColor( clearColor );
|
||||
renderer.setClearAlpha( clearAlpha || 0.0 );
|
||||
renderer.clear();
|
||||
|
||||
}
|
||||
|
||||
this.scene.traverseVisible( child => {
|
||||
|
||||
child._SSRPassBackupMaterial = child.material;
|
||||
if ( this._selects.includes( child ) ) {
|
||||
|
||||
child.material = this.metalnessOnMaterial;
|
||||
|
||||
} else {
|
||||
|
||||
child.material = this.metalnessOffMaterial;
|
||||
|
||||
}
|
||||
|
||||
} );
|
||||
renderer.render( this.scene, this.camera );
|
||||
this.scene.traverseVisible( child => {
|
||||
|
||||
child.material = child._SSRPassBackupMaterial;
|
||||
|
||||
} );
|
||||
|
||||
// restore original state
|
||||
|
||||
renderer.autoClear = originalAutoClear;
|
||||
renderer.setClearColor( this.originalClearColor );
|
||||
renderer.setClearAlpha( originalClearAlpha );
|
||||
this.scene.background = originalBackground;
|
||||
this.scene.fog = originalFog;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructor options of `SSRPass`.
|
||||
*
|
||||
* @typedef {Object} SSRPass~Options
|
||||
* @property {WebGLRenderer} renderer - The renderer.
|
||||
* @property {Scene} scene - The scene to render.
|
||||
* @property {Camera} camera - The camera.
|
||||
* @property {number} [width=512] - The width of the effect.
|
||||
* @property {number} [height=512] - The width of the effect.
|
||||
* @property {?Array<Object3D>} [selects=null] - Which 3D objects should be affected by SSR. If not set, the entire scene is affected.
|
||||
* @property {boolean} [bouncing=false] - Whether bouncing is enabled or not.
|
||||
* @property {?ReflectorForSSRPass} [groundReflector=null] - A ground reflector.
|
||||
**/
|
||||
|
||||
SSRPass.OUTPUT = {
|
||||
'Default': 0,
|
||||
'SSR': 1,
|
||||
'Beauty': 3,
|
||||
'Depth': 4,
|
||||
'Normal': 5,
|
||||
'Metalness': 7,
|
||||
};
|
||||
|
||||
export { SSRPass };
|
||||
@@ -0,0 +1,132 @@
|
||||
import {
|
||||
HalfFloatType,
|
||||
NoBlending,
|
||||
ShaderMaterial,
|
||||
UniformsUtils,
|
||||
WebGLRenderTarget
|
||||
} from 'three';
|
||||
import { Pass, FullScreenQuad } from './Pass.js';
|
||||
import { CopyShader } from '../shaders/CopyShader.js';
|
||||
|
||||
/**
|
||||
* A pass that saves the contents of the current read buffer in a render target.
|
||||
*
|
||||
* ```js
|
||||
* const savePass = new SavePass( customRenderTarget );
|
||||
* composer.addPass( savePass );
|
||||
* ```
|
||||
*
|
||||
* @augments Pass
|
||||
* @three_import import { SavePass } from 'three/addons/postprocessing/SavePass.js';
|
||||
*/
|
||||
class SavePass extends Pass {
|
||||
|
||||
/**
|
||||
* Constructs a new save pass.
|
||||
*
|
||||
* @param {WebGLRenderTarget} [renderTarget] - The render target for saving the read buffer.
|
||||
* If not provided, the pass automatically creates a render target.
|
||||
*/
|
||||
constructor( renderTarget ) {
|
||||
|
||||
super();
|
||||
|
||||
/**
|
||||
* The pass uniforms.
|
||||
*
|
||||
* @type {Object}
|
||||
*/
|
||||
this.uniforms = UniformsUtils.clone( CopyShader.uniforms );
|
||||
|
||||
/**
|
||||
* The pass material.
|
||||
*
|
||||
* @type {ShaderMaterial}
|
||||
*/
|
||||
this.material = new ShaderMaterial( {
|
||||
|
||||
uniforms: this.uniforms,
|
||||
vertexShader: CopyShader.vertexShader,
|
||||
fragmentShader: CopyShader.fragmentShader,
|
||||
blending: NoBlending
|
||||
|
||||
} );
|
||||
|
||||
/**
|
||||
* The render target which is used to save the read buffer.
|
||||
*
|
||||
* @type {WebGLRenderTarget}
|
||||
*/
|
||||
this.renderTarget = renderTarget;
|
||||
|
||||
if ( this.renderTarget === undefined ) {
|
||||
|
||||
this.renderTarget = new WebGLRenderTarget( 1, 1, { type: HalfFloatType, depthBuffer: false } ); // will be resized later
|
||||
this.renderTarget.texture.name = 'SavePass.rt';
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Overwritten to disable the swap.
|
||||
*
|
||||
* @type {boolean}
|
||||
* @default false
|
||||
*/
|
||||
this.needsSwap = false;
|
||||
|
||||
// internals
|
||||
|
||||
this._fsQuad = new FullScreenQuad( this.material );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs the save pass.
|
||||
*
|
||||
* @param {WebGLRenderer} renderer - The renderer.
|
||||
* @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
|
||||
* destination for the pass.
|
||||
* @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
|
||||
* previous pass from this buffer.
|
||||
* @param {number} deltaTime - The delta time in seconds.
|
||||
* @param {boolean} maskActive - Whether masking is active or not.
|
||||
*/
|
||||
render( renderer, writeBuffer, readBuffer/*, deltaTime, maskActive */ ) {
|
||||
|
||||
this.uniforms[ 'tDiffuse' ].value = readBuffer.texture;
|
||||
|
||||
renderer.setRenderTarget( this.renderTarget );
|
||||
if ( this.clear ) renderer.clear();
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the size of the pass.
|
||||
*
|
||||
* @param {number} width - The width to set.
|
||||
* @param {number} height - The height to set.
|
||||
*/
|
||||
setSize( width, height ) {
|
||||
|
||||
this.renderTarget.setSize( width, height );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Frees the GPU-related resources allocated by this instance. Call this
|
||||
* method whenever the pass is no longer used in your app.
|
||||
*/
|
||||
dispose() {
|
||||
|
||||
this.renderTarget.dispose();
|
||||
|
||||
this.material.dispose();
|
||||
|
||||
this._fsQuad.dispose();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export { SavePass };
|
||||
@@ -0,0 +1,135 @@
|
||||
import {
|
||||
ShaderMaterial,
|
||||
UniformsUtils
|
||||
} from 'three';
|
||||
import { Pass, FullScreenQuad } from './Pass.js';
|
||||
|
||||
/**
|
||||
* This pass can be used to create a post processing effect
|
||||
* with a raw GLSL shader object. Useful for implementing custom
|
||||
* effects.
|
||||
*
|
||||
* ```js
|
||||
* const fxaaPass = new ShaderPass( FXAAShader );
|
||||
* composer.addPass( fxaaPass );
|
||||
* ```
|
||||
*
|
||||
* @augments Pass
|
||||
* @three_import import { ShaderPass } from 'three/addons/postprocessing/ShaderPass.js';
|
||||
*/
|
||||
class ShaderPass extends Pass {
|
||||
|
||||
/**
|
||||
* Constructs a new shader pass.
|
||||
*
|
||||
* @param {Object|ShaderMaterial} [shader] - A shader object holding vertex and fragment shader as well as
|
||||
* defines and uniforms. It's also valid to pass a custom shader material.
|
||||
* @param {string} [textureID='tDiffuse'] - The name of the texture uniform that should sample
|
||||
* the read buffer.
|
||||
*/
|
||||
constructor( shader, textureID = 'tDiffuse' ) {
|
||||
|
||||
super();
|
||||
|
||||
/**
|
||||
* The name of the texture uniform that should sample the read buffer.
|
||||
*
|
||||
* @type {string}
|
||||
* @default 'tDiffuse'
|
||||
*/
|
||||
this.textureID = textureID;
|
||||
|
||||
/**
|
||||
* The pass uniforms.
|
||||
*
|
||||
* @type {?Object}
|
||||
*/
|
||||
this.uniforms = null;
|
||||
|
||||
/**
|
||||
* The pass material.
|
||||
*
|
||||
* @type {?ShaderMaterial}
|
||||
*/
|
||||
this.material = null;
|
||||
|
||||
if ( shader instanceof ShaderMaterial ) {
|
||||
|
||||
this.uniforms = shader.uniforms;
|
||||
|
||||
this.material = shader;
|
||||
|
||||
} else if ( shader ) {
|
||||
|
||||
this.uniforms = UniformsUtils.clone( shader.uniforms );
|
||||
|
||||
this.material = new ShaderMaterial( {
|
||||
|
||||
name: ( shader.name !== undefined ) ? shader.name : 'unspecified',
|
||||
defines: Object.assign( {}, shader.defines ),
|
||||
uniforms: this.uniforms,
|
||||
vertexShader: shader.vertexShader,
|
||||
fragmentShader: shader.fragmentShader
|
||||
|
||||
} );
|
||||
|
||||
}
|
||||
|
||||
// internals
|
||||
|
||||
this._fsQuad = new FullScreenQuad( this.material );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs the shader pass.
|
||||
*
|
||||
* @param {WebGLRenderer} renderer - The renderer.
|
||||
* @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
|
||||
* destination for the pass.
|
||||
* @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
|
||||
* previous pass from this buffer.
|
||||
* @param {number} deltaTime - The delta time in seconds.
|
||||
* @param {boolean} maskActive - Whether masking is active or not.
|
||||
*/
|
||||
render( renderer, writeBuffer, readBuffer /*, deltaTime, maskActive */ ) {
|
||||
|
||||
if ( this.uniforms[ this.textureID ] ) {
|
||||
|
||||
this.uniforms[ this.textureID ].value = readBuffer.texture;
|
||||
|
||||
}
|
||||
|
||||
this._fsQuad.material = this.material;
|
||||
|
||||
if ( this.renderToScreen ) {
|
||||
|
||||
renderer.setRenderTarget( null );
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
} else {
|
||||
|
||||
renderer.setRenderTarget( writeBuffer );
|
||||
// TODO: Avoid using autoClear properties, see https://github.com/mrdoob/three.js/pull/15571#issuecomment-465669600
|
||||
if ( this.clear ) renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Frees the GPU-related resources allocated by this instance. Call this
|
||||
* method whenever the pass is no longer used in your app.
|
||||
*/
|
||||
dispose() {
|
||||
|
||||
this.material.dispose();
|
||||
|
||||
this._fsQuad.dispose();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export { ShaderPass };
|
||||
@@ -0,0 +1,243 @@
|
||||
import {
|
||||
HalfFloatType,
|
||||
WebGLRenderTarget
|
||||
} from 'three';
|
||||
import { SSAARenderPass } from './SSAARenderPass.js';
|
||||
|
||||
/**
|
||||
*
|
||||
* Temporal Anti-Aliasing Render Pass.
|
||||
*
|
||||
* When there is no motion in the scene, the TAA render pass accumulates jittered camera
|
||||
* samples across frames to create a high quality anti-aliased result.
|
||||
*
|
||||
* Note: This effect uses no reprojection so it is no TRAA implementation.
|
||||
*
|
||||
* ```js
|
||||
* const taaRenderPass = new TAARenderPass( scene, camera );
|
||||
* taaRenderPass.unbiased = false;
|
||||
* composer.addPass( taaRenderPass );
|
||||
* ```
|
||||
*
|
||||
* @augments SSAARenderPass
|
||||
* @three_import import { TAARenderPass } from 'three/addons/postprocessing/TAARenderPass.js';
|
||||
*/
|
||||
class TAARenderPass extends SSAARenderPass {
|
||||
|
||||
/**
|
||||
* Constructs a new TAA render pass.
|
||||
*
|
||||
* @param {Scene} scene - The scene to render.
|
||||
* @param {Camera} camera - The camera.
|
||||
* @param {?(number|Color|string)} [clearColor=0x000000] - The clear color of the render pass.
|
||||
* @param {?number} [clearAlpha=0] - The clear alpha of the render pass.
|
||||
*/
|
||||
constructor( scene, camera, clearColor, clearAlpha ) {
|
||||
|
||||
super( scene, camera, clearColor, clearAlpha );
|
||||
|
||||
/**
|
||||
* Overwritten and set to 0 by default.
|
||||
*
|
||||
* @type {number}
|
||||
* @default 0
|
||||
*/
|
||||
this.sampleLevel = 0;
|
||||
|
||||
/**
|
||||
* Whether to accumulate frames or not. This enables
|
||||
* the TAA.
|
||||
*
|
||||
* @type {boolean}
|
||||
* @default false
|
||||
*/
|
||||
this.accumulate = false;
|
||||
|
||||
/**
|
||||
* The accumulation index.
|
||||
*
|
||||
* @type {number}
|
||||
* @default -1
|
||||
*/
|
||||
this.accumulateIndex = - 1;
|
||||
|
||||
// internals
|
||||
|
||||
this._sampleRenderTarget = null;
|
||||
this._holdRenderTarget = null;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs the TAA render pass.
|
||||
*
|
||||
* @param {WebGLRenderer} renderer - The renderer.
|
||||
* @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
|
||||
* destination for the pass.
|
||||
* @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
|
||||
* previous pass from this buffer.
|
||||
* @param {number} deltaTime - The delta time in seconds.
|
||||
* @param {boolean} maskActive - Whether masking is active or not.
|
||||
*/
|
||||
render( renderer, writeBuffer, readBuffer, deltaTime/*, maskActive*/ ) {
|
||||
|
||||
if ( this.accumulate === false ) {
|
||||
|
||||
super.render( renderer, writeBuffer, readBuffer, deltaTime );
|
||||
|
||||
this.accumulateIndex = - 1;
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
const jitterOffsets = _JitterVectors[ 5 ];
|
||||
|
||||
if ( this._sampleRenderTarget === null ) {
|
||||
|
||||
this._sampleRenderTarget = new WebGLRenderTarget( readBuffer.width, readBuffer.height, { type: HalfFloatType } );
|
||||
this._sampleRenderTarget.texture.name = 'TAARenderPass.sample';
|
||||
|
||||
}
|
||||
|
||||
if ( this._holdRenderTarget === null ) {
|
||||
|
||||
this._holdRenderTarget = new WebGLRenderTarget( readBuffer.width, readBuffer.height, { type: HalfFloatType, depthBuffer: false } );
|
||||
this._holdRenderTarget.texture.name = 'TAARenderPass.hold';
|
||||
|
||||
}
|
||||
|
||||
if ( this.accumulateIndex === - 1 ) {
|
||||
|
||||
super.render( renderer, this._holdRenderTarget, readBuffer, deltaTime );
|
||||
|
||||
this.accumulateIndex = 0;
|
||||
|
||||
}
|
||||
|
||||
const autoClear = renderer.autoClear;
|
||||
renderer.autoClear = false;
|
||||
|
||||
renderer.getClearColor( this._oldClearColor );
|
||||
const oldClearAlpha = renderer.getClearAlpha();
|
||||
|
||||
const sampleWeight = 1.0 / ( jitterOffsets.length );
|
||||
|
||||
if ( this.accumulateIndex >= 0 && this.accumulateIndex < jitterOffsets.length ) {
|
||||
|
||||
this._copyUniforms[ 'opacity' ].value = sampleWeight;
|
||||
this._copyUniforms[ 'tDiffuse' ].value = writeBuffer.texture;
|
||||
|
||||
// render the scene multiple times, each slightly jitter offset from the last and accumulate the results.
|
||||
const numSamplesPerFrame = Math.pow( 2, this.sampleLevel );
|
||||
for ( let i = 0; i < numSamplesPerFrame; i ++ ) {
|
||||
|
||||
const j = this.accumulateIndex;
|
||||
const jitterOffset = jitterOffsets[ j ];
|
||||
|
||||
if ( this.camera.setViewOffset ) {
|
||||
|
||||
this.camera.setViewOffset( readBuffer.width, readBuffer.height,
|
||||
jitterOffset[ 0 ] * 0.0625, jitterOffset[ 1 ] * 0.0625, // 0.0625 = 1 / 16
|
||||
readBuffer.width, readBuffer.height );
|
||||
|
||||
}
|
||||
|
||||
renderer.setRenderTarget( writeBuffer );
|
||||
renderer.setClearColor( this.clearColor, this.clearAlpha );
|
||||
renderer.clear();
|
||||
renderer.render( this.scene, this.camera );
|
||||
|
||||
renderer.setRenderTarget( this._sampleRenderTarget );
|
||||
if ( this.accumulateIndex === 0 ) {
|
||||
|
||||
renderer.setClearColor( 0x000000, 0.0 );
|
||||
renderer.clear();
|
||||
|
||||
}
|
||||
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
this.accumulateIndex ++;
|
||||
|
||||
if ( this.accumulateIndex >= jitterOffsets.length ) break;
|
||||
|
||||
}
|
||||
|
||||
if ( this.camera.clearViewOffset ) this.camera.clearViewOffset();
|
||||
|
||||
}
|
||||
|
||||
renderer.setClearColor( this.clearColor, this.clearAlpha );
|
||||
const accumulationWeight = this.accumulateIndex * sampleWeight;
|
||||
|
||||
if ( accumulationWeight > 0 ) {
|
||||
|
||||
this._copyUniforms[ 'opacity' ].value = 1.0;
|
||||
this._copyUniforms[ 'tDiffuse' ].value = this._sampleRenderTarget.texture;
|
||||
renderer.setRenderTarget( writeBuffer );
|
||||
renderer.clear();
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
}
|
||||
|
||||
if ( accumulationWeight < 1.0 ) {
|
||||
|
||||
this._copyUniforms[ 'opacity' ].value = 1.0 - accumulationWeight;
|
||||
this._copyUniforms[ 'tDiffuse' ].value = this._holdRenderTarget.texture;
|
||||
renderer.setRenderTarget( writeBuffer );
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
}
|
||||
|
||||
renderer.autoClear = autoClear;
|
||||
renderer.setClearColor( this._oldClearColor, oldClearAlpha );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Frees the GPU-related resources allocated by this instance. Call this
|
||||
* method whenever the pass is no longer used in your app.
|
||||
*/
|
||||
dispose() {
|
||||
|
||||
super.dispose();
|
||||
|
||||
if ( this._holdRenderTarget ) this._holdRenderTarget.dispose();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
const _JitterVectors = [
|
||||
[
|
||||
[ 0, 0 ]
|
||||
],
|
||||
[
|
||||
[ 4, 4 ], [ - 4, - 4 ]
|
||||
],
|
||||
[
|
||||
[ - 2, - 6 ], [ 6, - 2 ], [ - 6, 2 ], [ 2, 6 ]
|
||||
],
|
||||
[
|
||||
[ 1, - 3 ], [ - 1, 3 ], [ 5, 1 ], [ - 3, - 5 ],
|
||||
[ - 5, 5 ], [ - 7, - 1 ], [ 3, 7 ], [ 7, - 7 ]
|
||||
],
|
||||
[
|
||||
[ 1, 1 ], [ - 1, - 3 ], [ - 3, 2 ], [ 4, - 1 ],
|
||||
[ - 5, - 2 ], [ 2, 5 ], [ 5, 3 ], [ 3, - 5 ],
|
||||
[ - 2, 6 ], [ 0, - 7 ], [ - 4, - 6 ], [ - 6, 4 ],
|
||||
[ - 8, 0 ], [ 7, - 4 ], [ 6, 7 ], [ - 7, - 8 ]
|
||||
],
|
||||
[
|
||||
[ - 4, - 7 ], [ - 7, - 5 ], [ - 3, - 5 ], [ - 5, - 4 ],
|
||||
[ - 1, - 4 ], [ - 2, - 2 ], [ - 6, - 1 ], [ - 4, 0 ],
|
||||
[ - 7, 1 ], [ - 1, 2 ], [ - 6, 3 ], [ - 3, 3 ],
|
||||
[ - 7, 6 ], [ - 3, 6 ], [ - 5, 7 ], [ - 1, 7 ],
|
||||
[ 5, - 7 ], [ 1, - 6 ], [ 6, - 5 ], [ 4, - 4 ],
|
||||
[ 2, - 3 ], [ 7, - 2 ], [ 1, - 1 ], [ 4, - 1 ],
|
||||
[ 2, 1 ], [ 6, 2 ], [ 0, 4 ], [ 4, 4 ],
|
||||
[ 2, 5 ], [ 7, 5 ], [ 5, 6 ], [ 3, 7 ]
|
||||
]
|
||||
];
|
||||
|
||||
export { TAARenderPass };
|
||||
@@ -0,0 +1,131 @@
|
||||
import {
|
||||
ShaderMaterial,
|
||||
UniformsUtils
|
||||
} from 'three';
|
||||
import { Pass, FullScreenQuad } from './Pass.js';
|
||||
import { CopyShader } from '../shaders/CopyShader.js';
|
||||
|
||||
/**
|
||||
* This pass can be used to render a texture over the entire screen.
|
||||
*
|
||||
* ```js
|
||||
* const texture = new THREE.TextureLoader().load( 'textures/2294472375_24a3b8ef46_o.jpg' );
|
||||
* texture.colorSpace = THREE.SRGBColorSpace;
|
||||
*
|
||||
* const texturePass = new TexturePass( texture );
|
||||
* composer.addPass( texturePass );
|
||||
* ```
|
||||
*
|
||||
* @augments Pass
|
||||
* @three_import import { TexturePass } from 'three/addons/postprocessing/TexturePass.js';
|
||||
*/
|
||||
class TexturePass extends Pass {
|
||||
|
||||
/**
|
||||
* Constructs a new texture pass.
|
||||
*
|
||||
* @param {Texture} map - The texture to render.
|
||||
* @param {number} [opacity=1] - The opacity.
|
||||
*/
|
||||
constructor( map, opacity = 1 ) {
|
||||
|
||||
super();
|
||||
|
||||
const shader = CopyShader;
|
||||
|
||||
/**
|
||||
* The texture to render.
|
||||
*
|
||||
* @type {Texture}
|
||||
*/
|
||||
this.map = map;
|
||||
|
||||
/**
|
||||
* The opacity.
|
||||
*
|
||||
* @type {number}
|
||||
* @default 1
|
||||
*/
|
||||
this.opacity = opacity;
|
||||
|
||||
/**
|
||||
* Overwritten to disable the swap.
|
||||
*
|
||||
* @type {boolean}
|
||||
* @default false
|
||||
*/
|
||||
this.needsSwap = false;
|
||||
|
||||
/**
|
||||
* The pass uniforms.
|
||||
*
|
||||
* @type {Object}
|
||||
*/
|
||||
this.uniforms = UniformsUtils.clone( shader.uniforms );
|
||||
|
||||
/**
|
||||
* The pass material.
|
||||
*
|
||||
* @type {ShaderMaterial}
|
||||
*/
|
||||
this.material = new ShaderMaterial( {
|
||||
|
||||
uniforms: this.uniforms,
|
||||
vertexShader: shader.vertexShader,
|
||||
fragmentShader: shader.fragmentShader,
|
||||
depthTest: false,
|
||||
depthWrite: false,
|
||||
premultipliedAlpha: true
|
||||
|
||||
} );
|
||||
|
||||
// internals
|
||||
|
||||
this._fsQuad = new FullScreenQuad( null );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs the texture pass.
|
||||
*
|
||||
* @param {WebGLRenderer} renderer - The renderer.
|
||||
* @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
|
||||
* destination for the pass.
|
||||
* @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
|
||||
* previous pass from this buffer.
|
||||
* @param {number} deltaTime - The delta time in seconds.
|
||||
* @param {boolean} maskActive - Whether masking is active or not.
|
||||
*/
|
||||
render( renderer, writeBuffer, readBuffer /*, deltaTime, maskActive */ ) {
|
||||
|
||||
const oldAutoClear = renderer.autoClear;
|
||||
renderer.autoClear = false;
|
||||
|
||||
this._fsQuad.material = this.material;
|
||||
|
||||
this.uniforms[ 'opacity' ].value = this.opacity;
|
||||
this.uniforms[ 'tDiffuse' ].value = this.map;
|
||||
this.material.transparent = ( this.opacity < 1.0 );
|
||||
|
||||
renderer.setRenderTarget( this.renderToScreen ? null : readBuffer );
|
||||
if ( this.clear ) renderer.clear();
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
renderer.autoClear = oldAutoClear;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Frees the GPU-related resources allocated by this instance. Call this
|
||||
* method whenever the pass is no longer used in your app.
|
||||
*/
|
||||
dispose() {
|
||||
|
||||
this.material.dispose();
|
||||
this._fsQuad.dispose();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export { TexturePass };
|
||||
@@ -0,0 +1,541 @@
|
||||
import {
|
||||
AdditiveBlending,
|
||||
Color,
|
||||
HalfFloatType,
|
||||
MeshBasicMaterial,
|
||||
ShaderMaterial,
|
||||
UniformsUtils,
|
||||
Vector2,
|
||||
Vector3,
|
||||
WebGLRenderTarget
|
||||
} from 'three';
|
||||
import { Pass, FullScreenQuad } from './Pass.js';
|
||||
import { CopyShader } from '../shaders/CopyShader.js';
|
||||
import { LuminosityHighPassShader } from '../shaders/LuminosityHighPassShader.js';
|
||||
|
||||
/**
|
||||
* This pass is inspired by the bloom pass of Unreal Engine. It creates a
|
||||
* mip map chain of bloom textures and blurs them with different radii. Because
|
||||
* of the weighted combination of mips, and because larger blurs are done on
|
||||
* higher mips, this effect provides good quality and performance.
|
||||
*
|
||||
* When using this pass, tone mapping must be enabled in the renderer settings.
|
||||
*
|
||||
* Reference:
|
||||
* - [Bloom in Unreal Engine](https://docs.unrealengine.com/latest/INT/Engine/Rendering/PostProcessEffects/Bloom/)
|
||||
*
|
||||
* ```js
|
||||
* const resolution = new THREE.Vector2( window.innerWidth, window.innerHeight );
|
||||
* const bloomPass = new UnrealBloomPass( resolution, 1.5, 0.4, 0.85 );
|
||||
* composer.addPass( bloomPass );
|
||||
* ```
|
||||
*
|
||||
* @augments Pass
|
||||
* @three_import import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
|
||||
*/
|
||||
class UnrealBloomPass extends Pass {
|
||||
|
||||
/**
|
||||
* Constructs a new Unreal Bloom pass.
|
||||
*
|
||||
* @param {Vector2} [resolution] - The effect's resolution.
|
||||
* @param {number} [strength=1] - The Bloom strength.
|
||||
* @param {number} radius - The Bloom radius.
|
||||
* @param {number} threshold - The luminance threshold limits which bright areas contribute to the Bloom effect.
|
||||
*/
|
||||
constructor( resolution, strength = 1, radius, threshold ) {
|
||||
|
||||
super();
|
||||
|
||||
/**
|
||||
* The Bloom strength.
|
||||
*
|
||||
* @type {number}
|
||||
* @default 1
|
||||
*/
|
||||
this.strength = strength;
|
||||
|
||||
/**
|
||||
* The Bloom radius. Must be in the range `[0,1]`.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
this.radius = radius;
|
||||
|
||||
/**
|
||||
* The luminance threshold limits which bright areas contribute to the Bloom effect.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
this.threshold = threshold;
|
||||
|
||||
/**
|
||||
* The effect's resolution.
|
||||
*
|
||||
* @type {Vector2}
|
||||
* @default (256,256)
|
||||
*/
|
||||
this.resolution = ( resolution !== undefined ) ? new Vector2( resolution.x, resolution.y ) : new Vector2( 256, 256 );
|
||||
|
||||
/**
|
||||
* The effect's clear color
|
||||
*
|
||||
* @type {Color}
|
||||
* @default (0,0,0)
|
||||
*/
|
||||
this.clearColor = new Color( 0, 0, 0 );
|
||||
|
||||
/**
|
||||
* Overwritten to disable the swap.
|
||||
*
|
||||
* @type {boolean}
|
||||
* @default false
|
||||
*/
|
||||
this.needsSwap = false;
|
||||
|
||||
// internals
|
||||
|
||||
// render targets
|
||||
this.renderTargetsHorizontal = [];
|
||||
this.renderTargetsVertical = [];
|
||||
this.nMips = 5;
|
||||
let resx = Math.round( this.resolution.x / 2 );
|
||||
let resy = Math.round( this.resolution.y / 2 );
|
||||
|
||||
this.renderTargetBright = new WebGLRenderTarget( resx, resy, { type: HalfFloatType, depthBuffer: false } );
|
||||
this.renderTargetBright.texture.name = 'UnrealBloomPass.bright';
|
||||
this.renderTargetBright.texture.generateMipmaps = false;
|
||||
|
||||
for ( let i = 0; i < this.nMips; i ++ ) {
|
||||
|
||||
const renderTargetHorizontal = new WebGLRenderTarget( resx, resy, { type: HalfFloatType, depthBuffer: false } );
|
||||
|
||||
renderTargetHorizontal.texture.name = 'UnrealBloomPass.h' + i;
|
||||
renderTargetHorizontal.texture.generateMipmaps = false;
|
||||
|
||||
this.renderTargetsHorizontal.push( renderTargetHorizontal );
|
||||
|
||||
const renderTargetVertical = new WebGLRenderTarget( resx, resy, { type: HalfFloatType, depthBuffer: false } );
|
||||
|
||||
renderTargetVertical.texture.name = 'UnrealBloomPass.v' + i;
|
||||
renderTargetVertical.texture.generateMipmaps = false;
|
||||
|
||||
this.renderTargetsVertical.push( renderTargetVertical );
|
||||
|
||||
resx = Math.round( resx / 2 );
|
||||
|
||||
resy = Math.round( resy / 2 );
|
||||
|
||||
}
|
||||
|
||||
// luminosity high pass material
|
||||
|
||||
const highPassShader = LuminosityHighPassShader;
|
||||
this.highPassUniforms = UniformsUtils.clone( highPassShader.uniforms );
|
||||
|
||||
this.highPassUniforms[ 'luminosityThreshold' ].value = threshold;
|
||||
this.highPassUniforms[ 'smoothWidth' ].value = 0.01;
|
||||
|
||||
this.materialHighPassFilter = new ShaderMaterial( {
|
||||
uniforms: this.highPassUniforms,
|
||||
vertexShader: highPassShader.vertexShader,
|
||||
fragmentShader: highPassShader.fragmentShader
|
||||
} );
|
||||
|
||||
// gaussian blur materials
|
||||
|
||||
this.separableBlurMaterials = [];
|
||||
// These sizes have been changed to account for the altered coefficients-calculation to avoid blockiness,
|
||||
// while retaining the same blur-strength. For details see https://github.com/mrdoob/three.js/pull/31528
|
||||
const kernelSizeArray = [ 6, 10, 14, 18, 22 ];
|
||||
resx = Math.round( this.resolution.x / 2 );
|
||||
resy = Math.round( this.resolution.y / 2 );
|
||||
|
||||
for ( let i = 0; i < this.nMips; i ++ ) {
|
||||
|
||||
this.separableBlurMaterials.push( this._getSeparableBlurMaterial( kernelSizeArray[ i ] ) );
|
||||
|
||||
this.separableBlurMaterials[ i ].uniforms[ 'invSize' ].value = new Vector2( 1 / resx, 1 / resy );
|
||||
|
||||
resx = Math.round( resx / 2 );
|
||||
|
||||
resy = Math.round( resy / 2 );
|
||||
|
||||
}
|
||||
|
||||
// composite material
|
||||
|
||||
this.compositeMaterial = this._getCompositeMaterial( this.nMips );
|
||||
this.compositeMaterial.uniforms[ 'blurTexture1' ].value = this.renderTargetsVertical[ 0 ].texture;
|
||||
this.compositeMaterial.uniforms[ 'blurTexture2' ].value = this.renderTargetsVertical[ 1 ].texture;
|
||||
this.compositeMaterial.uniforms[ 'blurTexture3' ].value = this.renderTargetsVertical[ 2 ].texture;
|
||||
this.compositeMaterial.uniforms[ 'blurTexture4' ].value = this.renderTargetsVertical[ 3 ].texture;
|
||||
this.compositeMaterial.uniforms[ 'blurTexture5' ].value = this.renderTargetsVertical[ 4 ].texture;
|
||||
this.compositeMaterial.uniforms[ 'bloomStrength' ].value = strength;
|
||||
this.compositeMaterial.uniforms[ 'bloomRadius' ].value = 0.1;
|
||||
|
||||
const bloomFactors = [ 1.0, 0.8, 0.6, 0.4, 0.2 ];
|
||||
this.compositeMaterial.uniforms[ 'bloomFactors' ].value = bloomFactors;
|
||||
this.bloomTintColors = [ new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ) ];
|
||||
this.compositeMaterial.uniforms[ 'bloomTintColors' ].value = this.bloomTintColors;
|
||||
|
||||
// blend material
|
||||
|
||||
this.copyUniforms = UniformsUtils.clone( CopyShader.uniforms );
|
||||
|
||||
this.blendMaterial = new ShaderMaterial( {
|
||||
uniforms: this.copyUniforms,
|
||||
vertexShader: CopyShader.vertexShader,
|
||||
fragmentShader: CopyShader.fragmentShader,
|
||||
premultipliedAlpha: true,
|
||||
blending: AdditiveBlending,
|
||||
depthTest: false,
|
||||
depthWrite: false,
|
||||
transparent: true
|
||||
} );
|
||||
|
||||
this._oldClearColor = new Color();
|
||||
this._oldClearAlpha = 1;
|
||||
|
||||
this._basic = new MeshBasicMaterial();
|
||||
|
||||
this._fsQuad = new FullScreenQuad( null );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Frees the GPU-related resources allocated by this instance. Call this
|
||||
* method whenever the pass is no longer used in your app.
|
||||
*/
|
||||
dispose() {
|
||||
|
||||
for ( let i = 0; i < this.renderTargetsHorizontal.length; i ++ ) {
|
||||
|
||||
this.renderTargetsHorizontal[ i ].dispose();
|
||||
|
||||
}
|
||||
|
||||
for ( let i = 0; i < this.renderTargetsVertical.length; i ++ ) {
|
||||
|
||||
this.renderTargetsVertical[ i ].dispose();
|
||||
|
||||
}
|
||||
|
||||
this.renderTargetBright.dispose();
|
||||
|
||||
//
|
||||
|
||||
for ( let i = 0; i < this.separableBlurMaterials.length; i ++ ) {
|
||||
|
||||
this.separableBlurMaterials[ i ].dispose();
|
||||
|
||||
}
|
||||
|
||||
this.compositeMaterial.dispose();
|
||||
this.blendMaterial.dispose();
|
||||
this._basic.dispose();
|
||||
|
||||
//
|
||||
|
||||
this._fsQuad.dispose();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the size of the pass.
|
||||
*
|
||||
* @param {number} width - The width to set.
|
||||
* @param {number} height - The height to set.
|
||||
*/
|
||||
setSize( width, height ) {
|
||||
|
||||
let resx = Math.round( width / 2 );
|
||||
let resy = Math.round( height / 2 );
|
||||
|
||||
this.renderTargetBright.setSize( resx, resy );
|
||||
|
||||
for ( let i = 0; i < this.nMips; i ++ ) {
|
||||
|
||||
this.renderTargetsHorizontal[ i ].setSize( resx, resy );
|
||||
this.renderTargetsVertical[ i ].setSize( resx, resy );
|
||||
|
||||
this.separableBlurMaterials[ i ].uniforms[ 'invSize' ].value = new Vector2( 1 / resx, 1 / resy );
|
||||
|
||||
resx = Math.round( resx / 2 );
|
||||
resy = Math.round( resy / 2 );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs the Bloom pass.
|
||||
*
|
||||
* @param {WebGLRenderer} renderer - The renderer.
|
||||
* @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
|
||||
* destination for the pass.
|
||||
* @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
|
||||
* previous pass from this buffer.
|
||||
* @param {number} deltaTime - The delta time in seconds.
|
||||
* @param {boolean} maskActive - Whether masking is active or not.
|
||||
*/
|
||||
render( renderer, writeBuffer, readBuffer, deltaTime, maskActive ) {
|
||||
|
||||
renderer.getClearColor( this._oldClearColor );
|
||||
this._oldClearAlpha = renderer.getClearAlpha();
|
||||
const oldAutoClear = renderer.autoClear;
|
||||
renderer.autoClear = false;
|
||||
|
||||
renderer.setClearColor( this.clearColor, 0 );
|
||||
|
||||
if ( maskActive ) renderer.state.buffers.stencil.setTest( false );
|
||||
|
||||
// Render input to screen
|
||||
|
||||
if ( this.renderToScreen ) {
|
||||
|
||||
this._fsQuad.material = this._basic;
|
||||
this._basic.map = readBuffer.texture;
|
||||
|
||||
renderer.setRenderTarget( null );
|
||||
renderer.clear();
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
}
|
||||
|
||||
// 1. Extract Bright Areas
|
||||
|
||||
this.highPassUniforms[ 'tDiffuse' ].value = readBuffer.texture;
|
||||
this.highPassUniforms[ 'luminosityThreshold' ].value = this.threshold;
|
||||
this._fsQuad.material = this.materialHighPassFilter;
|
||||
|
||||
renderer.setRenderTarget( this.renderTargetBright );
|
||||
renderer.clear();
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
// 2. Blur All the mips progressively
|
||||
|
||||
let inputRenderTarget = this.renderTargetBright;
|
||||
|
||||
for ( let i = 0; i < this.nMips; i ++ ) {
|
||||
|
||||
this._fsQuad.material = this.separableBlurMaterials[ i ];
|
||||
|
||||
this.separableBlurMaterials[ i ].uniforms[ 'colorTexture' ].value = inputRenderTarget.texture;
|
||||
this.separableBlurMaterials[ i ].uniforms[ 'direction' ].value = UnrealBloomPass.BlurDirectionX;
|
||||
renderer.setRenderTarget( this.renderTargetsHorizontal[ i ] );
|
||||
renderer.clear();
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
this.separableBlurMaterials[ i ].uniforms[ 'colorTexture' ].value = this.renderTargetsHorizontal[ i ].texture;
|
||||
this.separableBlurMaterials[ i ].uniforms[ 'direction' ].value = UnrealBloomPass.BlurDirectionY;
|
||||
renderer.setRenderTarget( this.renderTargetsVertical[ i ] );
|
||||
renderer.clear();
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
inputRenderTarget = this.renderTargetsVertical[ i ];
|
||||
|
||||
}
|
||||
|
||||
// Composite All the mips
|
||||
|
||||
this._fsQuad.material = this.compositeMaterial;
|
||||
this.compositeMaterial.uniforms[ 'bloomStrength' ].value = this.strength;
|
||||
this.compositeMaterial.uniforms[ 'bloomRadius' ].value = this.radius;
|
||||
this.compositeMaterial.uniforms[ 'bloomTintColors' ].value = this.bloomTintColors;
|
||||
|
||||
renderer.setRenderTarget( this.renderTargetsHorizontal[ 0 ] );
|
||||
renderer.clear();
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
// Blend it additively over the input texture
|
||||
|
||||
this._fsQuad.material = this.blendMaterial;
|
||||
this.copyUniforms[ 'tDiffuse' ].value = this.renderTargetsHorizontal[ 0 ].texture;
|
||||
|
||||
if ( maskActive ) renderer.state.buffers.stencil.setTest( true );
|
||||
|
||||
if ( this.renderToScreen ) {
|
||||
|
||||
renderer.setRenderTarget( null );
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
} else {
|
||||
|
||||
renderer.setRenderTarget( readBuffer );
|
||||
this._fsQuad.render( renderer );
|
||||
|
||||
}
|
||||
|
||||
// Restore renderer settings
|
||||
|
||||
renderer.setClearColor( this._oldClearColor, this._oldClearAlpha );
|
||||
renderer.autoClear = oldAutoClear;
|
||||
|
||||
}
|
||||
|
||||
// internals
|
||||
|
||||
_getSeparableBlurMaterial( kernelRadius ) {
|
||||
|
||||
const coefficients = [];
|
||||
const sigma = kernelRadius / 3;
|
||||
|
||||
for ( let i = 0; i < kernelRadius; i ++ ) {
|
||||
|
||||
coefficients.push( 0.39894 * Math.exp( - 0.5 * i * i / ( sigma * sigma ) ) / sigma );
|
||||
|
||||
}
|
||||
|
||||
// merge adjacent taps into single bilinear fetches (linear sampling)
|
||||
|
||||
const offsets = [];
|
||||
const weights = [];
|
||||
|
||||
for ( let i = 1; i < kernelRadius; i += 2 ) {
|
||||
|
||||
const wa = coefficients[ i ];
|
||||
const wb = ( i + 1 < kernelRadius ) ? coefficients[ i + 1 ] : 0;
|
||||
const w = wa + wb;
|
||||
|
||||
offsets.push( ( i * wa + ( i + 1 ) * wb ) / w );
|
||||
weights.push( w );
|
||||
|
||||
}
|
||||
|
||||
return new ShaderMaterial( {
|
||||
|
||||
defines: {
|
||||
'KERNEL_PAIRS': offsets.length
|
||||
},
|
||||
|
||||
uniforms: {
|
||||
'colorTexture': { value: null },
|
||||
'invSize': { value: new Vector2( 0.5, 0.5 ) }, // inverse texture size
|
||||
'direction': { value: new Vector2( 0.5, 0.5 ) },
|
||||
'centerWeight': { value: coefficients[ 0 ] },
|
||||
'gaussianOffsets': { value: offsets },
|
||||
'gaussianWeights': { value: weights }
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
#include <common>
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
uniform sampler2D colorTexture;
|
||||
uniform vec2 invSize;
|
||||
uniform vec2 direction;
|
||||
uniform float centerWeight;
|
||||
uniform float gaussianOffsets[KERNEL_PAIRS];
|
||||
uniform float gaussianWeights[KERNEL_PAIRS];
|
||||
|
||||
void main() {
|
||||
|
||||
vec3 diffuseSum = texture2D( colorTexture, vUv ).rgb * centerWeight;
|
||||
|
||||
for ( int i = 0; i < KERNEL_PAIRS; i ++ ) {
|
||||
|
||||
vec2 uvOffset = direction * invSize * gaussianOffsets[ i ];
|
||||
vec3 sample1 = texture2D( colorTexture, vUv + uvOffset ).rgb;
|
||||
vec3 sample2 = texture2D( colorTexture, vUv - uvOffset ).rgb;
|
||||
diffuseSum += ( sample1 + sample2 ) * gaussianWeights[ i ];
|
||||
|
||||
}
|
||||
|
||||
gl_FragColor = vec4( diffuseSum, 1.0 );
|
||||
|
||||
}`
|
||||
} );
|
||||
|
||||
}
|
||||
|
||||
_getCompositeMaterial( nMips ) {
|
||||
|
||||
return new ShaderMaterial( {
|
||||
|
||||
defines: {
|
||||
'NUM_MIPS': nMips
|
||||
},
|
||||
|
||||
uniforms: {
|
||||
'blurTexture1': { value: null },
|
||||
'blurTexture2': { value: null },
|
||||
'blurTexture3': { value: null },
|
||||
'blurTexture4': { value: null },
|
||||
'blurTexture5': { value: null },
|
||||
'bloomStrength': { value: 1.0 },
|
||||
'bloomFactors': { value: null },
|
||||
'bloomTintColors': { value: null },
|
||||
'bloomRadius': { value: 0.0 }
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
uniform sampler2D blurTexture1;
|
||||
uniform sampler2D blurTexture2;
|
||||
uniform sampler2D blurTexture3;
|
||||
uniform sampler2D blurTexture4;
|
||||
uniform sampler2D blurTexture5;
|
||||
uniform float bloomStrength;
|
||||
uniform float bloomRadius;
|
||||
uniform float bloomFactors[NUM_MIPS];
|
||||
uniform vec3 bloomTintColors[NUM_MIPS];
|
||||
|
||||
float lerpBloomFactor( const in float factor ) {
|
||||
|
||||
float mirrorFactor = 1.2 - factor;
|
||||
return mix( factor, mirrorFactor, bloomRadius );
|
||||
|
||||
}
|
||||
|
||||
void main() {
|
||||
|
||||
// 3.0 for backwards compatibility with previous alpha-based intensity
|
||||
vec3 bloom = 3.0 * bloomStrength * (
|
||||
lerpBloomFactor( bloomFactors[ 0 ] ) * bloomTintColors[ 0 ] * texture2D( blurTexture1, vUv ).rgb +
|
||||
lerpBloomFactor( bloomFactors[ 1 ] ) * bloomTintColors[ 1 ] * texture2D( blurTexture2, vUv ).rgb +
|
||||
lerpBloomFactor( bloomFactors[ 2 ] ) * bloomTintColors[ 2 ] * texture2D( blurTexture3, vUv ).rgb +
|
||||
lerpBloomFactor( bloomFactors[ 3 ] ) * bloomTintColors[ 3 ] * texture2D( blurTexture4, vUv ).rgb +
|
||||
lerpBloomFactor( bloomFactors[ 4 ] ) * bloomTintColors[ 4 ] * texture2D( blurTexture5, vUv ).rgb
|
||||
);
|
||||
|
||||
float bloomAlpha = max( bloom.r, max( bloom.g, bloom.b ) );
|
||||
gl_FragColor = vec4( bloom, bloomAlpha );
|
||||
|
||||
}`
|
||||
} );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
UnrealBloomPass.BlurDirectionX = new Vector2( 1.0, 0.0 );
|
||||
UnrealBloomPass.BlurDirectionY = new Vector2( 0.0, 1.0 );
|
||||
|
||||
export { UnrealBloomPass };
|
||||
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
* @module ACESFilmicToneMappingShader
|
||||
* @three_import import { ACESFilmicToneMappingShader } from 'three/addons/shaders/ACESFilmicToneMappingShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* ACES Filmic Tone Mapping Shader by Stephen Hill.
|
||||
* Reference: [ltc_blit.fs](https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs)
|
||||
*
|
||||
* This implementation of ACES is modified to accommodate a brighter viewing environment.
|
||||
* The scale factor of 1/0.6 is subjective. See discussion in #19621.
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const ACESFilmicToneMappingShader = {
|
||||
|
||||
name: 'ACESFilmicToneMappingShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDiffuse': { value: null },
|
||||
'exposure': { value: 1.0 }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
#define saturate(a) clamp( a, 0.0, 1.0 )
|
||||
|
||||
uniform sampler2D tDiffuse;
|
||||
|
||||
uniform float exposure;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
vec3 RRTAndODTFit( vec3 v ) {
|
||||
|
||||
vec3 a = v * ( v + 0.0245786 ) - 0.000090537;
|
||||
vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;
|
||||
return a / b;
|
||||
|
||||
}
|
||||
|
||||
vec3 ACESFilmicToneMapping( vec3 color ) {
|
||||
|
||||
// sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
|
||||
const mat3 ACESInputMat = mat3(
|
||||
vec3( 0.59719, 0.07600, 0.02840 ), // transposed from source
|
||||
vec3( 0.35458, 0.90834, 0.13383 ),
|
||||
vec3( 0.04823, 0.01566, 0.83777 )
|
||||
);
|
||||
|
||||
// ODT_SAT => XYZ => D60_2_D65 => sRGB
|
||||
const mat3 ACESOutputMat = mat3(
|
||||
vec3( 1.60475, -0.10208, -0.00327 ), // transposed from source
|
||||
vec3( -0.53108, 1.10813, -0.07276 ),
|
||||
vec3( -0.07367, -0.00605, 1.07602 )
|
||||
);
|
||||
|
||||
color = ACESInputMat * color;
|
||||
|
||||
// Apply RRT and ODT
|
||||
color = RRTAndODTFit( color );
|
||||
|
||||
color = ACESOutputMat * color;
|
||||
|
||||
// Clamp to [0, 1]
|
||||
return saturate( color );
|
||||
|
||||
}
|
||||
|
||||
void main() {
|
||||
|
||||
vec4 tex = texture2D( tDiffuse, vUv );
|
||||
|
||||
tex.rgb *= exposure / 0.6; // pre-exposed, outside of the tone mapping function
|
||||
|
||||
gl_FragColor = vec4( ACESFilmicToneMapping( tex.rgb ), tex.a );
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { ACESFilmicToneMappingShader };
|
||||
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* @module AfterimageShader
|
||||
* @three_import import { AfterimageShader } from 'three/addons/shaders/AfterimageShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Inspired by [Three.js FBO motion trails](https://codepen.io/brunoimbrizi/pen/MoRJaN?page=1&).
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const AfterimageShader = {
|
||||
|
||||
name: 'AfterimageShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'damp': { value: 0.96 },
|
||||
'tOld': { value: null },
|
||||
'tNew': { value: null }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform float damp;
|
||||
|
||||
uniform sampler2D tOld;
|
||||
uniform sampler2D tNew;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
vec4 when_gt( vec4 x, float y ) {
|
||||
|
||||
return max( sign( x - y ), 0.0 );
|
||||
|
||||
}
|
||||
|
||||
void main() {
|
||||
|
||||
vec4 texelOld = texture2D( tOld, vUv );
|
||||
vec4 texelNew = texture2D( tNew, vUv );
|
||||
|
||||
texelOld *= damp * when_gt( texelOld, 0.1 );
|
||||
|
||||
gl_FragColor = max(texelNew, texelOld);
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { AfterimageShader };
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* @module BasicShader
|
||||
* @three_import import { BasicShader } from 'three/addons/shaders/BasicShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Simple shader for testing.
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const BasicShader = {
|
||||
|
||||
name: 'BasicShader',
|
||||
|
||||
uniforms: {},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
void main() {
|
||||
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
void main() {
|
||||
|
||||
gl_FragColor = vec4( 1.0, 0.0, 0.0, 0.5 );
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { BasicShader };
|
||||
@@ -0,0 +1,68 @@
|
||||
|
||||
/**
|
||||
* @module BleachBypassShader
|
||||
* @three_import import { BleachBypassShader } from 'three/addons/shaders/BleachBypassShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Bleach bypass shader [http://en.wikipedia.org/wiki/Bleach_bypass] based on
|
||||
* [Nvidia Shader library](http://developer.download.nvidia.com/shaderlibrary/webpages/shader_library.html#post_bleach_bypass).
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const BleachBypassShader = {
|
||||
|
||||
name: 'BleachBypassShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDiffuse': { value: null },
|
||||
'opacity': { value: 1.0 }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform float opacity;
|
||||
|
||||
uniform sampler2D tDiffuse;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vec4 base = texture2D( tDiffuse, vUv );
|
||||
|
||||
float lum = luminance( base.rgb );
|
||||
vec3 blend = vec3( lum );
|
||||
|
||||
float L = min( 1.0, max( 0.0, 10.0 * ( lum - 0.45 ) ) );
|
||||
|
||||
vec3 result1 = 2.0 * base.rgb * blend;
|
||||
vec3 result2 = 1.0 - 2.0 * ( 1.0 - blend ) * ( 1.0 - base.rgb );
|
||||
|
||||
vec3 newColor = mix( result1, result2, L );
|
||||
|
||||
float A2 = opacity * base.a;
|
||||
vec3 mixRGB = A2 * newColor.rgb;
|
||||
mixRGB += ( ( 1.0 - A2 ) * base.rgb );
|
||||
|
||||
gl_FragColor = vec4( mixRGB, base.a );
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { BleachBypassShader };
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* @module BlendShader
|
||||
* @three_import import { BlendShader } from 'three/addons/shaders/BlendShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Blends two textures.
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const BlendShader = {
|
||||
|
||||
name: 'BlendShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDiffuse1': { value: null },
|
||||
'tDiffuse2': { value: null },
|
||||
'mixRatio': { value: 0.5 },
|
||||
'opacity': { value: 1.0 }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform float opacity;
|
||||
uniform float mixRatio;
|
||||
|
||||
uniform sampler2D tDiffuse1;
|
||||
uniform sampler2D tDiffuse2;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vec4 texel1 = texture2D( tDiffuse1, vUv );
|
||||
vec4 texel2 = texture2D( tDiffuse2, vUv );
|
||||
gl_FragColor = opacity * mix( texel1, texel2, mixRatio );
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { BlendShader };
|
||||
@@ -0,0 +1,151 @@
|
||||
/**
|
||||
* @module BokehShader
|
||||
* @three_import import { BokehShader } from 'three/addons/shaders/BokehShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Depth-of-field shader with bokeh ported from
|
||||
* [GLSL shader by Martins Upitis](http://artmartinsh.blogspot.com/2010/02/glsl-lens-blur-filter-with-bokeh.html).
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const BokehShader = {
|
||||
|
||||
name: 'BokehShader',
|
||||
|
||||
defines: {
|
||||
'DEPTH_PACKING': 1,
|
||||
'PERSPECTIVE_CAMERA': 1,
|
||||
},
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tColor': { value: null },
|
||||
'tDepth': { value: null },
|
||||
'focus': { value: 1.0 },
|
||||
'aspect': { value: 1.0 },
|
||||
'aperture': { value: 0.025 },
|
||||
'maxblur': { value: 0.01 },
|
||||
'nearClip': { value: 1.0 },
|
||||
'farClip': { value: 1000.0 },
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
#include <common>
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
uniform sampler2D tColor;
|
||||
uniform sampler2D tDepth;
|
||||
|
||||
uniform float maxblur; // max blur amount
|
||||
uniform float aperture; // aperture - bigger values for shallower depth of field
|
||||
|
||||
uniform float nearClip;
|
||||
uniform float farClip;
|
||||
|
||||
uniform float focus;
|
||||
uniform float aspect;
|
||||
|
||||
#include <packing>
|
||||
|
||||
float getDepth( const in vec2 screenPosition ) {
|
||||
#if DEPTH_PACKING == 1
|
||||
return unpackRGBAToDepth( texture2D( tDepth, screenPosition ) );
|
||||
#else
|
||||
return texture2D( tDepth, screenPosition ).x;
|
||||
#endif
|
||||
}
|
||||
|
||||
float getViewZ( const in float depth ) {
|
||||
#if PERSPECTIVE_CAMERA == 1
|
||||
return perspectiveDepthToViewZ( depth, nearClip, farClip );
|
||||
#else
|
||||
return orthographicDepthToViewZ( depth, nearClip, farClip );
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
void main() {
|
||||
|
||||
vec2 aspectcorrect = vec2( 1.0, aspect );
|
||||
|
||||
float viewZ = getViewZ( getDepth( vUv ) );
|
||||
|
||||
float factor = ( focus + viewZ ); // viewZ is <= 0, so this is a difference equation
|
||||
|
||||
vec2 dofblur = vec2 ( clamp( factor * aperture, -maxblur, maxblur ) );
|
||||
|
||||
vec2 dofblur9 = dofblur * 0.9;
|
||||
vec2 dofblur7 = dofblur * 0.7;
|
||||
vec2 dofblur4 = dofblur * 0.4;
|
||||
|
||||
vec4 col = vec4( 0.0 );
|
||||
|
||||
col += texture2D( tColor, vUv.xy );
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( 0.0, 0.4 ) * aspectcorrect ) * dofblur );
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( 0.15, 0.37 ) * aspectcorrect ) * dofblur );
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( 0.29, 0.29 ) * aspectcorrect ) * dofblur );
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( -0.37, 0.15 ) * aspectcorrect ) * dofblur );
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( 0.40, 0.0 ) * aspectcorrect ) * dofblur );
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( 0.37, -0.15 ) * aspectcorrect ) * dofblur );
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( 0.29, -0.29 ) * aspectcorrect ) * dofblur );
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( -0.15, -0.37 ) * aspectcorrect ) * dofblur );
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( 0.0, -0.4 ) * aspectcorrect ) * dofblur );
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( -0.15, 0.37 ) * aspectcorrect ) * dofblur );
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( -0.29, 0.29 ) * aspectcorrect ) * dofblur );
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( 0.37, 0.15 ) * aspectcorrect ) * dofblur );
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( -0.4, 0.0 ) * aspectcorrect ) * dofblur );
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( -0.37, -0.15 ) * aspectcorrect ) * dofblur );
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( -0.29, -0.29 ) * aspectcorrect ) * dofblur );
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( 0.15, -0.37 ) * aspectcorrect ) * dofblur );
|
||||
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( 0.15, 0.37 ) * aspectcorrect ) * dofblur9 );
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( -0.37, 0.15 ) * aspectcorrect ) * dofblur9 );
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( 0.37, -0.15 ) * aspectcorrect ) * dofblur9 );
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( -0.15, -0.37 ) * aspectcorrect ) * dofblur9 );
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( -0.15, 0.37 ) * aspectcorrect ) * dofblur9 );
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( 0.37, 0.15 ) * aspectcorrect ) * dofblur9 );
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( -0.37, -0.15 ) * aspectcorrect ) * dofblur9 );
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( 0.15, -0.37 ) * aspectcorrect ) * dofblur9 );
|
||||
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( 0.29, 0.29 ) * aspectcorrect ) * dofblur7 );
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( 0.40, 0.0 ) * aspectcorrect ) * dofblur7 );
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( 0.29, -0.29 ) * aspectcorrect ) * dofblur7 );
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( 0.0, -0.4 ) * aspectcorrect ) * dofblur7 );
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( -0.29, 0.29 ) * aspectcorrect ) * dofblur7 );
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( -0.4, 0.0 ) * aspectcorrect ) * dofblur7 );
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( -0.29, -0.29 ) * aspectcorrect ) * dofblur7 );
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( 0.0, 0.4 ) * aspectcorrect ) * dofblur7 );
|
||||
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( 0.29, 0.29 ) * aspectcorrect ) * dofblur4 );
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( 0.4, 0.0 ) * aspectcorrect ) * dofblur4 );
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( 0.29, -0.29 ) * aspectcorrect ) * dofblur4 );
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( 0.0, -0.4 ) * aspectcorrect ) * dofblur4 );
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( -0.29, 0.29 ) * aspectcorrect ) * dofblur4 );
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( -0.4, 0.0 ) * aspectcorrect ) * dofblur4 );
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( -0.29, -0.29 ) * aspectcorrect ) * dofblur4 );
|
||||
col += texture2D( tColor, vUv.xy + ( vec2( 0.0, 0.4 ) * aspectcorrect ) * dofblur4 );
|
||||
|
||||
gl_FragColor = col / 41.0;
|
||||
gl_FragColor.a = 1.0;
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { BokehShader };
|
||||
@@ -0,0 +1,404 @@
|
||||
import {
|
||||
Vector2
|
||||
} from 'three';
|
||||
|
||||
/**
|
||||
* @module BokehShader2
|
||||
* @three_import import { BokehShader, BokehDepthShader } from 'three/addons/shaders/BokehShader2.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Depth-of-field shader with bokeh ported from
|
||||
* [GLSL shader by Martins Upitis](http://blenderartists.org/forum/showthread.php?237488-GLSL-depth-of-field-with-bokeh-v2-4-(update)).
|
||||
*
|
||||
* Requires #define RINGS and SAMPLES integers
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const BokehShader = {
|
||||
|
||||
name: 'BokehShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'textureWidth': { value: 1.0 },
|
||||
'textureHeight': { value: 1.0 },
|
||||
|
||||
'focalDepth': { value: 1.0 },
|
||||
'focalLength': { value: 24.0 },
|
||||
'fstop': { value: 0.9 },
|
||||
|
||||
'tColor': { value: null },
|
||||
'tDepth': { value: null },
|
||||
|
||||
'maxblur': { value: 1.0 },
|
||||
|
||||
'showFocus': { value: 0 },
|
||||
'manualdof': { value: 0 },
|
||||
'vignetting': { value: 0 },
|
||||
'depthblur': { value: 0 },
|
||||
|
||||
'threshold': { value: 0.5 },
|
||||
'gain': { value: 2.0 },
|
||||
'bias': { value: 0.5 },
|
||||
'fringe': { value: 0.7 },
|
||||
|
||||
'znear': { value: 0.1 },
|
||||
'zfar': { value: 100 },
|
||||
|
||||
'noise': { value: 1 },
|
||||
'dithering': { value: 0.0001 },
|
||||
'pentagon': { value: 0 },
|
||||
|
||||
'shaderFocus': { value: 1 },
|
||||
'focusCoords': { value: new Vector2() }
|
||||
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
#include <common>
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
uniform sampler2D tColor;
|
||||
uniform sampler2D tDepth;
|
||||
uniform float textureWidth;
|
||||
uniform float textureHeight;
|
||||
|
||||
uniform float focalDepth; //focal distance value in meters, but you may use autofocus option below
|
||||
uniform float focalLength; //focal length in mm
|
||||
uniform float fstop; //f-stop value
|
||||
uniform bool showFocus; //show debug focus point and focal range (red = focal point, green = focal range)
|
||||
|
||||
/*
|
||||
make sure that these two values are the same for your camera, otherwise distances will be wrong.
|
||||
*/
|
||||
|
||||
uniform float znear; // camera clipping start
|
||||
uniform float zfar; // camera clipping end
|
||||
|
||||
//------------------------------------------
|
||||
//user variables
|
||||
|
||||
const int samples = SAMPLES; //samples on the first ring
|
||||
const int rings = RINGS; //ring count
|
||||
|
||||
const int maxringsamples = rings * samples;
|
||||
|
||||
uniform bool manualdof; // manual dof calculation
|
||||
float ndofstart = 1.0; // near dof blur start
|
||||
float ndofdist = 2.0; // near dof blur falloff distance
|
||||
float fdofstart = 1.0; // far dof blur start
|
||||
float fdofdist = 3.0; // far dof blur falloff distance
|
||||
|
||||
float CoC = 0.03; //circle of confusion size in mm (35mm film = 0.03mm)
|
||||
|
||||
uniform bool vignetting; // use optical lens vignetting
|
||||
|
||||
float vignout = 1.3; // vignetting outer border
|
||||
float vignin = 0.0; // vignetting inner border
|
||||
float vignfade = 22.0; // f-stops till vignette fades
|
||||
|
||||
uniform bool shaderFocus;
|
||||
// disable if you use external focalDepth value
|
||||
|
||||
uniform vec2 focusCoords;
|
||||
// autofocus point on screen (0.0,0.0 - left lower corner, 1.0,1.0 - upper right)
|
||||
// if center of screen use vec2(0.5, 0.5);
|
||||
|
||||
uniform float maxblur;
|
||||
//clamp value of max blur (0.0 = no blur, 1.0 default)
|
||||
|
||||
uniform float threshold; // highlight threshold;
|
||||
uniform float gain; // highlight gain;
|
||||
|
||||
uniform float bias; // bokeh edge bias
|
||||
uniform float fringe; // bokeh chromatic aberration / fringing
|
||||
|
||||
uniform bool noise; //use noise instead of pattern for sample dithering
|
||||
|
||||
uniform float dithering;
|
||||
|
||||
uniform bool depthblur; // blur the depth buffer
|
||||
float dbsize = 1.25; // depth blur size
|
||||
|
||||
/*
|
||||
next part is experimental
|
||||
not looking good with small sample and ring count
|
||||
looks okay starting from samples = 4, rings = 4
|
||||
*/
|
||||
|
||||
uniform bool pentagon; //use pentagon as bokeh shape?
|
||||
float feather = 0.4; //pentagon shape feather
|
||||
|
||||
//------------------------------------------
|
||||
|
||||
float penta(vec2 coords) {
|
||||
//pentagonal shape
|
||||
float scale = float(rings) - 1.3;
|
||||
vec4 HS0 = vec4( 1.0, 0.0, 0.0, 1.0);
|
||||
vec4 HS1 = vec4( 0.309016994, 0.951056516, 0.0, 1.0);
|
||||
vec4 HS2 = vec4(-0.809016994, 0.587785252, 0.0, 1.0);
|
||||
vec4 HS3 = vec4(-0.809016994,-0.587785252, 0.0, 1.0);
|
||||
vec4 HS4 = vec4( 0.309016994,-0.951056516, 0.0, 1.0);
|
||||
vec4 HS5 = vec4( 0.0 ,0.0 , 1.0, 1.0);
|
||||
|
||||
vec4 one = vec4( 1.0 );
|
||||
|
||||
vec4 P = vec4((coords),vec2(scale, scale));
|
||||
|
||||
vec4 dist = vec4(0.0);
|
||||
float inorout = -4.0;
|
||||
|
||||
dist.x = dot( P, HS0 );
|
||||
dist.y = dot( P, HS1 );
|
||||
dist.z = dot( P, HS2 );
|
||||
dist.w = dot( P, HS3 );
|
||||
|
||||
dist = smoothstep( -feather, feather, dist );
|
||||
|
||||
inorout += dot( dist, one );
|
||||
|
||||
dist.x = dot( P, HS4 );
|
||||
dist.y = HS5.w - abs( P.z );
|
||||
|
||||
dist = smoothstep( -feather, feather, dist );
|
||||
inorout += dist.x;
|
||||
|
||||
return clamp( inorout, 0.0, 1.0 );
|
||||
}
|
||||
|
||||
float bdepth(vec2 coords) {
|
||||
// Depth buffer blur
|
||||
float d = 0.0;
|
||||
float kernel[9];
|
||||
vec2 offset[9];
|
||||
|
||||
vec2 wh = vec2(1.0/textureWidth,1.0/textureHeight) * dbsize;
|
||||
|
||||
offset[0] = vec2(-wh.x,-wh.y);
|
||||
offset[1] = vec2( 0.0, -wh.y);
|
||||
offset[2] = vec2( wh.x -wh.y);
|
||||
|
||||
offset[3] = vec2(-wh.x, 0.0);
|
||||
offset[4] = vec2( 0.0, 0.0);
|
||||
offset[5] = vec2( wh.x, 0.0);
|
||||
|
||||
offset[6] = vec2(-wh.x, wh.y);
|
||||
offset[7] = vec2( 0.0, wh.y);
|
||||
offset[8] = vec2( wh.x, wh.y);
|
||||
|
||||
kernel[0] = 1.0/16.0; kernel[1] = 2.0/16.0; kernel[2] = 1.0/16.0;
|
||||
kernel[3] = 2.0/16.0; kernel[4] = 4.0/16.0; kernel[5] = 2.0/16.0;
|
||||
kernel[6] = 1.0/16.0; kernel[7] = 2.0/16.0; kernel[8] = 1.0/16.0;
|
||||
|
||||
|
||||
for( int i=0; i<9; i++ ) {
|
||||
float tmp = texture2D(tDepth, coords + offset[i]).r;
|
||||
d += tmp * kernel[i];
|
||||
}
|
||||
|
||||
return d;
|
||||
}
|
||||
|
||||
|
||||
vec3 color(vec2 coords,float blur) {
|
||||
//processing the sample
|
||||
|
||||
vec3 col = vec3(0.0);
|
||||
vec2 texel = vec2(1.0/textureWidth,1.0/textureHeight);
|
||||
|
||||
col.r = texture2D(tColor,coords + vec2(0.0,1.0)*texel*fringe*blur).r;
|
||||
col.g = texture2D(tColor,coords + vec2(-0.866,-0.5)*texel*fringe*blur).g;
|
||||
col.b = texture2D(tColor,coords + vec2(0.866,-0.5)*texel*fringe*blur).b;
|
||||
|
||||
vec3 lumcoeff = vec3(0.299,0.587,0.114);
|
||||
float lum = dot(col.rgb, lumcoeff);
|
||||
float thresh = max((lum-threshold)*gain, 0.0);
|
||||
return col+mix(vec3(0.0),col,thresh*blur);
|
||||
}
|
||||
|
||||
vec3 debugFocus(vec3 col, float blur, float depth) {
|
||||
float edge = 0.002*depth; //distance based edge smoothing
|
||||
float m = clamp(smoothstep(0.0,edge,blur),0.0,1.0);
|
||||
float e = clamp(smoothstep(1.0-edge,1.0,blur),0.0,1.0);
|
||||
|
||||
col = mix(col,vec3(1.0,0.5,0.0),(1.0-m)*0.6);
|
||||
col = mix(col,vec3(0.0,0.5,1.0),((1.0-e)-(1.0-m))*0.2);
|
||||
|
||||
return col;
|
||||
}
|
||||
|
||||
float linearize(float depth) {
|
||||
return -zfar * znear / (depth * (zfar - znear) - zfar);
|
||||
}
|
||||
|
||||
float vignette() {
|
||||
float dist = distance(vUv.xy, vec2(0.5,0.5));
|
||||
dist = smoothstep(vignout+(fstop/vignfade), vignin+(fstop/vignfade), dist);
|
||||
return clamp(dist,0.0,1.0);
|
||||
}
|
||||
|
||||
float gather(float i, float j, int ringsamples, inout vec3 col, float w, float h, float blur) {
|
||||
float rings2 = float(rings);
|
||||
float step = PI*2.0 / float(ringsamples);
|
||||
float pw = cos(j*step)*i;
|
||||
float ph = sin(j*step)*i;
|
||||
float p = 1.0;
|
||||
if (pentagon) {
|
||||
p = penta(vec2(pw,ph));
|
||||
}
|
||||
col += color(vUv.xy + vec2(pw*w,ph*h), blur) * mix(1.0, i/rings2, bias) * p;
|
||||
return 1.0 * mix(1.0, i /rings2, bias) * p;
|
||||
}
|
||||
|
||||
void main() {
|
||||
//scene depth calculation
|
||||
|
||||
float depth = linearize(texture2D(tDepth,vUv.xy).x);
|
||||
|
||||
// Blur depth?
|
||||
if ( depthblur ) {
|
||||
depth = linearize(bdepth(vUv.xy));
|
||||
}
|
||||
|
||||
//focal plane calculation
|
||||
|
||||
float fDepth = focalDepth;
|
||||
|
||||
if (shaderFocus) {
|
||||
|
||||
fDepth = linearize(texture2D(tDepth,focusCoords).x);
|
||||
|
||||
}
|
||||
|
||||
// dof blur factor calculation
|
||||
|
||||
float blur = 0.0;
|
||||
|
||||
if (manualdof) {
|
||||
float a = depth-fDepth; // Focal plane
|
||||
float b = (a-fdofstart)/fdofdist; // Far DoF
|
||||
float c = (-a-ndofstart)/ndofdist; // Near Dof
|
||||
blur = (a>0.0) ? b : c;
|
||||
} else {
|
||||
float f = focalLength; // focal length in mm
|
||||
float d = fDepth*1000.0; // focal plane in mm
|
||||
float o = depth*1000.0; // depth in mm
|
||||
|
||||
float a = (o*f)/(o-f);
|
||||
float b = (d*f)/(d-f);
|
||||
float c = (d-f)/(d*fstop*CoC);
|
||||
|
||||
blur = abs(a-b)*c;
|
||||
}
|
||||
|
||||
blur = clamp(blur,0.0,1.0);
|
||||
|
||||
// calculation of pattern for dithering
|
||||
|
||||
vec2 noise = vec2(rand(vUv.xy), rand( vUv.xy + vec2( 0.4, 0.6 ) ) )*dithering*blur;
|
||||
|
||||
// getting blur x and y step factor
|
||||
|
||||
float w = (1.0/textureWidth)*blur*maxblur+noise.x;
|
||||
float h = (1.0/textureHeight)*blur*maxblur+noise.y;
|
||||
|
||||
// calculation of final color
|
||||
|
||||
vec3 col = vec3(0.0);
|
||||
|
||||
if(blur < 0.05) {
|
||||
//some optimization thingy
|
||||
col = texture2D(tColor, vUv.xy).rgb;
|
||||
} else {
|
||||
col = texture2D(tColor, vUv.xy).rgb;
|
||||
float s = 1.0;
|
||||
int ringsamples;
|
||||
|
||||
for (int i = 1; i <= rings; i++) {
|
||||
/*unboxstart*/
|
||||
ringsamples = i * samples;
|
||||
|
||||
for (int j = 0 ; j < maxringsamples ; j++) {
|
||||
if (j >= ringsamples) break;
|
||||
s += gather(float(i), float(j), ringsamples, col, w, h, blur);
|
||||
}
|
||||
/*unboxend*/
|
||||
}
|
||||
|
||||
col /= s; //divide by sample count
|
||||
}
|
||||
|
||||
if (showFocus) {
|
||||
col = debugFocus(col, blur, depth);
|
||||
}
|
||||
|
||||
if (vignetting) {
|
||||
col *= vignette();
|
||||
}
|
||||
|
||||
gl_FragColor.rgb = col;
|
||||
gl_FragColor.a = 1.0;
|
||||
|
||||
#include <tonemapping_fragment>
|
||||
#include <colorspace_fragment>
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
const BokehDepthShader = {
|
||||
|
||||
name: 'BokehDepthShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'mNear': { value: 1.0 },
|
||||
'mFar': { value: 1000.0 },
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying float vViewZDepth;
|
||||
|
||||
void main() {
|
||||
|
||||
#include <begin_vertex>
|
||||
#include <project_vertex>
|
||||
|
||||
vViewZDepth = - mvPosition.z;
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform float mNear;
|
||||
uniform float mFar;
|
||||
|
||||
varying float vViewZDepth;
|
||||
|
||||
void main() {
|
||||
|
||||
float color = 1.0 - smoothstep( mNear, mFar, vViewZDepth );
|
||||
gl_FragColor = vec4( vec3( color ), 1.0 );
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { BokehShader, BokehDepthShader };
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* @module BrightnessContrastShader
|
||||
* @three_import import { BrightnessContrastShader } from 'three/addons/shaders/BrightnessContrastShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Brightness and contrast adjustment {@link https://github.com/evanw/glfx.js}.
|
||||
* Brightness: -1 to 1 (-1 is solid black, 0 is no change, and 1 is solid white)
|
||||
* Contrast: -1 to 1 (-1 is solid gray, 0 is no change, and 1 is maximum contrast)
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const BrightnessContrastShader = {
|
||||
|
||||
name: 'BrightnessContrastShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDiffuse': { value: null },
|
||||
'brightness': { value: 0 },
|
||||
'contrast': { value: 0 }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform sampler2D tDiffuse;
|
||||
uniform float brightness;
|
||||
uniform float contrast;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
gl_FragColor = texture2D( tDiffuse, vUv );
|
||||
|
||||
gl_FragColor.rgb += brightness;
|
||||
|
||||
if (contrast > 0.0) {
|
||||
gl_FragColor.rgb = (gl_FragColor.rgb - 0.5) / (1.0 - contrast) + 0.5;
|
||||
} else {
|
||||
gl_FragColor.rgb = (gl_FragColor.rgb - 0.5) * (1.0 + contrast) + 0.5;
|
||||
}
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { BrightnessContrastShader };
|
||||
@@ -0,0 +1,59 @@
|
||||
import {
|
||||
Vector3
|
||||
} from 'three';
|
||||
|
||||
/**
|
||||
* @module ColorCorrectionShader
|
||||
* @three_import import { ColorCorrectionShader } from 'three/addons/shaders/ColorCorrectionShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Color correction shader.
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const ColorCorrectionShader = {
|
||||
|
||||
name: 'ColorCorrectionShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDiffuse': { value: null },
|
||||
'powRGB': { value: new Vector3( 2, 2, 2 ) },
|
||||
'mulRGB': { value: new Vector3( 1, 1, 1 ) },
|
||||
'addRGB': { value: new Vector3( 0, 0, 0 ) }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform sampler2D tDiffuse;
|
||||
uniform vec3 powRGB;
|
||||
uniform vec3 mulRGB;
|
||||
uniform vec3 addRGB;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
gl_FragColor = texture2D( tDiffuse, vUv );
|
||||
gl_FragColor.rgb = mulRGB * pow( ( gl_FragColor.rgb + addRGB ), powRGB );
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { ColorCorrectionShader };
|
||||
@@ -0,0 +1,57 @@
|
||||
import {
|
||||
Color
|
||||
} from 'three';
|
||||
|
||||
/**
|
||||
* @module ColorifyShader
|
||||
* @three_import import { ColorifyShader } from 'three/addons/shaders/ColorifyShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Colorify shader.
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const ColorifyShader = {
|
||||
|
||||
name: 'ColorifyShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDiffuse': { value: null },
|
||||
'color': { value: new Color( 0xffffff ) }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform vec3 color;
|
||||
uniform sampler2D tDiffuse;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vec4 texel = texture2D( tDiffuse, vUv );
|
||||
|
||||
float v = luminance( texel.xyz );
|
||||
|
||||
gl_FragColor = vec4( v * color, texel.w );
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { ColorifyShader };
|
||||
@@ -0,0 +1,74 @@
|
||||
import {
|
||||
Vector2
|
||||
} from 'three';
|
||||
|
||||
/**
|
||||
* @module ConvolutionShader
|
||||
* @three_import import { ConvolutionShader } from 'three/addons/shaders/ConvolutionShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Convolution shader ported from o3d sample to WebGL / GLSL.
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const ConvolutionShader = {
|
||||
|
||||
name: 'ConvolutionShader',
|
||||
|
||||
defines: {
|
||||
|
||||
'KERNEL_SIZE_FLOAT': '25.0',
|
||||
'KERNEL_SIZE_INT': '25'
|
||||
|
||||
},
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDiffuse': { value: null },
|
||||
'uImageIncrement': { value: new Vector2( 0.001953125, 0.0 ) },
|
||||
'cKernel': { value: [] }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
uniform vec2 uImageIncrement;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv - ( ( KERNEL_SIZE_FLOAT - 1.0 ) / 2.0 ) * uImageIncrement;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform float cKernel[ KERNEL_SIZE_INT ];
|
||||
|
||||
uniform sampler2D tDiffuse;
|
||||
uniform vec2 uImageIncrement;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vec2 imageCoord = vUv;
|
||||
vec4 sum = vec4( 0.0, 0.0, 0.0, 0.0 );
|
||||
|
||||
for( int i = 0; i < KERNEL_SIZE_INT; i ++ ) {
|
||||
|
||||
sum += texture2D( tDiffuse, imageCoord ) * cKernel[ i ];
|
||||
imageCoord += uImageIncrement;
|
||||
|
||||
}
|
||||
|
||||
gl_FragColor = sum;
|
||||
|
||||
}`
|
||||
};
|
||||
|
||||
export { ConvolutionShader };
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* @module CopyShader
|
||||
* @three_import import { CopyShader } from 'three/addons/shaders/CopyShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Full-screen copy shader pass.
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const CopyShader = {
|
||||
|
||||
name: 'CopyShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDiffuse': { value: null },
|
||||
'opacity': { value: 1.0 }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform float opacity;
|
||||
|
||||
uniform sampler2D tDiffuse;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vec4 texel = texture2D( tDiffuse, vUv );
|
||||
gl_FragColor = opacity * texel;
|
||||
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { CopyShader };
|
||||
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* @module DOFMipMapShader
|
||||
* @three_import import { DOFMipMapShader } from 'three/addons/shaders/DOFMipMapShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Depth-of-field shader using mipmaps from Matt Handley @applmak.
|
||||
*
|
||||
* Requires power-of-2 sized render target with enabled mipmaps.
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const DOFMipMapShader = {
|
||||
|
||||
name: 'DOFMipMapShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tColor': { value: null },
|
||||
'tDepth': { value: null },
|
||||
'focus': { value: 1.0 },
|
||||
'maxblur': { value: 1.0 }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform float focus;
|
||||
uniform float maxblur;
|
||||
|
||||
uniform sampler2D tColor;
|
||||
uniform sampler2D tDepth;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vec4 depth = texture2D( tDepth, vUv );
|
||||
|
||||
float factor = depth.x - focus;
|
||||
|
||||
vec4 col = texture2D( tColor, vUv, 2.0 * maxblur * abs( focus - depth.x ) );
|
||||
|
||||
gl_FragColor = col;
|
||||
gl_FragColor.a = 1.0;
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { DOFMipMapShader };
|
||||
@@ -0,0 +1,183 @@
|
||||
import {
|
||||
Vector2
|
||||
} from 'three';
|
||||
|
||||
/**
|
||||
* @module DepthLimitedBlurShader
|
||||
* @three_import import { DepthLimitedBlurShader, BlurShaderUtils } from 'three/addons/shaders/DepthLimitedBlurShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* A separable Gaussian blur shader that limits blurring across depth
|
||||
* discontinuities, stopping when the view-space depth difference to a
|
||||
* neighboring sample exceeds `depthCutoff`. This preserves edges and
|
||||
* avoids bleeding across them.
|
||||
*
|
||||
* Used by {@link SAOPass}.
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const DepthLimitedBlurShader = {
|
||||
|
||||
name: 'DepthLimitedBlurShader',
|
||||
|
||||
defines: {
|
||||
'KERNEL_RADIUS': 4,
|
||||
'DEPTH_PACKING': 1,
|
||||
'PERSPECTIVE_CAMERA': 1
|
||||
},
|
||||
|
||||
uniforms: {
|
||||
'tDiffuse': { value: null },
|
||||
'size': { value: new Vector2( 512, 512 ) },
|
||||
'sampleUvOffsets': { value: [ new Vector2( 0, 0 ) ] },
|
||||
'sampleWeights': { value: [ 1.0 ] },
|
||||
'tDepth': { value: null },
|
||||
'cameraNear': { value: 10 },
|
||||
'cameraFar': { value: 1000 },
|
||||
'depthCutoff': { value: 10 },
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
#include <common>
|
||||
|
||||
uniform vec2 size;
|
||||
|
||||
varying vec2 vUv;
|
||||
varying vec2 vInvSize;
|
||||
|
||||
void main() {
|
||||
vUv = uv;
|
||||
vInvSize = 1.0 / size;
|
||||
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
#include <common>
|
||||
#include <packing>
|
||||
|
||||
uniform sampler2D tDiffuse;
|
||||
uniform sampler2D tDepth;
|
||||
|
||||
uniform float cameraNear;
|
||||
uniform float cameraFar;
|
||||
uniform float depthCutoff;
|
||||
|
||||
uniform vec2 sampleUvOffsets[ KERNEL_RADIUS + 1 ];
|
||||
uniform float sampleWeights[ KERNEL_RADIUS + 1 ];
|
||||
|
||||
varying vec2 vUv;
|
||||
varying vec2 vInvSize;
|
||||
|
||||
float getDepth( const in vec2 screenPosition ) {
|
||||
#if DEPTH_PACKING == 1
|
||||
return unpackRGBAToDepth( texture2D( tDepth, screenPosition ) );
|
||||
#else
|
||||
return texture2D( tDepth, screenPosition ).x;
|
||||
#endif
|
||||
}
|
||||
|
||||
float getViewZ( const in float depth ) {
|
||||
#if PERSPECTIVE_CAMERA == 1
|
||||
return perspectiveDepthToViewZ( depth, cameraNear, cameraFar );
|
||||
#else
|
||||
return orthographicDepthToViewZ( depth, cameraNear, cameraFar );
|
||||
#endif
|
||||
}
|
||||
|
||||
void main() {
|
||||
float depth = getDepth( vUv );
|
||||
if( depth >= ( 1.0 - EPSILON ) ) {
|
||||
discard;
|
||||
}
|
||||
|
||||
float centerViewZ = -getViewZ( depth );
|
||||
bool rBreak = false, lBreak = false;
|
||||
|
||||
float weightSum = sampleWeights[0];
|
||||
vec4 diffuseSum = texture2D( tDiffuse, vUv ) * weightSum;
|
||||
|
||||
for( int i = 1; i <= KERNEL_RADIUS; i ++ ) {
|
||||
|
||||
float sampleWeight = sampleWeights[i];
|
||||
vec2 sampleUvOffset = sampleUvOffsets[i] * vInvSize;
|
||||
|
||||
vec2 sampleUv = vUv + sampleUvOffset;
|
||||
float viewZ = -getViewZ( getDepth( sampleUv ) );
|
||||
|
||||
if( abs( viewZ - centerViewZ ) > depthCutoff ) rBreak = true;
|
||||
|
||||
if( ! rBreak ) {
|
||||
diffuseSum += texture2D( tDiffuse, sampleUv ) * sampleWeight;
|
||||
weightSum += sampleWeight;
|
||||
}
|
||||
|
||||
sampleUv = vUv - sampleUvOffset;
|
||||
viewZ = -getViewZ( getDepth( sampleUv ) );
|
||||
|
||||
if( abs( viewZ - centerViewZ ) > depthCutoff ) lBreak = true;
|
||||
|
||||
if( ! lBreak ) {
|
||||
diffuseSum += texture2D( tDiffuse, sampleUv ) * sampleWeight;
|
||||
weightSum += sampleWeight;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
gl_FragColor = diffuseSum / weightSum;
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
const BlurShaderUtils = {
|
||||
|
||||
createSampleWeights: function ( kernelRadius, stdDev ) {
|
||||
|
||||
const weights = [];
|
||||
|
||||
for ( let i = 0; i <= kernelRadius; i ++ ) {
|
||||
|
||||
weights.push( gaussian( i, stdDev ) );
|
||||
|
||||
}
|
||||
|
||||
return weights;
|
||||
|
||||
},
|
||||
|
||||
createSampleOffsets: function ( kernelRadius, uvIncrement ) {
|
||||
|
||||
const offsets = [];
|
||||
|
||||
for ( let i = 0; i <= kernelRadius; i ++ ) {
|
||||
|
||||
offsets.push( uvIncrement.clone().multiplyScalar( i ) );
|
||||
|
||||
}
|
||||
|
||||
return offsets;
|
||||
|
||||
},
|
||||
|
||||
configure: function ( material, kernelRadius, stdDev, uvIncrement ) {
|
||||
|
||||
material.defines[ 'KERNEL_RADIUS' ] = kernelRadius;
|
||||
material.uniforms[ 'sampleUvOffsets' ].value = BlurShaderUtils.createSampleOffsets( kernelRadius, uvIncrement );
|
||||
material.uniforms[ 'sampleWeights' ].value = BlurShaderUtils.createSampleWeights( kernelRadius, stdDev );
|
||||
material.needsUpdate = true;
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
function gaussian( x, stdDev ) {
|
||||
|
||||
return Math.exp( - ( x * x ) / ( 2.0 * ( stdDev * stdDev ) ) ) / ( Math.sqrt( 2.0 * Math.PI ) * stdDev );
|
||||
|
||||
}
|
||||
|
||||
export { DepthLimitedBlurShader, BlurShaderUtils };
|
||||
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* @module DigitalGlitch
|
||||
* @three_import import { DigitalGlitch } from 'three/addons/shaders/DigitalGlitch.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Digital glitch shader.
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const DigitalGlitch = {
|
||||
|
||||
name: 'DigitalGlitch',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDiffuse': { value: null }, //diffuse texture
|
||||
'tDisp': { value: null }, //displacement texture for digital glitch squares
|
||||
'byp': { value: 0 }, //apply the glitch ?
|
||||
'amount': { value: 0.08 },
|
||||
'angle': { value: 0.02 },
|
||||
'seed': { value: 0.02 },
|
||||
'seed_x': { value: 0.02 }, //-1,1
|
||||
'seed_y': { value: 0.02 }, //-1,1
|
||||
'distortion_x': { value: 0.5 },
|
||||
'distortion_y': { value: 0.6 },
|
||||
'col_s': { value: 0.05 }
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
void main() {
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform int byp; //should we apply the glitch ?
|
||||
|
||||
uniform sampler2D tDiffuse;
|
||||
uniform sampler2D tDisp;
|
||||
|
||||
uniform float amount;
|
||||
uniform float angle;
|
||||
uniform float seed;
|
||||
uniform float seed_x;
|
||||
uniform float seed_y;
|
||||
uniform float distortion_x;
|
||||
uniform float distortion_y;
|
||||
uniform float col_s;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
|
||||
float rand(vec2 co){
|
||||
return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);
|
||||
}
|
||||
|
||||
void main() {
|
||||
if(byp<1) {
|
||||
vec2 p = vUv;
|
||||
float xs = floor(gl_FragCoord.x / 0.5);
|
||||
float ys = floor(gl_FragCoord.y / 0.5);
|
||||
//based on staffantans glitch shader for unity https://github.com/staffantan/unityglitch
|
||||
float disp = texture2D(tDisp, p*seed*seed).r;
|
||||
if(p.y<distortion_x+col_s && p.y>distortion_x-col_s*seed) {
|
||||
if(seed_x>0.){
|
||||
p.y = 1. - (p.y + distortion_y);
|
||||
}
|
||||
else {
|
||||
p.y = distortion_y;
|
||||
}
|
||||
}
|
||||
if(p.x<distortion_y+col_s && p.x>distortion_y-col_s*seed) {
|
||||
if(seed_y>0.){
|
||||
p.x=distortion_x;
|
||||
}
|
||||
else {
|
||||
p.x = 1. - (p.x + distortion_x);
|
||||
}
|
||||
}
|
||||
p.x+=disp*seed_x*(seed/5.);
|
||||
p.y+=disp*seed_y*(seed/5.);
|
||||
//base from RGB shift shader
|
||||
vec2 offset = amount * vec2( cos(angle), sin(angle));
|
||||
vec4 cr = texture2D(tDiffuse, p + offset);
|
||||
vec4 cga = texture2D(tDiffuse, p);
|
||||
vec4 cb = texture2D(tDiffuse, p - offset);
|
||||
gl_FragColor = vec4(cr.r, cga.g, cb.b, cga.a);
|
||||
//add noise
|
||||
vec4 snow = 200.*amount*vec4(rand(vec2(xs * seed,ys * seed*50.))*0.2);
|
||||
gl_FragColor = gl_FragColor+ snow;
|
||||
}
|
||||
else {
|
||||
gl_FragColor=texture2D (tDiffuse, vUv);
|
||||
}
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { DigitalGlitch };
|
||||
@@ -0,0 +1,75 @@
|
||||
import {
|
||||
Vector2
|
||||
} from 'three';
|
||||
|
||||
/**
|
||||
* @module DotScreenShader
|
||||
* @three_import import { DotScreenShader } from 'three/addons/shaders/DotScreenShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Dot screen shader based on [glfx.js sepia shader](https://github.com/evanw/glfx.js).
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const DotScreenShader = {
|
||||
|
||||
name: 'DotScreenShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDiffuse': { value: null },
|
||||
'tSize': { value: new Vector2( 256, 256 ) },
|
||||
'center': { value: new Vector2( 0.5, 0.5 ) },
|
||||
'angle': { value: 1.57 },
|
||||
'scale': { value: 1.0 }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform vec2 center;
|
||||
uniform float angle;
|
||||
uniform float scale;
|
||||
uniform vec2 tSize;
|
||||
|
||||
uniform sampler2D tDiffuse;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
float pattern() {
|
||||
|
||||
float s = sin( angle ), c = cos( angle );
|
||||
|
||||
vec2 tex = vUv * tSize - center;
|
||||
vec2 point = vec2( c * tex.x - s * tex.y, s * tex.x + c * tex.y ) * scale;
|
||||
|
||||
return ( sin( point.x ) * sin( point.y ) ) * 4.0;
|
||||
|
||||
}
|
||||
|
||||
void main() {
|
||||
|
||||
vec4 color = texture2D( tDiffuse, vUv );
|
||||
|
||||
float average = ( color.r + color.g + color.b ) / 3.0;
|
||||
|
||||
gl_FragColor = vec4( vec3( average * 10.0 - 5.0 + pattern() ), color.a );
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { DotScreenShader };
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* @module ExposureShader
|
||||
* @three_import import { ExposureShader } from 'three/addons/shaders/ExposureShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Exposure shader that scales the image color by an exposure factor.
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const ExposureShader = {
|
||||
|
||||
name: 'ExposureShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDiffuse': { value: null },
|
||||
'exposure': { value: 1.0 }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform float exposure;
|
||||
|
||||
uniform sampler2D tDiffuse;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
gl_FragColor = texture2D( tDiffuse, vUv );
|
||||
gl_FragColor.rgb *= exposure;
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { ExposureShader };
|
||||
@@ -0,0 +1,298 @@
|
||||
import {
|
||||
Vector2
|
||||
} from 'three';
|
||||
|
||||
/**
|
||||
* @module FXAAShader
|
||||
* @three_import import { FXAAShader } from 'three/addons/shaders/FXAAShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* FXAA algorithm from NVIDIA, C# implementation by Jasper Flick, GLSL port by Dave Hoskins.
|
||||
*
|
||||
* References:
|
||||
* - {@link http://developer.download.nvidia.com/assets/gamedev/files/sdk/11/FXAA_WhitePaper.pdf}.
|
||||
* - {@link https://catlikecoding.com/unity/tutorials/advanced-rendering/fxaa/}.
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const FXAAShader = {
|
||||
|
||||
name: 'FXAAShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDiffuse': { value: null },
|
||||
'resolution': { value: new Vector2( 1 / 1024, 1 / 512 ) }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform sampler2D tDiffuse;
|
||||
uniform vec2 resolution;
|
||||
varying vec2 vUv;
|
||||
|
||||
#define EDGE_STEP_COUNT 6
|
||||
#define EDGE_GUESS 8.0
|
||||
#define EDGE_STEPS 1.0, 1.5, 2.0, 2.0, 2.0, 4.0
|
||||
const float edgeSteps[EDGE_STEP_COUNT] = float[EDGE_STEP_COUNT]( EDGE_STEPS );
|
||||
|
||||
float _ContrastThreshold = 0.0312;
|
||||
float _RelativeThreshold = 0.063;
|
||||
float _SubpixelBlending = 1.0;
|
||||
|
||||
vec4 Sample( sampler2D tex2D, vec2 uv ) {
|
||||
|
||||
return texture( tex2D, uv );
|
||||
|
||||
}
|
||||
|
||||
float SampleLuminance( sampler2D tex2D, vec2 uv ) {
|
||||
|
||||
return dot( Sample( tex2D, uv ).rgb, vec3( 0.3, 0.59, 0.11 ) );
|
||||
|
||||
}
|
||||
|
||||
float SampleLuminance( sampler2D tex2D, vec2 texSize, vec2 uv, float uOffset, float vOffset ) {
|
||||
|
||||
uv += texSize * vec2(uOffset, vOffset);
|
||||
return SampleLuminance(tex2D, uv);
|
||||
|
||||
}
|
||||
|
||||
struct LuminanceData {
|
||||
|
||||
float m, n, e, s, w;
|
||||
float ne, nw, se, sw;
|
||||
float highest, lowest, contrast;
|
||||
|
||||
};
|
||||
|
||||
LuminanceData SampleLuminanceNeighborhood( sampler2D tex2D, vec2 texSize, vec2 uv ) {
|
||||
|
||||
LuminanceData l;
|
||||
l.m = SampleLuminance( tex2D, uv );
|
||||
l.n = SampleLuminance( tex2D, texSize, uv, 0.0, 1.0 );
|
||||
l.e = SampleLuminance( tex2D, texSize, uv, 1.0, 0.0 );
|
||||
l.s = SampleLuminance( tex2D, texSize, uv, 0.0, -1.0 );
|
||||
l.w = SampleLuminance( tex2D, texSize, uv, -1.0, 0.0 );
|
||||
|
||||
l.ne = SampleLuminance( tex2D, texSize, uv, 1.0, 1.0 );
|
||||
l.nw = SampleLuminance( tex2D, texSize, uv, -1.0, 1.0 );
|
||||
l.se = SampleLuminance( tex2D, texSize, uv, 1.0, -1.0 );
|
||||
l.sw = SampleLuminance( tex2D, texSize, uv, -1.0, -1.0 );
|
||||
|
||||
l.highest = max( max( max( max( l.n, l.e ), l.s ), l.w ), l.m );
|
||||
l.lowest = min( min( min( min( l.n, l.e ), l.s ), l.w ), l.m );
|
||||
l.contrast = l.highest - l.lowest;
|
||||
return l;
|
||||
|
||||
}
|
||||
|
||||
bool ShouldSkipPixel( LuminanceData l ) {
|
||||
|
||||
float threshold = max( _ContrastThreshold, _RelativeThreshold * l.highest );
|
||||
return l.contrast < threshold;
|
||||
|
||||
}
|
||||
|
||||
float DeterminePixelBlendFactor( LuminanceData l ) {
|
||||
|
||||
float f = 2.0 * ( l.n + l.e + l.s + l.w );
|
||||
f += l.ne + l.nw + l.se + l.sw;
|
||||
f *= 1.0 / 12.0;
|
||||
f = abs( f - l.m );
|
||||
f = clamp( f / l.contrast, 0.0, 1.0 );
|
||||
|
||||
float blendFactor = smoothstep( 0.0, 1.0, f );
|
||||
return blendFactor * blendFactor * _SubpixelBlending;
|
||||
|
||||
}
|
||||
|
||||
struct EdgeData {
|
||||
|
||||
bool isHorizontal;
|
||||
float pixelStep;
|
||||
float oppositeLuminance, gradient;
|
||||
|
||||
};
|
||||
|
||||
EdgeData DetermineEdge( vec2 texSize, LuminanceData l ) {
|
||||
|
||||
EdgeData e;
|
||||
float horizontal =
|
||||
abs( l.n + l.s - 2.0 * l.m ) * 2.0 +
|
||||
abs( l.ne + l.se - 2.0 * l.e ) +
|
||||
abs( l.nw + l.sw - 2.0 * l.w );
|
||||
float vertical =
|
||||
abs( l.e + l.w - 2.0 * l.m ) * 2.0 +
|
||||
abs( l.ne + l.nw - 2.0 * l.n ) +
|
||||
abs( l.se + l.sw - 2.0 * l.s );
|
||||
e.isHorizontal = horizontal >= vertical;
|
||||
|
||||
float pLuminance = e.isHorizontal ? l.n : l.e;
|
||||
float nLuminance = e.isHorizontal ? l.s : l.w;
|
||||
float pGradient = abs( pLuminance - l.m );
|
||||
float nGradient = abs( nLuminance - l.m );
|
||||
|
||||
e.pixelStep = e.isHorizontal ? texSize.y : texSize.x;
|
||||
|
||||
if (pGradient < nGradient) {
|
||||
|
||||
e.pixelStep = -e.pixelStep;
|
||||
e.oppositeLuminance = nLuminance;
|
||||
e.gradient = nGradient;
|
||||
|
||||
} else {
|
||||
|
||||
e.oppositeLuminance = pLuminance;
|
||||
e.gradient = pGradient;
|
||||
|
||||
}
|
||||
|
||||
return e;
|
||||
|
||||
}
|
||||
|
||||
float DetermineEdgeBlendFactor( sampler2D tex2D, vec2 texSize, LuminanceData l, EdgeData e, vec2 uv ) {
|
||||
|
||||
vec2 uvEdge = uv;
|
||||
vec2 edgeStep;
|
||||
if (e.isHorizontal) {
|
||||
|
||||
uvEdge.y += e.pixelStep * 0.5;
|
||||
edgeStep = vec2( texSize.x, 0.0 );
|
||||
|
||||
} else {
|
||||
|
||||
uvEdge.x += e.pixelStep * 0.5;
|
||||
edgeStep = vec2( 0.0, texSize.y );
|
||||
|
||||
}
|
||||
|
||||
float edgeLuminance = ( l.m + e.oppositeLuminance ) * 0.5;
|
||||
float gradientThreshold = e.gradient * 0.25;
|
||||
|
||||
vec2 puv = uvEdge + edgeStep * edgeSteps[0];
|
||||
float pLuminanceDelta = SampleLuminance( tex2D, puv ) - edgeLuminance;
|
||||
bool pAtEnd = abs( pLuminanceDelta ) >= gradientThreshold;
|
||||
|
||||
for ( int i = 1; i < EDGE_STEP_COUNT && !pAtEnd; i++ ) {
|
||||
|
||||
puv += edgeStep * edgeSteps[i];
|
||||
pLuminanceDelta = SampleLuminance( tex2D, puv ) - edgeLuminance;
|
||||
pAtEnd = abs( pLuminanceDelta ) >= gradientThreshold;
|
||||
|
||||
}
|
||||
|
||||
if ( !pAtEnd ) {
|
||||
|
||||
puv += edgeStep * EDGE_GUESS;
|
||||
|
||||
}
|
||||
|
||||
vec2 nuv = uvEdge - edgeStep * edgeSteps[0];
|
||||
float nLuminanceDelta = SampleLuminance( tex2D, nuv ) - edgeLuminance;
|
||||
bool nAtEnd = abs( nLuminanceDelta ) >= gradientThreshold;
|
||||
|
||||
for ( int i = 1; i < EDGE_STEP_COUNT && !nAtEnd; i++ ) {
|
||||
|
||||
nuv -= edgeStep * edgeSteps[i];
|
||||
nLuminanceDelta = SampleLuminance( tex2D, nuv ) - edgeLuminance;
|
||||
nAtEnd = abs( nLuminanceDelta ) >= gradientThreshold;
|
||||
|
||||
}
|
||||
|
||||
if ( !nAtEnd ) {
|
||||
|
||||
nuv -= edgeStep * EDGE_GUESS;
|
||||
|
||||
}
|
||||
|
||||
float pDistance, nDistance;
|
||||
if ( e.isHorizontal ) {
|
||||
|
||||
pDistance = puv.x - uv.x;
|
||||
nDistance = uv.x - nuv.x;
|
||||
|
||||
} else {
|
||||
|
||||
pDistance = puv.y - uv.y;
|
||||
nDistance = uv.y - nuv.y;
|
||||
|
||||
}
|
||||
|
||||
float shortestDistance;
|
||||
bool deltaSign;
|
||||
if ( pDistance <= nDistance ) {
|
||||
|
||||
shortestDistance = pDistance;
|
||||
deltaSign = pLuminanceDelta >= 0.0;
|
||||
|
||||
} else {
|
||||
|
||||
shortestDistance = nDistance;
|
||||
deltaSign = nLuminanceDelta >= 0.0;
|
||||
|
||||
}
|
||||
|
||||
if ( deltaSign == ( l.m - edgeLuminance >= 0.0 ) ) {
|
||||
|
||||
return 0.0;
|
||||
|
||||
}
|
||||
|
||||
return 0.5 - shortestDistance / ( pDistance + nDistance );
|
||||
|
||||
}
|
||||
|
||||
vec4 ApplyFXAA( sampler2D tex2D, vec2 texSize, vec2 uv ) {
|
||||
|
||||
LuminanceData luminance = SampleLuminanceNeighborhood( tex2D, texSize, uv );
|
||||
if ( ShouldSkipPixel( luminance ) ) {
|
||||
|
||||
return Sample( tex2D, uv );
|
||||
|
||||
}
|
||||
|
||||
float pixelBlend = DeterminePixelBlendFactor( luminance );
|
||||
EdgeData edge = DetermineEdge( texSize, luminance );
|
||||
float edgeBlend = DetermineEdgeBlendFactor( tex2D, texSize, luminance, edge, uv );
|
||||
float finalBlend = max( pixelBlend, edgeBlend );
|
||||
|
||||
if (edge.isHorizontal) {
|
||||
|
||||
uv.y += edge.pixelStep * finalBlend;
|
||||
|
||||
} else {
|
||||
|
||||
uv.x += edge.pixelStep * finalBlend;
|
||||
|
||||
}
|
||||
|
||||
return Sample( tex2D, uv );
|
||||
|
||||
}
|
||||
|
||||
void main() {
|
||||
|
||||
gl_FragColor = ApplyFXAA( tDiffuse, resolution.xy, vUv );
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { FXAAShader };
|
||||
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* @module FilmShader
|
||||
* @three_import import { FilmShader } from 'three/addons/shaders/FilmShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Film grain shader that adds animated noise to the image, with an optional
|
||||
* grayscale conversion.
|
||||
*
|
||||
* Used by {@link FilmPass}.
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const FilmShader = {
|
||||
|
||||
name: 'FilmShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDiffuse': { value: null },
|
||||
'time': { value: 0.0 },
|
||||
'intensity': { value: 0.5 },
|
||||
'grayscale': { value: false }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
#include <common>
|
||||
|
||||
uniform float intensity;
|
||||
uniform bool grayscale;
|
||||
uniform float time;
|
||||
|
||||
uniform sampler2D tDiffuse;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vec4 base = texture2D( tDiffuse, vUv );
|
||||
|
||||
float noise = rand( fract( vUv + time ) );
|
||||
|
||||
vec3 color = base.rgb + base.rgb * clamp( 0.1 + noise, 0.0, 1.0 );
|
||||
|
||||
color = mix( base.rgb, color, intensity );
|
||||
|
||||
if ( grayscale ) {
|
||||
|
||||
color = vec3( luminance( color ) ); // assuming linear-srgb
|
||||
|
||||
}
|
||||
|
||||
gl_FragColor = vec4( color, base.a );
|
||||
|
||||
}`,
|
||||
|
||||
};
|
||||
|
||||
export { FilmShader };
|
||||
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* @module FocusShader
|
||||
* @three_import import { FocusShader } from 'three/addons/shaders/FocusShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Focus shader based on [PaintEffect postprocess from ro.me](http://code.google.com/p/3-dreams-of-black/source/browse/deploy/js/effects/PaintEffect.js).
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const FocusShader = {
|
||||
|
||||
name: 'FocusShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDiffuse': { value: null },
|
||||
'screenWidth': { value: 1024 },
|
||||
'screenHeight': { value: 1024 },
|
||||
'sampleDistance': { value: 0.94 },
|
||||
'waveFactor': { value: 0.00125 }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform float screenWidth;
|
||||
uniform float screenHeight;
|
||||
uniform float sampleDistance;
|
||||
uniform float waveFactor;
|
||||
|
||||
uniform sampler2D tDiffuse;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vec4 color, org, tmp, add;
|
||||
float sample_dist, f;
|
||||
vec2 vin;
|
||||
vec2 uv = vUv;
|
||||
|
||||
add = color = org = texture2D( tDiffuse, uv );
|
||||
|
||||
vin = ( uv - vec2( 0.5 ) ) * vec2( 1.4 );
|
||||
sample_dist = dot( vin, vin ) * 2.0;
|
||||
|
||||
f = ( waveFactor * 100.0 + sample_dist ) * sampleDistance * 4.0;
|
||||
|
||||
vec2 sampleSize = vec2( 1.0 / screenWidth, 1.0 / screenHeight ) * vec2( f );
|
||||
|
||||
add += tmp = texture2D( tDiffuse, uv + vec2( 0.111964, 0.993712 ) * sampleSize );
|
||||
if( tmp.b < color.b ) color = tmp;
|
||||
|
||||
add += tmp = texture2D( tDiffuse, uv + vec2( 0.846724, 0.532032 ) * sampleSize );
|
||||
if( tmp.b < color.b ) color = tmp;
|
||||
|
||||
add += tmp = texture2D( tDiffuse, uv + vec2( 0.943883, -0.330279 ) * sampleSize );
|
||||
if( tmp.b < color.b ) color = tmp;
|
||||
|
||||
add += tmp = texture2D( tDiffuse, uv + vec2( 0.330279, -0.943883 ) * sampleSize );
|
||||
if( tmp.b < color.b ) color = tmp;
|
||||
|
||||
add += tmp = texture2D( tDiffuse, uv + vec2( -0.532032, -0.846724 ) * sampleSize );
|
||||
if( tmp.b < color.b ) color = tmp;
|
||||
|
||||
add += tmp = texture2D( tDiffuse, uv + vec2( -0.993712, -0.111964 ) * sampleSize );
|
||||
if( tmp.b < color.b ) color = tmp;
|
||||
|
||||
add += tmp = texture2D( tDiffuse, uv + vec2( -0.707107, 0.707107 ) * sampleSize );
|
||||
if( tmp.b < color.b ) color = tmp;
|
||||
|
||||
color = color * vec4( 2.0 ) - ( add / vec4( 8.0 ) );
|
||||
color = color + ( add / vec4( 8.0 ) - color ) * ( vec4( 1.0 ) - vec4( sample_dist * 0.5 ) );
|
||||
|
||||
gl_FragColor = vec4( color.rgb * color.rgb * vec3( 0.95 ) + color.rgb, 1.0 );
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { FocusShader };
|
||||
@@ -0,0 +1,103 @@
|
||||
import {
|
||||
Vector2
|
||||
} from 'three';
|
||||
|
||||
/**
|
||||
* @module FreiChenShader
|
||||
* @three_import import { FreiChenShader } from 'three/addons/shaders/FreiChenShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Edge Detection Shader using Frei-Chen filter.
|
||||
* Based on {@link http://rastergrid.com/blog/2011/01/frei-chen-edge-detector}.
|
||||
*
|
||||
* aspect: vec2 of (1/width, 1/height)
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const FreiChenShader = {
|
||||
|
||||
name: 'FreiChenShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDiffuse': { value: null },
|
||||
'aspect': { value: new Vector2( 512, 512 ) }
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform sampler2D tDiffuse;
|
||||
varying vec2 vUv;
|
||||
|
||||
uniform vec2 aspect;
|
||||
|
||||
vec2 texel = vec2( 1.0 / aspect.x, 1.0 / aspect.y );
|
||||
|
||||
|
||||
mat3 G[9];
|
||||
|
||||
// hard coded matrix values!!!! as suggested in https://github.com/neilmendoza/ofxPostProcessing/blob/master/src/EdgePass.cpp#L45
|
||||
|
||||
const mat3 g0 = mat3( 0.3535533845424652, 0, -0.3535533845424652, 0.5, 0, -0.5, 0.3535533845424652, 0, -0.3535533845424652 );
|
||||
const mat3 g1 = mat3( 0.3535533845424652, 0.5, 0.3535533845424652, 0, 0, 0, -0.3535533845424652, -0.5, -0.3535533845424652 );
|
||||
const mat3 g2 = mat3( 0, 0.3535533845424652, -0.5, -0.3535533845424652, 0, 0.3535533845424652, 0.5, -0.3535533845424652, 0 );
|
||||
const mat3 g3 = mat3( 0.5, -0.3535533845424652, 0, -0.3535533845424652, 0, 0.3535533845424652, 0, 0.3535533845424652, -0.5 );
|
||||
const mat3 g4 = mat3( 0, -0.5, 0, 0.5, 0, 0.5, 0, -0.5, 0 );
|
||||
const mat3 g5 = mat3( -0.5, 0, 0.5, 0, 0, 0, 0.5, 0, -0.5 );
|
||||
const mat3 g6 = mat3( 0.1666666716337204, -0.3333333432674408, 0.1666666716337204, -0.3333333432674408, 0.6666666865348816, -0.3333333432674408, 0.1666666716337204, -0.3333333432674408, 0.1666666716337204 );
|
||||
const mat3 g7 = mat3( -0.3333333432674408, 0.1666666716337204, -0.3333333432674408, 0.1666666716337204, 0.6666666865348816, 0.1666666716337204, -0.3333333432674408, 0.1666666716337204, -0.3333333432674408 );
|
||||
const mat3 g8 = mat3( 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408 );
|
||||
|
||||
void main(void)
|
||||
{
|
||||
|
||||
G[0] = g0,
|
||||
G[1] = g1,
|
||||
G[2] = g2,
|
||||
G[3] = g3,
|
||||
G[4] = g4,
|
||||
G[5] = g5,
|
||||
G[6] = g6,
|
||||
G[7] = g7,
|
||||
G[8] = g8;
|
||||
|
||||
mat3 I;
|
||||
float cnv[9];
|
||||
vec3 sample;
|
||||
|
||||
/* fetch the 3x3 neighbourhood and use the RGB vector's length as intensity value */
|
||||
for (float i=0.0; i<3.0; i++) {
|
||||
for (float j=0.0; j<3.0; j++) {
|
||||
sample = texture2D(tDiffuse, vUv + texel * vec2(i-1.0,j-1.0) ).rgb;
|
||||
I[int(i)][int(j)] = length(sample);
|
||||
}
|
||||
}
|
||||
|
||||
/* calculate the convolution values for all the masks */
|
||||
for (int i=0; i<9; i++) {
|
||||
float dp3 = dot(G[i][0], I[0]) + dot(G[i][1], I[1]) + dot(G[i][2], I[2]);
|
||||
cnv[i] = dp3 * dp3;
|
||||
}
|
||||
|
||||
float M = (cnv[0] + cnv[1]) + (cnv[2] + cnv[3]);
|
||||
float S = (cnv[4] + cnv[5]) + (cnv[6] + cnv[7]) + (cnv[8] + M);
|
||||
|
||||
gl_FragColor = vec4(vec3(sqrt(M/S)), 1.0);
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { FreiChenShader };
|
||||
@@ -0,0 +1,437 @@
|
||||
import {
|
||||
DataTexture,
|
||||
Matrix4,
|
||||
RepeatWrapping,
|
||||
Vector2,
|
||||
Vector3,
|
||||
} from 'three';
|
||||
|
||||
/**
|
||||
* @module GTAOShader
|
||||
* @three_import import { GTAOShader } from 'three/addons/shaders/GTAOShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* GTAO shader. Use by {@link GTAOPass}.
|
||||
*
|
||||
* References:
|
||||
* - [Practical Realtime Strategies for Accurate Indirect Occlusion](https://iryoku.com/downloads/Practical-Realtime-Strategies-for-Accurate-Indirect-Occlusion.pdf).
|
||||
* - [Horizon-Based Indirect Lighting (HBIL)](https://github.com/Patapom/GodComplex/blob/master/Tests/TestHBIL/2018%20Mayaux%20-%20Horizon-Based%20Indirect%20Lighting%20(HBIL).pdf)
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const GTAOShader = {
|
||||
|
||||
name: 'GTAOShader',
|
||||
|
||||
defines: {
|
||||
PERSPECTIVE_CAMERA: 1,
|
||||
SAMPLES: 16,
|
||||
NORMAL_VECTOR_TYPE: 1,
|
||||
SCREEN_SPACE_RADIUS: 0,
|
||||
SCREEN_SPACE_RADIUS_SCALE: 100.0,
|
||||
SCENE_CLIP_BOX: 0,
|
||||
},
|
||||
|
||||
uniforms: {
|
||||
tNormal: { value: null },
|
||||
tDepth: { value: null },
|
||||
tNoise: { value: null },
|
||||
resolution: { value: new Vector2() },
|
||||
cameraNear: { value: null },
|
||||
cameraFar: { value: null },
|
||||
cameraProjectionMatrix: { value: new Matrix4() },
|
||||
cameraProjectionMatrixInverse: { value: new Matrix4() },
|
||||
cameraWorldMatrix: { value: new Matrix4() },
|
||||
radius: { value: 0.25 },
|
||||
distanceExponent: { value: 1. },
|
||||
thickness: { value: 1. },
|
||||
distanceFallOff: { value: 1. },
|
||||
scale: { value: 1. },
|
||||
sceneBoxMin: { value: new Vector3( - 1, - 1, - 1 ) },
|
||||
sceneBoxMax: { value: new Vector3( 1, 1, 1 ) },
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
varying vec2 vUv;
|
||||
uniform highp sampler2D tNormal;
|
||||
uniform highp sampler2D tDepth;
|
||||
uniform sampler2D tNoise;
|
||||
uniform vec2 resolution;
|
||||
uniform float cameraNear;
|
||||
uniform float cameraFar;
|
||||
uniform mat4 cameraProjectionMatrix;
|
||||
uniform mat4 cameraProjectionMatrixInverse;
|
||||
uniform mat4 cameraWorldMatrix;
|
||||
uniform float radius;
|
||||
uniform float distanceExponent;
|
||||
uniform float thickness;
|
||||
uniform float distanceFallOff;
|
||||
uniform float scale;
|
||||
#if SCENE_CLIP_BOX == 1
|
||||
uniform vec3 sceneBoxMin;
|
||||
uniform vec3 sceneBoxMax;
|
||||
#endif
|
||||
|
||||
#include <common>
|
||||
#include <packing>
|
||||
|
||||
#ifndef FRAGMENT_OUTPUT
|
||||
#define FRAGMENT_OUTPUT vec4(vec3(ao), 1.)
|
||||
#endif
|
||||
|
||||
vec3 getViewPosition( const in vec2 screenPosition, const in float depth ) {
|
||||
#ifdef USE_REVERSED_DEPTH_BUFFER
|
||||
vec4 clipSpacePosition = vec4( vec2( screenPosition ) * 2.0 - 1.0, depth, 1.0 );
|
||||
#else
|
||||
vec4 clipSpacePosition = vec4( vec3( screenPosition, depth ) * 2.0 - 1.0, 1.0 );
|
||||
#endif
|
||||
vec4 viewSpacePosition = cameraProjectionMatrixInverse * clipSpacePosition;
|
||||
return viewSpacePosition.xyz / viewSpacePosition.w;
|
||||
}
|
||||
|
||||
float getDepth(const vec2 uv) {
|
||||
return textureLod(tDepth, uv.xy, 0.0).r;
|
||||
}
|
||||
|
||||
float fetchDepth(const ivec2 uv) {
|
||||
return texelFetch(tDepth, uv.xy, 0).r;
|
||||
}
|
||||
|
||||
float getViewZ(const in float depth) {
|
||||
#if PERSPECTIVE_CAMERA == 1
|
||||
return perspectiveDepthToViewZ(depth, cameraNear, cameraFar);
|
||||
#else
|
||||
return orthographicDepthToViewZ(depth, cameraNear, cameraFar);
|
||||
#endif
|
||||
}
|
||||
|
||||
vec3 computeNormalFromDepth(const vec2 uv) {
|
||||
vec2 size = vec2(textureSize(tDepth, 0));
|
||||
ivec2 p = ivec2(uv * size);
|
||||
float c0 = fetchDepth(p);
|
||||
float l2 = fetchDepth(p - ivec2(2, 0));
|
||||
float l1 = fetchDepth(p - ivec2(1, 0));
|
||||
float r1 = fetchDepth(p + ivec2(1, 0));
|
||||
float r2 = fetchDepth(p + ivec2(2, 0));
|
||||
float b2 = fetchDepth(p - ivec2(0, 2));
|
||||
float b1 = fetchDepth(p - ivec2(0, 1));
|
||||
float t1 = fetchDepth(p + ivec2(0, 1));
|
||||
float t2 = fetchDepth(p + ivec2(0, 2));
|
||||
float dl = abs((2.0 * l1 - l2) - c0);
|
||||
float dr = abs((2.0 * r1 - r2) - c0);
|
||||
float db = abs((2.0 * b1 - b2) - c0);
|
||||
float dt = abs((2.0 * t1 - t2) - c0);
|
||||
vec3 ce = getViewPosition(uv, c0).xyz;
|
||||
vec3 dpdx = (dl < dr) ? ce - getViewPosition((uv - vec2(1.0 / size.x, 0.0)), l1).xyz : -ce + getViewPosition((uv + vec2(1.0 / size.x, 0.0)), r1).xyz;
|
||||
vec3 dpdy = (db < dt) ? ce - getViewPosition((uv - vec2(0.0, 1.0 / size.y)), b1).xyz : -ce + getViewPosition((uv + vec2(0.0, 1.0 / size.y)), t1).xyz;
|
||||
return normalize(cross(dpdx, dpdy));
|
||||
}
|
||||
|
||||
vec3 getViewNormal(const vec2 uv) {
|
||||
#if NORMAL_VECTOR_TYPE == 2
|
||||
return normalize(textureLod(tNormal, uv, 0.).rgb);
|
||||
#elif NORMAL_VECTOR_TYPE == 1
|
||||
return unpackRGBToNormal(textureLod(tNormal, uv, 0.).rgb);
|
||||
#else
|
||||
return computeNormalFromDepth(uv);
|
||||
#endif
|
||||
}
|
||||
|
||||
vec3 getSceneUvAndDepth(vec3 sampleViewPos) {
|
||||
vec4 sampleClipPos = cameraProjectionMatrix * vec4(sampleViewPos, 1.);
|
||||
vec2 sampleUv = sampleClipPos.xy / sampleClipPos.w * 0.5 + 0.5;
|
||||
float sampleSceneDepth = getDepth(sampleUv);
|
||||
return vec3(sampleUv, sampleSceneDepth);
|
||||
}
|
||||
|
||||
void main() {
|
||||
float depth = getDepth(vUv.xy);
|
||||
|
||||
#ifdef USE_REVERSED_DEPTH_BUFFER
|
||||
if (depth <= 0.0) {
|
||||
discard;
|
||||
return;
|
||||
}
|
||||
#else
|
||||
if (depth >= 1.0) {
|
||||
discard;
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
|
||||
vec3 viewPos = getViewPosition(vUv, depth);
|
||||
vec3 viewNormal = getViewNormal(vUv);
|
||||
|
||||
float radiusToUse = radius;
|
||||
float distanceFalloffToUse = thickness;
|
||||
#if SCREEN_SPACE_RADIUS == 1
|
||||
float radiusScale = getViewPosition(vec2(0.5 + float(SCREEN_SPACE_RADIUS_SCALE) / resolution.x, 0.0), depth).x;
|
||||
radiusToUse *= radiusScale;
|
||||
distanceFalloffToUse *= radiusScale;
|
||||
#endif
|
||||
|
||||
#if SCENE_CLIP_BOX == 1
|
||||
vec3 worldPos = (cameraWorldMatrix * vec4(viewPos, 1.0)).xyz;
|
||||
float boxDistance = length(max(vec3(0.0), max(sceneBoxMin - worldPos, worldPos - sceneBoxMax)));
|
||||
if (boxDistance > radiusToUse) {
|
||||
discard;
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
|
||||
vec2 noiseResolution = vec2(textureSize(tNoise, 0));
|
||||
vec2 noiseUv = vUv * resolution / noiseResolution;
|
||||
vec4 noiseTexel = textureLod(tNoise, noiseUv, 0.0);
|
||||
vec3 randomVec = noiseTexel.xyz * 2.0 - 1.0;
|
||||
vec3 tangent = normalize(vec3(randomVec.xy, 0.));
|
||||
vec3 bitangent = vec3(-tangent.y, tangent.x, 0.);
|
||||
mat3 kernelMatrix = mat3(tangent, bitangent, vec3(0., 0., 1.));
|
||||
|
||||
const int DIRECTIONS = SAMPLES < 30 ? 3 : 5;
|
||||
const int STEPS = (SAMPLES + DIRECTIONS - 1) / DIRECTIONS;
|
||||
float ao = 0.0;
|
||||
for (int i = 0; i < DIRECTIONS; ++i) {
|
||||
|
||||
float angle = float(i) / float(DIRECTIONS) * PI;
|
||||
vec4 sampleDir = vec4(cos(angle), sin(angle), 0., 0.5 + 0.5 * noiseTexel.w);
|
||||
sampleDir.xyz = normalize(kernelMatrix * sampleDir.xyz);
|
||||
|
||||
#if PERSPECTIVE_CAMERA == 1
|
||||
vec3 viewDir = normalize(-viewPos.xyz);
|
||||
#else
|
||||
vec3 viewDir = vec3(0., 0., 1.);
|
||||
#endif
|
||||
vec3 sliceBitangent = normalize(cross(sampleDir.xyz, viewDir));
|
||||
vec3 sliceTangent = cross(sliceBitangent, viewDir);
|
||||
vec3 normalInSlice = normalize(viewNormal - sliceBitangent * dot(viewNormal, sliceBitangent));
|
||||
|
||||
vec3 tangentToNormalInSlice = cross(normalInSlice, sliceBitangent);
|
||||
vec2 cosHorizons = vec2(dot(viewDir, tangentToNormalInSlice), dot(viewDir, -tangentToNormalInSlice));
|
||||
|
||||
for (int j = 0; j < STEPS; ++j) {
|
||||
vec3 sampleViewOffset = sampleDir.xyz * radiusToUse * sampleDir.w * pow(float(j + 1) / float(STEPS), distanceExponent);
|
||||
|
||||
vec3 sampleSceneUvDepth = getSceneUvAndDepth(viewPos + sampleViewOffset);
|
||||
vec3 sampleSceneViewPos = getViewPosition(sampleSceneUvDepth.xy, sampleSceneUvDepth.z);
|
||||
vec3 viewDelta = sampleSceneViewPos - viewPos;
|
||||
if (abs(viewDelta.z) < thickness) {
|
||||
float sampleCosHorizon = dot(viewDir, normalize(viewDelta));
|
||||
cosHorizons.x += max(0., (sampleCosHorizon - cosHorizons.x) * mix(1., 2. / float(j + 2), distanceFallOff));
|
||||
}
|
||||
|
||||
sampleSceneUvDepth = getSceneUvAndDepth(viewPos - sampleViewOffset);
|
||||
sampleSceneViewPos = getViewPosition(sampleSceneUvDepth.xy, sampleSceneUvDepth.z);
|
||||
viewDelta = sampleSceneViewPos - viewPos;
|
||||
if (abs(viewDelta.z) < thickness) {
|
||||
float sampleCosHorizon = dot(viewDir, normalize(viewDelta));
|
||||
cosHorizons.y += max(0., (sampleCosHorizon - cosHorizons.y) * mix(1., 2. / float(j + 2), distanceFallOff));
|
||||
}
|
||||
}
|
||||
|
||||
vec2 sinHorizons = sqrt(1. - cosHorizons * cosHorizons);
|
||||
float nx = dot(normalInSlice, sliceTangent);
|
||||
float ny = dot(normalInSlice, viewDir);
|
||||
float nxb = 1. / 2. * (acos(cosHorizons.y) - acos(cosHorizons.x) + sinHorizons.x * cosHorizons.x - sinHorizons.y * cosHorizons.y);
|
||||
float nyb = 1. / 2. * (2. - cosHorizons.x * cosHorizons.x - cosHorizons.y * cosHorizons.y);
|
||||
float occlusion = nx * nxb + ny * nyb;
|
||||
ao += occlusion;
|
||||
}
|
||||
|
||||
ao = clamp(ao / float(DIRECTIONS), 0., 1.);
|
||||
#if SCENE_CLIP_BOX == 1
|
||||
ao = mix(ao, 1., smoothstep(0., radiusToUse, boxDistance));
|
||||
#endif
|
||||
ao = pow(ao, scale);
|
||||
|
||||
gl_FragColor = FRAGMENT_OUTPUT;
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* GTAO depth shader. Use by {@link GTAOPass}.
|
||||
*
|
||||
* @constant
|
||||
* @type {Object}
|
||||
*/
|
||||
const GTAODepthShader = {
|
||||
|
||||
name: 'GTAODepthShader',
|
||||
|
||||
defines: {
|
||||
PERSPECTIVE_CAMERA: 1
|
||||
},
|
||||
|
||||
uniforms: {
|
||||
tDepth: { value: null },
|
||||
cameraNear: { value: null },
|
||||
cameraFar: { value: null },
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
uniform sampler2D tDepth;
|
||||
uniform float cameraNear;
|
||||
uniform float cameraFar;
|
||||
varying vec2 vUv;
|
||||
|
||||
#include <packing>
|
||||
|
||||
float getLinearDepth( const in vec2 screenPosition ) {
|
||||
#if PERSPECTIVE_CAMERA == 1
|
||||
float fragCoordZ = texture2D( tDepth, screenPosition ).x;
|
||||
float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar );
|
||||
return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
|
||||
#else
|
||||
return texture2D( tDepth, screenPosition ).x;
|
||||
#endif
|
||||
}
|
||||
|
||||
void main() {
|
||||
float depth = getLinearDepth( vUv );
|
||||
gl_FragColor = vec4( vec3( 1.0 - depth ), 1.0 );
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* GTAO blend shader. Use by {@link GTAOPass}.
|
||||
*
|
||||
* @constant
|
||||
* @type {Object}
|
||||
*/
|
||||
const GTAOBlendShader = {
|
||||
|
||||
name: 'GTAOBlendShader',
|
||||
|
||||
uniforms: {
|
||||
tDiffuse: { value: null },
|
||||
intensity: { value: 1.0 }
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
uniform float intensity;
|
||||
uniform sampler2D tDiffuse;
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
vec4 texel = texture2D( tDiffuse, vUv );
|
||||
gl_FragColor = vec4(mix(vec3(1.), texel.rgb, intensity), texel.a);
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
|
||||
function generateMagicSquareNoise( size = 5 ) {
|
||||
|
||||
const noiseSize = Math.floor( size ) % 2 === 0 ? Math.floor( size ) + 1 : Math.floor( size );
|
||||
const magicSquare = generateMagicSquare( noiseSize );
|
||||
const noiseSquareSize = magicSquare.length;
|
||||
const data = new Uint8Array( noiseSquareSize * 4 );
|
||||
|
||||
for ( let inx = 0; inx < noiseSquareSize; ++ inx ) {
|
||||
|
||||
const iAng = magicSquare[ inx ];
|
||||
const angle = ( 2 * Math.PI * iAng ) / noiseSquareSize;
|
||||
const randomVec = new Vector3(
|
||||
Math.cos( angle ),
|
||||
Math.sin( angle ),
|
||||
0
|
||||
).normalize();
|
||||
data[ inx * 4 ] = ( randomVec.x * 0.5 + 0.5 ) * 255;
|
||||
data[ inx * 4 + 1 ] = ( randomVec.y * 0.5 + 0.5 ) * 255;
|
||||
data[ inx * 4 + 2 ] = 127;
|
||||
data[ inx * 4 + 3 ] = 255;
|
||||
|
||||
}
|
||||
|
||||
const noiseTexture = new DataTexture( data, noiseSize, noiseSize );
|
||||
noiseTexture.wrapS = RepeatWrapping;
|
||||
noiseTexture.wrapT = RepeatWrapping;
|
||||
noiseTexture.needsUpdate = true;
|
||||
|
||||
return noiseTexture;
|
||||
|
||||
}
|
||||
|
||||
function generateMagicSquare( size ) {
|
||||
|
||||
const noiseSize = Math.floor( size ) % 2 === 0 ? Math.floor( size ) + 1 : Math.floor( size );
|
||||
const noiseSquareSize = noiseSize * noiseSize;
|
||||
const magicSquare = Array( noiseSquareSize ).fill( 0 );
|
||||
let i = Math.floor( noiseSize / 2 );
|
||||
let j = noiseSize - 1;
|
||||
|
||||
for ( let num = 1; num <= noiseSquareSize; ) {
|
||||
|
||||
if ( i === - 1 && j === noiseSize ) {
|
||||
|
||||
j = noiseSize - 2;
|
||||
i = 0;
|
||||
|
||||
} else {
|
||||
|
||||
if ( j === noiseSize ) {
|
||||
|
||||
j = 0;
|
||||
|
||||
}
|
||||
|
||||
if ( i < 0 ) {
|
||||
|
||||
i = noiseSize - 1;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if ( magicSquare[ i * noiseSize + j ] !== 0 ) {
|
||||
|
||||
j -= 2;
|
||||
i ++;
|
||||
continue;
|
||||
|
||||
} else {
|
||||
|
||||
magicSquare[ i * noiseSize + j ] = num ++;
|
||||
|
||||
}
|
||||
|
||||
j ++;
|
||||
i --;
|
||||
|
||||
}
|
||||
|
||||
return magicSquare;
|
||||
|
||||
}
|
||||
|
||||
|
||||
export { generateMagicSquareNoise, GTAOShader, GTAODepthShader, GTAOBlendShader };
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* @module GammaCorrectionShader
|
||||
* @three_import import { GammaCorrectionShader } from 'three/addons/shaders/GammaCorrectionShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Gamma Correction Shader
|
||||
*
|
||||
* References:
|
||||
* - {@link http://en.wikipedia.org/wiki/gamma_correction}.
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const GammaCorrectionShader = {
|
||||
|
||||
name: 'GammaCorrectionShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDiffuse': { value: null }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform sampler2D tDiffuse;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vec4 tex = texture2D( tDiffuse, vUv );
|
||||
|
||||
gl_FragColor = sRGBTransferOETF( tex );
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { GammaCorrectionShader };
|
||||
@@ -0,0 +1,332 @@
|
||||
/**
|
||||
* @module HalftoneShader
|
||||
* @three_import import { HalftoneShader } from 'three/addons/shaders/HalftoneShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* RGB Halftone shader.
|
||||
*
|
||||
* Used by {@link HalftonePass}.
|
||||
*
|
||||
* Shape (1 = Dot, 2 = Ellipse, 3 = Line, 4 = Square, 5 = Diamond)
|
||||
* Blending Mode (1 = Linear, 2 = Multiply, 3 = Add, 4 = Lighter, 5 = Darker)
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const HalftoneShader = {
|
||||
|
||||
name: 'HalftoneShader',
|
||||
|
||||
uniforms: {
|
||||
'tDiffuse': { value: null },
|
||||
'shape': { value: 1 },
|
||||
'radius': { value: 4 },
|
||||
'rotateR': { value: Math.PI / 12 * 1 },
|
||||
'rotateG': { value: Math.PI / 12 * 2 },
|
||||
'rotateB': { value: Math.PI / 12 * 3 },
|
||||
'scatter': { value: 0 },
|
||||
'width': { value: 1 },
|
||||
'height': { value: 1 },
|
||||
'blending': { value: 1 },
|
||||
'blendingMode': { value: 1 },
|
||||
'greyscale': { value: false },
|
||||
'disable': { value: false }
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUV;
|
||||
|
||||
void main() {
|
||||
|
||||
vUV = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
#define SQRT2_MINUS_ONE 0.41421356
|
||||
#define SQRT2_HALF_MINUS_ONE 0.20710678
|
||||
#define PI 3.14159265
|
||||
#define PI2 6.28318531
|
||||
#define SHAPE_DOT 1
|
||||
#define SHAPE_ELLIPSE 2
|
||||
#define SHAPE_LINE 3
|
||||
#define SHAPE_SQUARE 4
|
||||
#define SHAPE_DIAMOND 5
|
||||
#define BLENDING_LINEAR 1
|
||||
#define BLENDING_MULTIPLY 2
|
||||
#define BLENDING_ADD 3
|
||||
#define BLENDING_LIGHTER 4
|
||||
#define BLENDING_DARKER 5
|
||||
uniform sampler2D tDiffuse;
|
||||
uniform float radius;
|
||||
uniform float rotateR;
|
||||
uniform float rotateG;
|
||||
uniform float rotateB;
|
||||
uniform float scatter;
|
||||
uniform float width;
|
||||
uniform float height;
|
||||
uniform int shape;
|
||||
uniform bool disable;
|
||||
uniform float blending;
|
||||
uniform int blendingMode;
|
||||
varying vec2 vUV;
|
||||
uniform bool greyscale;
|
||||
const int samples = 8;
|
||||
|
||||
float blend( float a, float b, float t ) {
|
||||
|
||||
// linear blend
|
||||
return a * ( 1.0 - t ) + b * t;
|
||||
|
||||
}
|
||||
|
||||
float hypot( float x, float y ) {
|
||||
|
||||
// vector magnitude
|
||||
return sqrt( x * x + y * y );
|
||||
|
||||
}
|
||||
|
||||
float rand( vec2 seed ){
|
||||
|
||||
// get pseudo-random number
|
||||
return fract( sin( dot( seed.xy, vec2( 12.9898, 78.233 ) ) ) * 43758.5453 );
|
||||
|
||||
}
|
||||
|
||||
float distanceToDotRadius( float channel, vec2 coord, vec2 normal, vec2 p, float angle, float rad_max ) {
|
||||
|
||||
// apply shape-specific transforms
|
||||
float dist = hypot( coord.x - p.x, coord.y - p.y );
|
||||
float rad = channel;
|
||||
|
||||
if ( shape == SHAPE_DOT ) {
|
||||
|
||||
rad = pow( abs( rad ), 1.125 ) * rad_max;
|
||||
|
||||
} else if ( shape == SHAPE_ELLIPSE ) {
|
||||
|
||||
rad = pow( abs( rad ), 1.125 ) * rad_max;
|
||||
|
||||
if ( dist != 0.0 ) {
|
||||
float dot_p = abs( ( p.x - coord.x ) / dist * normal.x + ( p.y - coord.y ) / dist * normal.y );
|
||||
dist = ( dist * ( 1.0 - SQRT2_HALF_MINUS_ONE ) ) + dot_p * dist * SQRT2_MINUS_ONE;
|
||||
}
|
||||
|
||||
} else if ( shape == SHAPE_LINE ) {
|
||||
|
||||
rad = pow( abs( rad ), 1.5) * rad_max;
|
||||
float dot_p = ( p.x - coord.x ) * normal.x + ( p.y - coord.y ) * normal.y;
|
||||
dist = hypot( normal.x * dot_p, normal.y * dot_p );
|
||||
|
||||
} else if ( shape == SHAPE_SQUARE ) {
|
||||
|
||||
float theta = atan( p.y - coord.y, p.x - coord.x ) - angle;
|
||||
float sin_t = abs( sin( theta ) );
|
||||
float cos_t = abs( cos( theta ) );
|
||||
rad = pow( abs( rad ), 1.4 );
|
||||
rad = rad_max * ( rad + ( ( sin_t > cos_t ) ? rad - sin_t * rad : rad - cos_t * rad ) );
|
||||
|
||||
} else if ( shape == SHAPE_DIAMOND ) {
|
||||
|
||||
float angle45 = PI / 4.0;
|
||||
float theta = atan( p.y - coord.y, p.x - coord.x ) - angle - angle45;
|
||||
float sin_t = abs( sin( theta ) );
|
||||
float cos_t = abs( cos( theta ) );
|
||||
rad = pow( abs( rad ), 1.4 );
|
||||
rad = rad_max * ( rad + ( ( sin_t > cos_t ) ? rad - sin_t * rad : rad - cos_t * rad ) );
|
||||
|
||||
}
|
||||
|
||||
return rad - dist;
|
||||
|
||||
}
|
||||
|
||||
struct Cell {
|
||||
|
||||
// grid sample positions
|
||||
vec2 normal;
|
||||
vec2 p1;
|
||||
vec2 p2;
|
||||
vec2 p3;
|
||||
vec2 p4;
|
||||
float samp2;
|
||||
float samp1;
|
||||
float samp3;
|
||||
float samp4;
|
||||
|
||||
};
|
||||
|
||||
vec4 getSample( vec2 point ) {
|
||||
|
||||
// multi-sampled point
|
||||
vec4 tex = texture2D( tDiffuse, vec2( point.x / width, point.y / height ) );
|
||||
float base = rand( vec2( floor( point.x ), floor( point.y ) ) ) * PI2;
|
||||
float step = PI2 / float( samples );
|
||||
float dist = radius * 0.66;
|
||||
|
||||
for ( int i = 0; i < samples; ++i ) {
|
||||
|
||||
float r = base + step * float( i );
|
||||
vec2 coord = point + vec2( cos( r ) * dist, sin( r ) * dist );
|
||||
tex += texture2D( tDiffuse, vec2( coord.x / width, coord.y / height ) );
|
||||
|
||||
}
|
||||
|
||||
tex /= float( samples ) + 1.0;
|
||||
return tex;
|
||||
|
||||
}
|
||||
|
||||
float getDotColour( Cell c, vec2 p, int channel, float angle, float aa ) {
|
||||
|
||||
// get colour for given point
|
||||
float dist_c_1, dist_c_2, dist_c_3, dist_c_4, res;
|
||||
|
||||
if ( channel == 0 ) {
|
||||
|
||||
c.samp1 = getSample( c.p1 ).r;
|
||||
c.samp2 = getSample( c.p2 ).r;
|
||||
c.samp3 = getSample( c.p3 ).r;
|
||||
c.samp4 = getSample( c.p4 ).r;
|
||||
|
||||
} else if (channel == 1) {
|
||||
|
||||
c.samp1 = getSample( c.p1 ).g;
|
||||
c.samp2 = getSample( c.p2 ).g;
|
||||
c.samp3 = getSample( c.p3 ).g;
|
||||
c.samp4 = getSample( c.p4 ).g;
|
||||
|
||||
} else {
|
||||
|
||||
c.samp1 = getSample( c.p1 ).b;
|
||||
c.samp3 = getSample( c.p3 ).b;
|
||||
c.samp2 = getSample( c.p2 ).b;
|
||||
c.samp4 = getSample( c.p4 ).b;
|
||||
|
||||
}
|
||||
|
||||
dist_c_1 = distanceToDotRadius( c.samp1, c.p1, c.normal, p, angle, radius );
|
||||
dist_c_2 = distanceToDotRadius( c.samp2, c.p2, c.normal, p, angle, radius );
|
||||
dist_c_3 = distanceToDotRadius( c.samp3, c.p3, c.normal, p, angle, radius );
|
||||
dist_c_4 = distanceToDotRadius( c.samp4, c.p4, c.normal, p, angle, radius );
|
||||
res = ( dist_c_1 > 0.0 ) ? clamp( dist_c_1 / aa, 0.0, 1.0 ) : 0.0;
|
||||
res += ( dist_c_2 > 0.0 ) ? clamp( dist_c_2 / aa, 0.0, 1.0 ) : 0.0;
|
||||
res += ( dist_c_3 > 0.0 ) ? clamp( dist_c_3 / aa, 0.0, 1.0 ) : 0.0;
|
||||
res += ( dist_c_4 > 0.0 ) ? clamp( dist_c_4 / aa, 0.0, 1.0 ) : 0.0;
|
||||
res = clamp( res, 0.0, 1.0 );
|
||||
|
||||
return res;
|
||||
|
||||
}
|
||||
|
||||
Cell getReferenceCell( vec2 p, vec2 origin, float grid_angle, float step ) {
|
||||
|
||||
// get containing cell
|
||||
Cell c;
|
||||
|
||||
// calc grid
|
||||
vec2 n = vec2( cos( grid_angle ), sin( grid_angle ) );
|
||||
float threshold = step * 0.5;
|
||||
float dot_normal = n.x * ( p.x - origin.x ) + n.y * ( p.y - origin.y );
|
||||
float dot_line = -n.y * ( p.x - origin.x ) + n.x * ( p.y - origin.y );
|
||||
vec2 offset = vec2( n.x * dot_normal, n.y * dot_normal );
|
||||
float offset_normal = mod( hypot( offset.x, offset.y ), step );
|
||||
float normal_dir = ( dot_normal < 0.0 ) ? 1.0 : -1.0;
|
||||
float normal_scale = ( ( offset_normal < threshold ) ? -offset_normal : step - offset_normal ) * normal_dir;
|
||||
float offset_line = mod( hypot( ( p.x - offset.x ) - origin.x, ( p.y - offset.y ) - origin.y ), step );
|
||||
float line_dir = ( dot_line < 0.0 ) ? 1.0 : -1.0;
|
||||
float line_scale = ( ( offset_line < threshold ) ? -offset_line : step - offset_line ) * line_dir;
|
||||
|
||||
// get closest corner
|
||||
c.normal = n;
|
||||
c.p1.x = p.x - n.x * normal_scale + n.y * line_scale;
|
||||
c.p1.y = p.y - n.y * normal_scale - n.x * line_scale;
|
||||
|
||||
// scatter
|
||||
if ( scatter != 0.0 ) {
|
||||
|
||||
float off_mag = scatter * threshold * 0.5;
|
||||
float off_angle = rand( vec2( floor( c.p1.x ), floor( c.p1.y ) ) ) * PI2;
|
||||
c.p1.x += cos( off_angle ) * off_mag;
|
||||
c.p1.y += sin( off_angle ) * off_mag;
|
||||
|
||||
}
|
||||
|
||||
// find corners
|
||||
float normal_step = normal_dir * ( ( offset_normal < threshold ) ? step : -step );
|
||||
float line_step = line_dir * ( ( offset_line < threshold ) ? step : -step );
|
||||
c.p2.x = c.p1.x - n.x * normal_step;
|
||||
c.p2.y = c.p1.y - n.y * normal_step;
|
||||
c.p3.x = c.p1.x + n.y * line_step;
|
||||
c.p3.y = c.p1.y - n.x * line_step;
|
||||
c.p4.x = c.p1.x - n.x * normal_step + n.y * line_step;
|
||||
c.p4.y = c.p1.y - n.y * normal_step - n.x * line_step;
|
||||
|
||||
return c;
|
||||
|
||||
}
|
||||
|
||||
float blendColour( float a, float b, float t ) {
|
||||
|
||||
// blend colours
|
||||
if ( blendingMode == BLENDING_LINEAR ) {
|
||||
return blend( a, b, 1.0 - t );
|
||||
} else if ( blendingMode == BLENDING_ADD ) {
|
||||
return blend( a, min( 1.0, a + b ), t );
|
||||
} else if ( blendingMode == BLENDING_MULTIPLY ) {
|
||||
return blend( a, max( 0.0, a * b ), t );
|
||||
} else if ( blendingMode == BLENDING_LIGHTER ) {
|
||||
return blend( a, max( a, b ), t );
|
||||
} else if ( blendingMode == BLENDING_DARKER ) {
|
||||
return blend( a, min( a, b ), t );
|
||||
} else {
|
||||
return blend( a, b, 1.0 - t );
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void main() {
|
||||
|
||||
if ( ! disable ) {
|
||||
|
||||
// setup
|
||||
vec2 p = vec2( vUV.x * width, vUV.y * height );
|
||||
vec2 origin = vec2( 0, 0 );
|
||||
float aa = ( radius < 2.5 ) ? radius * 0.5 : 1.25;
|
||||
|
||||
// get channel samples
|
||||
Cell cell_r = getReferenceCell( p, origin, rotateR, radius );
|
||||
Cell cell_g = getReferenceCell( p, origin, rotateG, radius );
|
||||
Cell cell_b = getReferenceCell( p, origin, rotateB, radius );
|
||||
float r = getDotColour( cell_r, p, 0, rotateR, aa );
|
||||
float g = getDotColour( cell_g, p, 1, rotateG, aa );
|
||||
float b = getDotColour( cell_b, p, 2, rotateB, aa );
|
||||
|
||||
// blend with original
|
||||
vec4 colour = texture2D( tDiffuse, vUV );
|
||||
r = blendColour( r, colour.r, blending );
|
||||
g = blendColour( g, colour.g, blending );
|
||||
b = blendColour( b, colour.b, blending );
|
||||
|
||||
if ( greyscale ) {
|
||||
r = g = b = (r + b + g) / 3.0;
|
||||
}
|
||||
|
||||
gl_FragColor = vec4( r, g, b, 1.0 );
|
||||
|
||||
} else {
|
||||
|
||||
gl_FragColor = texture2D( tDiffuse, vUV );
|
||||
|
||||
}
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { HalftoneShader };
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* @module HorizontalBlurShader
|
||||
* @three_import import { HorizontalBlurShader } from 'three/addons/shaders/HorizontalBlurShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Two pass Gaussian blur filter (horizontal and vertical blur shaders).
|
||||
*
|
||||
* References:
|
||||
* - {@link http://www.cake23.de/traveling-wavefronts-lit-up.html}.
|
||||
*
|
||||
* - 9 samples per pass
|
||||
* - standard deviation 2.7
|
||||
* - "h" and "v" parameters should be set to "1 / width" and "1 / height"
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const HorizontalBlurShader = {
|
||||
|
||||
name: 'HorizontalBlurShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDiffuse': { value: null },
|
||||
'h': { value: 1.0 / 512.0 }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform sampler2D tDiffuse;
|
||||
uniform float h;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vec4 sum = vec4( 0.0 );
|
||||
|
||||
sum += texture2D( tDiffuse, vec2( vUv.x - 4.0 * h, vUv.y ) ) * 0.051;
|
||||
sum += texture2D( tDiffuse, vec2( vUv.x - 3.0 * h, vUv.y ) ) * 0.0918;
|
||||
sum += texture2D( tDiffuse, vec2( vUv.x - 2.0 * h, vUv.y ) ) * 0.12245;
|
||||
sum += texture2D( tDiffuse, vec2( vUv.x - 1.0 * h, vUv.y ) ) * 0.1531;
|
||||
sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y ) ) * 0.1633;
|
||||
sum += texture2D( tDiffuse, vec2( vUv.x + 1.0 * h, vUv.y ) ) * 0.1531;
|
||||
sum += texture2D( tDiffuse, vec2( vUv.x + 2.0 * h, vUv.y ) ) * 0.12245;
|
||||
sum += texture2D( tDiffuse, vec2( vUv.x + 3.0 * h, vUv.y ) ) * 0.0918;
|
||||
sum += texture2D( tDiffuse, vec2( vUv.x + 4.0 * h, vUv.y ) ) * 0.051;
|
||||
|
||||
gl_FragColor = sum;
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { HorizontalBlurShader };
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* @module HorizontalTiltShiftShader
|
||||
* @three_import import { HorizontalTiltShiftShader } from 'three/addons/shaders/HorizontalTiltShiftShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Simple fake tilt-shift effect, modulating two pass Gaussian blur (see above) by vertical position.
|
||||
*
|
||||
* - 9 samples per pass
|
||||
* - standard deviation 2.7
|
||||
* - "h" and "v" parameters should be set to "1 / width" and "1 / height"
|
||||
* - "r" parameter control where "focused" horizontal line lies
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const HorizontalTiltShiftShader = {
|
||||
|
||||
name: 'HorizontalTiltShiftShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDiffuse': { value: null },
|
||||
'h': { value: 1.0 / 512.0 },
|
||||
'r': { value: 0.35 }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform sampler2D tDiffuse;
|
||||
uniform float h;
|
||||
uniform float r;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vec4 sum = vec4( 0.0 );
|
||||
|
||||
float hh = h * abs( r - vUv.y );
|
||||
|
||||
sum += texture2D( tDiffuse, vec2( vUv.x - 4.0 * hh, vUv.y ) ) * 0.051;
|
||||
sum += texture2D( tDiffuse, vec2( vUv.x - 3.0 * hh, vUv.y ) ) * 0.0918;
|
||||
sum += texture2D( tDiffuse, vec2( vUv.x - 2.0 * hh, vUv.y ) ) * 0.12245;
|
||||
sum += texture2D( tDiffuse, vec2( vUv.x - 1.0 * hh, vUv.y ) ) * 0.1531;
|
||||
sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y ) ) * 0.1633;
|
||||
sum += texture2D( tDiffuse, vec2( vUv.x + 1.0 * hh, vUv.y ) ) * 0.1531;
|
||||
sum += texture2D( tDiffuse, vec2( vUv.x + 2.0 * hh, vUv.y ) ) * 0.12245;
|
||||
sum += texture2D( tDiffuse, vec2( vUv.x + 3.0 * hh, vUv.y ) ) * 0.0918;
|
||||
sum += texture2D( tDiffuse, vec2( vUv.x + 4.0 * hh, vUv.y ) ) * 0.051;
|
||||
|
||||
gl_FragColor = sum;
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { HorizontalTiltShiftShader };
|
||||
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* @module HueSaturationShader
|
||||
* @three_import import { HueSaturationShader } from 'three/addons/shaders/HueSaturationShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Hue and saturation adjustment, {@link https://github.com/evanw/glfx.js}.
|
||||
*
|
||||
* hue: -1 to 1 (-1 is 180 degrees in the negative direction, 0 is no change, etc.
|
||||
* saturation: -1 to 1 (-1 is solid gray, 0 is no change, and 1 is maximum contrast)
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const HueSaturationShader = {
|
||||
|
||||
name: 'HueSaturationShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDiffuse': { value: null },
|
||||
'hue': { value: 0 },
|
||||
'saturation': { value: 0 }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform sampler2D tDiffuse;
|
||||
uniform float hue;
|
||||
uniform float saturation;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
gl_FragColor = texture2D( tDiffuse, vUv );
|
||||
|
||||
// hue
|
||||
float angle = hue * 3.14159265;
|
||||
float s = sin(angle), c = cos(angle);
|
||||
vec3 weights = (vec3(2.0 * c, -sqrt(3.0) * s - c, sqrt(3.0) * s - c) + 1.0) / 3.0;
|
||||
float len = length(gl_FragColor.rgb);
|
||||
gl_FragColor.rgb = vec3(
|
||||
dot(gl_FragColor.rgb, weights.xyz),
|
||||
dot(gl_FragColor.rgb, weights.zxy),
|
||||
dot(gl_FragColor.rgb, weights.yzx)
|
||||
);
|
||||
|
||||
// saturation
|
||||
float average = (gl_FragColor.r + gl_FragColor.g + gl_FragColor.b) / 3.0;
|
||||
if (saturation > 0.0) {
|
||||
gl_FragColor.rgb += (average - gl_FragColor.rgb) * (1.0 - 1.0 / (1.001 - saturation));
|
||||
} else {
|
||||
gl_FragColor.rgb += (average - gl_FragColor.rgb) * (-saturation);
|
||||
}
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { HueSaturationShader };
|
||||
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* @module KaleidoShader
|
||||
* @three_import import { KaleidoShader } from 'three/addons/shaders/KaleidoShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Kaleidoscope Shader.
|
||||
* Radial reflection around center point
|
||||
* Ported from: {@link http://pixelshaders.com/editor/}
|
||||
* by [Toby Schachman](http://tobyschachman.com/)
|
||||
*
|
||||
* sides: number of reflections
|
||||
* angle: initial angle in radians
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const KaleidoShader = {
|
||||
|
||||
name: 'KaleidoShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDiffuse': { value: null },
|
||||
'sides': { value: 6.0 },
|
||||
'angle': { value: 0.0 }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform sampler2D tDiffuse;
|
||||
uniform float sides;
|
||||
uniform float angle;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vec2 p = vUv - 0.5;
|
||||
float r = length(p);
|
||||
float a = atan(p.y, p.x) + angle;
|
||||
float tau = 2. * 3.1416 ;
|
||||
a = mod(a, tau/sides);
|
||||
a = abs(a - tau/sides/2.) ;
|
||||
p = r * vec2(cos(a), sin(a));
|
||||
vec4 color = texture2D(tDiffuse, p + 0.5);
|
||||
gl_FragColor = color;
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { KaleidoShader };
|
||||
@@ -0,0 +1,68 @@
|
||||
import {
|
||||
Color
|
||||
} from 'three';
|
||||
|
||||
/**
|
||||
* @module LuminosityHighPassShader
|
||||
* @three_import import { LuminosityHighPassShader } from 'three/addons/shaders/LuminosityHighPassShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Luminosity high pass shader.
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const LuminosityHighPassShader = {
|
||||
|
||||
name: 'LuminosityHighPassShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDiffuse': { value: null },
|
||||
'luminosityThreshold': { value: 1.0 },
|
||||
'smoothWidth': { value: 1.0 },
|
||||
'defaultColor': { value: new Color( 0x000000 ) },
|
||||
'defaultOpacity': { value: 0.0 }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform sampler2D tDiffuse;
|
||||
uniform vec3 defaultColor;
|
||||
uniform float defaultOpacity;
|
||||
uniform float luminosityThreshold;
|
||||
uniform float smoothWidth;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vec4 texel = texture2D( tDiffuse, vUv );
|
||||
|
||||
float v = luminance( texel.xyz );
|
||||
|
||||
vec4 outputColor = vec4( defaultColor.rgb, defaultOpacity );
|
||||
|
||||
float alpha = smoothstep( luminosityThreshold, luminosityThreshold + smoothWidth, v );
|
||||
|
||||
gl_FragColor = mix( outputColor, texel, alpha );
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { LuminosityHighPassShader };
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* @module LuminosityShader
|
||||
* @three_import import { LuminosityShader } from 'three/addons/shaders/LuminosityShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Luminosity shader.
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const LuminosityShader = {
|
||||
|
||||
name: 'LuminosityShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDiffuse': { value: null }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
#include <common>
|
||||
|
||||
uniform sampler2D tDiffuse;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vec4 texel = texture2D( tDiffuse, vUv );
|
||||
|
||||
float l = luminance( texel.rgb );
|
||||
|
||||
gl_FragColor = vec4( l, l, l, texel.w );
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { LuminosityShader };
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* @module MirrorShader
|
||||
* @three_import import { MirrorShader } from 'three/addons/shaders/MirrorShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Copies half the input to the other half.
|
||||
*
|
||||
* side: side of input to mirror (0 = left, 1 = right, 2 = top, 3 = bottom).
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const MirrorShader = {
|
||||
|
||||
name: 'MirrorShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDiffuse': { value: null },
|
||||
'side': { value: 1 }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform sampler2D tDiffuse;
|
||||
uniform int side;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vec2 p = vUv;
|
||||
if (side == 0){
|
||||
if (p.x > 0.5) p.x = 1.0 - p.x;
|
||||
}else if (side == 1){
|
||||
if (p.x < 0.5) p.x = 1.0 - p.x;
|
||||
}else if (side == 2){
|
||||
if (p.y < 0.5) p.y = 1.0 - p.y;
|
||||
}else if (side == 3){
|
||||
if (p.y > 0.5) p.y = 1.0 - p.y;
|
||||
}
|
||||
vec4 color = texture2D(tDiffuse, p);
|
||||
gl_FragColor = color;
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { MirrorShader };
|
||||
@@ -0,0 +1,60 @@
|
||||
import {
|
||||
Vector2
|
||||
} from 'three';
|
||||
|
||||
/**
|
||||
* @module NormalMapShader
|
||||
* @three_import import { NormalMapShader } from 'three/addons/shaders/NormalMapShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Normal map shader, compute normals from heightmap.
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const NormalMapShader = {
|
||||
|
||||
name: 'NormalMapShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'heightMap': { value: null },
|
||||
'resolution': { value: new Vector2( 512, 512 ) },
|
||||
'scale': { value: new Vector2( 1, 1 ) },
|
||||
'height': { value: 0.05 }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform float height;
|
||||
uniform vec2 resolution;
|
||||
uniform sampler2D heightMap;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
float val = texture2D( heightMap, vUv ).x;
|
||||
|
||||
float valU = texture2D( heightMap, vUv + vec2( 1.0 / resolution.x, 0.0 ) ).x;
|
||||
float valV = texture2D( heightMap, vUv + vec2( 0.0, 1.0 / resolution.y ) ).x;
|
||||
|
||||
gl_FragColor = vec4( ( 0.5 * normalize( vec3( val - valU, val - valV, height ) ) + 0.5 ), 1.0 );
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { NormalMapShader };
|
||||
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* @module OutputShader
|
||||
* @three_import import { OutputShader } from 'three/addons/shaders/OutputShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Performs tone mapping and color space conversion for
|
||||
* FX workflows.
|
||||
*
|
||||
* Used by {@link OutputPass}.
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const OutputShader = {
|
||||
|
||||
name: 'OutputShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDiffuse': { value: null },
|
||||
'toneMappingExposure': { value: 1 }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
precision highp float;
|
||||
|
||||
uniform mat4 modelViewMatrix;
|
||||
uniform mat4 projectionMatrix;
|
||||
|
||||
attribute vec3 position;
|
||||
attribute vec2 uv;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
precision highp float;
|
||||
|
||||
uniform sampler2D tDiffuse;
|
||||
|
||||
#include <tonemapping_pars_fragment>
|
||||
#include <colorspace_pars_fragment>
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
gl_FragColor = texture2D( tDiffuse, vUv );
|
||||
|
||||
// tone mapping
|
||||
|
||||
#ifdef LINEAR_TONE_MAPPING
|
||||
|
||||
gl_FragColor.rgb = LinearToneMapping( gl_FragColor.rgb );
|
||||
|
||||
#elif defined( REINHARD_TONE_MAPPING )
|
||||
|
||||
gl_FragColor.rgb = ReinhardToneMapping( gl_FragColor.rgb );
|
||||
|
||||
#elif defined( CINEON_TONE_MAPPING )
|
||||
|
||||
gl_FragColor.rgb = CineonToneMapping( gl_FragColor.rgb );
|
||||
|
||||
#elif defined( ACES_FILMIC_TONE_MAPPING )
|
||||
|
||||
gl_FragColor.rgb = ACESFilmicToneMapping( gl_FragColor.rgb );
|
||||
|
||||
#elif defined( AGX_TONE_MAPPING )
|
||||
|
||||
gl_FragColor.rgb = AgXToneMapping( gl_FragColor.rgb );
|
||||
|
||||
#elif defined( NEUTRAL_TONE_MAPPING )
|
||||
|
||||
gl_FragColor.rgb = NeutralToneMapping( gl_FragColor.rgb );
|
||||
|
||||
#elif defined( CUSTOM_TONE_MAPPING )
|
||||
|
||||
gl_FragColor.rgb = CustomToneMapping( gl_FragColor.rgb );
|
||||
|
||||
#endif
|
||||
|
||||
// color space
|
||||
|
||||
#ifdef SRGB_TRANSFER
|
||||
|
||||
gl_FragColor = sRGBTransferOETF( gl_FragColor );
|
||||
|
||||
#endif
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { OutputShader };
|
||||
@@ -0,0 +1,230 @@
|
||||
import {
|
||||
Matrix4,
|
||||
Vector2,
|
||||
Vector3,
|
||||
} from 'three';
|
||||
|
||||
/**
|
||||
* @module PoissonDenoiseShader
|
||||
* @three_import import { PoissonDenoiseShader } from 'three/addons/shaders/PoissonDenoiseShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Poisson Denoise Shader.
|
||||
*
|
||||
* References:
|
||||
* - [Self-Supervised Poisson-Gaussian Denoising](https://openaccess.thecvf.com/content/WACV2021/papers/Khademi_Self-Supervised_Poisson-Gaussian_Denoising_WACV_2021_paper.pdf).
|
||||
* - [Poisson2Sparse: Self-Supervised Poisson Denoising From a Single Image](https://arxiv.org/pdf/2206.01856.pdf)
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const PoissonDenoiseShader = {
|
||||
|
||||
name: 'PoissonDenoiseShader',
|
||||
|
||||
defines: {
|
||||
'SAMPLES': 16,
|
||||
'SAMPLE_VECTORS': generatePdSamplePointInitializer( 16, 2, 1 ),
|
||||
'NORMAL_VECTOR_TYPE': 1,
|
||||
},
|
||||
|
||||
uniforms: {
|
||||
'tDiffuse': { value: null },
|
||||
'tNormal': { value: null },
|
||||
'tDepth': { value: null },
|
||||
'tNoise': { value: null },
|
||||
'resolution': { value: new Vector2() },
|
||||
'cameraProjectionMatrixInverse': { value: new Matrix4() },
|
||||
'lumaPhi': { value: 5. },
|
||||
'depthPhi': { value: 5. },
|
||||
'normalPhi': { value: 5. },
|
||||
'radius': { value: 4. },
|
||||
'index': { value: 0 }
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
uniform sampler2D tDiffuse;
|
||||
uniform sampler2D tNormal;
|
||||
uniform sampler2D tDepth;
|
||||
uniform sampler2D tNoise;
|
||||
uniform vec2 resolution;
|
||||
uniform mat4 cameraProjectionMatrixInverse;
|
||||
uniform float lumaPhi;
|
||||
uniform float depthPhi;
|
||||
uniform float normalPhi;
|
||||
uniform float radius;
|
||||
uniform int index;
|
||||
|
||||
#include <common>
|
||||
#include <packing>
|
||||
|
||||
#ifndef SAMPLE_LUMINANCE
|
||||
#define SAMPLE_LUMINANCE dot(vec3(0.2125, 0.7154, 0.0721), a)
|
||||
#endif
|
||||
|
||||
#ifndef FRAGMENT_OUTPUT
|
||||
#define FRAGMENT_OUTPUT vec4(denoised, 1.)
|
||||
#endif
|
||||
|
||||
float getLuminance(const in vec3 a) {
|
||||
return SAMPLE_LUMINANCE;
|
||||
}
|
||||
|
||||
const vec3 poissonDisk[SAMPLES] = SAMPLE_VECTORS;
|
||||
|
||||
vec3 getViewPosition( const in vec2 screenPosition, const in float depth ) {
|
||||
#ifdef USE_REVERSED_DEPTH_BUFFER
|
||||
vec4 clipSpacePosition = vec4( vec2( screenPosition ) * 2.0 - 1.0, depth, 1.0 );
|
||||
#else
|
||||
vec4 clipSpacePosition = vec4( vec3( screenPosition, depth ) * 2.0 - 1.0, 1.0 );
|
||||
#endif
|
||||
vec4 viewSpacePosition = cameraProjectionMatrixInverse * clipSpacePosition;
|
||||
return viewSpacePosition.xyz / viewSpacePosition.w;
|
||||
}
|
||||
|
||||
float getDepth(const vec2 uv) {
|
||||
return textureLod(tDepth, uv.xy, 0.0).r;
|
||||
}
|
||||
|
||||
float fetchDepth(const ivec2 uv) {
|
||||
return texelFetch(tDepth, uv.xy, 0).r;
|
||||
}
|
||||
|
||||
vec3 computeNormalFromDepth(const vec2 uv) {
|
||||
vec2 size = vec2(textureSize(tDepth, 0));
|
||||
ivec2 p = ivec2(uv * size);
|
||||
float c0 = fetchDepth(p);
|
||||
float l2 = fetchDepth(p - ivec2(2, 0));
|
||||
float l1 = fetchDepth(p - ivec2(1, 0));
|
||||
float r1 = fetchDepth(p + ivec2(1, 0));
|
||||
float r2 = fetchDepth(p + ivec2(2, 0));
|
||||
float b2 = fetchDepth(p - ivec2(0, 2));
|
||||
float b1 = fetchDepth(p - ivec2(0, 1));
|
||||
float t1 = fetchDepth(p + ivec2(0, 1));
|
||||
float t2 = fetchDepth(p + ivec2(0, 2));
|
||||
float dl = abs((2.0 * l1 - l2) - c0);
|
||||
float dr = abs((2.0 * r1 - r2) - c0);
|
||||
float db = abs((2.0 * b1 - b2) - c0);
|
||||
float dt = abs((2.0 * t1 - t2) - c0);
|
||||
vec3 ce = getViewPosition(uv, c0).xyz;
|
||||
vec3 dpdx = (dl < dr) ? ce - getViewPosition((uv - vec2(1.0 / size.x, 0.0)), l1).xyz
|
||||
: -ce + getViewPosition((uv + vec2(1.0 / size.x, 0.0)), r1).xyz;
|
||||
vec3 dpdy = (db < dt) ? ce - getViewPosition((uv - vec2(0.0, 1.0 / size.y)), b1).xyz
|
||||
: -ce + getViewPosition((uv + vec2(0.0, 1.0 / size.y)), t1).xyz;
|
||||
return normalize(cross(dpdx, dpdy));
|
||||
}
|
||||
|
||||
vec3 getViewNormal(const vec2 uv) {
|
||||
#if NORMAL_VECTOR_TYPE == 2
|
||||
return normalize(textureLod(tNormal, uv, 0.).rgb);
|
||||
#elif NORMAL_VECTOR_TYPE == 1
|
||||
return unpackRGBToNormal(textureLod(tNormal, uv, 0.).rgb);
|
||||
#else
|
||||
return computeNormalFromDepth(uv);
|
||||
#endif
|
||||
}
|
||||
|
||||
void denoiseSample(in vec3 center, in vec3 viewNormal, in vec3 viewPos, in vec2 sampleUv, inout vec3 denoised, inout float totalWeight) {
|
||||
vec4 sampleTexel = textureLod(tDiffuse, sampleUv, 0.0);
|
||||
float sampleDepth = getDepth(sampleUv);
|
||||
vec3 sampleNormal = getViewNormal(sampleUv);
|
||||
vec3 neighborColor = sampleTexel.rgb;
|
||||
vec3 viewPosSample = getViewPosition(sampleUv, sampleDepth);
|
||||
|
||||
float normalDiff = dot(viewNormal, sampleNormal);
|
||||
float normalSimilarity = pow(max(normalDiff, 0.), normalPhi);
|
||||
float lumaDiff = abs(getLuminance(neighborColor) - getLuminance(center));
|
||||
float lumaSimilarity = max(1.0 - lumaDiff / lumaPhi, 0.0);
|
||||
float depthDiff = abs(dot(viewPos - viewPosSample, viewNormal));
|
||||
float depthSimilarity = max(1. - depthDiff / depthPhi, 0.);
|
||||
float w = lumaSimilarity * depthSimilarity * normalSimilarity;
|
||||
|
||||
denoised += w * neighborColor;
|
||||
totalWeight += w;
|
||||
}
|
||||
|
||||
void main() {
|
||||
float depth = getDepth(vUv.xy);
|
||||
vec3 viewNormal = getViewNormal(vUv);
|
||||
if (depth == 1. || dot(viewNormal, viewNormal) == 0.) {
|
||||
discard;
|
||||
return;
|
||||
}
|
||||
vec4 texel = textureLod(tDiffuse, vUv, 0.0);
|
||||
vec3 center = texel.rgb;
|
||||
vec3 viewPos = getViewPosition(vUv, depth);
|
||||
|
||||
vec2 noiseResolution = vec2(textureSize(tNoise, 0));
|
||||
vec2 noiseUv = vUv * resolution / noiseResolution;
|
||||
vec4 noiseTexel = textureLod(tNoise, noiseUv, 0.0);
|
||||
vec2 noiseVec = vec2(sin(noiseTexel[index % 4] * 2. * PI), cos(noiseTexel[index % 4] * 2. * PI));
|
||||
mat2 rotationMatrix = mat2(noiseVec.x, -noiseVec.y, noiseVec.x, noiseVec.y);
|
||||
|
||||
float totalWeight = 1.0;
|
||||
vec3 denoised = texel.rgb;
|
||||
for (int i = 0; i < SAMPLES; i++) {
|
||||
vec3 sampleDir = poissonDisk[i];
|
||||
vec2 offset = rotationMatrix * (sampleDir.xy * (1. + sampleDir.z * (radius - 1.)) / resolution);
|
||||
vec2 sampleUv = vUv + offset;
|
||||
denoiseSample(center, viewNormal, viewPos, sampleUv, denoised, totalWeight);
|
||||
}
|
||||
|
||||
if (totalWeight > 0.) {
|
||||
denoised /= totalWeight;
|
||||
}
|
||||
gl_FragColor = FRAGMENT_OUTPUT;
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
function generatePdSamplePointInitializer( samples, rings, radiusExponent ) {
|
||||
|
||||
const poissonDisk = generateDenoiseSamples(
|
||||
samples,
|
||||
rings,
|
||||
radiusExponent,
|
||||
);
|
||||
|
||||
let glslCode = 'vec3[SAMPLES](';
|
||||
|
||||
for ( let i = 0; i < samples; i ++ ) {
|
||||
|
||||
const sample = poissonDisk[ i ];
|
||||
glslCode += `vec3(${sample.x}, ${sample.y}, ${sample.z})${( i < samples - 1 ) ? ',' : ')'}`;
|
||||
|
||||
}
|
||||
|
||||
return glslCode;
|
||||
|
||||
}
|
||||
|
||||
function generateDenoiseSamples( numSamples, numRings, radiusExponent ) {
|
||||
|
||||
const samples = [];
|
||||
|
||||
for ( let i = 0; i < numSamples; i ++ ) {
|
||||
|
||||
const angle = 2 * Math.PI * numRings * i / numSamples;
|
||||
const radius = Math.pow( i / ( numSamples - 1 ), radiusExponent );
|
||||
samples.push( new Vector3( Math.cos( angle ), Math.sin( angle ), radius ) );
|
||||
|
||||
}
|
||||
|
||||
return samples;
|
||||
|
||||
}
|
||||
|
||||
export { generatePdSamplePointInitializer, PoissonDenoiseShader };
|
||||
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* @module RGBShiftShader
|
||||
* @three_import import { RGBShiftShader } from 'three/addons/shaders/RGBShiftShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* RGB Shift Shader
|
||||
* Shifts red and blue channels from center in opposite directions
|
||||
* Ported from https://web.archive.org/web/20090820185047/http://kriss.cx/tom/2009/05/rgb-shift/
|
||||
* by Tom Butterworth / https://web.archive.org/web/20090810054752/http://kriss.cx/tom/
|
||||
*
|
||||
* amount: shift distance (1 is width of input)
|
||||
* angle: shift angle in radians
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const RGBShiftShader = {
|
||||
|
||||
name: 'RGBShiftShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDiffuse': { value: null },
|
||||
'amount': { value: 0.005 },
|
||||
'angle': { value: 0.0 }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform sampler2D tDiffuse;
|
||||
uniform float amount;
|
||||
uniform float angle;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vec2 offset = amount * vec2( cos(angle), sin(angle));
|
||||
vec4 cr = texture2D(tDiffuse, vUv + offset);
|
||||
vec4 cga = texture2D(tDiffuse, vUv);
|
||||
vec4 cb = texture2D(tDiffuse, vUv - offset);
|
||||
gl_FragColor = vec4(cr.r, cga.g, cb.b, cga.a);
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { RGBShiftShader };
|
||||
@@ -0,0 +1,201 @@
|
||||
import {
|
||||
Matrix4,
|
||||
Vector2
|
||||
} from 'three';
|
||||
|
||||
/**
|
||||
* @module SAOShader
|
||||
* @three_import import { SAOShader } from 'three/addons/shaders/SAOShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* SAO shader.
|
||||
*
|
||||
* Used by {@link SAOPass}.
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const SAOShader = {
|
||||
|
||||
name: 'SAOShader',
|
||||
|
||||
defines: {
|
||||
'NUM_SAMPLES': 7,
|
||||
'NUM_RINGS': 4,
|
||||
'DIFFUSE_TEXTURE': 0,
|
||||
'PERSPECTIVE_CAMERA': 1
|
||||
},
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDepth': { value: null },
|
||||
'tDiffuse': { value: null },
|
||||
'tNormal': { value: null },
|
||||
'size': { value: new Vector2( 512, 512 ) },
|
||||
|
||||
'cameraNear': { value: 1 },
|
||||
'cameraFar': { value: 100 },
|
||||
'cameraProjectionMatrix': { value: new Matrix4() },
|
||||
'cameraInverseProjectionMatrix': { value: new Matrix4() },
|
||||
|
||||
'scale': { value: 1.0 },
|
||||
'intensity': { value: 0.1 },
|
||||
'bias': { value: 0.5 },
|
||||
|
||||
'minResolution': { value: 0.0 },
|
||||
'kernelRadius': { value: 100.0 },
|
||||
'randomSeed': { value: 0.0 }
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
#include <common>
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
#if DIFFUSE_TEXTURE == 1
|
||||
uniform sampler2D tDiffuse;
|
||||
#endif
|
||||
|
||||
uniform highp sampler2D tDepth;
|
||||
uniform highp sampler2D tNormal;
|
||||
|
||||
uniform float cameraNear;
|
||||
uniform float cameraFar;
|
||||
uniform mat4 cameraProjectionMatrix;
|
||||
uniform mat4 cameraInverseProjectionMatrix;
|
||||
|
||||
uniform float scale;
|
||||
uniform float intensity;
|
||||
uniform float bias;
|
||||
uniform float kernelRadius;
|
||||
uniform float minResolution;
|
||||
uniform vec2 size;
|
||||
uniform float randomSeed;
|
||||
|
||||
// RGBA depth
|
||||
|
||||
#include <packing>
|
||||
|
||||
vec4 getDefaultColor( const in vec2 screenPosition ) {
|
||||
#if DIFFUSE_TEXTURE == 1
|
||||
return texture2D( tDiffuse, vUv );
|
||||
#else
|
||||
return vec4( 1.0 );
|
||||
#endif
|
||||
}
|
||||
|
||||
float getDepth( const in vec2 screenPosition ) {
|
||||
return texture2D( tDepth, screenPosition ).x;
|
||||
}
|
||||
|
||||
float getViewZ( const in float depth ) {
|
||||
#if PERSPECTIVE_CAMERA == 1
|
||||
return perspectiveDepthToViewZ( depth, cameraNear, cameraFar );
|
||||
#else
|
||||
return orthographicDepthToViewZ( depth, cameraNear, cameraFar );
|
||||
#endif
|
||||
}
|
||||
|
||||
vec3 getViewPosition( const in vec2 screenPosition, const in float depth, const in float viewZ ) {
|
||||
float clipW = cameraProjectionMatrix[2][3] * viewZ + cameraProjectionMatrix[3][3];
|
||||
vec4 clipPosition = vec4( ( vec3( screenPosition, depth ) - 0.5 ) * 2.0, 1.0 );
|
||||
clipPosition *= clipW; // unprojection.
|
||||
|
||||
return ( cameraInverseProjectionMatrix * clipPosition ).xyz;
|
||||
}
|
||||
|
||||
vec3 getViewNormal( const in vec3 viewPosition, const in vec2 screenPosition ) {
|
||||
return unpackRGBToNormal( texture2D( tNormal, screenPosition ).xyz );
|
||||
}
|
||||
|
||||
float scaleDividedByCameraFar;
|
||||
float minResolutionMultipliedByCameraFar;
|
||||
|
||||
float getOcclusion( const in vec3 centerViewPosition, const in vec3 centerViewNormal, const in vec3 sampleViewPosition ) {
|
||||
vec3 viewDelta = sampleViewPosition - centerViewPosition;
|
||||
float viewDistance = length( viewDelta );
|
||||
float scaledScreenDistance = scaleDividedByCameraFar * viewDistance;
|
||||
|
||||
return max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - bias) / (1.0 + pow2( scaledScreenDistance ) );
|
||||
}
|
||||
|
||||
// moving costly divides into consts
|
||||
const float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES );
|
||||
const float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES );
|
||||
|
||||
float getAmbientOcclusion( const in vec3 centerViewPosition ) {
|
||||
// precompute some variables require in getOcclusion.
|
||||
scaleDividedByCameraFar = scale / cameraFar;
|
||||
minResolutionMultipliedByCameraFar = minResolution * cameraFar;
|
||||
vec3 centerViewNormal = getViewNormal( centerViewPosition, vUv );
|
||||
|
||||
// jsfiddle that shows sample pattern: https://jsfiddle.net/a16ff1p7/
|
||||
float angle = rand( vUv + randomSeed ) * PI2;
|
||||
vec2 radius = vec2( kernelRadius * INV_NUM_SAMPLES ) / size;
|
||||
vec2 radiusStep = radius;
|
||||
|
||||
float occlusionSum = 0.0;
|
||||
float weightSum = 0.0;
|
||||
|
||||
for( int i = 0; i < NUM_SAMPLES; i ++ ) {
|
||||
vec2 sampleUv = vUv + vec2( cos( angle ), sin( angle ) ) * radius;
|
||||
radius += radiusStep;
|
||||
angle += ANGLE_STEP;
|
||||
|
||||
float sampleDepth = getDepth( sampleUv );
|
||||
#ifdef USE_REVERSED_DEPTH_BUFFER
|
||||
if( sampleDepth <= 0.0 + EPSILON ) {
|
||||
continue;
|
||||
}
|
||||
#else
|
||||
if( sampleDepth >= 1.0 - EPSILON ) {
|
||||
continue;
|
||||
}
|
||||
#endif
|
||||
|
||||
float sampleViewZ = getViewZ( sampleDepth );
|
||||
vec3 sampleViewPosition = getViewPosition( sampleUv, sampleDepth, sampleViewZ );
|
||||
occlusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition );
|
||||
weightSum += 1.0;
|
||||
}
|
||||
|
||||
if( weightSum == 0.0 ) discard;
|
||||
|
||||
return occlusionSum * ( intensity / weightSum );
|
||||
}
|
||||
|
||||
void main() {
|
||||
float centerDepth = getDepth( vUv );
|
||||
|
||||
#ifdef USE_REVERSED_DEPTH_BUFFER
|
||||
if( centerDepth <= 0.0 + EPSILON ) {
|
||||
discard;
|
||||
}
|
||||
#else
|
||||
if( centerDepth >= 1.0 - EPSILON ) {
|
||||
discard;
|
||||
}
|
||||
#endif
|
||||
|
||||
float centerViewZ = getViewZ( centerDepth );
|
||||
vec3 viewPosition = getViewPosition( vUv, centerDepth, centerViewZ );
|
||||
|
||||
float ambientOcclusion = getAmbientOcclusion( viewPosition );
|
||||
|
||||
gl_FragColor = getDefaultColor( vUv );
|
||||
gl_FragColor.xyz *= 1.0 - ambientOcclusion;
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { SAOShader };
|
||||
@@ -0,0 +1,489 @@
|
||||
import {
|
||||
Vector2
|
||||
} from 'three';
|
||||
|
||||
/**
|
||||
* WebGL port of Subpixel Morphological Antialiasing (SMAA) v2.8
|
||||
* Preset: SMAA 1x Medium (with color edge detection)
|
||||
*
|
||||
* References:
|
||||
* - {@link https://github.com/iryoku/smaa/releases/tag/v2.8}
|
||||
*
|
||||
* @module SMAAShader
|
||||
* @three_import import { SMAAShader } from 'three/addons/shaders/SMAAShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* SMAA Edges shader.
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const SMAAEdgesShader = {
|
||||
|
||||
name: 'SMAAEdgesShader',
|
||||
|
||||
defines: {
|
||||
|
||||
'SMAA_THRESHOLD': '0.1'
|
||||
|
||||
},
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDiffuse': { value: null },
|
||||
'resolution': { value: new Vector2( 1 / 1024, 1 / 512 ) }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
uniform vec2 resolution;
|
||||
|
||||
varying vec2 vUv;
|
||||
varying vec4 vOffset[ 3 ];
|
||||
|
||||
void SMAAEdgeDetectionVS( vec2 texcoord ) {
|
||||
vOffset[ 0 ] = texcoord.xyxy + resolution.xyxy * vec4( -1.0, 0.0, 0.0, 1.0 ); // WebGL port note: Changed sign in W component
|
||||
vOffset[ 1 ] = texcoord.xyxy + resolution.xyxy * vec4( 1.0, 0.0, 0.0, -1.0 ); // WebGL port note: Changed sign in W component
|
||||
vOffset[ 2 ] = texcoord.xyxy + resolution.xyxy * vec4( -2.0, 0.0, 0.0, 2.0 ); // WebGL port note: Changed sign in W component
|
||||
}
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
|
||||
SMAAEdgeDetectionVS( vUv );
|
||||
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform sampler2D tDiffuse;
|
||||
|
||||
varying vec2 vUv;
|
||||
varying vec4 vOffset[ 3 ];
|
||||
|
||||
vec4 SMAAColorEdgeDetectionPS( vec2 texcoord, vec4 offset[3], sampler2D colorTex ) {
|
||||
vec2 threshold = vec2( SMAA_THRESHOLD, SMAA_THRESHOLD );
|
||||
|
||||
// Calculate color deltas:
|
||||
vec4 delta;
|
||||
vec3 C = texture2D( colorTex, texcoord ).rgb;
|
||||
|
||||
vec3 Cleft = texture2D( colorTex, offset[0].xy ).rgb;
|
||||
vec3 t = abs( C - Cleft );
|
||||
delta.x = max( max( t.r, t.g ), t.b );
|
||||
|
||||
vec3 Ctop = texture2D( colorTex, offset[0].zw ).rgb;
|
||||
t = abs( C - Ctop );
|
||||
delta.y = max( max( t.r, t.g ), t.b );
|
||||
|
||||
// We do the usual threshold:
|
||||
vec2 edges = step( threshold, delta.xy );
|
||||
|
||||
// Then discard if there is no edge:
|
||||
if ( dot( edges, vec2( 1.0, 1.0 ) ) == 0.0 )
|
||||
discard;
|
||||
|
||||
// Calculate right and bottom deltas:
|
||||
vec3 Cright = texture2D( colorTex, offset[1].xy ).rgb;
|
||||
t = abs( C - Cright );
|
||||
delta.z = max( max( t.r, t.g ), t.b );
|
||||
|
||||
vec3 Cbottom = texture2D( colorTex, offset[1].zw ).rgb;
|
||||
t = abs( C - Cbottom );
|
||||
delta.w = max( max( t.r, t.g ), t.b );
|
||||
|
||||
// Calculate the maximum delta in the direct neighborhood:
|
||||
float maxDelta = max( max( max( delta.x, delta.y ), delta.z ), delta.w );
|
||||
|
||||
// Calculate left-left and top-top deltas:
|
||||
vec3 Cleftleft = texture2D( colorTex, offset[2].xy ).rgb;
|
||||
t = abs( C - Cleftleft );
|
||||
delta.z = max( max( t.r, t.g ), t.b );
|
||||
|
||||
vec3 Ctoptop = texture2D( colorTex, offset[2].zw ).rgb;
|
||||
t = abs( C - Ctoptop );
|
||||
delta.w = max( max( t.r, t.g ), t.b );
|
||||
|
||||
// Calculate the final maximum delta:
|
||||
maxDelta = max( max( maxDelta, delta.z ), delta.w );
|
||||
|
||||
// Local contrast adaptation in action:
|
||||
edges.xy *= step( 0.5 * maxDelta, delta.xy );
|
||||
|
||||
return vec4( edges, 0.0, 0.0 );
|
||||
}
|
||||
|
||||
void main() {
|
||||
|
||||
gl_FragColor = SMAAColorEdgeDetectionPS( vUv, vOffset, tDiffuse );
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* SMAA Weights shader.
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const SMAAWeightsShader = {
|
||||
|
||||
name: 'SMAAWeightsShader',
|
||||
|
||||
defines: {
|
||||
|
||||
'SMAA_MAX_SEARCH_STEPS': '8',
|
||||
'SMAA_AREATEX_MAX_DISTANCE': '16',
|
||||
'SMAA_AREATEX_PIXEL_SIZE': '( 1.0 / vec2( 160.0, 560.0 ) )',
|
||||
'SMAA_AREATEX_SUBTEX_SIZE': '( 1.0 / 7.0 )'
|
||||
|
||||
},
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDiffuse': { value: null },
|
||||
'tArea': { value: null },
|
||||
'tSearch': { value: null },
|
||||
'resolution': { value: new Vector2( 1 / 1024, 1 / 512 ) }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
uniform vec2 resolution;
|
||||
|
||||
varying vec2 vUv;
|
||||
varying vec4 vOffset[ 3 ];
|
||||
varying vec2 vPixcoord;
|
||||
|
||||
void SMAABlendingWeightCalculationVS( vec2 texcoord ) {
|
||||
vPixcoord = texcoord / resolution;
|
||||
|
||||
// We will use these offsets for the searches later on (see @PSEUDO_GATHER4):
|
||||
vOffset[ 0 ] = texcoord.xyxy + resolution.xyxy * vec4( -0.25, 0.125, 1.25, 0.125 ); // WebGL port note: Changed sign in Y and W components
|
||||
vOffset[ 1 ] = texcoord.xyxy + resolution.xyxy * vec4( -0.125, 0.25, -0.125, -1.25 ); // WebGL port note: Changed sign in Y and W components
|
||||
|
||||
// And these for the searches, they indicate the ends of the loops:
|
||||
vOffset[ 2 ] = vec4( vOffset[ 0 ].xz, vOffset[ 1 ].yw ) + vec4( -2.0, 2.0, -2.0, 2.0 ) * resolution.xxyy * float( SMAA_MAX_SEARCH_STEPS );
|
||||
|
||||
}
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
|
||||
SMAABlendingWeightCalculationVS( vUv );
|
||||
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
#define SMAASampleLevelZeroOffset( tex, coord, offset ) texture2D( tex, coord + float( offset ) * resolution, 0.0 )
|
||||
|
||||
uniform sampler2D tDiffuse;
|
||||
uniform sampler2D tArea;
|
||||
uniform sampler2D tSearch;
|
||||
uniform vec2 resolution;
|
||||
|
||||
varying vec2 vUv;
|
||||
varying vec4 vOffset[3];
|
||||
varying vec2 vPixcoord;
|
||||
|
||||
#if __VERSION__ == 100
|
||||
vec2 round( vec2 x ) {
|
||||
return sign( x ) * floor( abs( x ) + 0.5 );
|
||||
}
|
||||
#endif
|
||||
|
||||
float SMAASearchLength( sampler2D searchTex, vec2 e, float bias, float scale ) {
|
||||
// Not required if searchTex accesses are set to point:
|
||||
// float2 SEARCH_TEX_PIXEL_SIZE = 1.0 / float2(66.0, 33.0);
|
||||
// e = float2(bias, 0.0) + 0.5 * SEARCH_TEX_PIXEL_SIZE +
|
||||
// e * float2(scale, 1.0) * float2(64.0, 32.0) * SEARCH_TEX_PIXEL_SIZE;
|
||||
e.r = bias + e.r * scale;
|
||||
return 255.0 * texture2D( searchTex, e, 0.0 ).r;
|
||||
}
|
||||
|
||||
float SMAASearchXLeft( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) {
|
||||
/**
|
||||
* @PSEUDO_GATHER4
|
||||
* This texcoord has been offset by (-0.25, -0.125) in the vertex shader to
|
||||
* sample between edge, thus fetching four edges in a row.
|
||||
* Sampling with different offsets in each direction allows to disambiguate
|
||||
* which edges are active from the four fetched ones.
|
||||
*/
|
||||
vec2 e = vec2( 0.0, 1.0 );
|
||||
|
||||
for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for
|
||||
e = texture2D( edgesTex, texcoord, 0.0 ).rg;
|
||||
texcoord -= vec2( 2.0, 0.0 ) * resolution;
|
||||
if ( ! ( texcoord.x > end && e.g > 0.8281 && e.r == 0.0 ) ) break;
|
||||
}
|
||||
|
||||
// We correct the previous (-0.25, -0.125) offset we applied:
|
||||
texcoord.x += 0.25 * resolution.x;
|
||||
|
||||
// The searches are bias by 1, so adjust the coords accordingly:
|
||||
texcoord.x += resolution.x;
|
||||
|
||||
// Disambiguate the length added by the last step:
|
||||
texcoord.x += 2.0 * resolution.x; // Undo last step
|
||||
texcoord.x -= resolution.x * SMAASearchLength(searchTex, e, 0.0, 0.5);
|
||||
|
||||
return texcoord.x;
|
||||
}
|
||||
|
||||
float SMAASearchXRight( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) {
|
||||
vec2 e = vec2( 0.0, 1.0 );
|
||||
|
||||
for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for
|
||||
e = texture2D( edgesTex, texcoord, 0.0 ).rg;
|
||||
texcoord += vec2( 2.0, 0.0 ) * resolution;
|
||||
if ( ! ( texcoord.x < end && e.g > 0.8281 && e.r == 0.0 ) ) break;
|
||||
}
|
||||
|
||||
texcoord.x -= 0.25 * resolution.x;
|
||||
texcoord.x -= resolution.x;
|
||||
texcoord.x -= 2.0 * resolution.x;
|
||||
texcoord.x += resolution.x * SMAASearchLength( searchTex, e, 0.5, 0.5 );
|
||||
|
||||
return texcoord.x;
|
||||
}
|
||||
|
||||
float SMAASearchYUp( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) {
|
||||
vec2 e = vec2( 1.0, 0.0 );
|
||||
|
||||
for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for
|
||||
e = texture2D( edgesTex, texcoord, 0.0 ).rg;
|
||||
texcoord += vec2( 0.0, 2.0 ) * resolution; // WebGL port note: Changed sign
|
||||
if ( ! ( texcoord.y > end && e.r > 0.8281 && e.g == 0.0 ) ) break;
|
||||
}
|
||||
|
||||
texcoord.y -= 0.25 * resolution.y; // WebGL port note: Changed sign
|
||||
texcoord.y -= resolution.y; // WebGL port note: Changed sign
|
||||
texcoord.y -= 2.0 * resolution.y; // WebGL port note: Changed sign
|
||||
texcoord.y += resolution.y * SMAASearchLength( searchTex, e.gr, 0.0, 0.5 ); // WebGL port note: Changed sign
|
||||
|
||||
return texcoord.y;
|
||||
}
|
||||
|
||||
float SMAASearchYDown( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) {
|
||||
vec2 e = vec2( 1.0, 0.0 );
|
||||
|
||||
for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for
|
||||
e = texture2D( edgesTex, texcoord, 0.0 ).rg;
|
||||
texcoord -= vec2( 0.0, 2.0 ) * resolution; // WebGL port note: Changed sign
|
||||
if ( ! ( texcoord.y < end && e.r > 0.8281 && e.g == 0.0 ) ) break;
|
||||
}
|
||||
|
||||
texcoord.y += 0.25 * resolution.y; // WebGL port note: Changed sign
|
||||
texcoord.y += resolution.y; // WebGL port note: Changed sign
|
||||
texcoord.y += 2.0 * resolution.y; // WebGL port note: Changed sign
|
||||
texcoord.y -= resolution.y * SMAASearchLength( searchTex, e.gr, 0.5, 0.5 ); // WebGL port note: Changed sign
|
||||
|
||||
return texcoord.y;
|
||||
}
|
||||
|
||||
vec2 SMAAArea( sampler2D areaTex, vec2 dist, float e1, float e2, float offset ) {
|
||||
// Rounding prevents precision errors of bilinear filtering:
|
||||
vec2 texcoord = float( SMAA_AREATEX_MAX_DISTANCE ) * round( 4.0 * vec2( e1, e2 ) ) + dist;
|
||||
|
||||
// We do a scale and bias for mapping to texel space:
|
||||
texcoord = SMAA_AREATEX_PIXEL_SIZE * texcoord + ( 0.5 * SMAA_AREATEX_PIXEL_SIZE );
|
||||
|
||||
// Move to proper place, according to the subpixel offset:
|
||||
texcoord.y += SMAA_AREATEX_SUBTEX_SIZE * offset;
|
||||
|
||||
return texture2D( areaTex, texcoord, 0.0 ).rg;
|
||||
}
|
||||
|
||||
vec4 SMAABlendingWeightCalculationPS( vec2 texcoord, vec2 pixcoord, vec4 offset[ 3 ], sampler2D edgesTex, sampler2D areaTex, sampler2D searchTex, ivec4 subsampleIndices ) {
|
||||
vec4 weights = vec4( 0.0, 0.0, 0.0, 0.0 );
|
||||
|
||||
vec2 e = texture2D( edgesTex, texcoord ).rg;
|
||||
|
||||
if ( e.g > 0.0 ) { // Edge at north
|
||||
vec2 d;
|
||||
|
||||
// Find the distance to the left:
|
||||
vec2 coords;
|
||||
coords.x = SMAASearchXLeft( edgesTex, searchTex, offset[ 0 ].xy, offset[ 2 ].x );
|
||||
coords.y = offset[ 1 ].y; // offset[1].y = texcoord.y - 0.25 * resolution.y (@CROSSING_OFFSET)
|
||||
d.x = coords.x;
|
||||
|
||||
// Now fetch the left crossing edges, two at a time using bilinear
|
||||
// filtering. Sampling at -0.25 (see @CROSSING_OFFSET) enables to
|
||||
// discern what value each edge has:
|
||||
float e1 = texture2D( edgesTex, coords, 0.0 ).r;
|
||||
|
||||
// Find the distance to the right:
|
||||
coords.x = SMAASearchXRight( edgesTex, searchTex, offset[ 0 ].zw, offset[ 2 ].y );
|
||||
d.y = coords.x;
|
||||
|
||||
// We want the distances to be in pixel units (doing this here allow to
|
||||
// better interleave arithmetic and memory accesses):
|
||||
d = d / resolution.x - pixcoord.x;
|
||||
|
||||
// SMAAArea below needs a sqrt, as the areas texture is compressed
|
||||
// quadratically:
|
||||
vec2 sqrt_d = sqrt( abs( d ) );
|
||||
|
||||
// Fetch the right crossing edges:
|
||||
coords.y -= 1.0 * resolution.y; // WebGL port note: Added
|
||||
float e2 = SMAASampleLevelZeroOffset( edgesTex, coords, ivec2( 1, 0 ) ).r;
|
||||
|
||||
// Ok, we know how this pattern looks like, now it is time for getting
|
||||
// the actual area:
|
||||
weights.rg = SMAAArea( areaTex, sqrt_d, e1, e2, float( subsampleIndices.y ) );
|
||||
}
|
||||
|
||||
if ( e.r > 0.0 ) { // Edge at west
|
||||
vec2 d;
|
||||
|
||||
// Find the distance to the top:
|
||||
vec2 coords;
|
||||
|
||||
coords.y = SMAASearchYUp( edgesTex, searchTex, offset[ 1 ].xy, offset[ 2 ].z );
|
||||
coords.x = offset[ 0 ].x; // offset[1].x = texcoord.x - 0.25 * resolution.x;
|
||||
d.x = coords.y;
|
||||
|
||||
// Fetch the top crossing edges:
|
||||
float e1 = texture2D( edgesTex, coords, 0.0 ).g;
|
||||
|
||||
// Find the distance to the bottom:
|
||||
coords.y = SMAASearchYDown( edgesTex, searchTex, offset[ 1 ].zw, offset[ 2 ].w );
|
||||
d.y = coords.y;
|
||||
|
||||
// We want the distances to be in pixel units:
|
||||
d = d / resolution.y - pixcoord.y;
|
||||
|
||||
// SMAAArea below needs a sqrt, as the areas texture is compressed
|
||||
// quadratically:
|
||||
vec2 sqrt_d = sqrt( abs( d ) );
|
||||
|
||||
// Fetch the bottom crossing edges:
|
||||
coords.y -= 1.0 * resolution.y; // WebGL port note: Added
|
||||
float e2 = SMAASampleLevelZeroOffset( edgesTex, coords, ivec2( 0, 1 ) ).g;
|
||||
|
||||
// Get the area for this direction:
|
||||
weights.ba = SMAAArea( areaTex, sqrt_d, e1, e2, float( subsampleIndices.x ) );
|
||||
}
|
||||
|
||||
return weights;
|
||||
}
|
||||
|
||||
void main() {
|
||||
|
||||
gl_FragColor = SMAABlendingWeightCalculationPS( vUv, vPixcoord, vOffset, tDiffuse, tArea, tSearch, ivec4( 0.0 ) );
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* SMAA Blend shader.
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const SMAABlendShader = {
|
||||
|
||||
name: 'SMAABlendShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDiffuse': { value: null },
|
||||
'tColor': { value: null },
|
||||
'resolution': { value: new Vector2( 1 / 1024, 1 / 512 ) }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
uniform vec2 resolution;
|
||||
|
||||
varying vec2 vUv;
|
||||
varying vec4 vOffset[ 2 ];
|
||||
|
||||
void SMAANeighborhoodBlendingVS( vec2 texcoord ) {
|
||||
vOffset[ 0 ] = texcoord.xyxy + resolution.xyxy * vec4( -1.0, 0.0, 0.0, 1.0 ); // WebGL port note: Changed sign in W component
|
||||
vOffset[ 1 ] = texcoord.xyxy + resolution.xyxy * vec4( 1.0, 0.0, 0.0, -1.0 ); // WebGL port note: Changed sign in W component
|
||||
}
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
|
||||
SMAANeighborhoodBlendingVS( vUv );
|
||||
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform sampler2D tDiffuse;
|
||||
uniform sampler2D tColor;
|
||||
uniform vec2 resolution;
|
||||
|
||||
varying vec2 vUv;
|
||||
varying vec4 vOffset[ 2 ];
|
||||
|
||||
vec4 SMAANeighborhoodBlendingPS( vec2 texcoord, vec4 offset[ 2 ], sampler2D colorTex, sampler2D blendTex ) {
|
||||
// Fetch the blending weights for current pixel:
|
||||
vec4 a;
|
||||
a.xz = texture2D( blendTex, texcoord ).xz;
|
||||
a.y = texture2D( blendTex, offset[ 1 ].zw ).g;
|
||||
a.w = texture2D( blendTex, offset[ 1 ].xy ).a;
|
||||
|
||||
// Is there any blending weight with a value greater than 0.0?
|
||||
if ( dot(a, vec4( 1.0, 1.0, 1.0, 1.0 )) < 1e-5 ) {
|
||||
return texture2D( colorTex, texcoord, 0.0 );
|
||||
} else {
|
||||
// Up to 4 lines can be crossing a pixel (one through each edge). We
|
||||
// favor blending by choosing the line with the maximum weight for each
|
||||
// direction:
|
||||
vec2 offset;
|
||||
offset.x = a.a > a.b ? a.a : -a.b; // left vs. right
|
||||
offset.y = a.g > a.r ? -a.g : a.r; // top vs. bottom // WebGL port note: Changed signs
|
||||
|
||||
// Then we go in the direction that has the maximum weight:
|
||||
if ( abs( offset.x ) > abs( offset.y )) { // horizontal vs. vertical
|
||||
offset.y = 0.0;
|
||||
} else {
|
||||
offset.x = 0.0;
|
||||
}
|
||||
|
||||
// Fetch the opposite color and lerp by hand:
|
||||
vec4 C = texture2D( colorTex, texcoord, 0.0 );
|
||||
texcoord += sign( offset ) * resolution;
|
||||
vec4 Cop = texture2D( colorTex, texcoord, 0.0 );
|
||||
float s = abs( offset.x ) > abs( offset.y ) ? abs( offset.x ) : abs( offset.y );
|
||||
|
||||
// WebGL port note: Added gamma correction
|
||||
C.xyz = pow(C.xyz, vec3(2.2));
|
||||
Cop.xyz = pow(Cop.xyz, vec3(2.2));
|
||||
vec4 mixed = mix(C, Cop, s);
|
||||
mixed.xyz = pow(mixed.xyz, vec3(1.0 / 2.2));
|
||||
|
||||
return mixed;
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
|
||||
gl_FragColor = SMAANeighborhoodBlendingPS( vUv, vOffset, tColor, tDiffuse );
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { SMAAEdgesShader, SMAAWeightsShader, SMAABlendShader };
|
||||
@@ -0,0 +1,331 @@
|
||||
import {
|
||||
Matrix4,
|
||||
Vector2
|
||||
} from 'three';
|
||||
|
||||
/**
|
||||
* @module SSAOShader
|
||||
* @three_import import { SSAOShader } from 'three/addons/shaders/SSAOShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* SSAO shader.
|
||||
*
|
||||
* References:
|
||||
* - {@link http://john-chapman-graphics.blogspot.com/2013/01/ssao-tutorial.html}
|
||||
* - {@link https://learnopengl.com/Advanced-Lighting/SSAO}
|
||||
* - {@link https://github.com/McNopper/OpenGL/blob/master/Example28/shader/ssao.frag.glsl}
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const SSAOShader = {
|
||||
|
||||
name: 'SSAOShader',
|
||||
|
||||
defines: {
|
||||
'PERSPECTIVE_CAMERA': 1,
|
||||
'KERNEL_SIZE': 32
|
||||
},
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tNormal': { value: null },
|
||||
'tDepth': { value: null },
|
||||
'tNoise': { value: null },
|
||||
'kernel': { value: null },
|
||||
'cameraNear': { value: null },
|
||||
'cameraFar': { value: null },
|
||||
'resolution': { value: new Vector2() },
|
||||
'cameraProjectionMatrix': { value: new Matrix4() },
|
||||
'cameraInverseProjectionMatrix': { value: new Matrix4() },
|
||||
'kernelRadius': { value: 8 },
|
||||
'minDistance': { value: 0.005 },
|
||||
'maxDistance': { value: 0.05 },
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
uniform highp sampler2D tNormal;
|
||||
uniform highp sampler2D tDepth;
|
||||
uniform sampler2D tNoise;
|
||||
|
||||
uniform vec3 kernel[ KERNEL_SIZE ];
|
||||
|
||||
uniform vec2 resolution;
|
||||
|
||||
uniform float cameraNear;
|
||||
uniform float cameraFar;
|
||||
uniform mat4 cameraProjectionMatrix;
|
||||
uniform mat4 cameraInverseProjectionMatrix;
|
||||
|
||||
uniform float kernelRadius;
|
||||
uniform float minDistance; // avoid artifacts caused by neighbour fragments with minimal depth difference
|
||||
uniform float maxDistance; // avoid the influence of fragments which are too far away
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
#include <packing>
|
||||
|
||||
#ifdef USE_REVERSED_DEPTH_BUFFER
|
||||
|
||||
const float depthThreshold = 0.0;
|
||||
|
||||
#else
|
||||
|
||||
const float depthThreshold = 1.0;
|
||||
|
||||
#endif
|
||||
|
||||
float getDepth( const in vec2 screenPosition ) {
|
||||
|
||||
return texture2D( tDepth, screenPosition ).x;
|
||||
|
||||
}
|
||||
|
||||
float getLinearDepth( const in vec2 screenPosition ) {
|
||||
|
||||
#if PERSPECTIVE_CAMERA == 1
|
||||
|
||||
float fragCoordZ = texture2D( tDepth, screenPosition ).x;
|
||||
float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar );
|
||||
return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
|
||||
|
||||
#else
|
||||
|
||||
return texture2D( tDepth, screenPosition ).x;
|
||||
|
||||
#endif
|
||||
|
||||
}
|
||||
|
||||
float getViewZ( const in float depth ) {
|
||||
|
||||
#if PERSPECTIVE_CAMERA == 1
|
||||
|
||||
return perspectiveDepthToViewZ( depth, cameraNear, cameraFar );
|
||||
|
||||
#else
|
||||
|
||||
return orthographicDepthToViewZ( depth, cameraNear, cameraFar );
|
||||
|
||||
#endif
|
||||
|
||||
}
|
||||
|
||||
vec3 getViewPosition( const in vec2 screenPosition, const in float depth, const in float viewZ ) {
|
||||
|
||||
float clipW = cameraProjectionMatrix[2][3] * viewZ + cameraProjectionMatrix[3][3];
|
||||
|
||||
vec4 clipPosition = vec4( ( vec3( screenPosition, depth ) - 0.5 ) * 2.0, 1.0 );
|
||||
|
||||
clipPosition *= clipW; // unprojection.
|
||||
|
||||
return ( cameraInverseProjectionMatrix * clipPosition ).xyz;
|
||||
|
||||
}
|
||||
|
||||
vec3 getViewNormal( const in vec2 screenPosition ) {
|
||||
|
||||
return unpackRGBToNormal( texture2D( tNormal, screenPosition ).xyz );
|
||||
|
||||
}
|
||||
|
||||
void main() {
|
||||
|
||||
float depth = getDepth( vUv );
|
||||
|
||||
if ( depth == depthThreshold ) {
|
||||
|
||||
gl_FragColor = vec4( 1.0 ); // don't influence background
|
||||
|
||||
} else {
|
||||
|
||||
float viewZ = getViewZ( depth );
|
||||
|
||||
vec3 viewPosition = getViewPosition( vUv, depth, viewZ );
|
||||
vec3 viewNormal = getViewNormal( vUv );
|
||||
|
||||
vec2 noiseScale = vec2( resolution.x / 4.0, resolution.y / 4.0 );
|
||||
vec3 random = vec3( texture2D( tNoise, vUv * noiseScale ).r );
|
||||
|
||||
// compute matrix used to reorient a kernel vector
|
||||
|
||||
vec3 tangent = normalize( random - viewNormal * dot( random, viewNormal ) );
|
||||
vec3 bitangent = cross( viewNormal, tangent );
|
||||
mat3 kernelMatrix = mat3( tangent, bitangent, viewNormal );
|
||||
|
||||
float occlusion = 0.0;
|
||||
|
||||
for ( int i = 0; i < KERNEL_SIZE; i ++ ) {
|
||||
|
||||
vec3 sampleVector = kernelMatrix * kernel[ i ]; // reorient sample vector in view space
|
||||
vec3 samplePoint = viewPosition + ( sampleVector * kernelRadius ); // calculate sample point
|
||||
|
||||
vec4 samplePointNDC = cameraProjectionMatrix * vec4( samplePoint, 1.0 ); // project point and calculate NDC
|
||||
samplePointNDC /= samplePointNDC.w;
|
||||
|
||||
vec2 samplePointUv = samplePointNDC.xy * 0.5 + 0.5; // compute uv coordinates
|
||||
|
||||
float realDepth = getLinearDepth( samplePointUv ); // get linear depth from depth texture
|
||||
float sampleDepth = viewZToOrthographicDepth( samplePoint.z, cameraNear, cameraFar ); // compute linear depth of the sample view Z value
|
||||
float delta = sampleDepth - realDepth;
|
||||
|
||||
if ( delta > minDistance && delta < maxDistance ) { // if fragment is before sample point, increase occlusion
|
||||
|
||||
occlusion += 1.0;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
occlusion = clamp( occlusion / float( KERNEL_SIZE ), 0.0, 1.0 );
|
||||
|
||||
gl_FragColor = vec4( vec3( 1.0 - occlusion ), 1.0 );
|
||||
|
||||
}
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* SSAO depth shader.
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const SSAODepthShader = {
|
||||
|
||||
name: 'SSAODepthShader',
|
||||
|
||||
defines: {
|
||||
'PERSPECTIVE_CAMERA': 1
|
||||
},
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDepth': { value: null },
|
||||
'cameraNear': { value: null },
|
||||
'cameraFar': { value: null },
|
||||
|
||||
},
|
||||
|
||||
vertexShader:
|
||||
|
||||
`varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader:
|
||||
|
||||
`uniform sampler2D tDepth;
|
||||
|
||||
uniform float cameraNear;
|
||||
uniform float cameraFar;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
#include <packing>
|
||||
|
||||
float getLinearDepth( const in vec2 screenPosition ) {
|
||||
|
||||
#if PERSPECTIVE_CAMERA == 1
|
||||
|
||||
float fragCoordZ = texture2D( tDepth, screenPosition ).x;
|
||||
float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar );
|
||||
return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
|
||||
|
||||
#else
|
||||
|
||||
return texture2D( tDepth, screenPosition ).x;
|
||||
|
||||
#endif
|
||||
|
||||
}
|
||||
|
||||
void main() {
|
||||
|
||||
float depth = getLinearDepth( vUv );
|
||||
gl_FragColor = vec4( vec3( 1.0 - depth ), 1.0 );
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* SSAO blur shader.
|
||||
*
|
||||
* @constant
|
||||
* @type {Object}
|
||||
*/
|
||||
const SSAOBlurShader = {
|
||||
|
||||
name: 'SSAOBlurShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDiffuse': { value: null },
|
||||
'resolution': { value: new Vector2() }
|
||||
|
||||
},
|
||||
|
||||
vertexShader:
|
||||
|
||||
`varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader:
|
||||
|
||||
`uniform sampler2D tDiffuse;
|
||||
|
||||
uniform vec2 resolution;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vec2 texelSize = ( 1.0 / resolution );
|
||||
float result = 0.0;
|
||||
|
||||
for ( int i = - 2; i <= 2; i ++ ) {
|
||||
|
||||
for ( int j = - 2; j <= 2; j ++ ) {
|
||||
|
||||
vec2 offset = ( vec2( float( i ), float( j ) ) ) * texelSize;
|
||||
result += texture2D( tDiffuse, vUv + offset ).r;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
gl_FragColor = vec4( vec3( result / ( 5.0 * 5.0 ) ), 1.0 );
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { SSAOShader, SSAODepthShader, SSAOBlurShader };
|
||||
@@ -0,0 +1,396 @@
|
||||
import {
|
||||
Matrix4,
|
||||
Vector2
|
||||
} from 'three';
|
||||
|
||||
|
||||
/**
|
||||
* A collection of shaders used for SSR.
|
||||
*
|
||||
* References:
|
||||
* - [3D Game Shaders For Beginners, Screen Space Reflection (SSR)](https://lettier.github.io/3d-game-shaders-for-beginners/screen-space-reflection.html).
|
||||
*
|
||||
* @module SSRShader
|
||||
* @three_import import * as SSRShader from 'three/addons/shaders/SSRShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* SSR shader.
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const SSRShader = {
|
||||
|
||||
name: 'SSRShader',
|
||||
|
||||
defines: {
|
||||
MAX_STEP: 0,
|
||||
PERSPECTIVE_CAMERA: true,
|
||||
DISTANCE_ATTENUATION: true,
|
||||
FRESNEL: true,
|
||||
INFINITE_THICK: false,
|
||||
SELECTIVE: false,
|
||||
},
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDiffuse': { value: null },
|
||||
'tNormal': { value: null },
|
||||
'tMetalness': { value: null },
|
||||
'tDepth': { value: null },
|
||||
'cameraNear': { value: null },
|
||||
'cameraFar': { value: null },
|
||||
'resolution': { value: new Vector2() },
|
||||
'cameraProjectionMatrix': { value: new Matrix4() },
|
||||
'cameraInverseProjectionMatrix': { value: new Matrix4() },
|
||||
'opacity': { value: .5 },
|
||||
'maxDistance': { value: 180 },
|
||||
'cameraRange': { value: 0 },
|
||||
'thickness': { value: .018 }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}
|
||||
|
||||
`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
// precision highp float;
|
||||
precision highp sampler2D;
|
||||
varying vec2 vUv;
|
||||
uniform sampler2D tDepth;
|
||||
uniform sampler2D tNormal;
|
||||
uniform sampler2D tMetalness;
|
||||
uniform sampler2D tDiffuse;
|
||||
uniform float cameraRange;
|
||||
uniform vec2 resolution;
|
||||
uniform float opacity;
|
||||
uniform float cameraNear;
|
||||
uniform float cameraFar;
|
||||
uniform float maxDistance;
|
||||
uniform float thickness;
|
||||
uniform mat4 cameraProjectionMatrix;
|
||||
uniform mat4 cameraInverseProjectionMatrix;
|
||||
#include <packing>
|
||||
float pointToLineDistance(vec3 x0, vec3 x1, vec3 x2) {
|
||||
//x0: point, x1: linePointA, x2: linePointB
|
||||
//https://mathworld.wolfram.com/Point-LineDistance3-Dimensional.html
|
||||
return length(cross(x0-x1,x0-x2))/length(x2-x1);
|
||||
}
|
||||
float pointPlaneDistance(vec3 point,vec3 planePoint,vec3 planeNormal){
|
||||
// https://mathworld.wolfram.com/Point-PlaneDistance.html
|
||||
//// https://en.wikipedia.org/wiki/Plane_(geometry)
|
||||
//// http://paulbourke.net/geometry/pointlineplane/
|
||||
float a=planeNormal.x,b=planeNormal.y,c=planeNormal.z;
|
||||
float x0=point.x,y0=point.y,z0=point.z;
|
||||
float x=planePoint.x,y=planePoint.y,z=planePoint.z;
|
||||
float d=-(a*x+b*y+c*z);
|
||||
float distance=a*x0+b*y0+c*z0+d;
|
||||
return distance;
|
||||
}
|
||||
float getDepth( const in vec2 uv ) {
|
||||
return texture2D( tDepth, uv ).x;
|
||||
}
|
||||
float getViewZ( const in float depth ) {
|
||||
#ifdef PERSPECTIVE_CAMERA
|
||||
return perspectiveDepthToViewZ( depth, cameraNear, cameraFar );
|
||||
#else
|
||||
return orthographicDepthToViewZ( depth, cameraNear, cameraFar );
|
||||
#endif
|
||||
}
|
||||
vec3 getViewPosition( const in vec2 uv, const in float depth/*clip space*/, const in float clipW ) {
|
||||
vec4 clipPosition = vec4( ( vec3( uv, depth ) - 0.5 ) * 2.0, 1.0 );//ndc
|
||||
clipPosition *= clipW; //clip
|
||||
return ( cameraInverseProjectionMatrix * clipPosition ).xyz;//view
|
||||
}
|
||||
vec3 getViewNormal( const in vec2 uv ) {
|
||||
return unpackRGBToNormal( texture2D( tNormal, uv ).xyz );
|
||||
}
|
||||
vec2 viewPositionToXY(vec3 viewPosition){
|
||||
vec2 xy;
|
||||
vec4 clip=cameraProjectionMatrix*vec4(viewPosition,1);
|
||||
xy=clip.xy;//clip
|
||||
float clipW=clip.w;
|
||||
xy/=clipW;//NDC
|
||||
xy=(xy+1.)/2.;//uv
|
||||
xy*=resolution;//screen
|
||||
return xy;
|
||||
}
|
||||
void main(){
|
||||
#ifdef SELECTIVE
|
||||
float metalness=texture2D(tMetalness,vUv).r;
|
||||
if(metalness==0.) return;
|
||||
#endif
|
||||
|
||||
float depth = getDepth( vUv );
|
||||
float viewZ = getViewZ( depth );
|
||||
if(-viewZ>=cameraFar) return;
|
||||
|
||||
float clipW = cameraProjectionMatrix[2][3] * viewZ+cameraProjectionMatrix[3][3];
|
||||
vec3 viewPosition=getViewPosition( vUv, depth, clipW );
|
||||
|
||||
vec2 d0=gl_FragCoord.xy;
|
||||
vec2 d1;
|
||||
|
||||
vec3 viewNormal=getViewNormal( vUv );
|
||||
|
||||
#ifdef PERSPECTIVE_CAMERA
|
||||
vec3 viewIncidentDir=normalize(viewPosition);
|
||||
vec3 viewReflectDir=reflect(viewIncidentDir,viewNormal);
|
||||
#else
|
||||
vec3 viewIncidentDir=vec3(0,0,-1);
|
||||
vec3 viewReflectDir=reflect(viewIncidentDir,viewNormal);
|
||||
#endif
|
||||
|
||||
float maxReflectRayLen=maxDistance/dot(-viewIncidentDir,viewNormal);
|
||||
// dot(a,b)==length(a)*length(b)*cos(theta) // https://www.mathsisfun.com/algebra/vectors-dot-product.html
|
||||
// if(a.isNormalized&&b.isNormalized) dot(a,b)==cos(theta)
|
||||
// maxDistance/maxReflectRayLen=cos(theta)
|
||||
// maxDistance/maxReflectRayLen==dot(a,b)
|
||||
// maxReflectRayLen==maxDistance/dot(a,b)
|
||||
|
||||
vec3 d1viewPosition=viewPosition+viewReflectDir*maxReflectRayLen;
|
||||
#ifdef PERSPECTIVE_CAMERA
|
||||
if(d1viewPosition.z>-cameraNear){
|
||||
//https://tutorial.math.lamar.edu/Classes/CalcIII/EqnsOfLines.aspx
|
||||
float t=(-cameraNear-viewPosition.z)/viewReflectDir.z;
|
||||
d1viewPosition=viewPosition+viewReflectDir*t;
|
||||
}
|
||||
#endif
|
||||
d1=viewPositionToXY(d1viewPosition);
|
||||
|
||||
float xLen=d1.x-d0.x;
|
||||
float yLen=d1.y-d0.y;
|
||||
float totalStep=max(abs(xLen),abs(yLen));
|
||||
float xSpan=xLen/totalStep;
|
||||
float ySpan=yLen/totalStep;
|
||||
float sStep=1./totalStep;
|
||||
float s=sStep; // start at sStep since loop starts at i=1
|
||||
for(float i=1.;i<float(MAX_STEP);i++){
|
||||
if(i>=totalStep) break;
|
||||
vec2 xy=vec2(d0.x+i*xSpan,d0.y+i*ySpan);
|
||||
if(xy.x<0.||xy.x>resolution.x||xy.y<0.||xy.y>resolution.y) break;
|
||||
vec2 uv=xy/resolution;
|
||||
|
||||
float d = getDepth(uv);
|
||||
float vZ = getViewZ( d );
|
||||
if(-vZ>=cameraFar) continue;
|
||||
float cW = cameraProjectionMatrix[2][3] * vZ+cameraProjectionMatrix[3][3];
|
||||
vec3 vP=getViewPosition( uv, d, cW );
|
||||
|
||||
#ifdef PERSPECTIVE_CAMERA
|
||||
// https://comp.nus.edu.sg/~lowkl/publications/lowk_persp_interp_techrep.pdf
|
||||
float recipVPZ=1./viewPosition.z;
|
||||
float viewReflectRayZ=1./(recipVPZ+s*(1./d1viewPosition.z-recipVPZ));
|
||||
#else
|
||||
float viewReflectRayZ=viewPosition.z+s*(d1viewPosition.z-viewPosition.z);
|
||||
#endif
|
||||
|
||||
// if(viewReflectRayZ>vZ) continue; // will cause "npm run make-screenshot webgl_postprocessing_ssr" high probability hang.
|
||||
// https://github.com/mrdoob/three.js/pull/21539#issuecomment-821061164
|
||||
if(viewReflectRayZ<=vZ){
|
||||
|
||||
bool hit;
|
||||
#ifdef INFINITE_THICK
|
||||
hit=true;
|
||||
#else
|
||||
float away=pointToLineDistance(vP,viewPosition,d1viewPosition);
|
||||
|
||||
float minThickness;
|
||||
vec2 xyNeighbor=xy;
|
||||
xyNeighbor.x+=1.;
|
||||
vec2 uvNeighbor=xyNeighbor/resolution;
|
||||
vec3 vPNeighbor=getViewPosition(uvNeighbor,d,cW);
|
||||
minThickness=vPNeighbor.x-vP.x;
|
||||
minThickness*=3.;
|
||||
float tk=max(minThickness,thickness);
|
||||
|
||||
hit=away<=tk;
|
||||
#endif
|
||||
|
||||
if(hit){
|
||||
vec3 vN=getViewNormal( uv );
|
||||
if(dot(viewReflectDir,vN)>=0.) break; // treat backfaces as opaque
|
||||
float distance=pointPlaneDistance(vP,viewPosition,viewNormal);
|
||||
if(distance>maxDistance) break;
|
||||
float op=opacity;
|
||||
#ifdef DISTANCE_ATTENUATION
|
||||
float ratio=1.-(distance/maxDistance);
|
||||
float attenuation=ratio*ratio;
|
||||
op=opacity*attenuation;
|
||||
#endif
|
||||
#ifdef FRESNEL
|
||||
float fresnelCoe=(dot(viewIncidentDir,viewReflectDir)+1.)/2.;
|
||||
op*=fresnelCoe;
|
||||
#endif
|
||||
vec4 reflectColor=texture2D(tDiffuse,uv);
|
||||
gl_FragColor.xyz=reflectColor.xyz;
|
||||
gl_FragColor.a=op;
|
||||
break;
|
||||
}
|
||||
}
|
||||
s+=sStep;
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* SSR Depth shader.
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const SSRDepthShader = {
|
||||
|
||||
name: 'SSRDepthShader',
|
||||
|
||||
defines: {
|
||||
'PERSPECTIVE_CAMERA': 1
|
||||
},
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDepth': { value: null },
|
||||
'cameraNear': { value: null },
|
||||
'cameraFar': { value: null },
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}
|
||||
|
||||
`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform sampler2D tDepth;
|
||||
|
||||
uniform float cameraNear;
|
||||
uniform float cameraFar;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
#include <packing>
|
||||
|
||||
float getLinearDepth( const in vec2 uv ) {
|
||||
|
||||
#if PERSPECTIVE_CAMERA == 1
|
||||
|
||||
float fragCoordZ = texture2D( tDepth, uv ).x;
|
||||
float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar );
|
||||
return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
|
||||
|
||||
#else
|
||||
|
||||
return texture2D( tDepth, uv ).x;
|
||||
|
||||
#endif
|
||||
|
||||
}
|
||||
|
||||
void main() {
|
||||
|
||||
float depth = getLinearDepth( vUv );
|
||||
float d = 1.0 - depth;
|
||||
// d=(d-.999)*1000.;
|
||||
gl_FragColor = vec4( vec3( d ), 1.0 );
|
||||
|
||||
}
|
||||
|
||||
`
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* SSR Blur shader.
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const SSRBlurShader = {
|
||||
|
||||
name: 'SSRBlurShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDiffuse': { value: null },
|
||||
'resolution': { value: new Vector2() },
|
||||
'opacity': { value: .5 },
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}
|
||||
|
||||
`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform sampler2D tDiffuse;
|
||||
uniform vec2 resolution;
|
||||
varying vec2 vUv;
|
||||
void main() {
|
||||
//reverse engineering from PhotoShop blur filter, then change coefficient
|
||||
|
||||
vec2 texelSize = ( 1.0 / resolution );
|
||||
|
||||
vec4 c=texture2D(tDiffuse,vUv);
|
||||
|
||||
vec2 offset;
|
||||
|
||||
offset=(vec2(-1,0))*texelSize;
|
||||
vec4 cl=texture2D(tDiffuse,vUv+offset);
|
||||
|
||||
offset=(vec2(1,0))*texelSize;
|
||||
vec4 cr=texture2D(tDiffuse,vUv+offset);
|
||||
|
||||
offset=(vec2(0,-1))*texelSize;
|
||||
vec4 cb=texture2D(tDiffuse,vUv+offset);
|
||||
|
||||
offset=(vec2(0,1))*texelSize;
|
||||
vec4 ct=texture2D(tDiffuse,vUv+offset);
|
||||
|
||||
// float coeCenter=.5;
|
||||
// float coeSide=.125;
|
||||
float coeCenter=.2;
|
||||
float coeSide=.2;
|
||||
float a=c.a*coeCenter+cl.a*coeSide+cr.a*coeSide+cb.a*coeSide+ct.a*coeSide;
|
||||
vec3 rgb=(c.rgb*c.a*coeCenter+cl.rgb*cl.a*coeSide+cr.rgb*cr.a*coeSide+cb.rgb*cb.a*coeSide+ct.rgb*ct.a*coeSide)/a;
|
||||
gl_FragColor=vec4(rgb,a);
|
||||
|
||||
}
|
||||
`
|
||||
|
||||
|
||||
};
|
||||
|
||||
export { SSRShader, SSRDepthShader, SSRBlurShader };
|
||||
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* @module SepiaShader
|
||||
* @three_import import { SepiaShader } from 'three/addons/shaders/SepiaShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Sepia tone shader based on [glfx.js sepia shader](https://github.com/evanw/glfx.js).
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const SepiaShader = {
|
||||
|
||||
name: 'SepiaShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDiffuse': { value: null },
|
||||
'amount': { value: 1.0 }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform float amount;
|
||||
|
||||
uniform sampler2D tDiffuse;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vec4 color = texture2D( tDiffuse, vUv );
|
||||
vec3 c = color.rgb;
|
||||
|
||||
color.r = dot( c, vec3( 1.0 - 0.607 * amount, 0.769 * amount, 0.189 * amount ) );
|
||||
color.g = dot( c, vec3( 0.349 * amount, 1.0 - 0.314 * amount, 0.168 * amount ) );
|
||||
color.b = dot( c, vec3( 0.272 * amount, 0.534 * amount, 1.0 - 0.869 * amount ) );
|
||||
|
||||
gl_FragColor = vec4( min( vec3( 1.0 ), color.rgb ), color.a );
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { SepiaShader };
|
||||
@@ -0,0 +1,98 @@
|
||||
import {
|
||||
Vector2
|
||||
} from 'three';
|
||||
|
||||
/**
|
||||
* @module SobelOperatorShader
|
||||
* @three_import import { SobelOperatorShader } from 'three/addons/shaders/SobelOperatorShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Sobel Edge Detection (see {@link https://youtu.be/uihBwtPIBxM}).
|
||||
*
|
||||
* As mentioned in the video the Sobel operator expects a grayscale image as input.
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const SobelOperatorShader = {
|
||||
|
||||
name: 'SobelOperatorShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDiffuse': { value: null },
|
||||
'resolution': { value: new Vector2() }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform sampler2D tDiffuse;
|
||||
uniform vec2 resolution;
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vec2 texel = vec2( 1.0 / resolution.x, 1.0 / resolution.y );
|
||||
|
||||
// kernel definition (in glsl matrices are filled in column-major order)
|
||||
|
||||
const mat3 Gx = mat3( -1, -2, -1, 0, 0, 0, 1, 2, 1 ); // x direction kernel
|
||||
const mat3 Gy = mat3( -1, 0, 1, -2, 0, 2, -1, 0, 1 ); // y direction kernel
|
||||
|
||||
// fetch the 3x3 neighbourhood of a fragment
|
||||
|
||||
// first column
|
||||
|
||||
float tx0y0 = texture2D( tDiffuse, vUv + texel * vec2( -1, -1 ) ).r;
|
||||
float tx0y1 = texture2D( tDiffuse, vUv + texel * vec2( -1, 0 ) ).r;
|
||||
float tx0y2 = texture2D( tDiffuse, vUv + texel * vec2( -1, 1 ) ).r;
|
||||
|
||||
// second column
|
||||
|
||||
float tx1y0 = texture2D( tDiffuse, vUv + texel * vec2( 0, -1 ) ).r;
|
||||
float tx1y1 = texture2D( tDiffuse, vUv + texel * vec2( 0, 0 ) ).r;
|
||||
float tx1y2 = texture2D( tDiffuse, vUv + texel * vec2( 0, 1 ) ).r;
|
||||
|
||||
// third column
|
||||
|
||||
float tx2y0 = texture2D( tDiffuse, vUv + texel * vec2( 1, -1 ) ).r;
|
||||
float tx2y1 = texture2D( tDiffuse, vUv + texel * vec2( 1, 0 ) ).r;
|
||||
float tx2y2 = texture2D( tDiffuse, vUv + texel * vec2( 1, 1 ) ).r;
|
||||
|
||||
// gradient value in x direction
|
||||
|
||||
float valueGx = Gx[0][0] * tx0y0 + Gx[1][0] * tx1y0 + Gx[2][0] * tx2y0 +
|
||||
Gx[0][1] * tx0y1 + Gx[1][1] * tx1y1 + Gx[2][1] * tx2y1 +
|
||||
Gx[0][2] * tx0y2 + Gx[1][2] * tx1y2 + Gx[2][2] * tx2y2;
|
||||
|
||||
// gradient value in y direction
|
||||
|
||||
float valueGy = Gy[0][0] * tx0y0 + Gy[1][0] * tx1y0 + Gy[2][0] * tx2y0 +
|
||||
Gy[0][1] * tx0y1 + Gy[1][1] * tx1y1 + Gy[2][1] * tx2y1 +
|
||||
Gy[0][2] * tx0y2 + Gy[1][2] * tx1y2 + Gy[2][2] * tx2y2;
|
||||
|
||||
// magnitude of the total gradient
|
||||
|
||||
float G = sqrt( ( valueGx * valueGx ) + ( valueGy * valueGy ) );
|
||||
|
||||
gl_FragColor = vec4( vec3( G ), 1 );
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { SobelOperatorShader };
|
||||
@@ -0,0 +1,95 @@
|
||||
import {
|
||||
Color,
|
||||
ShaderChunk,
|
||||
ShaderLib,
|
||||
UniformsUtils
|
||||
} from 'three';
|
||||
|
||||
function replaceAll( string, find, replace ) {
|
||||
|
||||
return string.split( find ).join( replace );
|
||||
|
||||
}
|
||||
|
||||
const meshphong_frag_head = ShaderChunk[ 'meshphong_frag' ].slice( 0, ShaderChunk[ 'meshphong_frag' ].indexOf( 'void main() {' ) );
|
||||
const meshphong_frag_body = ShaderChunk[ 'meshphong_frag' ].slice( ShaderChunk[ 'meshphong_frag' ].indexOf( 'void main() {' ) );
|
||||
|
||||
/**
|
||||
* @module SubsurfaceScatteringShader
|
||||
* @three_import import { SubsurfaceScatteringShader } from 'three/addons/shaders/SubsurfaceScatteringShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Subsurface Scattering shader.
|
||||
*
|
||||
* Based on GDC 2011 – [Approximating Translucency for a Fast, Cheap and Convincing Subsurface Scattering Look](https://colinbarrebrisebois.com/2011/03/07/gdc-2011-approximating-translucency-for-a-fast-cheap-and-convincing-subsurface-scattering-look/)
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const SubsurfaceScatteringShader = {
|
||||
|
||||
name: 'SubsurfaceScatteringShader',
|
||||
|
||||
uniforms: UniformsUtils.merge( [
|
||||
ShaderLib[ 'phong' ].uniforms,
|
||||
{
|
||||
'thicknessMap': { value: null },
|
||||
'thicknessColor': { value: new Color( 0xffffff ) },
|
||||
'thicknessDistortion': { value: 0.1 },
|
||||
'thicknessAmbient': { value: 0.0 },
|
||||
'thicknessAttenuation': { value: 0.1 },
|
||||
'thicknessPower': { value: 2.0 },
|
||||
'thicknessScale': { value: 10.0 }
|
||||
}
|
||||
|
||||
] ),
|
||||
|
||||
vertexShader: [
|
||||
'#define USE_UV',
|
||||
ShaderChunk[ 'meshphong_vert' ],
|
||||
].join( '\n' ),
|
||||
|
||||
fragmentShader: [
|
||||
'#define USE_UV',
|
||||
'#define SUBSURFACE',
|
||||
|
||||
meshphong_frag_head,
|
||||
|
||||
'uniform sampler2D thicknessMap;',
|
||||
'uniform float thicknessPower;',
|
||||
'uniform float thicknessScale;',
|
||||
'uniform float thicknessDistortion;',
|
||||
'uniform float thicknessAmbient;',
|
||||
'uniform float thicknessAttenuation;',
|
||||
'uniform vec3 thicknessColor;',
|
||||
|
||||
'void RE_Direct_Scattering(const in IncidentLight directLight, const in vec2 uv, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, inout ReflectedLight reflectedLight) {',
|
||||
' vec3 thickness = thicknessColor * texture2D(thicknessMap, uv).r;',
|
||||
' vec3 scatteringHalf = normalize(directLight.direction + (geometryNormal * thicknessDistortion));',
|
||||
' float scatteringDot = pow(saturate(dot(geometryViewDir, -scatteringHalf)), thicknessPower) * thicknessScale;',
|
||||
' vec3 scatteringIllu = (scatteringDot + thicknessAmbient) * thickness;',
|
||||
' reflectedLight.directDiffuse += scatteringIllu * thicknessAttenuation * directLight.color;',
|
||||
'}',
|
||||
|
||||
meshphong_frag_body.replace( '#include <lights_fragment_begin>',
|
||||
|
||||
replaceAll(
|
||||
ShaderChunk[ 'lights_fragment_begin' ],
|
||||
'RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );',
|
||||
[
|
||||
'RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );',
|
||||
|
||||
'#if defined( SUBSURFACE ) && defined( USE_UV )',
|
||||
' RE_Direct_Scattering(directLight, vUv, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, reflectedLight);',
|
||||
'#endif',
|
||||
].join( '\n' )
|
||||
),
|
||||
|
||||
),
|
||||
|
||||
].join( '\n' ),
|
||||
|
||||
};
|
||||
|
||||
export { SubsurfaceScatteringShader };
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* @module TriangleBlurShader
|
||||
* @three_import import { TriangleBlurShader } from 'three/addons/shaders/TriangleBlurShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Simulates the look of the two-strip technicolor process popular in early 20th century films.
|
||||
* More historical info here: {@link http://www.widescreenmuseum.com/oldcolor/technicolor1.htm}
|
||||
* Demo here: {@link http://charliehoey.com/technicolor_shader/shader_test.html}
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const TechnicolorShader = {
|
||||
|
||||
name: 'TechnicolorShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDiffuse': { value: null }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform sampler2D tDiffuse;
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vec4 tex = texture2D( tDiffuse, vec2( vUv.x, vUv.y ) );
|
||||
vec4 newTex = vec4(tex.r, (tex.g + tex.b) * .5, (tex.g + tex.b) * .5, 1.0);
|
||||
|
||||
gl_FragColor = newTex;
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { TechnicolorShader };
|
||||
@@ -0,0 +1,349 @@
|
||||
import {
|
||||
Color,
|
||||
Vector3
|
||||
} from 'three';
|
||||
|
||||
/**
|
||||
* Collection of toon shaders.
|
||||
*
|
||||
* @module TriangleBlurShader
|
||||
* @three_import import * as ToonShader from 'three/addons/shaders/ToonShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Toon1 shader.
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const ToonShader1 = {
|
||||
|
||||
name: 'ToonShader1',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'uDirLightPos': { value: new Vector3() },
|
||||
'uDirLightColor': { value: new Color( 0xeeeeee ) },
|
||||
|
||||
'uAmbientLightColor': { value: new Color( 0x050505 ) },
|
||||
|
||||
'uBaseColor': { value: new Color( 0xffffff ) }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec3 vNormal;
|
||||
varying vec3 vRefract;
|
||||
|
||||
void main() {
|
||||
|
||||
vec4 worldPosition = modelMatrix * vec4( position, 1.0 );
|
||||
vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
|
||||
vec3 worldNormal = normalize ( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal );
|
||||
|
||||
vNormal = normalize( normalMatrix * normal );
|
||||
|
||||
vec3 I = worldPosition.xyz - cameraPosition;
|
||||
vRefract = refract( normalize( I ), worldNormal, 1.02 );
|
||||
|
||||
gl_Position = projectionMatrix * mvPosition;
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform vec3 uBaseColor;
|
||||
|
||||
uniform vec3 uDirLightPos;
|
||||
uniform vec3 uDirLightColor;
|
||||
|
||||
uniform vec3 uAmbientLightColor;
|
||||
|
||||
varying vec3 vNormal;
|
||||
|
||||
varying vec3 vRefract;
|
||||
|
||||
void main() {
|
||||
|
||||
float directionalLightWeighting = max( dot( normalize( vNormal ), uDirLightPos ), 0.0);
|
||||
vec3 lightWeighting = uAmbientLightColor + uDirLightColor * directionalLightWeighting;
|
||||
|
||||
float intensity = smoothstep( - 0.5, 1.0, pow( length(lightWeighting), 20.0 ) );
|
||||
intensity += length(lightWeighting) * 0.2;
|
||||
|
||||
float cameraWeighting = dot( normalize( vNormal ), vRefract );
|
||||
intensity += pow( 1.0 - length( cameraWeighting ), 6.0 );
|
||||
intensity = intensity * 0.2 + 0.3;
|
||||
|
||||
if ( intensity < 0.50 ) {
|
||||
|
||||
gl_FragColor = vec4( 2.0 * intensity * uBaseColor, 1.0 );
|
||||
|
||||
} else {
|
||||
|
||||
gl_FragColor = vec4( 1.0 - 2.0 * ( 1.0 - intensity ) * ( 1.0 - uBaseColor ), 1.0 );
|
||||
|
||||
}
|
||||
|
||||
#include <colorspace_fragment>
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
/**
|
||||
* Toon2 shader.
|
||||
*
|
||||
* @constant
|
||||
* @type {Object}
|
||||
*/
|
||||
const ToonShader2 = {
|
||||
|
||||
uniforms: {
|
||||
|
||||
'uDirLightPos': { value: new Vector3() },
|
||||
'uDirLightColor': { value: new Color( 0xeeeeee ) },
|
||||
|
||||
'uAmbientLightColor': { value: new Color( 0x050505 ) },
|
||||
|
||||
'uBaseColor': { value: new Color( 0xeeeeee ) },
|
||||
'uLineColor1': { value: new Color( 0x808080 ) },
|
||||
'uLineColor2': { value: new Color( 0x000000 ) },
|
||||
'uLineColor3': { value: new Color( 0x000000 ) },
|
||||
'uLineColor4': { value: new Color( 0x000000 ) }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec3 vNormal;
|
||||
|
||||
void main() {
|
||||
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
vNormal = normalize( normalMatrix * normal );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform vec3 uBaseColor;
|
||||
uniform vec3 uLineColor1;
|
||||
uniform vec3 uLineColor2;
|
||||
uniform vec3 uLineColor3;
|
||||
uniform vec3 uLineColor4;
|
||||
|
||||
uniform vec3 uDirLightPos;
|
||||
uniform vec3 uDirLightColor;
|
||||
|
||||
uniform vec3 uAmbientLightColor;
|
||||
|
||||
varying vec3 vNormal;
|
||||
|
||||
void main() {
|
||||
|
||||
float camera = max( dot( normalize( vNormal ), vec3( 0.0, 0.0, 1.0 ) ), 0.4);
|
||||
float light = max( dot( normalize( vNormal ), uDirLightPos ), 0.0);
|
||||
|
||||
gl_FragColor = vec4( uBaseColor, 1.0 );
|
||||
|
||||
if ( length(uAmbientLightColor + uDirLightColor * light) < 1.00 ) {
|
||||
|
||||
gl_FragColor *= vec4( uLineColor1, 1.0 );
|
||||
|
||||
}
|
||||
|
||||
if ( length(uAmbientLightColor + uDirLightColor * camera) < 0.50 ) {
|
||||
|
||||
gl_FragColor *= vec4( uLineColor2, 1.0 );
|
||||
|
||||
}
|
||||
|
||||
#include <colorspace_fragment>
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Toon Hatching shader.
|
||||
*
|
||||
* @constant
|
||||
* @type {Object}
|
||||
*/
|
||||
const ToonShaderHatching = {
|
||||
|
||||
uniforms: {
|
||||
|
||||
'uDirLightPos': { value: new Vector3() },
|
||||
'uDirLightColor': { value: new Color( 0xeeeeee ) },
|
||||
|
||||
'uAmbientLightColor': { value: new Color( 0x050505 ) },
|
||||
|
||||
'uBaseColor': { value: new Color( 0xffffff ) },
|
||||
'uLineColor1': { value: new Color( 0x000000 ) },
|
||||
'uLineColor2': { value: new Color( 0x000000 ) },
|
||||
'uLineColor3': { value: new Color( 0x000000 ) },
|
||||
'uLineColor4': { value: new Color( 0x000000 ) }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec3 vNormal;
|
||||
|
||||
void main() {
|
||||
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
vNormal = normalize( normalMatrix * normal );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform vec3 uBaseColor;
|
||||
uniform vec3 uLineColor1;
|
||||
uniform vec3 uLineColor2;
|
||||
uniform vec3 uLineColor3;
|
||||
uniform vec3 uLineColor4;
|
||||
|
||||
uniform vec3 uDirLightPos;
|
||||
uniform vec3 uDirLightColor;
|
||||
|
||||
uniform vec3 uAmbientLightColor;
|
||||
|
||||
varying vec3 vNormal;
|
||||
|
||||
void main() {
|
||||
|
||||
float directionalLightWeighting = max( dot( normalize(vNormal), uDirLightPos ), 0.0);
|
||||
vec3 lightWeighting = uAmbientLightColor + uDirLightColor * directionalLightWeighting;
|
||||
|
||||
gl_FragColor = vec4( uBaseColor, 1.0 );
|
||||
|
||||
if ( length(lightWeighting) < 1.00 ) {
|
||||
|
||||
if ( mod(gl_FragCoord.x + gl_FragCoord.y, 10.0) == 0.0) {
|
||||
|
||||
gl_FragColor = vec4( uLineColor1, 1.0 );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if ( length(lightWeighting) < 0.75 ) {
|
||||
|
||||
if (mod(gl_FragCoord.x - gl_FragCoord.y, 10.0) == 0.0) {
|
||||
|
||||
gl_FragColor = vec4( uLineColor2, 1.0 );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if ( length(lightWeighting) < 0.50 ) {
|
||||
|
||||
if (mod(gl_FragCoord.x + gl_FragCoord.y - 5.0, 10.0) == 0.0) {
|
||||
|
||||
gl_FragColor = vec4( uLineColor3, 1.0 );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if ( length(lightWeighting) < 0.3465 ) {
|
||||
|
||||
if (mod(gl_FragCoord.x - gl_FragCoord.y - 5.0, 10.0) == 0.0) {
|
||||
|
||||
gl_FragColor = vec4( uLineColor4, 1.0 );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#include <colorspace_fragment>
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Toon Dotted shader.
|
||||
*
|
||||
* @constant
|
||||
* @type {Object}
|
||||
*/
|
||||
const ToonShaderDotted = {
|
||||
|
||||
uniforms: {
|
||||
|
||||
'uDirLightPos': { value: new Vector3() },
|
||||
'uDirLightColor': { value: new Color( 0xeeeeee ) },
|
||||
|
||||
'uAmbientLightColor': { value: new Color( 0x050505 ) },
|
||||
|
||||
'uBaseColor': { value: new Color( 0xffffff ) },
|
||||
'uLineColor1': { value: new Color( 0x000000 ) }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec3 vNormal;
|
||||
|
||||
void main() {
|
||||
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
vNormal = normalize( normalMatrix * normal );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform vec3 uBaseColor;
|
||||
uniform vec3 uLineColor1;
|
||||
uniform vec3 uLineColor2;
|
||||
uniform vec3 uLineColor3;
|
||||
uniform vec3 uLineColor4;
|
||||
|
||||
uniform vec3 uDirLightPos;
|
||||
uniform vec3 uDirLightColor;
|
||||
|
||||
uniform vec3 uAmbientLightColor;
|
||||
|
||||
varying vec3 vNormal;
|
||||
|
||||
void main() {
|
||||
|
||||
float directionalLightWeighting = max( dot( normalize(vNormal), uDirLightPos ), 0.0);
|
||||
vec3 lightWeighting = uAmbientLightColor + uDirLightColor * directionalLightWeighting;
|
||||
|
||||
gl_FragColor = vec4( uBaseColor, 1.0 );
|
||||
|
||||
if ( length(lightWeighting) < 1.00 ) {
|
||||
|
||||
if ( ( mod(gl_FragCoord.x, 4.001) + mod(gl_FragCoord.y, 4.0) ) > 6.00 ) {
|
||||
|
||||
gl_FragColor = vec4( uLineColor1, 1.0 );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if ( length(lightWeighting) < 0.50 ) {
|
||||
|
||||
if ( ( mod(gl_FragCoord.x + 2.0, 4.001) + mod(gl_FragCoord.y + 2.0, 4.0) ) > 6.00 ) {
|
||||
|
||||
gl_FragColor = vec4( uLineColor1, 1.0 );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#include <colorspace_fragment>
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { ToonShader1, ToonShader2, ToonShaderHatching, ToonShaderDotted };
|
||||
@@ -0,0 +1,79 @@
|
||||
import {
|
||||
Vector2
|
||||
} from 'three';
|
||||
|
||||
/**
|
||||
* @module TriangleBlurShader
|
||||
* @three_import import { TriangleBlurShader } from 'three/addons/shaders/TriangleBlurShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Triangle blur shader based on [glfx.js triangle blur shader](https://github.com/evanw/glfx.js).
|
||||
*
|
||||
* A basic blur filter, which convolves the image with a
|
||||
* pyramid filter. The pyramid filter is separable and is applied as two
|
||||
* perpendicular triangle filters.
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const TriangleBlurShader = {
|
||||
|
||||
name: 'TriangleBlurShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'texture': { value: null },
|
||||
'delta': { value: new Vector2( 1, 1 ) }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
#include <common>
|
||||
|
||||
#define ITERATIONS 10.0
|
||||
|
||||
uniform sampler2D texture;
|
||||
uniform vec2 delta;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vec4 color = vec4( 0.0 );
|
||||
|
||||
float total = 0.0;
|
||||
|
||||
// randomize the lookup values to hide the fixed number of samples
|
||||
|
||||
float offset = rand( vUv );
|
||||
|
||||
for ( float t = -ITERATIONS; t <= ITERATIONS; t ++ ) {
|
||||
|
||||
float percent = ( t + offset - 0.5 ) / ITERATIONS;
|
||||
float weight = 1.0 - abs( percent );
|
||||
|
||||
color += texture2D( texture, vUv + delta * percent ) * weight;
|
||||
total += weight;
|
||||
|
||||
}
|
||||
|
||||
gl_FragColor = color / total;
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { TriangleBlurShader };
|
||||
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* @module UnpackDepthRGBAShader
|
||||
* @three_import import { UnpackDepthRGBAShader } from 'three/addons/shaders/UnpackDepthRGBAShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Depth visualization shader that shows depth values as monochrome color.
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const UnpackDepthRGBAShader = {
|
||||
|
||||
name: 'UnpackDepthRGBAShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDiffuse': { value: null },
|
||||
'opacity': { value: 1.0 }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform float opacity;
|
||||
|
||||
uniform sampler2D tDiffuse;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
float depth = texture2D( tDiffuse, vUv ).r;
|
||||
|
||||
#ifdef USE_REVERSED_DEPTH_BUFFER
|
||||
|
||||
gl_FragColor = vec4( vec3( depth ), opacity );
|
||||
|
||||
#else
|
||||
|
||||
gl_FragColor = vec4( vec3( 1.0 - depth ), opacity );
|
||||
|
||||
#endif
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { UnpackDepthRGBAShader };
|
||||
@@ -0,0 +1,137 @@
|
||||
import {
|
||||
UniformsLib,
|
||||
UniformsUtils,
|
||||
Matrix4
|
||||
} from 'three';
|
||||
|
||||
/**
|
||||
* @module VelocityShader
|
||||
* @three_import import { VelocityShader } from 'three/addons/shaders/VelocityShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Mesh velocity shader by @bhouston.
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const VelocityShader = {
|
||||
|
||||
name: 'VelocityShader',
|
||||
|
||||
uniforms: UniformsUtils.merge( [
|
||||
UniformsLib.common,
|
||||
UniformsLib.displacementmap,
|
||||
{
|
||||
modelMatrixPrev: { value: new Matrix4() },
|
||||
currentProjectionViewMatrix: { value: new Matrix4() },
|
||||
previousProjectionViewMatrix: { value: new Matrix4() }
|
||||
}
|
||||
] ),
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
#define NORMAL
|
||||
|
||||
#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
|
||||
|
||||
varying vec3 vViewPosition;
|
||||
|
||||
#endif
|
||||
|
||||
#include <common>
|
||||
#include <packing>
|
||||
#include <uv_pars_vertex>
|
||||
#include <displacementmap_pars_vertex>
|
||||
#include <normal_pars_vertex>
|
||||
#include <morphtarget_pars_vertex>
|
||||
#include <skinning_pars_vertex>
|
||||
#include <logdepthbuf_pars_vertex>
|
||||
#include <clipping_planes_pars_vertex>
|
||||
|
||||
uniform mat4 previousProjectionViewMatrix;
|
||||
uniform mat4 currentProjectionViewMatrix;
|
||||
|
||||
uniform mat4 modelMatrixPrev;
|
||||
|
||||
varying vec4 clipPositionCurrent;
|
||||
varying vec4 clipPositionPrevious;
|
||||
|
||||
void main() {
|
||||
|
||||
|
||||
#include <uv_vertex>
|
||||
|
||||
#include <beginnormal_vertex>
|
||||
#include <morphnormal_vertex>
|
||||
#include <skinbase_vertex>
|
||||
#include <skinnormal_vertex>
|
||||
#include <defaultnormal_vertex>
|
||||
#include <normal_vertex>
|
||||
|
||||
#include <begin_vertex>
|
||||
#include <morphtarget_vertex>
|
||||
#include <displacementmap_vertex>
|
||||
#include <morphtarget_vertex>
|
||||
#include <skinning_vertex>
|
||||
|
||||
#ifdef USE_SKINNING
|
||||
|
||||
vec4 mvPosition = modelViewMatrix * skinned;
|
||||
clipPositionCurrent = currentProjectionViewMatrix * modelMatrix * skinned;
|
||||
clipPositionPrevious = previousProjectionViewMatrix * modelMatrixPrev * skinned;
|
||||
|
||||
#else
|
||||
|
||||
vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );
|
||||
clipPositionCurrent = currentProjectionViewMatrix * modelMatrix * vec4( transformed, 1.0 );
|
||||
clipPositionPrevious = previousProjectionViewMatrix * modelMatrixPrev * vec4( transformed, 1.0 );
|
||||
|
||||
#endif
|
||||
|
||||
gl_Position = projectionMatrix * mvPosition;
|
||||
|
||||
#include <logdepthbuf_vertex>
|
||||
#include <clipping_planes_vertex>
|
||||
}
|
||||
`,
|
||||
fragmentShader: /* glsl */`
|
||||
#define NORMAL
|
||||
|
||||
uniform float opacity;
|
||||
|
||||
#include <packing>
|
||||
#include <uv_pars_fragment>
|
||||
#include <map_pars_fragment>
|
||||
#include <alphamap_pars_fragment>
|
||||
#include <alphatest_pars_fragment>
|
||||
#include <logdepthbuf_pars_fragment>
|
||||
#include <clipping_planes_pars_fragment>
|
||||
|
||||
varying vec4 clipPositionCurrent;
|
||||
varying vec4 clipPositionPrevious;
|
||||
|
||||
void main() {
|
||||
|
||||
vec4 diffuseColor = vec4( 1.0 );
|
||||
diffuseColor.a = opacity;
|
||||
|
||||
#include <map_fragment>
|
||||
#include <alphamap_fragment>
|
||||
#include <alphatest_fragment>
|
||||
|
||||
vec2 ndcPositionCurrent = clipPositionCurrent.xy/clipPositionCurrent.w;
|
||||
vec2 ndcPositionPrevious = clipPositionPrevious.xy/clipPositionPrevious.w;
|
||||
vec2 vel = ( ndcPositionCurrent - ndcPositionPrevious ) * 0.5;
|
||||
vel = vel * 0.5 + 0.5;
|
||||
vec2 v1 = packDepthToRG(vel.x);
|
||||
vec2 v2 = packDepthToRG(vel.y);
|
||||
gl_FragColor = vec4(v1.x, v1.y, v2.x, v2.y);
|
||||
|
||||
#include <logdepthbuf_fragment>
|
||||
|
||||
}
|
||||
|
||||
`
|
||||
};
|
||||
|
||||
export { VelocityShader };
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* @module VerticalBlurShader
|
||||
* @three_import import { VerticalBlurShader } from 'three/addons/shaders/VerticalBlurShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Two pass Gaussian blur filter (horizontal and vertical blur shaders)
|
||||
* - see {@link http://www.cake23.de/traveling-wavefronts-lit-up.html}
|
||||
*
|
||||
* - 9 samples per pass
|
||||
* - standard deviation 2.7
|
||||
* - "h" and "v" parameters should be set to "1 / width" and "1 / height"
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const VerticalBlurShader = {
|
||||
|
||||
name: 'VerticalBlurShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDiffuse': { value: null },
|
||||
'v': { value: 1.0 / 512.0 }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform sampler2D tDiffuse;
|
||||
uniform float v;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vec4 sum = vec4( 0.0 );
|
||||
|
||||
sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 4.0 * v ) ) * 0.051;
|
||||
sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 3.0 * v ) ) * 0.0918;
|
||||
sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 2.0 * v ) ) * 0.12245;
|
||||
sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 1.0 * v ) ) * 0.1531;
|
||||
sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y ) ) * 0.1633;
|
||||
sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 1.0 * v ) ) * 0.1531;
|
||||
sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 2.0 * v ) ) * 0.12245;
|
||||
sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 3.0 * v ) ) * 0.0918;
|
||||
sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 4.0 * v ) ) * 0.051;
|
||||
|
||||
gl_FragColor = sum;
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { VerticalBlurShader };
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* @module VerticalTiltShiftShader
|
||||
* @three_import import { VerticalTiltShiftShader } from 'three/addons/shaders/VerticalTiltShiftShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Simple fake tilt-shift effect, modulating two pass Gaussian blur (see above) by vertical position
|
||||
*
|
||||
* - 9 samples per pass
|
||||
* - standard deviation 2.7
|
||||
* - "h" and "v" parameters should be set to "1 / width" and "1 / height"
|
||||
* - "r" parameter control where "focused" horizontal line lies
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const VerticalTiltShiftShader = {
|
||||
|
||||
name: 'VerticalTiltShiftShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDiffuse': { value: null },
|
||||
'v': { value: 1.0 / 512.0 },
|
||||
'r': { value: 0.35 }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform sampler2D tDiffuse;
|
||||
uniform float v;
|
||||
uniform float r;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vec4 sum = vec4( 0.0 );
|
||||
|
||||
float vv = v * abs( r - vUv.y );
|
||||
|
||||
sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 4.0 * vv ) ) * 0.051;
|
||||
sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 3.0 * vv ) ) * 0.0918;
|
||||
sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 2.0 * vv ) ) * 0.12245;
|
||||
sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 1.0 * vv ) ) * 0.1531;
|
||||
sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y ) ) * 0.1633;
|
||||
sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 1.0 * vv ) ) * 0.1531;
|
||||
sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 2.0 * vv ) ) * 0.12245;
|
||||
sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 3.0 * vv ) ) * 0.0918;
|
||||
sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 4.0 * vv ) ) * 0.051;
|
||||
|
||||
gl_FragColor = sum;
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { VerticalTiltShiftShader };
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* @module VignetteShader
|
||||
* @three_import import { VignetteShader } from 'three/addons/shaders/VignetteShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Based on [PaintEffect postprocess from ro.me](https://github.com/dataarts/3-dreams-of-black/blob/master/deploy/js/effects/PaintEffect.js).
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const VignetteShader = {
|
||||
|
||||
name: 'VignetteShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'tDiffuse': { value: null },
|
||||
'offset': { value: 1.0 },
|
||||
'darkness': { value: 1.0 }
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform float offset;
|
||||
uniform float darkness;
|
||||
|
||||
uniform sampler2D tDiffuse;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
|
||||
// Eskil's vignette
|
||||
|
||||
vec4 texel = texture2D( tDiffuse, vUv );
|
||||
vec2 uv = ( vUv - vec2( 0.5 ) ) * vec2( offset );
|
||||
gl_FragColor = vec4( mix( texel.rgb, vec3( 1.0 - darkness ), dot( uv, uv ) ), texel.a );
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { VignetteShader };
|
||||
@@ -0,0 +1,285 @@
|
||||
import {
|
||||
Vector2,
|
||||
Vector3
|
||||
} from 'three';
|
||||
|
||||
/**
|
||||
* @module VolumeShader
|
||||
* @three_import import { VolumeRenderShader1 } from 'three/addons/shaders/VolumeShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Shaders to render 3D volumes using raycasting.
|
||||
* The applied techniques are based on similar implementations in the Visvis and Vispy projects.
|
||||
* This is not the only approach, therefore it's marked 1.
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const VolumeRenderShader1 = {
|
||||
|
||||
name: 'VolumeRenderShader1',
|
||||
|
||||
uniforms: {
|
||||
'u_size': { value: new Vector3( 1, 1, 1 ) },
|
||||
'u_renderstyle': { value: 0 },
|
||||
'u_renderthreshold': { value: 0.5 },
|
||||
'u_clim': { value: new Vector2( 1, 1 ) },
|
||||
'u_data': { value: null },
|
||||
'u_cmdata': { value: null }
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
varying vec3 v_position;
|
||||
varying vec3 v_cameraInObj;
|
||||
varying vec3 v_viewDirInObj;
|
||||
|
||||
void main() {
|
||||
vec4 position4 = vec4(position, 1.0);
|
||||
|
||||
v_position = position;
|
||||
|
||||
// Express the camera position and view direction in the object's local
|
||||
// space so the fragment shader can build the per-fragment view ray.
|
||||
// For perspective cameras, rays converge at v_cameraInObj.
|
||||
// For orthographic cameras, rays travel along v_viewDirInObj.
|
||||
v_cameraInObj = (inverse(modelMatrix) * vec4(cameraPosition, 1.0)).xyz;
|
||||
v_viewDirInObj = (inverse(modelViewMatrix) * vec4(0.0, 0.0, -1.0, 0.0)).xyz;
|
||||
|
||||
gl_Position = projectionMatrix * modelViewMatrix * position4;
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
precision highp float;
|
||||
precision mediump sampler3D;
|
||||
|
||||
uniform vec3 u_size;
|
||||
uniform int u_renderstyle;
|
||||
uniform float u_renderthreshold;
|
||||
uniform vec2 u_clim;
|
||||
|
||||
uniform sampler3D u_data;
|
||||
uniform sampler2D u_cmdata;
|
||||
|
||||
varying vec3 v_position;
|
||||
varying vec3 v_cameraInObj;
|
||||
varying vec3 v_viewDirInObj;
|
||||
|
||||
// The maximum distance through our rendering volume is sqrt(3).
|
||||
const int MAX_STEPS = 887; // 887 for 512^3, 1774 for 1024^3
|
||||
const int REFINEMENT_STEPS = 4;
|
||||
const float relative_step_size = 1.0;
|
||||
const vec4 ambient_color = vec4(0.2, 0.4, 0.2, 1.0);
|
||||
const vec4 diffuse_color = vec4(0.8, 0.2, 0.2, 1.0);
|
||||
const vec4 specular_color = vec4(1.0, 1.0, 1.0, 1.0);
|
||||
const float shininess = 40.0;
|
||||
|
||||
void cast_mip(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray);
|
||||
void cast_iso(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray);
|
||||
|
||||
float sample1(vec3 texcoords);
|
||||
vec4 apply_colormap(float val);
|
||||
vec4 add_lighting(float val, vec3 loc, vec3 step, vec3 view_ray);
|
||||
|
||||
|
||||
void main() {
|
||||
// Per-fragment ray direction in object space, pointing from the back
|
||||
// face toward the camera. For perspective cameras the rays converge
|
||||
// at the camera position; for orthographic cameras they are parallel
|
||||
// to the view direction.
|
||||
vec3 view_ray = isOrthographic
|
||||
? normalize(-v_viewDirInObj)
|
||||
: normalize(v_cameraInObj - v_position);
|
||||
|
||||
// Slab-based ray/AABB intersection: v_position lies on the back face
|
||||
// of the cuboid, so stepping along view_ray traverses the volume and
|
||||
// exits through the front face at t = distance.
|
||||
vec3 t1 = (vec3(-0.5) - v_position) / view_ray;
|
||||
vec3 t2 = (u_size - vec3(0.5) - v_position) / view_ray;
|
||||
vec3 tmax = max(t1, t2);
|
||||
float distance = min(min(tmax.x, tmax.y), tmax.z);
|
||||
|
||||
// Decide how many steps to take
|
||||
int nsteps = int(distance / relative_step_size + 0.5);
|
||||
if ( nsteps < 1 )
|
||||
discard;
|
||||
|
||||
// Get starting location and step vector in texture coordinates
|
||||
vec3 front = v_position + view_ray * distance;
|
||||
vec3 step = ((v_position - front) / u_size) / float(nsteps);
|
||||
vec3 start_loc = front / u_size;
|
||||
|
||||
// For testing: show the number of steps. This helps to establish
|
||||
// whether the rays are correctly oriented
|
||||
//'gl_FragColor = vec4(0.0, float(nsteps) / 1.0 / u_size.x, 1.0, 1.0);
|
||||
//'return;
|
||||
|
||||
if (u_renderstyle == 0)
|
||||
cast_mip(start_loc, step, nsteps, view_ray);
|
||||
else if (u_renderstyle == 1)
|
||||
cast_iso(start_loc, step, nsteps, view_ray);
|
||||
|
||||
if (gl_FragColor.a < 0.05)
|
||||
discard;
|
||||
}
|
||||
|
||||
|
||||
float sample1(vec3 texcoords) {
|
||||
/* Sample float value from a 3D texture. Assumes intensity data. */
|
||||
return texture(u_data, texcoords.xyz).r;
|
||||
}
|
||||
|
||||
|
||||
vec4 apply_colormap(float val) {
|
||||
val = (val - u_clim[0]) / (u_clim[1] - u_clim[0]);
|
||||
float n = float(textureSize(u_cmdata, 0).x); // see #33842
|
||||
val = (val * (n - 1.0) + 0.5) / n;
|
||||
return texture2D(u_cmdata, vec2(val, 0.5));
|
||||
}
|
||||
|
||||
|
||||
void cast_mip(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray) {
|
||||
|
||||
float max_val = -1e6;
|
||||
int max_i = 100;
|
||||
vec3 loc = start_loc;
|
||||
|
||||
// Enter the raycasting loop. In WebGL 1 the loop index cannot be compared with
|
||||
// non-constant expression. So we use a hard-coded max, and an additional condition
|
||||
// inside the loop.
|
||||
for (int iter=0; iter<MAX_STEPS; iter++) {
|
||||
if (iter >= nsteps)
|
||||
break;
|
||||
// Sample from the 3D texture
|
||||
float val = sample1(loc);
|
||||
// Apply MIP operation
|
||||
if (val > max_val) {
|
||||
max_val = val;
|
||||
max_i = iter;
|
||||
}
|
||||
// Advance location deeper into the volume
|
||||
loc += step;
|
||||
}
|
||||
|
||||
// Refine location, gives crispier images
|
||||
vec3 iloc = start_loc + step * (float(max_i) - 0.5);
|
||||
vec3 istep = step / float(REFINEMENT_STEPS);
|
||||
for (int i=0; i<REFINEMENT_STEPS; i++) {
|
||||
max_val = max(max_val, sample1(iloc));
|
||||
iloc += istep;
|
||||
}
|
||||
|
||||
// Resolve final color
|
||||
gl_FragColor = apply_colormap(max_val);
|
||||
}
|
||||
|
||||
|
||||
void cast_iso(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray) {
|
||||
|
||||
gl_FragColor = vec4(0.0); // init transparent
|
||||
vec4 color3 = vec4(0.0); // final color
|
||||
vec3 dstep = 1.5 / u_size; // step to sample derivative
|
||||
vec3 loc = start_loc;
|
||||
|
||||
float low_threshold = u_renderthreshold - 0.02 * (u_clim[1] - u_clim[0]);
|
||||
|
||||
// Enter the raycasting loop. In WebGL 1 the loop index cannot be compared with
|
||||
// non-constant expression. So we use a hard-coded max, and an additional condition
|
||||
// inside the loop.
|
||||
for (int iter=0; iter<MAX_STEPS; iter++) {
|
||||
if (iter >= nsteps)
|
||||
break;
|
||||
|
||||
// Sample from the 3D texture
|
||||
float val = sample1(loc);
|
||||
|
||||
if (val > low_threshold) {
|
||||
// Take the last interval in smaller steps
|
||||
vec3 iloc = loc - 0.5 * step;
|
||||
vec3 istep = step / float(REFINEMENT_STEPS);
|
||||
for (int i=0; i<REFINEMENT_STEPS; i++) {
|
||||
val = sample1(iloc);
|
||||
if (val > u_renderthreshold) {
|
||||
gl_FragColor = add_lighting(val, iloc, dstep, view_ray);
|
||||
return;
|
||||
}
|
||||
iloc += istep;
|
||||
}
|
||||
}
|
||||
|
||||
// Advance location deeper into the volume
|
||||
loc += step;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
vec4 add_lighting(float val, vec3 loc, vec3 step, vec3 view_ray)
|
||||
{
|
||||
// Calculate color by incorporating lighting
|
||||
|
||||
// View direction
|
||||
vec3 V = normalize(view_ray);
|
||||
|
||||
// calculate normal vector from gradient
|
||||
vec3 N;
|
||||
float val1, val2;
|
||||
val1 = sample1(loc + vec3(-step[0], 0.0, 0.0));
|
||||
val2 = sample1(loc + vec3(+step[0], 0.0, 0.0));
|
||||
N[0] = val1 - val2;
|
||||
val = max(max(val1, val2), val);
|
||||
val1 = sample1(loc + vec3(0.0, -step[1], 0.0));
|
||||
val2 = sample1(loc + vec3(0.0, +step[1], 0.0));
|
||||
N[1] = val1 - val2;
|
||||
val = max(max(val1, val2), val);
|
||||
val1 = sample1(loc + vec3(0.0, 0.0, -step[2]));
|
||||
val2 = sample1(loc + vec3(0.0, 0.0, +step[2]));
|
||||
N[2] = val1 - val2;
|
||||
val = max(max(val1, val2), val);
|
||||
|
||||
float gm = length(N); // gradient magnitude
|
||||
N = normalize(N);
|
||||
|
||||
// Flip normal so it points towards viewer
|
||||
float Nselect = float(dot(N, V) > 0.0);
|
||||
N = (2.0 * Nselect - 1.0) * N; // == Nselect * N - (1.0-Nselect)*N;
|
||||
|
||||
// Init colors
|
||||
vec4 ambient_color = vec4(0.0, 0.0, 0.0, 0.0);
|
||||
vec4 diffuse_color = vec4(0.0, 0.0, 0.0, 0.0);
|
||||
vec4 specular_color = vec4(0.0, 0.0, 0.0, 0.0);
|
||||
|
||||
// note: could allow multiple lights
|
||||
for (int i=0; i<1; i++)
|
||||
{
|
||||
// Get light direction (make sure to prevent zero division)
|
||||
vec3 L = normalize(view_ray); //lightDirs[i];
|
||||
float lightEnabled = float( length(L) > 0.0 );
|
||||
L = normalize(L + (1.0 - lightEnabled));
|
||||
|
||||
// Calculate lighting properties
|
||||
float lambertTerm = clamp(dot(N, L), 0.0, 1.0);
|
||||
vec3 H = normalize(L+V); // Halfway vector
|
||||
float specularTerm = pow(max(dot(H, N), 0.0), shininess);
|
||||
|
||||
// Calculate mask
|
||||
float mask1 = lightEnabled;
|
||||
|
||||
// Calculate colors
|
||||
ambient_color += mask1 * ambient_color; // * gl_LightSource[i].ambient;
|
||||
diffuse_color += mask1 * lambertTerm;
|
||||
specular_color += mask1 * specularTerm * specular_color;
|
||||
}
|
||||
|
||||
// Calculate final color by componing different components
|
||||
vec4 final_color;
|
||||
vec4 color = apply_colormap(val);
|
||||
final_color = color * (ambient_color + diffuse_color) + specular_color;
|
||||
final_color.a = color.a;
|
||||
return final_color;
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { VolumeRenderShader1 };
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* @module WaterRefractionShader
|
||||
* @three_import import { WaterRefractionShader } from 'three/addons/shaders/WaterRefractionShader.js';
|
||||
*/
|
||||
|
||||
/**
|
||||
* Basic water refraction shader.
|
||||
*
|
||||
* @constant
|
||||
* @type {ShaderMaterial~Shader}
|
||||
*/
|
||||
const WaterRefractionShader = {
|
||||
|
||||
name: 'WaterRefractionShader',
|
||||
|
||||
uniforms: {
|
||||
|
||||
'color': {
|
||||
value: null
|
||||
},
|
||||
|
||||
'time': {
|
||||
value: 0
|
||||
},
|
||||
|
||||
'tDiffuse': {
|
||||
value: null
|
||||
},
|
||||
|
||||
'tDudv': {
|
||||
value: null
|
||||
},
|
||||
|
||||
'textureMatrix': {
|
||||
value: null
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
vertexShader: /* glsl */`
|
||||
|
||||
uniform mat4 textureMatrix;
|
||||
|
||||
varying vec2 vUv;
|
||||
varying vec4 vUvRefraction;
|
||||
|
||||
void main() {
|
||||
|
||||
vUv = uv;
|
||||
|
||||
vUvRefraction = textureMatrix * vec4( position, 1.0 );
|
||||
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
|
||||
}`,
|
||||
|
||||
fragmentShader: /* glsl */`
|
||||
|
||||
uniform vec3 color;
|
||||
uniform float time;
|
||||
uniform sampler2D tDiffuse;
|
||||
uniform sampler2D tDudv;
|
||||
|
||||
varying vec2 vUv;
|
||||
varying vec4 vUvRefraction;
|
||||
|
||||
float blendOverlay( float base, float blend ) {
|
||||
|
||||
return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );
|
||||
|
||||
}
|
||||
|
||||
vec3 blendOverlay( vec3 base, vec3 blend ) {
|
||||
|
||||
return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ),blendOverlay( base.b, blend.b ) );
|
||||
|
||||
}
|
||||
|
||||
void main() {
|
||||
|
||||
float waveStrength = 0.5;
|
||||
float waveSpeed = 0.03;
|
||||
|
||||
// simple distortion (ripple) via dudv map (see https://www.youtube.com/watch?v=6B7IF6GOu7s)
|
||||
|
||||
vec2 distortedUv = texture2D( tDudv, vec2( vUv.x + time * waveSpeed, vUv.y ) ).rg * waveStrength;
|
||||
distortedUv = vUv.xy + vec2( distortedUv.x, distortedUv.y + time * waveSpeed );
|
||||
vec2 distortion = ( texture2D( tDudv, distortedUv ).rg * 2.0 - 1.0 ) * waveStrength;
|
||||
|
||||
// new uv coords
|
||||
|
||||
vec4 uv = vec4( vUvRefraction );
|
||||
uv.xy += distortion;
|
||||
|
||||
vec4 base = texture2DProj( tDiffuse, uv );
|
||||
|
||||
gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 );
|
||||
|
||||
#include <tonemapping_fragment>
|
||||
#include <colorspace_fragment>
|
||||
|
||||
}`
|
||||
|
||||
};
|
||||
|
||||
export { WaterRefractionShader };
|
||||
+61162
File diff suppressed because it is too large.
Load diff
+19537
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,726 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Hero 分镜方案对照 · 数据驱动决策</title>
|
||||
<style>
|
||||
:root { --ink:#0b0a08; --line:rgba(255,255,255,.12); --amber:#ffb457; }
|
||||
* { box-sizing: border-box; }
|
||||
html, body { height:100%; margin:0; }
|
||||
body {
|
||||
background: var(--ink); color:#fff; overflow:hidden;
|
||||
font-family:-apple-system,BlinkMacSystemFont,'PingFang SC','Helvetica Neue',Arial,sans-serif;
|
||||
-webkit-font-smoothing:antialiased;
|
||||
}
|
||||
#host { position:fixed; inset:0; }
|
||||
#host canvas { display:block; width:100%; height:100%; }
|
||||
#scrim {
|
||||
position:fixed; inset:0; pointer-events:none;
|
||||
background:linear-gradient(90deg,rgba(11,10,8,.94) 0%,rgba(11,10,8,.9) 32%,rgba(11,10,8,.62) 55%,rgba(11,10,8,.16) 100%);
|
||||
}
|
||||
#veil { position:fixed; inset:0; background:#07080a; opacity:0; pointer-events:none; }
|
||||
#vignette { position:fixed; inset:0; pointer-events:none;
|
||||
background:radial-gradient(120% 90% at 50% 45%,transparent 45%,rgba(0,0,0,.55) 100%); }
|
||||
|
||||
#copy { position:fixed; left:6vw; top:50%; transform:translateY(-50%); width:min(38rem,46vw); pointer-events:none; }
|
||||
#copy .eyebrow { display:flex; align-items:center; gap:12px; }
|
||||
#copy .eyebrow i { display:block; width:32px; height:1px; background:#c41e3a; }
|
||||
#copy .eyebrow span { font-size:13px; font-weight:500; letter-spacing:.15em; color:rgba(255,255,255,.75); }
|
||||
#copy h1 { margin:24px 0 0; font-size:clamp(28px,3.1vw,44px); line-height:1.14; font-weight:700; letter-spacing:-.01em; }
|
||||
#copy p { margin:18px 0 0; font-size:15px; line-height:1.72; color:rgba(255,255,255,.75); max-width:32rem; }
|
||||
#copy .ctas { display:flex; gap:16px; margin-top:30px; }
|
||||
#copy .cta { padding:13px 26px; font-size:14px; font-weight:600; border-radius:2px; }
|
||||
#copy .cta.primary { background:#c41e3a; color:#fff; }
|
||||
#copy .cta.secondary { border:1px solid rgba(255,255,255,.4); color:#fff; }
|
||||
|
||||
#caption { position:fixed; left:6vw; bottom:26px; display:flex; align-items:center; gap:12px; pointer-events:none; font-size:13px; }
|
||||
#caption i { display:block; width:24px; height:1px; background:rgba(255,255,255,.3); }
|
||||
#caption b { font-weight:500; letter-spacing:.08em; color:rgba(255,255,255,.7); }
|
||||
#caption span { color:rgba(255,255,255,.5); }
|
||||
|
||||
#panel {
|
||||
position:fixed; top:16px; right:16px; width:326px; padding:15px 15px 13px;
|
||||
background:rgba(14,13,12,.88); border:1px solid var(--line); border-radius:4px;
|
||||
backdrop-filter:blur(14px); font-size:12px;
|
||||
}
|
||||
#panel h2 { margin:0 0 2px; font-size:12px; font-weight:600; letter-spacing:.06em; }
|
||||
#panel .sub { margin:0 0 11px; font-size:11px; line-height:1.6; color:rgba(255,255,255,.42); }
|
||||
.variants { display:grid; gap:5px; }
|
||||
.vbtn {
|
||||
display:block; width:100%; text-align:left; padding:7px 9px; cursor:pointer;
|
||||
background:transparent; border:1px solid rgba(255,255,255,.1); border-radius:3px;
|
||||
color:rgba(255,255,255,.72); font-size:12px; font-family:inherit; transition:120ms;
|
||||
}
|
||||
.vbtn:hover { border-color:rgba(255,255,255,.28); color:#fff; }
|
||||
.vbtn.on { border-color:rgba(255,255,255,.55); background:rgba(255,255,255,.07); color:#fff; }
|
||||
.vbtn em { display:block; font-style:normal; margin-top:3px; font-size:10.5px; line-height:1.5; color:rgba(255,255,255,.38); }
|
||||
.vbtn.on em { color:rgba(255,255,255,.55); }
|
||||
.vbtn .k { display:inline-block; margin-right:6px; color:rgba(255,255,255,.3); font-variant-numeric:tabular-nums; }
|
||||
.row { display:flex; gap:6px; margin-top:11px; }
|
||||
.row button {
|
||||
flex:1; padding:6px 0; cursor:pointer; text-align:center; font-size:11px;
|
||||
background:transparent; border:1px solid rgba(255,255,255,.1); border-radius:3px;
|
||||
color:rgba(255,255,255,.6); font-family:inherit;
|
||||
}
|
||||
.row button:hover { border-color:rgba(255,255,255,.3); color:#fff; }
|
||||
#tl { width:100%; margin:11px 0 3px; accent-color:#c41e3a; }
|
||||
.ticks { display:flex; justify-content:space-between; font-size:10px; color:rgba(255,255,255,.28); font-variant-numeric:tabular-nums; }
|
||||
#readout { margin-top:9px; padding-top:9px; border-top:1px solid rgba(255,255,255,.08);
|
||||
display:flex; justify-content:space-between; font-size:10.5px; color:rgba(255,255,255,.42); font-variant-numeric:tabular-nums; }
|
||||
#readout b { color:var(--amber); font-weight:500; }
|
||||
#hint { position:fixed; left:50%; bottom:26px; transform:translateX(-50%); font-size:11px; color:rgba(255,255,255,.25); pointer-events:none; }
|
||||
#err { position:fixed; inset:0; display:none; place-items:center; text-align:center; padding:40px; font-size:13px; color:#ff9b9b; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="host"></div>
|
||||
<div id="scrim"></div>
|
||||
<div id="vignette"></div>
|
||||
<div id="veil"></div>
|
||||
|
||||
<div id="copy">
|
||||
<div class="eyebrow"><i></i><span>企业数字化转型</span></div>
|
||||
<h1>让每一家企业都拥有数据驱动的决策能力</h1>
|
||||
<p>专业核心团队,以结果导向的服务理念,做中国企业数字化转型的同行者与成长伙伴,从战略诊断到系统落地、再到持续陪跑,让每一份技术投入都转化为可衡量的成长。</p>
|
||||
<div class="ctas"><span class="cta primary">预约咨询</span><span class="cta secondary">看行业实践</span></div>
|
||||
</div>
|
||||
|
||||
<div id="caption"><i></i><b id="cap-label">01 数据汇入</b><span id="cap-detail">冷通道 · 数据逐格累积</span></div>
|
||||
|
||||
<div id="panel">
|
||||
<h2>Hero 分镜方案对照</h2>
|
||||
<p class="sub">同机位 · 同时长(43.26s)· 三拍结构相同,只换「决策」的内容模型。</p>
|
||||
<div class="variants" id="variants"></div>
|
||||
<input id="tl" type="range" min="0" max="43260" step="10" value="0" />
|
||||
<div class="ticks"><span>0s</span><span>16.4s</span><span>29.8s</span><span>42.8s</span></div>
|
||||
<div class="row">
|
||||
<button id="btn-play">暂停</button>
|
||||
<button id="btn-settle">跳到落定帧</button>
|
||||
<button id="btn-copy">文案层</button>
|
||||
</div>
|
||||
<div id="readout"><span>镜头 <b id="ro-shot">s1-aisle</b></span><span>k <b id="ro-k">0.00</b></span><span>t <b id="ro-t">0.0s</b></span></div>
|
||||
</div>
|
||||
|
||||
<div id="hint">键盘 1–4 切方案 · 空格播放/暂停</div>
|
||||
<div id="err"></div>
|
||||
|
||||
<script type="importmap">
|
||||
{ "imports": {
|
||||
"three": "/node_modules/three/build/three.module.js",
|
||||
"three/addons/": "/node_modules/three/examples/jsm/"
|
||||
} }
|
||||
</script>
|
||||
|
||||
<script type="module">
|
||||
import * as THREE from 'three';
|
||||
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
|
||||
|
||||
/* ═══════════ 机位与时长:与 hero-scene.tsx 完全一致 ═══════════ */
|
||||
const SHOTS = [
|
||||
{ id:'s1-aisle', ms:16000,
|
||||
from:{ pos:[ 2.8, 2.3, 9.5], tgt:[0.1,1.35,-18] },
|
||||
to: { pos:[-0.55,1.5, 4.6], tgt:[0.15,1.28,-22] } },
|
||||
{ id:'s2-array', ms:13000,
|
||||
from:{ pos:[5.2,-28.6,3.2], tgt:[0,-40,-11] },
|
||||
to: { pos:[1.6,-31.2,-6.4], tgt:[0,-40,-13] } },
|
||||
{ id:'s3-closeup', ms:13000,
|
||||
from:{ pos:[-0.62,1.52,-0.6], tgt:[2.0,1.35,-5.4] },
|
||||
to: { pos:[-0.5,1.24,-5.2], tgt:[2.05,1.28,-9.6] } },
|
||||
];
|
||||
const DIP_MS = 420;
|
||||
const CYCLE_MS = SHOTS.reduce((a,s)=>a+s.ms+DIP_MS, 0);
|
||||
const S3_SETTLE = 0.62;
|
||||
const T_S3 = SHOTS[0].ms + DIP_MS + SHOTS[1].ms + DIP_MS;
|
||||
const T_SETTLE = T_S3 + SHOTS[2].ms * S3_SETTLE;
|
||||
|
||||
const CAPTIONS = {
|
||||
's1-aisle': { label:'01 数据汇入', detail:'冷通道 · 数据逐格累积' },
|
||||
's2-array': { label:'02 全局评估', detail:'模块化阵列 · 全部选项同框' },
|
||||
's3-closeup': { label:'03 判断落定', detail:'单柜视角 · 一柜长明' },
|
||||
};
|
||||
|
||||
const VARIANTS = [
|
||||
{ id:'base', name:'基线(现状)', desc:'只有运镜与灯,画面里没有任何「决策对象」。对照组。' },
|
||||
{ id:'gate', name:'V1 阈值触发', desc:'内容=数据格逐格累积 → 填满后越过闸门 → 触发唯一动作。因果链最直白。' },
|
||||
{ id:'pick', name:'V2 候选筛选', desc:'内容=6 个候选被评估 → 俯视图里 5 个逐个转灰熄灭 → 回到走廊只剩 1 个被锁定。' },
|
||||
{ id:'path', name:'V3 路径选择', desc:'内容=3 条并行路径 → 2 条先后熄灭 → 1 条保持并通向目标柜。决策即「排除」。' },
|
||||
];
|
||||
|
||||
const SCENE_BG = 0x07080a, FARM_Y = -40;
|
||||
const RACK_W=1.0, RACK_H=2.0, RACK_D=0.6, RACK_COUNT=72, RACK_STEP=0.66, LED_PER_RACK=3;
|
||||
const REAL_PER_SIDE = 40;
|
||||
const COL=6, ROW=10, GAP=1.15, FARM_RACK=0.7;
|
||||
/* 目标柜:S3 相机终点 z=-5.2、看向 z=-9.6 ⇒ 目标必须在视线前方,不能贴身 */
|
||||
const TARGET = { i:24, z:-9.84, x:1.505, ys:[0.55,1.07,1.59] };
|
||||
const LED_PALETTE = [0x4a7cff,0x63d2ff,0x2f6bff,0xffb457,0x46e08a];
|
||||
const AMBER = 0xffb457, CYAN = 0x63d2ff;
|
||||
|
||||
const host = document.getElementById('host');
|
||||
const veil = document.getElementById('veil');
|
||||
const errBox = document.getElementById('err');
|
||||
let renderer;
|
||||
try {
|
||||
renderer = new THREE.WebGLRenderer({ antialias:true, alpha:false, powerPreference:'high-performance' });
|
||||
} catch (e) {
|
||||
errBox.style.display='grid'; errBox.textContent='WebGL 不可用:'+e.message; throw e;
|
||||
}
|
||||
renderer.setPixelRatio(Math.min(window.devicePixelRatio||1, 1.5));
|
||||
renderer.setSize(host.clientWidth, host.clientHeight, false);
|
||||
renderer.toneMapping = THREE.ACESFilmicToneMapping;
|
||||
renderer.toneMappingExposure = 1.32;
|
||||
renderer.outputColorSpace = THREE.SRGBColorSpace;
|
||||
host.appendChild(renderer.domElement);
|
||||
|
||||
const scene = new THREE.Scene();
|
||||
scene.background = new THREE.Color(SCENE_BG);
|
||||
scene.fog = new THREE.Fog(SCENE_BG, 16, 78);
|
||||
const camera = new THREE.PerspectiveCamera(38, host.clientWidth/host.clientHeight, 0.1, 400);
|
||||
const m4 = new THREE.Matrix4();
|
||||
|
||||
/* ═══════════ 舞台(与线上同一套几何) ═══════════ */
|
||||
const floorMat = new THREE.MeshStandardMaterial({ color:0x0d1116, roughness:.3, metalness:.5 });
|
||||
const floor = new THREE.Mesh(new THREE.PlaneGeometry(44,96), floorMat);
|
||||
floor.rotation.x = -Math.PI/2; scene.add(floor);
|
||||
|
||||
const rackGeo = new THREE.BoxGeometry(RACK_W, RACK_H, RACK_D);
|
||||
const rackMat = new THREE.MeshStandardMaterial({ color:0x1c222a, roughness:.5, metalness:.3 });
|
||||
const racks = new THREE.InstancedMesh(rackGeo, rackMat, RACK_COUNT*2);
|
||||
for (let side=0; side<2; side++) {
|
||||
const x = side===0 ? -2.05 : 2.05;
|
||||
for (let i=0;i<RACK_COUNT;i++) { m4.makeTranslation(x, RACK_H/2, 6-i*RACK_STEP); racks.setMatrixAt(side*RACK_COUNT+i, m4); }
|
||||
}
|
||||
racks.instanceMatrix.needsUpdate = true; scene.add(racks);
|
||||
|
||||
const ledGeo = new THREE.PlaneGeometry(0.44,0.018);
|
||||
const ledMat = new THREE.MeshBasicMaterial({ toneMapped:false });
|
||||
const ledCount = RACK_COUNT*2*LED_PER_RACK;
|
||||
const leds = new THREE.InstancedMesh(ledGeo, ledMat, ledCount);
|
||||
const ledBase = new Float32Array(ledCount*3);
|
||||
{
|
||||
const c=new THREE.Color(), v=new THREE.Vector3(), q=new THREE.Quaternion(), s=new THREE.Vector3(1,1,1), e=new THREE.Euler();
|
||||
let n=0;
|
||||
for (let side=0; side<2; side++) {
|
||||
const x = side===0 ? -2.05+RACK_W/2+0.001 : 2.05-RACK_W/2-0.001;
|
||||
e.set(0, side===0 ? Math.PI/2 : -Math.PI/2, 0); q.setFromEuler(e);
|
||||
for (let i=0;i<RACK_COUNT;i++) {
|
||||
const z = 6-i*RACK_STEP;
|
||||
for (let k=0;k<LED_PER_RACK;k++) {
|
||||
v.set(x, 0.55+k*0.52, z); m4.compose(v,q,s); leds.setMatrixAt(n, m4);
|
||||
const pick = (i*7+k*3+side)%11;
|
||||
const hex = pick===0 ? LED_PALETTE[3] : pick===5 ? LED_PALETTE[4] : LED_PALETTE[(i+k)%3];
|
||||
c.setHex(hex); leds.setColorAt(n, c);
|
||||
ledBase[n*3]=c.r; ledBase[n*3+1]=c.g; ledBase[n*3+2]=c.b; n++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
leds.instanceMatrix.needsUpdate = true;
|
||||
if (leds.instanceColor) leds.instanceColor.needsUpdate = true;
|
||||
scene.add(leds);
|
||||
|
||||
const ceil = new THREE.Mesh(new THREE.PlaneGeometry(44,96), new THREE.MeshStandardMaterial({ color:0x0a0c10, roughness:1 }));
|
||||
ceil.rotation.x = Math.PI/2; ceil.position.y = 3.1; scene.add(ceil);
|
||||
|
||||
const strip = new THREE.Mesh(new THREE.PlaneGeometry(0.34,92), new THREE.MeshBasicMaterial({ color:0x38434f, toneMapped:false }));
|
||||
strip.rotation.x = Math.PI/2; strip.position.set(0,3.08,-36); scene.add(strip);
|
||||
|
||||
const lamps = new THREE.InstancedMesh(new THREE.BoxGeometry(0.5,0.04,1.5),
|
||||
new THREE.MeshBasicMaterial({ color:0x8fa2ba, toneMapped:false }), 16);
|
||||
for (let i=0;i<16;i++) { m4.makeTranslation(0,3.05,5-i*3.4); lamps.setMatrixAt(i, m4); }
|
||||
lamps.instanceMatrix.needsUpdate = true; scene.add(lamps);
|
||||
|
||||
const skirtMat = new THREE.MeshBasicMaterial({ color:0x16263a, toneMapped:false });
|
||||
const skirtGeo = new THREE.BoxGeometry(0.035,0.02,92);
|
||||
for (const x of [-1.46,1.46]) { const m=new THREE.Mesh(skirtGeo, skirtMat); m.position.set(x,0.05,-36); scene.add(m); }
|
||||
|
||||
const farm = new THREE.Group(); farm.position.y = FARM_Y; scene.add(farm);
|
||||
const farmFloor = new THREE.Mesh(new THREE.PlaneGeometry(30,30), floorMat);
|
||||
farmFloor.rotation.x = -Math.PI/2; farm.add(farmFloor);
|
||||
|
||||
const farmRackMat = new THREE.MeshStandardMaterial({ color:0x2b333d, roughness:.55, metalness:.3 });
|
||||
const farmRacks = new THREE.InstancedMesh(rackGeo, farmRackMat, COL*ROW);
|
||||
{
|
||||
let fi=0;
|
||||
for (let c=0;c<COL;c++) for (let r=0;r<ROW;r++) {
|
||||
m4.makeTranslation((c-(COL-1)/2)*GAP, RACK_H/2, -8-r*GAP);
|
||||
m4.scale(new THREE.Vector3(FARM_RACK,1,FARM_RACK));
|
||||
farmRacks.setMatrixAt(fi++, m4);
|
||||
}
|
||||
}
|
||||
farmRacks.instanceMatrix.needsUpdate = true; farm.add(farmRacks);
|
||||
|
||||
const aisleMats = [];
|
||||
const aisleGeo = new THREE.BoxGeometry(0.05,0.02,ROW*GAP+0.6);
|
||||
for (let c=0;c<=COL;c++) {
|
||||
const mat = new THREE.MeshBasicMaterial({ color:0x2a4c6e, toneMapped:false });
|
||||
aisleMats.push(mat);
|
||||
const a = new THREE.Mesh(aisleGeo, mat);
|
||||
a.position.set((c-COL/2)*GAP, 0.03, -8-((ROW-1)*GAP)/2);
|
||||
farm.add(a);
|
||||
}
|
||||
|
||||
const hemi = new THREE.HemisphereLight(0x1b2430, 0x030405, 0.5); scene.add(hemi);
|
||||
const corridorLights = [];
|
||||
for (const z of [6,-3,-12,-22,-34]) {
|
||||
const p = new THREE.PointLight(0xdce4ee, 34, 30, 2); p.position.set(0,2.75,z);
|
||||
scene.add(p); corridorLights.push(p);
|
||||
}
|
||||
const farmLights = [];
|
||||
for (const [fx,fz] of [[0,-10],[0,-19]]) {
|
||||
const p = new THREE.PointLight(0xdce4ee, 220, 30, 2); p.position.set(fx,FARM_Y+7,fz);
|
||||
scene.add(p); farmLights.push(p);
|
||||
}
|
||||
const HEMI_BASE = hemi.intensity;
|
||||
const LIGHTS_BASE = corridorLights.map(l=>l.intensity);
|
||||
const FARM_LIGHTS_BASE = farmLights.map(l=>l.intensity);
|
||||
|
||||
/* ── 目标柜灯带:必须外挂。近景 40 台已被 GLB 顶替,其 LED 材质是所有实例共享的一份,
|
||||
无法逐台调 ⇒ 「单柜长明」只能靠叠一层我们自己的发光片。 ── */
|
||||
const decisionMat = new THREE.MeshBasicMaterial({ color:AMBER, toneMapped:false, transparent:true, opacity:0 });
|
||||
const decisionStrips = new THREE.Group();
|
||||
for (const y of TARGET.ys) {
|
||||
const m = new THREE.Mesh(new THREE.PlaneGeometry(0.46,0.032), decisionMat);
|
||||
m.position.set(TARGET.x, y, TARGET.z); m.rotation.y = -Math.PI/2;
|
||||
decisionStrips.add(m);
|
||||
}
|
||||
scene.add(decisionStrips);
|
||||
|
||||
/* 整面薄光:只点三条灯带在 5m 外读成「一点橘」,整面微亮才读成「这一台被选中」 */
|
||||
const decisionPlate = new THREE.MeshBasicMaterial({
|
||||
color:AMBER, toneMapped:false, transparent:true, opacity:0,
|
||||
blending:THREE.AdditiveBlending, depthWrite:false,
|
||||
});
|
||||
{
|
||||
const p = new THREE.Mesh(new THREE.PlaneGeometry(0.62,1.96), decisionPlate);
|
||||
p.position.set(TARGET.x-0.006, 1.02, TARGET.z+0.01); p.rotation.y = -Math.PI/2;
|
||||
scene.add(p);
|
||||
}
|
||||
|
||||
const glowTex = (() => {
|
||||
const cv=document.createElement('canvas'); cv.width=cv.height=128;
|
||||
const g=cv.getContext('2d');
|
||||
const rg=g.createRadialGradient(64,64,2,64,64,64);
|
||||
rg.addColorStop(0,'rgba(255,255,255,.95)');
|
||||
rg.addColorStop(.35,'rgba(255,190,110,.35)');
|
||||
rg.addColorStop(1,'rgba(0,0,0,0)');
|
||||
g.fillStyle=rg; g.fillRect(0,0,128,128);
|
||||
const t=new THREE.CanvasTexture(cv); t.colorSpace=THREE.SRGBColorSpace; return t;
|
||||
})();
|
||||
const decisionGlow = new THREE.MeshBasicMaterial({
|
||||
color:AMBER, map:glowTex, toneMapped:false, transparent:true, opacity:0,
|
||||
blending:THREE.AdditiveBlending, depthWrite:false,
|
||||
});
|
||||
{
|
||||
const g = new THREE.Mesh(new THREE.PlaneGeometry(1.6,1.5), decisionGlow);
|
||||
g.position.set(TARGET.x-0.02, 1.06, TARGET.z); g.rotation.y=-Math.PI/2; scene.add(g);
|
||||
}
|
||||
|
||||
/* ═══════════ 真实机柜资产(CC0) ═══════════ */
|
||||
const darken = (src) => {
|
||||
const c = src.clone();
|
||||
if (/led/i.test(c.name||'')) { c.toneMapped=false; if (c.color) c.color.multiplyScalar(.3); return c; }
|
||||
if (c.color) c.color.multiplyScalar(.09);
|
||||
if (typeof c.roughness==='number') c.roughness = Math.min(1, c.roughness+.12);
|
||||
if (typeof c.metalness==='number') c.metalness = Math.max(0, c.metalness-.08);
|
||||
return c;
|
||||
};
|
||||
const rackTransform = (side,i,t) => t.compose(
|
||||
new THREE.Vector3(side===0?-2.05:2.05, 0, 6-i*RACK_STEP),
|
||||
new THREE.Quaternion().setFromEuler(new THREE.Euler(0, side===0?Math.PI/2:-Math.PI/2, 0)),
|
||||
new THREE.Vector3(1,1,1),
|
||||
);
|
||||
async function loadRealRacks() {
|
||||
const gltf = await new GLTFLoader().loadAsync('/public/models/server-rack.glb');
|
||||
gltf.scene.updateMatrixWorld(true);
|
||||
const parts = [];
|
||||
gltf.scene.traverse((o) => {
|
||||
if (!o.isMesh) return;
|
||||
if (/led_glow/i.test(o.name)) return;
|
||||
const mat = Array.isArray(o.material) ? o.material[0] : o.material;
|
||||
if (!mat) return;
|
||||
parts.push({ geometry:o.geometry, material:darken(mat), local:o.matrixWorld.clone() });
|
||||
});
|
||||
if (!parts.length) return;
|
||||
for (const p of parts) {
|
||||
const inst = new THREE.InstancedMesh(p.geometry, p.material, REAL_PER_SIDE*2);
|
||||
let n=0;
|
||||
for (let side=0;side<2;side++) for (let i=0;i<REAL_PER_SIDE;i++) {
|
||||
rackTransform(side,i,m4).multiply(p.local); inst.setMatrixAt(n++, m4);
|
||||
}
|
||||
inst.instanceMatrix.needsUpdate = true; scene.add(inst);
|
||||
|
||||
const fi2 = new THREE.InstancedMesh(p.geometry, p.material, COL*ROW);
|
||||
let fn=0;
|
||||
for (let c=0;c<COL;c++) for (let r=0;r<ROW;r++) {
|
||||
m4.makeTranslation((c-(COL-1)/2)*GAP, 0, -8-r*GAP); fi2.setMatrixAt(fn++, m4);
|
||||
}
|
||||
fi2.instanceMatrix.needsUpdate = true; farm.add(fi2);
|
||||
}
|
||||
for (let side=0;side<2;side++) for (let i=0;i<REAL_PER_SIDE;i++) {
|
||||
m4.makeScale(0,0,0);
|
||||
racks.setMatrixAt(side*RACK_COUNT+i, m4);
|
||||
for (let k=0;k<LED_PER_RACK;k++) leds.setMatrixAt(side*RACK_COUNT*LED_PER_RACK+i*LED_PER_RACK+k, m4);
|
||||
}
|
||||
racks.instanceMatrix.needsUpdate = true;
|
||||
leds.instanceMatrix.needsUpdate = true;
|
||||
farmRacks.visible = false;
|
||||
}
|
||||
|
||||
/* ══════════════════ 决策内容物(三个模型共享的零件库) ══════════════════ */
|
||||
const stripeTex = () => {
|
||||
const cv=document.createElement('canvas'); cv.width=8; cv.height=128;
|
||||
const g=cv.getContext('2d');
|
||||
g.fillStyle='#000'; g.fillRect(0,0,8,128);
|
||||
const grd=g.createLinearGradient(0,0,0,128);
|
||||
grd.addColorStop(0,'rgba(120,210,255,0)');
|
||||
grd.addColorStop(.5,'rgba(190,240,255,1)');
|
||||
grd.addColorStop(1,'rgba(120,210,255,0)');
|
||||
g.fillStyle=grd; g.fillRect(0,0,8,128);
|
||||
const t=new THREE.CanvasTexture(cv);
|
||||
t.wrapS=t.wrapT=THREE.RepeatWrapping; t.colorSpace=THREE.SRGBColorSpace;
|
||||
return t;
|
||||
};
|
||||
|
||||
/* V1 数据格:8 格贴在右排柜面(视线可见侧,且不被左侧压暗吃掉),逐格点亮=累积 */
|
||||
const gate = { cells:[], gateFrame:null, farmThresh:null };
|
||||
{
|
||||
const geo = new THREE.PlaneGeometry(0.5, 0.5);
|
||||
for (let i=0;i<8;i++) {
|
||||
const mat = new THREE.MeshBasicMaterial({ color:0x0d1a28, toneMapped:false });
|
||||
const m = new THREE.Mesh(geo, mat);
|
||||
m.position.set(1.503, 1.15, 1.4 - i*0.66);
|
||||
m.rotation.y = -Math.PI/2;
|
||||
m.visible = false;
|
||||
scene.add(m);
|
||||
gate.cells.push(m);
|
||||
}
|
||||
/* 闸门:四根发光条围成的门。0.05 厚在 12m 外只剩 1px,实测等于没有 */
|
||||
const frameMat = new THREE.MeshBasicMaterial({ color:0x2f6bff, toneMapped:false, transparent:true, opacity:.8, blending:THREE.AdditiveBlending, depthWrite:false });
|
||||
const gf = new THREE.Group();
|
||||
for (const [x, y, w, h] of [[-1.62,1.05,0.16,2.1],[1.62,1.05,0.16,2.1],[0,2.08,3.4,0.16]]) {
|
||||
const bar = new THREE.Mesh(new THREE.BoxGeometry(w, h, 0.16), frameMat);
|
||||
bar.position.set(x, y, 0); gf.add(bar);
|
||||
}
|
||||
gf.position.set(0, 0, -5.4); gf.visible = false;
|
||||
scene.add(gf);
|
||||
gate.gateFrame = gf; gate.frameMat = frameMat;
|
||||
|
||||
const ftMat = new THREE.MeshBasicMaterial({ color:0x2f6bff, toneMapped:false, transparent:true, opacity:.6, blending:THREE.AdditiveBlending, depthWrite:false });
|
||||
/* 俯视档的闸线必须浮到柜顶之上:放在地面会被 2m 高的机柜整片遮住(实测) */
|
||||
const ft = new THREE.Mesh(new THREE.BoxGeometry(9.4, 0.05, 0.09), ftMat);
|
||||
ft.position.set(0, FARM_Y+2.06, -12.2); ft.visible = false;
|
||||
scene.add(ft);
|
||||
gate.farmThresh = ft; gate.farmThreshMat = ftMat;
|
||||
}
|
||||
|
||||
/* V2 候选:走廊右排 6 台机柜各挂一个评估框 + 俯视图里 6 个候选格 */
|
||||
const pick = { frames:[], marks:[], candIdx:[8,12,16,20,24,28] };
|
||||
{
|
||||
for (const i of pick.candIdx) {
|
||||
const mat = new THREE.LineBasicMaterial({ color:0x4f8dff, transparent:true, opacity:0 });
|
||||
const f = new THREE.LineSegments(new THREE.EdgesGeometry(new THREE.BoxGeometry(0.68, 2.02, 1.16)), mat);
|
||||
f.position.set(2.05, 1.01, 6-i*RACK_STEP);
|
||||
f.visible = false; scene.add(f);
|
||||
pick.frames.push({ mesh:f, mat });
|
||||
}
|
||||
const pairs = [[0,1],[2,3],[4,2],[1,6],[3,8],[5,5]];
|
||||
for (const [c,r] of pairs) {
|
||||
const mat = new THREE.MeshBasicMaterial({ color:0x4f8dff, toneMapped:false, transparent:true, opacity:0, blending:THREE.AdditiveBlending, depthWrite:false });
|
||||
const m = new THREE.Mesh(new THREE.PlaneGeometry(0.95,0.95), mat);
|
||||
m.rotation.x = -Math.PI/2;
|
||||
/* 贴柜顶而不是地面:地面候选格会被机柜自身遮挡,俯视档等于看不见 */
|
||||
m.position.set((c-(COL-1)/2)*GAP, FARM_Y+2.04, -8-r*GAP);
|
||||
m.visible = false; scene.add(m);
|
||||
pick.marks.push({ mesh:m, mat });
|
||||
}
|
||||
}
|
||||
|
||||
/* V3 路径:走廊地面 3 条 + 俯视阵列地面 3 条,都是「流动的光带」 */
|
||||
const pathV = { corridor:[], farmP:[] };
|
||||
{
|
||||
const corridorX = [-0.15, 0.65, 1.45];
|
||||
const farmX = [-2.3, 0, 2.3];
|
||||
for (let i=0;i<3;i++) {
|
||||
const tex = stripeTex(); tex.repeat.set(1, 14);
|
||||
const mat = new THREE.MeshBasicMaterial({ map:tex, color:0x7fd4ff, toneMapped:false, transparent:true, opacity:0, blending:THREE.AdditiveBlending, depthWrite:false });
|
||||
const m = new THREE.Mesh(new THREE.BoxGeometry(0.16, 0.012, 26), mat);
|
||||
m.position.set(corridorX[i], 0.02, -6);
|
||||
m.visible = false; scene.add(m);
|
||||
pathV.corridor.push({ mesh:m, mat, tex });
|
||||
|
||||
const ftex = stripeTex(); ftex.repeat.set(1, 10);
|
||||
const fmat = new THREE.MeshBasicMaterial({ map:ftex, color:0x7fd4ff, toneMapped:false, transparent:true, opacity:0, blending:THREE.AdditiveBlending, depthWrite:false });
|
||||
/* 俯视档的路径走「通道」而不是柜顶:通道本身就是阵列里的负空间,从上方看最清楚 */
|
||||
const fm = new THREE.Mesh(new THREE.BoxGeometry(0.34, 0.012, 12.6), fmat);
|
||||
fm.position.set(farmX[i], FARM_Y+0.09, -13.3);
|
||||
fm.visible = false; scene.add(fm);
|
||||
pathV.farmP.push({ mesh:fm, mat:fmat, tex:ftex });
|
||||
}
|
||||
}
|
||||
|
||||
/* ══════════════ 时间线 ══════════════ */
|
||||
const tmpPos = new THREE.Vector3(), tmpTgt = new THREE.Vector3();
|
||||
const easeK = (k) => k*k*(3-2*k);
|
||||
function poseOf(shot, k, outPos, outTgt) {
|
||||
const e = easeK(k);
|
||||
outPos.set(
|
||||
shot.from.pos[0]+(shot.to.pos[0]-shot.from.pos[0])*e,
|
||||
shot.from.pos[1]+(shot.to.pos[1]-shot.from.pos[1])*e,
|
||||
shot.from.pos[2]+(shot.to.pos[2]-shot.from.pos[2])*e);
|
||||
outTgt.set(
|
||||
shot.from.tgt[0]+(shot.to.tgt[0]-shot.from.tgt[0])*e,
|
||||
shot.from.tgt[1]+(shot.to.tgt[1]-shot.from.tgt[1])*e,
|
||||
shot.from.tgt[2]+(shot.to.tgt[2]-shot.from.tgt[2])*e);
|
||||
}
|
||||
function beatAt(t) {
|
||||
let acc=0;
|
||||
for (let i=0;i<SHOTS.length;i++) {
|
||||
const s = SHOTS[i];
|
||||
if (t < acc+s.ms) return { shot:s, k:(t-acc)/s.ms, dip:-1, prev:null };
|
||||
acc += s.ms;
|
||||
if (t < acc+DIP_MS) return { shot:SHOTS[(i+1)%SHOTS.length], k:0, dip:(t-acc)/DIP_MS, prev:s };
|
||||
acc += DIP_MS;
|
||||
}
|
||||
return { shot:SHOTS[0], k:0, dip:-1, prev:null };
|
||||
}
|
||||
const smoothstep = (x,a,b) => { const t=Math.min(1,Math.max(0,(x-a)/(b-a))); return t*t*(3-2*t); };
|
||||
|
||||
/* ══════════════ 变体状态 ══════════════ */
|
||||
let variant='gate', currentShotId='', playing=true, clockT=0, lastNow=performance.now();
|
||||
let dimFactor=1;
|
||||
|
||||
function showOnly(map) {
|
||||
const vis = (o, on) => { (o.mesh ?? o).visible = on; };
|
||||
gate.cells.forEach(o => vis(o, map.gate));
|
||||
gate.gateFrame.visible = map.gate;
|
||||
gate.farmThresh.visible = false;
|
||||
pick.frames.forEach(f => vis(f, map.pick));
|
||||
pick.marks.forEach(m => vis(m, false));
|
||||
pathV.corridor.forEach(p => vis(p, map.path));
|
||||
pathV.farmP.forEach(p => vis(p, false));
|
||||
if (variant !== 'pick') pick.frames.forEach(f => { f.mat.opacity = 0; });
|
||||
if (variant !== 'path') pathV.corridor.forEach(p => { p.mat.opacity = 0; });
|
||||
if (variant !== 'gate') gate.cells.forEach(c => { c.material.color.setHex(0x0d1a28); });
|
||||
}
|
||||
|
||||
function setVariant(id) {
|
||||
variant = id;
|
||||
showOnly({ gate: id==='gate', pick: id==='pick', path: id==='path' });
|
||||
for (const b of document.querySelectorAll('.vbtn')) b.classList.toggle('on', b.dataset.id===id);
|
||||
}
|
||||
|
||||
/* 场景退暗 + 单柜长明:三个模型共用的「落定」语法 */
|
||||
function applySettle(p) {
|
||||
const d = 1 - 0.42*smoothstep(p, .42, 1);
|
||||
dimFactor = d;
|
||||
hemi.intensity = HEMI_BASE*d;
|
||||
corridorLights.forEach((l,i)=>{ l.intensity = LIGHTS_BASE[i]*d; });
|
||||
farmLights.forEach((l,i)=>{ l.intensity = FARM_LIGHTS_BASE[i]*d; });
|
||||
const q = smoothstep(p, .45, .92);
|
||||
decisionMat.opacity = q;
|
||||
decisionPlate.opacity = 0.16*q;
|
||||
decisionGlow.opacity = 0.42*smoothstep(p, .5, 1);
|
||||
const c = new THREE.Color();
|
||||
for (let n=0;n<ledCount;n++) {
|
||||
c.setRGB(ledBase[n*3]*d, ledBase[n*3+1]*d, ledBase[n*3+2]*d);
|
||||
leds.setColorAt(n, c);
|
||||
}
|
||||
if (leds.instanceColor) leds.instanceColor.needsUpdate = true;
|
||||
skirtMat.color.setHex(0x16263a).multiplyScalar(d);
|
||||
for (const m of aisleMats) m.color.setHex(0x2a4c6e).multiplyScalar(d);
|
||||
}
|
||||
|
||||
/* ── V1 阈值触发 ──
|
||||
内容:12 格数据逐格填满 → 闸门亮起 → 填满瞬间闸门闪白并触发唯一动作。
|
||||
可指着说:「这是数据在攒」「这是判据线」「越过它就动了」。 */
|
||||
const cCellOff = new THREE.Color(0x0d1a28), cCellOn = new THREE.Color(0x7fd4ff);
|
||||
function updateGate(t, beat) {
|
||||
const id = beat.shot.id;
|
||||
gate.cells.forEach(c => { c.visible = true; });
|
||||
gate.gateFrame.visible = true;
|
||||
|
||||
if (id === 's1-aisle') {
|
||||
/* 8 格:k 走完时正好填满 → 填满即触发,不是「一直在填」 */
|
||||
const n = Math.floor(beat.k * 9);
|
||||
gate.cells.forEach((c,i) => {
|
||||
c.material.color.copy(i < n ? cCellOn : cCellOff);
|
||||
});
|
||||
gate.frameMat.color.setHex(0x2f6bff);
|
||||
gate.frameMat.opacity = 0.3 + 0.35*beat.k;
|
||||
} else if (id === 's2-array') {
|
||||
/* 俯视:整片阵列被读一遍,末端闸线在数据跑到头时闪白 */
|
||||
gate.cells.forEach(c => { c.material.color.copy(cCellOn); });
|
||||
const lit = smoothstep(beat.k, .15, .95);
|
||||
aisleMats.forEach((m,i) => {
|
||||
const reach = smoothstep(lit*8.6 - i, 0, 1);
|
||||
m.color.setHex(0x2a4c6e).lerp(new THREE.Color(CYAN), reach*0.9);
|
||||
});
|
||||
gate.farmThresh.visible = true;
|
||||
const flash = smoothstep(beat.k, .82, .95);
|
||||
gate.farmThreshMat.color.setHex(0x2f6bff).lerp(new THREE.Color(0xffffff), flash);
|
||||
gate.farmThreshMat.opacity = 0.35 + 0.65*flash;
|
||||
} else {
|
||||
gate.cells.forEach(c => { c.material.color.copy(cCellOn); });
|
||||
/* 落定瞬间:闸门由蓝转白并常亮 —— 这是「触发」,不是「装饰」 */
|
||||
const trig = smoothstep(beat.k, .55, .8);
|
||||
gate.frameMat.color.setHex(0x2f6bff).lerp(new THREE.Color(0xffffff), trig);
|
||||
gate.frameMat.opacity = 0.5 + 0.5*trig;
|
||||
}
|
||||
}
|
||||
|
||||
/* ── V2 候选筛选 ──
|
||||
内容:6 个候选(右排 6 台柜的评估框)→ 俯视图里 6 个候选格 → 5 个逐个转灰熄灭 → 剩 1 个。 */
|
||||
const cCand = new THREE.Color(0x4f8dff), cCandDead = new THREE.Color(0x2a2f38);
|
||||
function updatePick(t, beat) {
|
||||
const id = beat.shot.id;
|
||||
const KEEP = 4; // candIdx[4] = i:24 ⇒ 正是目标柜
|
||||
|
||||
if (id === 's1-aisle') {
|
||||
pick.frames.forEach((f,i) => {
|
||||
f.mesh.visible = true;
|
||||
const appear = smoothstep(beat.k, i*0.09, i*0.09+0.18);
|
||||
f.mat.opacity = 0.75*appear;
|
||||
f.mat.color.copy(cCand);
|
||||
});
|
||||
pick.frames.forEach(()=>{});
|
||||
} else if (id === 's2-array') {
|
||||
pick.frames.forEach(f => { f.mesh.visible = false; });
|
||||
pick.marks.forEach((mk,i) => {
|
||||
mk.mesh.visible = true;
|
||||
/* 淘汰自 k=0.32 起,每 0.1 一轮;第 KEEP 个永不淘汰 */
|
||||
const d = i === KEEP ? 0 : smoothstep(beat.k, 0.32 + i*0.09, 0.4 + i*0.09);
|
||||
mk.mat.color.copy(cCand).lerp(cCandDead, d);
|
||||
mk.mat.opacity = (1 - d*0.85) * 0.9;
|
||||
});
|
||||
} else {
|
||||
pick.marks.forEach(mk => { mk.mesh.visible = false; });
|
||||
pick.frames.forEach((f,i) => {
|
||||
const alive = i === KEEP;
|
||||
f.mesh.visible = alive || beat.k < 0.3;
|
||||
f.mat.color.copy(alive ? new THREE.Color(AMBER) : cCandDead);
|
||||
f.mat.opacity = alive ? (0.55 + 0.45*smoothstep(beat.k, .55, .85)) : (1-smoothstep(beat.k,0,.3))*0.35;
|
||||
});
|
||||
}
|
||||
/* 锁定框永远跟着目标柜(V2 的「选定」由评估框本身承担) */
|
||||
if (id === 's3-closeup') {
|
||||
const p = smoothstep(beat.k, .5, .9);
|
||||
pick.frames[KEEP].mat.opacity = 0.55 + 0.45*p;
|
||||
}
|
||||
}
|
||||
|
||||
/* ── V3 路径选择 ──
|
||||
内容:3 条并行路径同时有数据在跑 → 俯视时 2 条先后熄灭 → 只剩 1 条通向目标柜。 */
|
||||
function updatePath(t, beat, dt) {
|
||||
const id = beat.shot.id;
|
||||
const KEEP = 1;
|
||||
pathV.corridor.forEach((p,i) => {
|
||||
p.tex.offset.y -= dt * 0.6;
|
||||
});
|
||||
pathV.farmP.forEach((p) => { p.tex.offset.y -= dt * 0.5; });
|
||||
|
||||
if (id === 's1-aisle') {
|
||||
pathV.corridor.forEach((p,i) => {
|
||||
p.mesh.visible = true;
|
||||
const exist = smoothstep(beat.k, i*0.08, i*0.08+0.2);
|
||||
const dying = i === KEEP ? 0 : smoothstep(beat.k, .72 + i*0.05, .92 + i*0.05);
|
||||
p.mat.opacity = 0.9*exist*(1-dying*0.92);
|
||||
p.mesh.visible = p.mat.opacity > 0.02;
|
||||
});
|
||||
pathV.farmP.forEach(p => { p.mesh.visible = false; });
|
||||
} else if (id === 's2-array') {
|
||||
pathV.corridor.forEach(p => { p.mesh.visible = false; });
|
||||
pathV.farmP.forEach((p,i) => {
|
||||
p.mesh.visible = true;
|
||||
const dying = i === KEEP ? 0 : smoothstep(beat.k, .28 + (i===0?0:.18), .46 + (i===0?0:.18));
|
||||
p.mat.opacity = 0.85*(1-dying*0.95);
|
||||
p.mesh.visible = p.mat.opacity > 0.02;
|
||||
});
|
||||
} else {
|
||||
pathV.farmP.forEach(p => { p.mesh.visible = false; });
|
||||
pathV.corridor.forEach((p,i) => {
|
||||
p.mesh.visible = i === KEEP;
|
||||
p.mat.opacity = i === KEEP ? 0.9 : 0;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/* ══════════════ 主循环 ══════════════ */
|
||||
const roShot=document.getElementById('ro-shot'), roK=document.getElementById('ro-k'), roT=document.getElementById('ro-t');
|
||||
function frame(now) {
|
||||
const dt = Math.min(0.05, (now-lastNow)/1000); lastNow = now;
|
||||
if (playing) clockT = (clockT + dt*1000) % CYCLE_MS;
|
||||
|
||||
const beat = beatAt(clockT);
|
||||
let k = beat.k;
|
||||
if (beat.shot.id === 's3-closeup') k = Math.min(1, k/S3_SETTLE);
|
||||
|
||||
if (beat.dip >= 0) {
|
||||
if (beat.dip < 0.5) { poseOf(beat.prev, 1, tmpPos, tmpTgt); veil.style.opacity = String(Math.min(1, beat.dip*2)); }
|
||||
else { poseOf(beat.shot, 0, tmpPos, tmpTgt); veil.style.opacity = String(Math.max(0, (1-beat.dip)*2)); }
|
||||
} else {
|
||||
poseOf(beat.shot, k, tmpPos, tmpTgt); veil.style.opacity = '0';
|
||||
}
|
||||
camera.position.copy(tmpPos); camera.lookAt(tmpTgt);
|
||||
|
||||
applySettle(beat.shot.id === 's3-closeup' ? k : 0);
|
||||
|
||||
if (variant === 'gate') updateGate(clockT, beat);
|
||||
else if (variant === 'pick') updatePick(clockT, beat);
|
||||
else if (variant === 'path') updatePath(clockT, beat, dt);
|
||||
|
||||
renderer.render(scene, camera);
|
||||
|
||||
if (beat.shot.id !== currentShotId) {
|
||||
currentShotId = beat.shot.id;
|
||||
const cap = CAPTIONS[currentShotId];
|
||||
document.getElementById('cap-label').textContent = cap.label;
|
||||
document.getElementById('cap-detail').textContent = cap.detail;
|
||||
roShot.textContent = currentShotId;
|
||||
}
|
||||
roK.textContent = k.toFixed(2);
|
||||
roT.textContent = (clockT/1000).toFixed(1)+'s';
|
||||
document.getElementById('tl').value = String(Math.round(clockT));
|
||||
requestAnimationFrame(frame);
|
||||
}
|
||||
|
||||
/* ══════════════ UI ══════════════ */
|
||||
const wrap = document.getElementById('variants');
|
||||
VARIANTS.forEach((v,i) => {
|
||||
const b = document.createElement('button');
|
||||
b.className='vbtn'; b.dataset.id=v.id;
|
||||
b.innerHTML = `<b><span class="k">${i+1}</span>${v.name}</b><em>${v.desc}</em>`;
|
||||
b.onclick = () => setVariant(v.id);
|
||||
wrap.appendChild(b);
|
||||
});
|
||||
const tl = document.getElementById('tl');
|
||||
tl.addEventListener('input', () => { clockT = Number(tl.value); playing = false; syncPlay(); });
|
||||
const btnPlay = document.getElementById('btn-play');
|
||||
function syncPlay(){ btnPlay.textContent = playing ? '暂停' : '播放'; }
|
||||
btnPlay.onclick = () => { playing = !playing; syncPlay(); };
|
||||
document.getElementById('btn-settle').onclick = () => { clockT = T_SETTLE; playing=false; syncPlay(); };
|
||||
let copyOn = true;
|
||||
document.getElementById('btn-copy').onclick = () => {
|
||||
copyOn = !copyOn;
|
||||
document.getElementById('copy').style.opacity = copyOn ? '1':'0';
|
||||
document.getElementById('scrim').style.opacity = copyOn ? '1':'.25';
|
||||
};
|
||||
window.addEventListener('keydown', (e) => {
|
||||
const n = Number(e.key);
|
||||
if (n>=1 && n<=VARIANTS.length) setVariant(VARIANTS[n-1].id);
|
||||
if (e.code === 'Space') { e.preventDefault(); playing = !playing; syncPlay(); }
|
||||
});
|
||||
window.addEventListener('resize', () => {
|
||||
const w=host.clientWidth, h=host.clientHeight; if (!w||!h) return;
|
||||
renderer.setSize(w,h,false); camera.aspect=w/h; camera.updateProjectionMatrix();
|
||||
});
|
||||
|
||||
/* ══════════════ 启动 ══════════════ */
|
||||
poseOf(SHOTS[0], .5, tmpPos, tmpTgt);
|
||||
camera.position.copy(tmpPos); camera.lookAt(tmpTgt);
|
||||
setVariant('gate');
|
||||
loadRealRacks().catch(()=>{});
|
||||
requestAnimationFrame(frame);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"generatedAt": "2026-10-19T22:27:06.722Z",
|
||||
"runDate": "2026-10-20",
|
||||
"evidenceRunDir": "docs/acceptance/2026-10-20-axe",
|
||||
"generatedAt": "2026-11-26T11:58:25.510Z",
|
||||
"runDate": "2026-11-26",
|
||||
"evidenceRunDir": "docs/acceptance/2026-11-26-axe",
|
||||
"latestPointer": "docs/acceptance/2026-09-21-axe/axe-evidence.json",
|
||||
"base": "http://localhost:3100",
|
||||
"axeCore": "4.11.4",
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
# 2026-10-21 全系统验收(UI / UE / UX 视觉为重点)
|
||||
|
||||
> 状态:进行中(axe / Lighthouse / 全量 E2E 结果待补)。本文件只写**已经实际执行**的读数;未执行项明确标为「待补 / 未做」。
|
||||
|
||||
## 0. 结论(暂定)
|
||||
|
||||
- **判定:有条件通过(暂定)**——未发现 P0/P1,但存在 **5 类 P2** 视觉/UE 问题:网格空槽、指标大字换行、Admin 移动端公共 tab bar 泄漏、Admin 移动端表格塌陷、联系表单在 1440×900 首屏之下。
|
||||
- 验收对象:`dev` @ `dee0c483`,本地重建 `BUILD_ID=i17AJGx-nZqOkCudx46f9`;生产线上 `BUILD_ID=KO7S41-qvKY89xp5Kczbl`(发布 `2f86c441`,2026-10-20 14:05)。
|
||||
- 核心读数:静态/单元门禁全绿;视觉回归 **123 passed / 2 failed**(两例均为 webkit dwell 装配竞态,非像素回归);全路由 sweep **195 次运行 / 0 hard failure**;Admin **45 次运行 / 0 hard failure**;生产只读 **34/35 路由 200**(`/_not-found` 404 为契约);安全响应头 **8/8**。**axe 全站门禁首跑 EXIT=1(firefox-only 6/3 个 contrast 节点),但隔离复跑 5/5 为 0,静态令牌配对均 ≥4.58:1 ⇒ 判为门禁 settle 竞态,尚未取得可信的 a11y 全绿读数(见 §6/TA-05)。**
|
||||
- **未授权动作**:未写视觉基线、未改产品源码、未 commit/push、未部署、未写生产库;写库 E2E 仅打 `/tmp` 副本库。
|
||||
|
||||
## 1. 环境与取证
|
||||
|
||||
| 项 | 读数 |
|
||||
|---|---|
|
||||
| 分支 / HEAD | `dev` / `dee0c4835c8446a46c7694587610876a70b20aa4`(与 `origin/dev`、`origin/main` 同步,工作树干净) |
|
||||
| 本地构建 | `npm run build:clean` EXIT=0,2026-10-21 09:20:25–09:20:53;`dist/BUILD_ID = i17AJGx-nZqOkCudx46f9`,与 `dist/standalone/dist/BUILD_ID` 一致 |
|
||||
| standalone 装配 | `dist/standalone/{server.js,dist/static,public}` 三项齐备(`ASSEMBLY_OK`) |
|
||||
| 主服务 | `node dist/standalone/server.js` on `127.0.0.1:3100`,PID 49285,启动 09:48:37;`DATABASE_URL=file:/tmp/novalon-qa-20261021/dev.db` |
|
||||
| DB 副本 | `sqlite3 prisma/dev.db ".backup ..."` → `/tmp/novalon-qa-20261021/dev.db`,1,241,088 bytes |
|
||||
| 生产发布 | `BUILD_ID=KO7S41-qvKY89xp5Kczbl`(`docs/development/deploy-runbook.md` §3.4) |
|
||||
|
||||
**装配口径两处必须记住**(本轮实际踩到):
|
||||
|
||||
1. `npm run build:clean` **不会触发** `postbuild` 钩子(npm 只跑 `postbuild:clean`),本次按 `package.json:9` 的 postbuild 命令手工装配后才得到可用产物。后续用 `npm run build` 或补 `postbuild:clean`。
|
||||
2. 本地 `.env.local` 与 `.env.production` 的加密密钥**不同**:构建内联了 `.env.local` 的 `NEXT_PUBLIC_ENCRYPTION_SECRET`,而 standalone 运行时用了 `.env.production` 的 `ENCRYPTION_SECRET`,导致所有加密响应解密失败、Admin 仪表盘全 `-`。生产两端一致(已逐项验证),属**本地验收环境装配缺陷**;本轮以 `ENCRYPTION_SECRET=<.env.local 值>` 重启服务后 Admin 恢复正常。
|
||||
|
||||
## 2. 门禁矩阵(逐条 EXIT)
|
||||
|
||||
| 检查 | 命令 | EXIT | 真实读数 | 证据 |
|
||||
|---|---|---|---|---|
|
||||
| 类型 | `npm run type-check` | 0 | 0 error | `logs/gate-typecheck.log` |
|
||||
| E2E 类型 | `npm run type-check:e2e` | 0 | 0 error | `logs/gate-typecheck-e2e.log` |
|
||||
| Lint | `npm run lint` | 0 | **0 error / 84 warning** | `logs/gate-lint.log` |
|
||||
| 单元 + 覆盖率 | `npm run test:coverage` | 0 | **149 suites / 1815 tests**;All files **89.56 stmts / 88.28 branch / 88.18 funcs / 89.56 lines** | `logs/gate-coverage.log` |
|
||||
| 真库集成 | `npm run test:integration:real` | 0 | **4 suites / 23 tests**;`prisma/dev.db` inode+size+mtime 守卫通过 | `logs/gate-integration-real.log` |
|
||||
| 静态 a11y | `npm run check:a11y` | 0 | 11/11 页 0 问题;对比度/标题/品牌令牌三件套全绿 | `logs/gate-a11y.log` |
|
||||
| 视觉语法 | `npm run check:visual` | 0 | grammar/accents 及 selftest 通过;R10 hover-lift 棘轮未升 | `logs/gate-visual-check.log` |
|
||||
| 动效约束 | `npm run check:motion` | 0 | 256 文件、0 违规 | `logs/gate-motion.log` |
|
||||
| 包键一致性 | `npm run check:package-keys` | 0 | 通过 | `logs/gate-package-keys.log` |
|
||||
| 生产安全头 | `npm run test:security:headers` | 0 | **8/8 PASS**(CSP/HSTS/XFO/nosniff/Referrer/Permissions/XSS/ACAO) | `logs/security-headers.log` |
|
||||
|
||||
## 3. 视觉回归(只读,不写基线)
|
||||
|
||||
命令:`cd e2e && E2E_TARGET=production DATABASE_URL=file:/tmp/novalon-qa-20261021/dev.db npx playwright test visual-regression.spec.ts --update-snapshots=none`
|
||||
|
||||
- **123 passed / 2 failed / 5.3m / EXIT=1**;5 个 project、127 张既有基线,未写任何参照。
|
||||
- 两例红均在 `visual-webkit-desktop` L1:
|
||||
- `/products`:154,897 px(ratio 0.01);隔离 `--workers=1` 复跑 **passed**。
|
||||
- `/about/brand`:1,411,676 px(ratio 0.04);隔离复跑仍红。
|
||||
- **归因:测试装配 dwell 竞态,不是像素回归。** actual/expected **页高一致**,差异带内 actual 是 `opacity:0` 的空白(品牌使命/愿景、时间线等 ScrollReveal 区块未显影),符合 `docs/lessons-learned.md` §5.51 签名 1。独立探针:webkit 同页 120ms/步快速滚动后 mission/timeline opacity=0;改成 350ms/步后均为 1。`/products` 隔离转绿进一步排除产品回归。
|
||||
- **不据此更新基线**:若把竞态固化成参照,会把「未显影」写进批准资产。
|
||||
|
||||
## 4. 全路由视觉 / UI / UX Sweep
|
||||
|
||||
脚本:`scripts/acceptance/sweep-routes.mjs`(新增,复用 2026-10-20 首页探针的 settle / 懒加载 / 祖先 opacity 逻辑)。
|
||||
分母:`check:axe:routes` 的机器清单 **35 条**(sitemap ∪ 预渲染 ∪ BFS;含 `/_not-found`、`/cases`、`/privacy`、`/terms`、动态 slug),不是人工数的 22 条。
|
||||
|
||||
- 矩阵:35 × `{1440 浅/深, 834 浅, 390 浅/深}` × chromium = 175;另 firefox/webkit 抽 `/ /about /contact /products` + 一条详情 × `{1440 浅, 390 浅}` = 20;合计 **195 次运行**。
|
||||
- **0 hard failure**:
|
||||
- 祖先链 opacity <0.99:**0**
|
||||
- 横向溢出:**0**
|
||||
- 破图(eager + 逐屏滚动后 `complete && naturalWidth>0`):**0**
|
||||
- `pageerror`:**0**
|
||||
- 同源 4xx/5xx:**0**(唯一例外 `/_not-found` 文档 404,按契约豁免)
|
||||
- console error:**5 次,全部是 `/_not-found` 的 404 资源提示**
|
||||
- **设计契约实测**:
|
||||
- 品牌红触达:最少 **1**(`/privacy`),其余页面 ≥2;`/privacy`、`/terms`、404 暗色低于「每页 ≥3」的规则(见 P3)。
|
||||
- 红色像素占比最高 **4.37%**(404 页),全部 <10%。
|
||||
- 直角/字阶/动效:`check:visual` + `check:motion` 静态门全绿;运行时副作用见 P2。
|
||||
- **联系表单首屏**:form top = **1064px @1440×900**、1547 @834、1254 @390 → **三种视口都不在首屏**(DESIGN.md 称 contact 为紧凑档、表单回首屏,见 P2)。
|
||||
|
||||
## 5. Admin UI / UX(9 页 × 5 组合 + 状态)
|
||||
|
||||
- 登录:`admin/admin123`(UI 表单,水合后 1.2s 再提交);Dashboard 实测 **16 模型 / 38 条目 / 6 区域 / 3 活跃用户 / 已发布 38**;登录失败提示「用户名或密码错误」已实测。
|
||||
- 45 次运行(9 路由 × 5 组合)**0 hard failure**;390 档 18 次运行全部检出 **公共站点的 `mobile-tab-bar`**。
|
||||
- 已覆盖状态:登录错误、Dashboard 数据、内容列表、编辑器(`/new`,因列表项为 `router.push` 按钮、无 `<a>`,未抓到既有条目 id)、空媒体库、通知、角色、用户、区域、删除确认弹窗(打开后取消,未写库)、`e2e_editor` 直访 `/admin/users` 的拒绝态。
|
||||
- 主要发现:
|
||||
- **公共移动 tab bar 泄漏到全部 `/admin` 与 `/admin/login`**(根布局 `src/app/layout.tsx:218` 无条件渲染 `<MobileTabBar />`)。
|
||||
- **390 内容列表不可用**:标题列被压成逐字竖排(「四 川 睿 新…」),状态签也竖排;表格为 `w-full` + 外层 `overflow-x-auto`,只压缩不滚动(`src/app/admin/content/[modelCode]/page.tsx:179-180`)。
|
||||
- 拒绝态保留了「创建用户」按钮与表头,仅以横幅提示「仅管理员可查看用户列表」;无权限时仍显示可点击入口(P3)。
|
||||
- Admin 暗色主题整体可用,活动项对比偏低(P3)。
|
||||
- 移动端触控目标偏小:密码可见性按钮 16×16、菜单按钮 28×28、登录按钮高 43px(P3)。
|
||||
|
||||
## 6. a11y / 性能 / 线上只读
|
||||
|
||||
- **axe 全站节点计数:未通过,但判为门禁 settle 竞态,不是产品对比度缺陷。**
|
||||
- 首跑(`axe/axe-evidence.json`):EXIT=1,**firefox/light 6 nodes、firefox/dark 3 nodes**,chromium 两主题 0;节点集中在首页 ledger 指标、「配套服务」卡、首页行业卡 `text-white/70`、about 数据标签。
|
||||
- 原样重跑(`axe-rerun/axe-evidence.json`):EXIT=1,但**失败集合漂移**为 **chromium/dark 3、firefox/light 1、firefox/dark 1**,chromium/light 0 ⇒ 不是稳定的静态对比度对。
|
||||
- 隔离复跑:同一 gate 时序在 firefox/light `/` 上 **5/5 为 0**;受控慢滚动 + `reducedMotion:'reduce'` 的 20 次运行(5 路由 × chromium/firefox × light/dark)**0 violation**(`axe-fixed-settle.json`)。
|
||||
- 静态配对复核:`text-muted/bg-secondary=5.31:1`、`text-secondary/brand-soft12=9.53:1`、`brand-ink/brand-soft12=4.58:1`、`dark muted/bg-primary=4.98:1` ⇒ 均 ≥4.5:1。
|
||||
- 机理:gate 的 `settle()` 是「直接跳到底 → 回顶 → 400ms」,`ScrollReveal` 元素在 axe 运行时可能仍处入场中间态;有效 opacity <1 会把 5.31:1 压到 ~2:1。与 `docs/lessons-learned.md` §5.51 同族。
|
||||
- **结论口径**:本轮不把 axe 红计为产品 a11y 缺陷,但**也不能宣称全站 a11y 全绿**;门禁本身需修(逐屏 dwell / 等 reveal 完成 / reduce 模式)后再作为发布判据。
|
||||
- **Lighthouse:EXIT=0,33/33 run 全部断言通过**(11 URL × 3 run,`:3200` 自起 standalone,桌面 preset)。
|
||||
- 四类目(performance / accessibility / best-practices / SEO)在 11 条 URL 上**中位数全部 1.00**。
|
||||
- 中位 Core Web Vitals:FCP **246–336ms**、LCP **534–822ms**、CLS **0**、TBT **0ms**、SI **266–572ms**。
|
||||
- 明细:`lighthouse-summary.json`(只统计 2026-10-21 10:00 之后的报告,避开 `.lighthouseci/` 的历史轮次)。
|
||||
- **线上只读冒烟**(仅 GET):35 路由中 **34 条 200**,`/_not-found` 404(契约);首访最慢 `/products/erp-upgrade 4.79s`、`/team 4.32s`,二次访问 1.43s / 1.12s(冷 ISR 首访,不是持续慢)。
|
||||
- **线上 8 次同口径运行**(`prod-compare/`,/ /about /contact /products × 1440/390):opacity=1、无横向溢出、0 破图、0 console/pageerror、0 失败请求;H1 与本地一致。
|
||||
- **本地 vs 线上资产指纹**:19 个 `_next/static` 引用中 15 个相同、4 个不同(CSS + 3 JS)。原因:线上是 `2f86c441`(BUILD_ID KO7S41…),本地 HEAD 还含 `b125d16a`(hero hover token)等后续提交。**像素对照只作参考,不作回归判据**。
|
||||
- **webkit axe**:仍不在任何门禁矩阵内(已知缺口,如实保留)。
|
||||
|
||||
## 7. UX 行为补测
|
||||
|
||||
- **定向 spec:136 passed / 8 skipped / 0 failed / 2.1m / EXIT=0**(production 目标、副本库、4 project)。
|
||||
- 覆盖 `first-paint-visibility`(无 JS 兜底 / 水合交接)、`reduced-motion-hydration`(reduce 下 #418 与末段可见)、`client-navigation-visibility`(白屏回归守卫)、`nav-keyboard`、`nav-dropdown`、`p6-missing-paths`(含联系表单完整成功提交)、`p5-edge-cases`、404/错误边界。
|
||||
- 8 skipped 均为 `nav-keyboard` 在 `chromium-mobile` / `webkit` 上的设计性跳过(桌面下拉键盘用例不适用于移动档)。
|
||||
- 联系表单「填写有效信息并提交成功」实测通过 ⇒ 加密链路与 `/api/contact` 在本地产物上可用(前提:运行时 secret 与构建内联 secret 一致)。
|
||||
- `[待补]` 全量功能 E2E(4 project,副本库;含 `cms-workflow` / `user-journey`)。
|
||||
- 已由 sweep 覆盖:35 路由客户端渲染可见性、移动 tab bar 可见性、触控盒分布、404、暗色主题切换、表单在场与首屏位置。
|
||||
|
||||
## 8. 缺陷清单
|
||||
|
||||
### P0 / P1
|
||||
|
||||
无。
|
||||
|
||||
### P2(计入「有条件通过」)
|
||||
|
||||
| ID | 缺陷 | 证据 | 影响面 |
|
||||
|---|---|---|---|
|
||||
| DEF-01 | **网格列数与内容量不匹配,产生大面积空槽**(可见的 `bg-border-primary` 灰块):6 步放进 4 列、3 指标放进 4 列、4 服务放进 2 列、2 产品放进 5 列(`col-span` 还挂在卡片内层而非 grid 子项)、首页 5 指标放进 4 列 | `sweep-summary.json`:**19 条路由 / 73 次运行命中**;截图 `products__1440__light__chromium__full.webp`、`products_erp__1440__light__chromium__full.webp`、`services__1440__light__chromium__full.webp`、`solutions_manufacturing__1440__light__chromium__full.webp` | 产品详情、服务、解决方案、产品 hub、首页 |
|
||||
| DEF-02 | **指标大字在 1440 宽度换行**:81px 字号落在 209px 内容宽里,`40%+` / `99.2%` / `3-6个月` / `+113%` 被拆成两行 | `sweep-summary.json`:8 次运行;`products_erp__1440__light__chromium__full.webp`、`products_crm__1440__light__chromium__full.webp` | `/products/erp`、`/products/crm`(1440 浅/深) |
|
||||
| DEF-03 | **公共移动 tab bar 泄漏到 Admin**:`/admin`、`/admin/login` 及全部子页在 390 档显示「首页/行业/能力/洞察/联系」,fixed 覆盖 admin 内容 | `admin-content_news__390__light__chromium__hero.jpg`;report `admin.tabBarOn390=18/18` | 全部 9 个 admin 路由 |
|
||||
| DEF-04 | **Admin 移动端内容表塌陷**:标题列逐字竖排、状态签竖排,表格只压缩不横向滚动 | 同上 screenshot;源码 `src/app/admin/content/[modelCode]/page.tsx:179-180` | `/admin/content/*`、`/admin/users` 等表格页 390 档 |
|
||||
| DEF-05 | **联系表单不在首屏**:form top 1064 @1440×900(DESIGN.md 称 contact 紧凑档、表单回首屏) | `contact__1440__light__chromium__full.webp`;sweep `form.top` | `/contact` 全视口 |
|
||||
|
||||
**DEF-01 源码定位**(只报告,不改):`src/app/(marketing)/products/product-detail-content-v3.tsx:232`(6 步 / 4 列)、`src/components/content/sections.tsx:355`(3 指标 / 4 列)、`src/app/(marketing)/services/services-content-v3.tsx:193-199`(4 服务 / 2 列 + 首项 span 2)、`src/app/(marketing)/solutions/solution-detail-content-v3.tsx:296-325`(5 列 grid;`+` 与配套服务在 grid 外)、`src/app/(marketing)/home-content-v16.tsx:239`(5 指标 / 4 列)。
|
||||
|
||||
### P3(记录,不阻断)
|
||||
|
||||
- **红色触达计数是「元素级令牌」口径,不是视觉面积口径**:`/privacy` 计 1、`/terms` 计 2、404 暗色计 2,但这三页都有整幅红底 hero(视觉红色占比 2.6% / 2.5% / 4.4%)。**不将其登记为「红色稀缺」缺陷**;若要判「每页 ≥3 触达」,需要把伪元素/渐变/背景图纳入计数,属仪器口径待改。
|
||||
- Admin 拒绝态仍渲染「创建用户」按钮与表头(`admin-permission-denied__1440__light__chromium__full.jpg`)。
|
||||
- Admin 移动端触控目标 <44px:密码可见性 16×16、菜单 28×28、登录按钮 43px。
|
||||
- Dashboard「最近通知」在 160 条通知(全部已读)下显示「暂无通知」;面板名为「最近通知」,空态语义偏窄。
|
||||
- Admin 暗色活动项对比偏低(如侧栏「仪表盘」深底上的深色块)。
|
||||
|
||||
### 测试/环境装配(不计入产品缺陷)
|
||||
|
||||
- **TA-01**:webkit 视觉门禁 dwell 竞态(2 例),详见 §3;`--workers=1` 仍可能红,签名是「同高空白带」。
|
||||
- **TA-02**:`build:clean` 不触发 `postbuild`,standalone 装配需手工补。
|
||||
- **TA-03**:本地 `.env.local` / `.env.production` 加密密钥不一致 ⇒ 加密响应解密失败、Admin 全 `-`;生产两端一致。
|
||||
- **TA-04**:`/_not-found` 文档 404 曾被 harness 误判为 hard failure;已在 sweep 中按契约豁免。
|
||||
- **TA-05**:全站 axe 门禁的 `settle()`(跳底→回顶→400ms)在带动画的页面上不稳定:两次连跑失败集合漂移(firefox 6/3 → chromium/dark 3 + firefox 1/1),隔离 5/5 与受控 20/20 均为 0。**门禁需改为逐屏 dwell / 等 reveal 完成 / reduce 模式**,否则 `check:axe` 的红绿不可复现。
|
||||
|
||||
## 9. 未做 / 不可自动判
|
||||
|
||||
- 真机 iOS/Android、VoiceOver/NVDA 等屏幕阅读器实测。
|
||||
- 颜色校准/不同显示器色差;摄影构图与中文排版节奏的审美判断(本报告只做启发式评审)。
|
||||
- 联系表单真实邮件送达、生产库与本地副本一致性。
|
||||
- webkit axe 矩阵(现有 axe 只跑 chromium+firefox)。
|
||||
- **全站 axe 的可信全绿读数**:门禁 settle 竞态(TA-05)未修,现有两次全站跑均红且失败集合漂移;仅静态 a11y 三件套与受控抽检为绿。
|
||||
- hover/半透明/伪元素对比度(axe 与静态门不判)。
|
||||
- framer JS 动效时长的运行时测量(`check:motion` 只扫源码;浏览器 computed 读不到 framer duration)。
|
||||
- 视觉基线的重写/新增(本轮未获授权;只读比对)。
|
||||
- 全量变异测试、Sentry 投递、Axe 之外的第三方审计。
|
||||
|
||||
## 10. 复跑与证据
|
||||
|
||||
```bash
|
||||
# 1) 构建 + 装配(build:clean 需手工补 postbuild)
|
||||
npm run build:clean
|
||||
rm -rf dist/standalone/dist/static dist/standalone/public
|
||||
mkdir -p dist/standalone/dist
|
||||
cp -R dist/static dist/standalone/dist/static
|
||||
cp -R public dist/standalone/public
|
||||
|
||||
# 2) 副本库
|
||||
sqlite3 prisma/dev.db ".backup '/tmp/novalon-qa-20261021/dev.db'"
|
||||
|
||||
# 3) 服务(运行时 ENCRYPTION_SECRET 必须与构建内联的 public secret 一致)
|
||||
DATABASE_URL=file:/tmp/novalon-qa-20261021/dev.db ENCRYPTION_SECRET=<.env.local 值> \
|
||||
HOSTNAME=127.0.0.1 PORT=3100 node dist/standalone/server.js
|
||||
|
||||
# 4) 全路由 sweep
|
||||
BASE=http://127.0.0.1:3100 ROUTES=/tmp/qa-routes.xml OUT=docs/acceptance/2026-10-21-full-qa \
|
||||
node scripts/acceptance/sweep-routes.mjs
|
||||
|
||||
# 5) contact sheet
|
||||
node scripts/acceptance/contact-sheet.mjs \
|
||||
docs/acceptance/2026-10-21-full-qa/screenshots/public \
|
||||
docs/acceptance/2026-10-21-full-qa/contact-sheets
|
||||
```
|
||||
|
||||
证据目录:`README.md`、`build-attestation.json`、`routes.json`、`report.json`、`report-public.json`、`sweep-summary.json`、`screenshots/{public,admin}`、`prod-compare/`、`axe/`、`logs/`。
|
||||
DB 指纹:运行前 `logs/../`(`/tmp/novalon-qa-20261021/db.sha256.before`、`db.stat.before`)与运行后见 §11 `[待补]`。
|
||||
@@ -0,0 +1,122 @@
|
||||
[
|
||||
{
|
||||
"engine": "chromium",
|
||||
"theme": "light",
|
||||
"path": "/",
|
||||
"violations": []
|
||||
},
|
||||
{
|
||||
"engine": "chromium",
|
||||
"theme": "light",
|
||||
"path": "/about",
|
||||
"violations": []
|
||||
},
|
||||
{
|
||||
"engine": "chromium",
|
||||
"theme": "light",
|
||||
"path": "/solutions/logistics",
|
||||
"violations": []
|
||||
},
|
||||
{
|
||||
"engine": "chromium",
|
||||
"theme": "light",
|
||||
"path": "/products/erp",
|
||||
"violations": []
|
||||
},
|
||||
{
|
||||
"engine": "chromium",
|
||||
"theme": "light",
|
||||
"path": "/contact",
|
||||
"violations": []
|
||||
},
|
||||
{
|
||||
"engine": "chromium",
|
||||
"theme": "dark",
|
||||
"path": "/",
|
||||
"violations": []
|
||||
},
|
||||
{
|
||||
"engine": "chromium",
|
||||
"theme": "dark",
|
||||
"path": "/about",
|
||||
"violations": []
|
||||
},
|
||||
{
|
||||
"engine": "chromium",
|
||||
"theme": "dark",
|
||||
"path": "/solutions/logistics",
|
||||
"violations": []
|
||||
},
|
||||
{
|
||||
"engine": "chromium",
|
||||
"theme": "dark",
|
||||
"path": "/products/erp",
|
||||
"violations": []
|
||||
},
|
||||
{
|
||||
"engine": "chromium",
|
||||
"theme": "dark",
|
||||
"path": "/contact",
|
||||
"violations": []
|
||||
},
|
||||
{
|
||||
"engine": "firefox",
|
||||
"theme": "light",
|
||||
"path": "/",
|
||||
"violations": []
|
||||
},
|
||||
{
|
||||
"engine": "firefox",
|
||||
"theme": "light",
|
||||
"path": "/about",
|
||||
"violations": []
|
||||
},
|
||||
{
|
||||
"engine": "firefox",
|
||||
"theme": "light",
|
||||
"path": "/solutions/logistics",
|
||||
"violations": []
|
||||
},
|
||||
{
|
||||
"engine": "firefox",
|
||||
"theme": "light",
|
||||
"path": "/products/erp",
|
||||
"violations": []
|
||||
},
|
||||
{
|
||||
"engine": "firefox",
|
||||
"theme": "light",
|
||||
"path": "/contact",
|
||||
"violations": []
|
||||
},
|
||||
{
|
||||
"engine": "firefox",
|
||||
"theme": "dark",
|
||||
"path": "/",
|
||||
"violations": []
|
||||
},
|
||||
{
|
||||
"engine": "firefox",
|
||||
"theme": "dark",
|
||||
"path": "/about",
|
||||
"violations": []
|
||||
},
|
||||
{
|
||||
"engine": "firefox",
|
||||
"theme": "dark",
|
||||
"path": "/solutions/logistics",
|
||||
"violations": []
|
||||
},
|
||||
{
|
||||
"engine": "firefox",
|
||||
"theme": "dark",
|
||||
"path": "/products/erp",
|
||||
"violations": []
|
||||
},
|
||||
{
|
||||
"engine": "firefox",
|
||||
"theme": "dark",
|
||||
"path": "/contact",
|
||||
"violations": []
|
||||
}
|
||||
]
|
||||
Loaded 100 of 545 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user