feat(hero): 机房场景退役 + 抽象数据场落库(ADR-0016 §17 撤回 / §17.5 继任)

退役(零视觉影响:NEXT_PUBLIC_HERO_SCENE 从未在任何 .env* 设置):
- 删 hero-scene.tsx(694行)/caption/单测/文案真源/CC0 机柜/海报帧
- R26 删除、R22 登记归零、e2e heroSceneMask 移除(无命中的假安全网)
- R22 自证改可注入(夹具不再依赖生产条目)

落库(flag NEXT_PUBLIC_HERO_FIELD 样期默认关 ⇒ 基线零影响):
- hero-field.tsx 三拍:噪声→增长→判断;bloom 半分辨率;DPR≤1.5
- 降级统一看结论帧(reduced-motion 定格 T_HOLD=40500 非 0)
- 文案真源含承诺词正则守卫(禁帮助/赋能/提升/%/倍)
- 海报帧 capture 脚本与资产同批入库(1920x864/26.9KB,可复现)
- eslint 忽略 demo/**/vendor/**(vendored three 不可被 lint-staged --fix 改写)

守卫重建:R26 指向 hero-field(43260ms/3 拍合规);R22 登记 HeroField 条目
验证:tsc 0 / eslint 0 error / jest 162 套件 1906 例 / check:grammar 26+26
  / check:a11y 0 违规 / 默认构建首页 DOM 冒烟 E 案不变
This commit was merged in pull request #65.
This commit is contained in:
zhangxiang committed 2026-12-02 19:27:55 +08:00
1 parent 2bb342cfa9
commit 6ce794164a
108 files changed
+98666 -1005

No files matched your search

+17 -15
View File
@@ -84,26 +84,28 @@ Switch / Slider 的白底圆钮。
决策状态:✅ 2026-06-29 确认
#### 例外:首屏 3D 场景分镜(ADR-0016,2026-12-02)
#### ~~例外:首屏 3D 场景分镜~~ [已撤回]
**只对首页首屏的 3D 场景层**开一档窄例外,允许**分镜式编排**(多机位时间线 + 压黑转场)。
依据:对标 Porsche Consulting 的 hero 本就是「一条片子里的几个镜头」;本站没有实拍素材,
用闭合运镜模拟「一直在走」。
**2026-12-02 晚撤回**:该例外唯一的作用对象(`src/components/home/hero-scene.tsx`,机房分镜)
已整体退役,理由是**题材不成立**,不是实现有缺陷:
例外同时受四条约束,缺一条即不成立:
- 机房语义是「数据的存放地」,而首屏要讲的是「数据如何变成判断」—— 画面里从来没有
「选项 / 判据 / 结论」这些对象,任何光效最多表达「设备在运行」;
- 换成「抽象数据场」后,三拍仍是分镜式编排,但**例外条款本身不再需要**:
它当初是为了给「循环」开一档窄口子,而新的三拍节奏(43.26s)由具体实现自行满足
①–④,没有再走例外。
| # | 约束 | 判据 |
|---|---|---|
| ① | **一轮周期落在 [20s, 60s]** | `check:grammar` **R26** 解析 `ms:` 与 `DIP_MS` 求和 |
| ② | **不得脉冲式重复**(同一动画等间隔重复仍禁 —— 这正是 E 案拒掉 `pulseVertical` 的理由) | 无静态形态,人工评审兜(R26 note 明写) |
| ③ | **`prefers-reduced-motion` 必须定格** | R26 检查 `prefers-reduced-motion` 存在 |
| ④ | **离屏 / 切后台必须停** | R26 检查 `IntersectionObserver` + `visibilitychange` 同时存在 |
随之撤回的还有:`check:grammar` 的 **R26**(其唯一判据就是解析该文件的 `ms:` 与 `DIP_MS`)、
海报帧 `hero-scene-poster.webp`、CC0 资产 `server-rack.glb`,以及 R22 登记表里的对应条目
(登记表因此归零 —— 首屏回到**零视觉层**)。
另禁 `autoRotate`(自转=同一动画重复播放),由 R26 直接判红。
⚠ **对新场景的约束已随落地重建(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 案,基线零影响。
⚠ 例外**不外溢**:营销页正文、卡片、导航、移动档一律不适用;移动档首屏不跑 WebGL(落 E 案)。
决策状态:✅ 2026-12-02 用户认可(ADR-0016 §10.5;R26 已落地,含三向自证与突变验证)
决策状态:❌ 2026-12-02 撤回(ADR-0016 §12 撤回段)
### 服务编号+色条编码(Service Number + Color Bar)
服务模块的区分方式,取代纯颜色编码:
+936
View File
@@ -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 };
+191
View File
@@ -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 };
+36
View File
@@ -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 };
+56
View File
@@ -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 };
+151
View File
@@ -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 };
+404
View File
@@ -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 };
+52
View File
@@ -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 };
+104
View File
@@ -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 };
+298
View File
@@ -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 };
+73
View File
@@ -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 };
+94
View File
@@ -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 };
+437
View File
@@ -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 };
+62
View File
@@ -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 };
+103
View File
@@ -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 };
+201
View File
@@ -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 };
+489
View File
@@ -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 };
+331
View File
@@ -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 };
+396
View File
@@ -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 };
+57
View File
@@ -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 };
+349
View File
@@ -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 };
+285
View File
@@ -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 };
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+726
View File
@@ -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>
+63
View File
@@ -492,3 +492,66 @@ InstancedMesh,只处理其一就会留下悬空的发光片。这类"半替换
视觉上远景不再是方块,走廊纵深到 26m 都是真机细节;代价是单帧三角面从 390k 升到 971k。
**这是「用性能余量换一致观感」的典型交易,且已用台数档位表把上限钉住** ——
以后要再加,必须先跑同一张表,不能凭「应该还行」。
---
## 17. 撤回(2026-12-02 18:20)
**本 ADR 全部条款作废。** 首屏 3D 场景(`src/components/home/hero-scene.tsx`,694 行)连同
其角标组件、文案真源、CC0 资产与海报帧一并从仓库移除。
### 17.1 撤回理由(不是实现缺陷,是题材不成立)
用户的原话是「这个机房的动画没有体现数据驱动决策」。复盘后确认这是**内容层**判断,与画质、
运镜、性能都无关:
- 机房的语义是「数据的**存放**地」;首屏要说的是「数据如何变成**判断**」。
- 决策的必要内容是「多个选项 + 判据 + 排除 + 落定」。机房画面里从来没有「选项」这个对象,
所以无论怎么打光、加粒子、加扫描线,最多只能表达「设备在运行」。
- 上一轮为此做过三个光效方案(灯带脉动 / 数据粒子 / 扫描显影),三个都被同一句话否掉 ——
它们都是「光在动」,画面里没有一个可以指着命名的决策对象。**这是本文档最该记住的教训:
先定「拍什么」,再谈「怎么拍」;技术层讨论得再完整,题材错了也是零。**
### 17.2 替代方案(已定,尚未落地)
抽象数据场:**噪声 → 增长 → 判断**。散点与随机碎片 → 从左向右画出单调上升的曲线 →
镜头收向「曲线 × 判据线」的交点、数据按到交点的距离退场、判据线锁定。
当晚已落地 `src/components/home/hero-field.tsx`(flag `NEXT_PUBLIC_HERO_FIELD` 样期,默认关)。它的三拍仍是分镜式编排,因此 R26 判据**随落地重建**并指向新组件 —— 撤回的是机房那套实现与资产,不是守卫本身。
### 17.3 随之撤回的具体项
| 项 | 处置 |
|---|---|
| `src/components/home/hero-scene.tsx`、`hero-scene-caption.tsx` 及其单测 | 删除(`src/components/home/` 目录随之移除) |
| `src/lib/constants/hero-scenes.ts` 及其单测 | 删除 |
| `public/models/server-rack.glb`、`LICENSE-server-rack.txt` | 删除(CC0,无需保留许可文件) |
| `public/images/home/hero-scene-poster.webp` | 删除 |
| `check:grammar` **R26** | 删除规则、夹具与上限常量;`expect` 清单同步 |
| R22 登记表(`HERO_VISUAL_REGISTRY`) | 条目清空 —— 首屏回到**零视觉层**;登记机制保留并改为可注入,使自证不再依赖生产条目 |
| `e2e/visual-regression.spec.ts` 的 `heroSceneMask` | 删除(选择器已无命中,留着是假的安全网) |
| `NEXT_PUBLIC_HERO_SCENE` / `..._CAPTURE` | 不再被读取(两个旗标在全部 `.env*` 中本就未设置,故本次无视觉影响) |
### 17.4 可复现性说明
被删的场景原型仍可从 git 历史取回(本 ADR 的 §1–§16 即为它的完整设计记录与实测数据)。
保留本文件的目的是让「为什么它被删」和「它当时做到了什么」都留在仓库里 ——
下一版首屏若要复用其中任何一条经验(雾的远近、实例化档位、海报帧生成、billboard 判据线),
不必重新试错。
### 17.5 继任者落地(同日晚)
抽象数据场已进 `src/components/home/hero-field.tsx` + `hero-field-caption.tsx` +
`src/lib/constants/hero-field-scenes.ts`(flag `NEXT_PUBLIC_HERO_FIELD` 样期,默认关 ⇒ 基线零影响)。
三拍:噪声 → 增长 → 判断。判据线与越线点是本版新增的**内容物** ——
机房的教训(§17.1)直接决定了这一版的设计原则:每一拍都要有可命名的内容物。
随落地重建的守卫与登记:
| 项 | 处置 |
|---|---|
| `check:grammar` **R26** | 重建,指向 `hero-field.tsx`(判据同 §10.5:周期 [20s,60s] / reduced-motion 定格 / 离屏停 / 禁 autoRotate) |
| R22 登记表 | 新条目:marker `HeroField` · poster `/images/home/hero-field-poster.webp` |
| 海报帧 | `scripts/capture-hero-field-poster.mjs`(生产构建 + CAPTURE 模式抓 canvas → sharp → webp,**可复现**,补掉 §6.2 那条已知债) |
| 降级原则 | 所有非动画档(reduced-motion / WebGL 失败 / 移动档)统一看**结论帧**,不是第一拍 |
+31 -15
View File
@@ -114,29 +114,45 @@
- 正文构型改判载体:**R23**(`<StageIndex` / `<BandIndex`,分母 5);
- 仍在使用的内容图(行业缩略图、洞察卡封面、新闻配图、品牌页)照旧按本文件 §4 三步登记。
## 6. 3D 资产(2026-12-02 新增,ADR-0016)
## 6. 3D 资产 ~~(2026-12-02 新增,ADR-0016)~~ [当日撤回]
### 6.1 登记
### 6.1 撤回(2026-12-02 18:20)
| 项 | 值 |
本节 §6.2 记录的是**当天早些时候**登记过的 3D 资产,全部已随 ADR-0016 撤回一并删除:
| 已删除项 | 原用途 | 为何不保留 |
|---|---|---|
| `public/models/server-rack.glb`(954KB,CC0) | 首屏机房近景/俯视阵列实例化 | 承载它的场景已退役;CC0 无署名义务,无需为留存许可而留文件 |
| `public/models/LICENSE-server-rack.txt` | 随包许可 | 同上 |
| `public/images/home/hero-scene-poster.webp`(17KB) | 首屏 LCP / WebGL 降级 / 移动档 | 无消费方;且其生成脚本本就未入库(原登记为已知债),留一个无法复现的派生资产没有意义 |
**保留本节的原因**:以后若再引入 3D 资产,§6.2 那套登记字段(来源 / 许可 / 生成方式披露 / 规格 / 消费方 / 对原资产的修改)仍是正确的模板;而「派生资产必须可复现」的教训(生成脚本未入库 ⇒ 换资产后无法重生成)比资产本身更值得留下 —— 这条已在新资产上兑现:见 §7。
### 6.2 历史记录(已作废,仅供追溯)
| 项 | 原值 |
|---|---|
| 文件 | `public/models/server-rack.glb`(954KB) |
| 随包许可 | `public/models/LICENSE-server-rack.txt`(与模型同目录,便于审计时一起取) |
| 来源 | Grab3D《Server Rack》light 版 — `https://grab3d.com/models/electronics/server-rack` |
| 许可 | **CC0 1.0**(明示放弃著作权,无署名义务,可商用) |
| 生成方式披露 | 程序化(Blender 脚本);**无 AI 生成几何或贴图**(随包 LICENSE 原文) |
| 规格 | 14,851 三角面 / 6 primitive / 4 张 1K 贴图 / 真实尺寸 0.60×1.07×2.00m |
| 消费方 | `src/components/home/hero-scene.tsx`(走廊近景每排 40 台 + 俯视阵列 60 台,实例化) |
| 对原资产的修改 | `color × 0.09` 压深(白壳→深金属);LED 豁免并压 0.3;**跳过 `server-rack_led_glow`**(走廊尺度上连成电子束) |
| 消费方(已删) | `src/components/home/hero-scene.tsx` |
| 对原资产的修改 | `color × 0.09` 压深(白壳→深金属);LED 豁免并压 0.3;跳过 `server-rack_led_glow` |
### 6.2 派生资产
| 文件 | 由谁生成 | 用途 | 可复现性 |
|---|---|---|---|
| `public/images/home/hero-scene-poster.webp`(17KB) | 上述模型的 **canvas 像素**(`toDataURL` + `NEXT_PUBLIC_HERO_SCENE_CAPTURE=1`) | 首屏 LCP / WebGL 失败降级 / 移动档 | ⚠ 生成脚本目前在 `.workbuddy/tmp/make-poster.mjs`,**未入库** —— 换资产后需要它,登记为已知债 |
### 6.3 §5.4 的订正(只增不删)
### 6.3 §5.4 的订正(保留,仍然成立)
§5.4 写的「R22(17 个营销首屏零影像)」在 **2026-12-02 同日**已随第三次改判失效:R22 现为
**视觉层登记制**(载体白名单 + 出处 + 海报存在性 + 表过期),本文件 §6.1 登记的就是它的第一份登记项。
「17 个首屏零影像」的历史读数不再作为现行依据。
**视觉层登记制**(载体白名单 + 出处 + 海报存在性 + 表过期)。撤回 3D 资产后该登记表**归零**,
即「当前一个视觉层都不批」—— 规则仍在守,只是没有被批准的例外。
## 7. 首屏抽象数据场的派生资产(2026-12-02 新增,继任 ADR-0016 撤回后的空位)
| 项 | 值 |
|---|---|
| 文件 | `public/images/home/hero-field-poster.webp` |
| 来源 | `src/components/home/hero-field.tsx` 场景的**结论态定格帧**(`canvas.toDataURL`,`NEXT_PUBLIC_HERO_FIELD_CAPTURE=1`) |
| 生成方式 | `scripts/capture-hero-field-poster.mjs`(生产构建 + Playwright 抓画布 → sharp → webp 1920 宽,**已入库、可复现**) |
| 消费方 | `src/components/home/hero-field.tsx`(首屏 LCP / WebGL 失败降级 / 移动档之外的桌面兜底) |
| 已知债 | 无 —— 生成脚本本次与资产同批入库(机房场景 §6.2 的教训兑现) |
+2 -24
View File
@@ -76,22 +76,6 @@ const VISUAL_TEST_PAGES = [
{ path: '/visual-regression-404-probe', name: 'not-found', label: '404 页面' },
];
/**
* 首屏 3D 场景区的 mask(ADR-0016 §4.3)。
*
* WebGL 在 headless 下的栅格化结果**跨机器不稳定**(同机同驱动稳定,换 CI 机器就变),
* 把场景像素写进基线等于把 GPU 写进参照文件 —— 以后每次硬件变动都会红一批,且无法归因。
*
* mask 之后基线仍守**版式**(文字位置、CTA 几何、scrim 边界、首屏高度),场景本身由
* 海报帧基线单独守(海报帧是静态图,进基线合理)。
*
* flag 默认关时该选择器零匹配 ⇒ mask 是 no-op,**225 张基线零重采**(这是可以预判的:
* mask 只影响命中元素,没命中就等于没写)。
*/
function heroSceneMask(page: Page) {
return [page.locator('[data-testid="hero-scene"]')];
}
async function waitForPageStable(page: Page) {
await page.waitForLoadState('networkidle');
await page.waitForTimeout(2000);
@@ -193,8 +177,6 @@ test.describe('L1: 全页面视觉回归测试', () => {
fullPage: true,
animations: 'disabled',
caret: 'hide',
// 仅首页会命中;其余页零匹配 ⇒ 行为不变(见 heroSceneMask 注释)
mask: heroSceneMask(page),
});
});
}
@@ -390,9 +372,7 @@ test.describe('L2: 主题切换视觉测试', () => {
await expect(page.locator('html')).toHaveAttribute('data-theme', 'light');
await expect(page.locator('main').first()).toHaveScreenshot('theme-light-main.png', {
mask: heroSceneMask(page),
});
await expect(page.locator('main').first()).toHaveScreenshot('theme-light-main.png');
});
});
@@ -405,9 +385,7 @@ test.describe('L2: 主题切换视觉测试', () => {
await expect(page.locator('html')).toHaveAttribute('data-theme', 'dark');
await expect(page.locator('main').first()).toHaveScreenshot('theme-dark-main.png', {
mask: heroSceneMask(page),
});
await expect(page.locator('main').first()).toHaveScreenshot('theme-dark-main.png');
});
});
});
+4
View File
@@ -111,6 +111,10 @@ const config = [
'.lighthouseci/**',
'test-results/**',
'release-acceptance-reports/**',
// demo/**/vendor/** 是为让 demo 脱离 /node_modules 自包含而内置的 three 库本体与附件,
// 第三方 vendored 文件既不该被 lint(181 errors 全是 three 源码风格问题),
// 更不能被 lint-staged 的 `eslint --fix` 自动改写——那会损坏库文件。
'demo/**/vendor/**',
'.trae/**',
'*.log',
'*.txt',
@@ -0,0 +1 @@
source=capture date=2026-12-02T11:01:08.994Z srcPx=1920x864
Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

-14
View File
@@ -1,14 +0,0 @@
CC0 1.0 Universal (CC0 1.0) Public Domain Dedication
To the extent possible under law, Grab3D has waived all copyright and related or neighboring rights to the
3D models, textures and images in this package. This work is published from: Germany.
https://creativecommons.org/publicdomain/zero/1.0/legalcode
Origin / AI disclosure
----------------------
Method: procedural (no AI-generated geometry or textures, AI-assisted code)
Built procedurally with Blender scripts. The scripts were written with the help of an AI coding assistant. No
generative AI model produced the geometry or textures directly.
If your platform asks whether AI was used in the creation process, note that the generator scripts were
written with an AI coding assistant.
Binary file not shown.
+48
View File
@@ -0,0 +1,48 @@
/**
* 抓取首屏「抽象数据场」的海报帧(结论态定格)。
*
* 用法(三步,顺序不能反):
* 1. NEXT_PUBLIC_HERO_FIELD=1 NEXT_PUBLIC_HERO_FIELD_CAPTURE=1 ./node_modules/.bin/next build
* 2. NEXT_PUBLIC_HERO_FIELD=1 NEXT_PUBLIC_HERO_FIELD_CAPTURE=1 ./node_modules/.bin/next start -p 3123
* 3. node scripts/capture-hero-field-poster.mjs --url http://localhost:3123/
*
* 为什么不用 dev server:flag 是构建期内联的,dev 是热编译但与生产栅格化路径不同;
* 海报帧要的是**结论态的确定性像素**,用生产构建抓取才有可复现性。
*
* 产出:public/images/home/hero-field-poster.webp(登记于 asset-provenance §6 与 R22 登记表)。
*/
import { chromium } from 'playwright';
import sharp from 'sharp';
import { mkdirSync, writeFileSync } from 'node:fs';
import path from 'node:path';
const args = process.argv.slice(2);
const urlIdx = args.indexOf('--url');
const url = urlIdx !== -1 ? args[urlIdx + 1] : 'http://localhost:3123/';
const outRel = 'public/images/home/hero-field-poster.webp';
const browser = await chromium.launch({ args: ['--no-proxy-server'] });
const page = await browser.newPage({ viewport: { width: 1920, height: 1080 }, deviceScaleFactor: 1 });
await page.goto(url, { waitUntil: 'load', timeout: 180000 });
// 等场景完成首帧(CAPTURE 模式下定格在结论帧,不进 rAF 循环)
await page.waitForSelector('[data-testid="hero-field"][data-rendered="1"]', { timeout: 60000 });
await page.waitForTimeout(1500);
const dataUrl = await page.evaluate(() => {
const canvas = document.querySelector('[data-testid="hero-field"] canvas');
if (!canvas) throw new Error('hero-field 画布不存在 —— flag 是否开启?');
return canvas.toDataURL('image/png');
});
const png = Buffer.from(dataUrl.split(',')[1], 'base64');
const meta = await sharp(png).metadata();
console.log(`画布像素 ${meta.width}×${meta.height},转 webp(1920 宽)…`);
const outAbs = path.join(process.cwd(), outRel);
mkdirSync(path.dirname(outAbs), { recursive: true });
await sharp(png).resize({ width: 1920 }).webp({ quality: 82 }).toFile(outAbs);
writeFileSync(path.join(process.cwd(), 'public/images/home/hero-field-poster.png.meta.txt'),
`source=capture date=${new Date().toISOString()} srcPx=${meta.width}x${meta.height}\n`);
console.log(`✓ 已写入 ${outRel}`);
await browser.close();
+63 -52
View File
@@ -53,24 +53,20 @@ const HOVER_LIFT_CEILING = 28;
const EXTERNAL_OWNED = ["--radix-accordion-content-height"];
/**
* R26 的落点:首屏 3D 场景组件。放在模块级而不是规则内部,是因为**自证夹具也要用它** ——
* 路径手抄两份的结局是这个仓已经踩过的「夹具写死旧路径 ⇒ 判据看起来坏了」。
*/
/**
* R22 的**视觉层登记表**(2026-12-02 第三态:零影像 → 登记制,理由见规则注释)。
* R22 的**视觉层登记表**(2026-12-02 第五态:登记制恢复为一条)。
*
* 变迁:三态登记 `HeroScene`(机房场景)→ 四态随机房撤回**归零** → 五态随抽象数据场落地
* 恢复为一条。R22 的语义不变:"任何视觉层都要先登记",登记即批准、未登记即判红。
*
* 每一条必须给三样东西,缺一样这条登记就无效:
* marker —— 载体标记,必须真的出现在首屏区块内(防「登记了但载体已换」)
* origin —— 出处(ADR 编号),供追溯为什么允许它出现在首屏
* poster —— 海报帧相对 `public/` 的路径,必须真实存在(防「降级链写在文档里」)
*
* 新增任何首屏视觉层都必须在这里登记 —— 这正是零影像时代那条硬禁的替代物:
* 不再问「有没有影像」,而问「这个视觉层是谁批准的、失败时退到哪」。
*/
const HERO_VISUAL_REGISTRY = new Map([
[
"src/app/(marketing)/home-content-v17.tsx",
{ markers: ["HeroScene"], origin: "ADR-0016 §3", poster: "/images/home/hero-scene-poster.webp" },
{ markers: ["HeroField"], origin: "ADR-0016 §17.5", poster: "/images/home/hero-field-poster.webp" },
],
]);
@@ -78,18 +74,16 @@ const HERO_VISUAL_REGISTRY = new Map([
* 首屏「视觉层」的载体集合,捕获组 = 载体名(与登记表 `markers` 用同一套字符串)。
* `canvas` 单列是因为有人会绕过组件直接画 —— 零影像时代它整个落在扫描盲区。
*/
const VISUAL_LAYER_RE = /<(HeroPlate|Image|HeroScene|canvas|Canvas)\b/g;
const VISUAL_LAYER_RE = /<(HeroPlate|Image|HeroField|canvas|Canvas)\b/g;
const HERO_SCENE_FILE = "src/components/home/hero-scene.tsx";
/**
* 分镜一轮的时长上下限(ADR-0016 §10.5 例外条款 ①②)。
* 上限 60s:再长就不再是「环境」,观众会开始等下一镜;
* 下限 20s:太短就有脉冲感 —— 而「同一动画的等间隔重复」正是 E 案拒掉 pulseVertical 的理由。
*/
/* R26 的落点:首屏抽象数据场组件(ADR-0016 §17.5)。路径单点维护,自证夹具引用它。 */
const HERO_FIELD_FILE = "src/components/home/hero-field.tsx";
/* 分镜一轮的时长上下限(ADR-0016 §10.5 例外条款 ①②,随 §17.5 继任者沿用)。 */
const HERO_CYCLE_CEILING = 60_000;
const HERO_CYCLE_FLOOR = 20_000;
/**
/**
* R22 的落点:ADR-0011 §4.2 的「六页 hub × 一组参数」在 2026-12-01 扩到**全部营销页首屏**。
*
@@ -767,7 +761,7 @@ function checkGrammar(rawText, rawFiles, twConfig = "", opts = {}) {
* 次日又裁定首页改用**全幅 3D 场景**(ADR-0016)⇒ 零影像这条不再成立。
*
* **为什么不是「零影像」而是「登记制」**:零影像只能回答「影像有没有偷偷回来」,
* 却对 `<canvas>` / `<HeroScene>` 完全失明 —— 而它才是今天首屏最重的视觉层。
* 却对 `<canvas>` / `<HeroPlate>` 完全失明 —— 而它们才是首屏最重的视觉层。
* 一个对主要形态静默放行的闸,等于没有闸。
*
* 现行语义:首屏出现任何视觉层(影像 / 3D 场景 / canvas)时,**该文件必须在
@@ -798,10 +792,15 @@ function checkGrammar(rawText, rawFiles, twConfig = "", opts = {}) {
const j = src.indexOf('</section>', i);
return j === -1 ? src.slice(i) : src.slice(i, j);
};
/* 登记表可注入:自证夹具不该依赖生产数据(本仓踩过「夹具写死生产条目 ⇒ 条目一删判据就崩」)。
生产调用不传,仍用下面的 HERO_VISUAL_REGISTRY。 */
const registry = opts.visualRegistry ?? HERO_VISUAL_REGISTRY;
const posterExists = opts.posterExists ??
((p) => existsSync(path.join(process.cwd(), "public", p.replace(/^\//, ""))));
for (const rel of hubPresent) {
const src = stripComments(files.get(rel) ?? "", { line: true });
const scope = heroSlice(src);
const entry = HERO_VISUAL_REGISTRY.get(rel);
const entry = registry.get(rel);
const tokens = [...scope.matchAll(VISUAL_LAYER_RE)].map((m) => m[1]);
if (!entry) {
if (tokens.length > 0) {
@@ -819,13 +818,12 @@ function checkGrammar(rawText, rawFiles, twConfig = "", opts = {}) {
if (!entry.markers.some((m) => tokens.includes(m))) {
r22Red.push(`${rel}:登记表批准的是 ${entry.markers.map((m) => `<${m}>`).join(" / ")},但首屏内一个都没找到 —— 登记表过期(换了载体没改登记,或标记被删)`);
}
const posterAbs = path.join(process.cwd(), "public", entry.poster.replace(/^\//, ""));
if (!existsSync(posterAbs)) {
if (!posterExists(entry.poster)) {
r22Red.push(`${rel}:登记的海报帧 public${entry.poster} 不存在 —— 降级链是假的(WebGL 失败/移动档会露出空白)`);
}
}
// 登记表里登记了却不在扫描名单里的文件 = 表在自说自话
for (const rel of HERO_VISUAL_REGISTRY.keys()) {
for (const rel of registry.keys()) {
if (!HUB_HERO_FILES.includes(rel)) {
r22Red.push(`${rel}:在 R22 登记表里,但不在 HUB_HERO_FILES —— 登记与扫描面不一致,这一条对它空转`);
}
@@ -834,7 +832,7 @@ function checkGrammar(rawText, rawFiles, twConfig = "", opts = {}) {
r22Red.push(`营销页首屏只找到 ${hubPresent.length}/${hubFloor} 页 —— 路径改名或文件被移动,本条对缺的那几页空转`);
}
rule({ id: "R22", name: "营销页首屏视觉层必须登记(载体 + 出处 + 海报帧)", denominator: hubPresent.length, red: r22Red,
note: `找到 ${hubPresent.length}/${HUB_HERO_FILES.length} 页 · 已登记 ${HERO_VISUAL_REGISTRY.size} 页 · 未登记文件出现 ${VISUAL_LAYER_RE.source} 任一即判红` });
note: `找到 ${hubPresent.length}/${HUB_HERO_FILES.length} 页 · 已登记 ${registry.size} 页 · 未登记文件出现 ${VISUAL_LAYER_RE.source} 任一即判红` });
/**
* R23 正文构型:每页必须命中登记过的那一件(表见 COMPOSITION_FILES 注释)。
@@ -913,8 +911,10 @@ function checkGrammar(rawText, rawFiles, twConfig = "", opts = {}) {
note: `裸写 ${rawTotal} 处 · 上限 ${rawCeiling}(次数口径,新增第 ${rawCeiling + 1} 处即判红)${rawTotal < rawCeiling ? " ⇒ 请把上限下调到实测值" : ""}`,
});
/**
* R26 首屏 3D 场景契约 —— ADR-0016 §10.5 那条例外条款的**机器可判部分**。
* R26 首屏抽象数据场契约 —— ADR-0016 §17.5 分镜判据的**机器可判部分**
* (机房场景撤回后随继任者重建;判据同 §10.5)。
*
* 为什么必须有这条:例外条款如果只写在 CONTEXT 里,就是把「首屏可以循环」交给下一个人
* 自觉。`check:motion` 只扫 CSS 时长字面量与贝塞尔曲线,**WebGL 的 rAF 完全在它视野外**
@@ -925,17 +925,17 @@ function checkGrammar(rawText, rawFiles, twConfig = "", opts = {}) {
* ② 必须尊重 `prefers-reduced-motion`(定格);
* ③ 必须离屏/后台即停(`IntersectionObserver` + `visibilitychange` 两者都要);
* ④ 禁止 `autoRotate`(自转 = 同一动画重复播放,例外条款明禁)。
* 「不得脉冲式重复」没有静态形态可判,与 R22 的排版支点同理,交由人工评审 —— note 里写明,不假装自动。
* 「不得脉冲式重复」没有静态形态可判,交由人工评审 —— note 里写明,不假装自动。
*
* 文件不存在时**不判红**(与 R22 缺页判红相反):场景是可选特性,未启用就是 E 案,
* 缺席不是违规。但一旦存在,就必须满足上述四条 —— 否则等于开了口子没人守。
*/
const heroSceneSrc = files.get(HERO_SCENE_FILE);
const heroFieldSrc = files.get(HERO_FIELD_FILE);
const r26Red = [];
let cycleMs = 0;
let shotCount = 0;
if (heroSceneSrc) {
const live = stripComments(heroSceneSrc, { line: true });
if (heroFieldSrc) {
const live = stripComments(heroFieldSrc, { line: true });
const shotMs = [...live.matchAll(/\bms:\s*(\d+)/g)].map((m) => Number(m[1]));
const dipMatch = live.match(/DIP_MS\s*=\s*(\d+)/);
const dipMs = dipMatch ? Number(dipMatch[1]) : 0;
@@ -943,11 +943,11 @@ function checkGrammar(rawText, rawFiles, twConfig = "", opts = {}) {
cycleMs = shotMs.reduce((a, b) => a + b, 0) + dipMs * Math.max(shotCount, 1);
if (shotCount === 0) {
r26Red.push(`${HERO_SCENE_FILE}:解析不到任何 \`ms:\` 镜头时长 —— 结构已变,本条对本文件空转(请同步改判据)`);
r26Red.push(`${HERO_FIELD_FILE}:解析不到任何 \`ms:\` 拍次时长 —— 结构已变,本条对本文件空转(请同步改判据)`);
} else if (cycleMs > HERO_CYCLE_CEILING) {
r26Red.push(`分镜一轮 ${cycleMs}ms > 上限 ${HERO_CYCLE_CEILING}ms(${shotCount} 镜)—— 例外条款只允许「环境级」编排`);
r26Red.push(`分镜一轮 ${cycleMs}ms > 上限 ${HERO_CYCLE_CEILING}ms(${shotCount} 拍)—— 例外条款只允许「环境级」编排`);
} else if (cycleMs < HERO_CYCLE_FLOOR) {
r26Red.push(`分镜一轮 ${cycleMs}ms < 下限 ${HERO_CYCLE_FLOOR}ms(${shotCount} 镜)—— 过短即成脉冲式重复`);
r26Red.push(`分镜一轮 ${cycleMs}ms < 下限 ${HERO_CYCLE_FLOOR}ms(${shotCount} 拍)—— 过短即成脉冲式重复`);
}
if (!/prefers-reduced-motion/.test(live)) {
r26Red.push("未尊重 prefers-reduced-motion —— 例外条款要求静态定格,不能强制所有人看运镜");
@@ -961,11 +961,11 @@ function checkGrammar(rawText, rawFiles, twConfig = "", opts = {}) {
}
rule({
id: "R26",
name: "首屏 3D 场景契约(周期 / 定格 / 离屏停 / 禁自转)",
denominator: heroSceneSrc ? 1 : 0,
name: "首屏抽象数据场契约(周期 / 定格 / 离屏停 / 禁自转)",
denominator: heroFieldSrc ? 1 : 0,
red: r26Red,
note: heroSceneSrc
? `周期 ${cycleMs}ms(${shotCount} 镜)· 区间 [${HERO_CYCLE_FLOOR}, ${HERO_CYCLE_CEILING}]ms · 「不得脉冲式重复」无静态形态,由人工评审兜`
note: heroFieldSrc
? `周期 ${cycleMs}ms(${shotCount} 拍)· 区间 [${HERO_CYCLE_FLOOR}, ${HERO_CYCLE_CEILING}]ms · 「不得脉冲式重复」无静态形态,由人工评审兜`
: "场景组件未启用(E 案)—— 本条不适用",
});
@@ -975,14 +975,16 @@ function checkGrammar(rawText, rawFiles, twConfig = "", opts = {}) {
// ---- 自证(负例):喂一批明知违规的样本,不判红就宣布上面全部不作数 ----
function selftest() {
const bad = `:root {\n --radius-xs: 3px;\n --radius-sm: 6px;\n --radius-full: 0px;\n --shadow-brand: 0 6px 24px rgba(196,30,58,.22);\n --badge-radius: var(--radius-full);\n}\n.bain-card:hover { transform: translateY(-4px); }\n/* R21 的「已定义」一侧:夹具里必须真实存在一个自定义类名,否则只会测到"全判红" */\n.container-x { max-width: 1360px; }\n`;
// R26 三向自证夹具:①周期超标 ②合规基线 ③缺 reduced-motion。
// 三份都刻意不含 className / 高档字阶,避免污染 R1–R25 的读数(夹具互相串味是这仓踩过的坑)。
const heroDirty = `const SHOTS = [{ ms: 40000 }, { ms: 40000 }];\nconst DIP_MS = 420;\nconst prefersReduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;\nnew IntersectionObserver(() => {});\ndocument.addEventListener('visibilitychange', () => {});\n`;
const heroClean = `const SHOTS = [{ ms: 16000 }, { ms: 13000 }, { ms: 13000 }];\nconst DIP_MS = 420;\nconst prefersReduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;\nnew IntersectionObserver(() => {});\ndocument.addEventListener('visibilitychange', () => {});\n`;
const heroNoReduced = heroClean.replace("prefers-reduced-motion", "no-such-motion-query");
const fieldDirty = `const ACTS = [{ ms: 40000 }, { ms: 40000 }];\nconst DIP_MS = 420;\nconst prefersReduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;\nnew IntersectionObserver(() => {});\ndocument.addEventListener('visibilitychange', () => {});\n`;
const fieldClean = `const ACTS = [{ ms: 16000 }, { ms: 13000 }, { ms: 13000 }];\nconst DIP_MS = 420;\nconst prefersReduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;\nnew IntersectionObserver(() => {});\ndocument.addEventListener('visibilitychange', () => {});\n`;
const fieldNoReduced = fieldClean.replace("prefers-reduced-motion", "no-such-motion-query");
const files = new Map([
[HERO_SCENE_FILE, heroDirty],
[HERO_FIELD_FILE, fieldDirty],
["src/app/globals.css", bad],
["src/components/ui/cta-button.tsx", 'className="rounded-full"'],
// R9 双向都要被抓到:文字档仍是胶囊 **且** icon 档被方角化
@@ -1053,13 +1055,13 @@ function selftest() {
* 第二向是防「一律报红」的坏判据,第三向是防「只认周期、其余三条形同虚设」。
*/
const r26RedFor = (src) =>
checkGrammar(bad, new Map([[HERO_SCENE_FILE, src]]), RADIX_REF, {
checkGrammar(bad, new Map([[HERO_FIELD_FILE, src]]), RADIX_REF, {
compositionUnmetCeiling: 0,
rawStatementCeiling: 0,
}).find((x) => x.id === "R26").red;
const r26TooLong = r26RedFor(heroDirty);
const r26Clean = r26RedFor(heroClean);
const r26NoReduced = r26RedFor(heroNoReduced);
const r26TooLong = r26RedFor(fieldDirty);
const r26Clean = r26RedFor(fieldClean);
const r26NoReduced = r26RedFor(fieldNoReduced);
const r26CatchesPeriod = r26TooLong.some((m) => m.includes("上限"));
const r26PassesClean = r26Clean.length === 0;
const r26CatchesReduced = r26NoReduced.some((m) => m.includes("prefers-reduced-motion"));
@@ -1076,11 +1078,15 @@ function selftest() {
* 第三维单独测「注释掉的 <HeroPlate> 不算数」—— 这是本仓踩过的同一类坑
* (`constants.ts` 注释里的示例 import 曾骗过再导出正则)。
*/
// ── R22 登记制自证(2026-12-02 第三态)──
// 五向:未登记载体判红 / 登记页通过 / 表过期判红 / 未批准载体判红 / 注释不算数 / 缺页判红。
// 登记页的文件名从登记表里取,不手抄 —— 手抄路径腐化过一次(夹具写死旧路径 ⇒ 判据看着像坏了)。
const REG_REL = [...HERO_VISUAL_REGISTRY.keys()][0];
const REG_APPROVED = `export function Hero(){ return (<div><${HERO_VISUAL_REGISTRY.get(REG_REL).markers[0]} /></div>); }`;
// ── R22 登记制自证(2026-12-02 第四态:生产登记表已归零)──
// 六向:未登记载体判红 / 登记页通过 / 表过期判红 / 未批准载体判红 / 注释不算数 / 缺页判红。
// ⚠ 生产登记表现在是**空表**(首屏零视觉层)。若夹具从生产表里取条目,表一空自证就崩 ——
// 所以这里注入一张夹具表,测的是「登记机制」而不是「当前登记了什么」。
const REG_REL = HUB_HERO_FILES[0];
const FIXTURE_REG = new Map([
[REG_REL, { markers: ["HeroPlate"], origin: "fixture", poster: "/_fixture-poster.webp" }],
]);
const REG_APPROVED = `export function Hero(){ return (<div><${FIXTURE_REG.get(REG_REL).markers[0]} /></div>); }`;
const hubDirty = 'export function Hero(){ return (<div><HeroPlate variant="facade" /></div>); }';
const hubCanvas = 'export function Hero(){ return (<div><canvas /></div>); }';
const hubClean = 'export function Hero(){ return (<div className="text-6xl">纯排版首屏</div>); }';
@@ -1092,7 +1098,12 @@ function selftest() {
);
};
const r22RedFor = (map, opts) =>
checkGrammar(bad, map, "", { floor: 0, ...opts }).find((x) => x.id === "R22").red;
checkGrammar(bad, map, "", {
floor: 0,
visualRegistry: FIXTURE_REG,
posterExists: () => true,
...opts,
}).find((x) => x.id === "R22").red;
const r22Clean = r22RedFor(cleanMap(), { hubFloor: 0 });
const r22Plate = r22RedFor(cleanMap(hubDirty), { hubFloor: 0 });
const r22Canvas = r22RedFor(cleanMap(hubCanvas), { hubFloor: 0 });
@@ -1101,7 +1112,7 @@ function selftest() {
new Map(HUB_HERO_FILES.map((r) => [r, hubClean])),
{ hubFloor: 0 },
);
// 未批准载体:登记页里出现 <Image(只批准了 HeroScene)
// 未批准载体:登记页里出现 <Image>(夹具表只批准了 HeroPlate)
const r22Unapproved = r22RedFor(
new Map(HUB_HERO_FILES.map((r) => [r, r === REG_REL ? `${REG_APPROVED}<Image src="/x.webp" alt="" />` : hubClean])),
{ hubFloor: 0 },
@@ -1138,8 +1149,8 @@ function selftest() {
* 只测「区块外有图 → 不报」的话,判据可能已经不再扫首屏。
*/
const HOME_REL = HUB_HERO_FILES[0];
const homeWithCover = `<section data-testid="hero-section"><HeroScene /><h1>好</h1></section><section><Image src="/cover.webp" alt="" /></section>`;
const homeWithHeroImg = `<section data-testid="hero-section"><HeroScene /><Image src="/x.webp" alt="" /><h1>差</h1></section><section><Image src="/cover.webp" alt="" /></section>`;
const homeWithCover = `<section data-testid="hero-section"><HeroPlate /><h1>好</h1></section><section><Image src="/cover.webp" alt="" /></section>`;
const homeWithHeroImg = `<section data-testid="hero-section"><HeroPlate /><Image src="/x.webp" alt="" /><h1>差</h1></section><section><Image src="/cover.webp" alt="" /></section>`;
const r22Cover = r22RedFor(new Map([[HOME_REL, homeWithCover]]), { hubFloor: 0, floor: 0 });
const r22HeroImg = r22RedFor(new Map([[HOME_REL, homeWithHeroImg]]), { hubFloor: 0, floor: 0 });
const r22ScopeOk = r22Cover.length === 0 && r22HeroImg.length === 1 && r22HeroImg[0].includes(HOME_REL);
+17 -27
View File
@@ -30,8 +30,8 @@ import { SectionLabel } from '@/components/ui/page-decoration';
import { MetricsBasisNote } from '@/components/ui/metrics-basis-note';
import { DisplayStatement } from '@/components/ui/display-statement';
import { DoubleChevron } from '@/components/ui/double-chevron';
import { HeroScene, HERO_SCENE_ENABLED } from '@/components/home/hero-scene';
import { HeroSceneCaption } from '@/components/home/hero-scene-caption';
import { HeroField, HERO_FIELD_ENABLED } from '@/components/home/hero-field';
import { HeroFieldCaption } from '@/components/home/hero-field-caption';
import { HatchField } from '@/components/ui/hatch-field';
import { BandSpacer } from '@/components/ui/band-spacer';
import { IndustryTabs } from '@/components/sections/industry-tabs';
@@ -137,15 +137,14 @@ function HomeHero({ heroData }: { heroData?: Row | null }) {
className="relative isolate overflow-hidden bg-[#0B0A08] text-white"
data-testid="hero-section"
>
{/* 全幅 3D 场景(Phase 0 灰盒原型,flag `NEXT_PUBLIC_HERO_SCENE` 默认关)。
flag 关时下面两行都不进 DOM —— 默认路径仍是 E 案,基线不受影响。
⚠ 场景是**替代网格层**的底图,不是叠加层:两者同时在场会双重上纹理,
且网格的 44px hairline 会在机柜上凭空浮出来。故二选一。 */}
{HERO_SCENE_ENABLED && <HeroScene />}
{HERO_SCENE_ENABLED ? (
/* 压暗层:左侧起,0.94 → 0.12。这层是**可读性设施**不是滤镜 ——
文字块底下的合成底色由它决定(对标同款:`c-collageOverlay__textbox` 压在压暗层上)。
等宽分档写成行内样式是因为它是一条连续的色标,拆成 Tailwind 多个 stop 反而看不清。 */
{/* 全幅「抽象数据场」(噪声 → 增长 → 判断,ADR-0016 §17.2 继任者)。
flag `NEXT_PUBLIC_HERO_FIELD` 样期默认关:关时下面两行都不进 DOM ——
默认路径仍是 E 案,视觉基线零影响。场景是**替代网格层**的底图,不是叠加层,故二选一。 */}
{HERO_FIELD_ENABLED && <HeroField />}
{HERO_FIELD_ENABLED ? (
/* 压暗层:左侧起,0.94 → 0.16。这层是**可读性设施**不是滤镜 ——
文字块底下的合成底色由它决定。等宽分档写成行内样式是因为它是一条连续的色标,
拆成 Tailwind 多个 stop 反而看不清。 */
<div
aria-hidden="true"
className="pointer-events-none absolute inset-0"
@@ -155,7 +154,7 @@ function HomeHero({ heroData }: { heroData?: Row | null }) {
}}
/>
) : (
/* L1 工程网格:纯装饰、零 JS、指针穿透。放在 container 之前,靠 DOM 顺序垫底 */
/* L1 工程网格:纯装饰、零 JS、指针穿透。放在 container 之前,靠 DOM 顺序垫底。 */
<div aria-hidden="true" className="hero-grid-overlay--dark pointer-events-none absolute inset-0" />
)}
<div className="container-x relative flex min-h-[74vh] items-center py-14 md:min-h-[80vh] md:py-20">
@@ -169,14 +168,7 @@ function HomeHero({ heroData }: { heroData?: Row | null }) {
computed 却是 rgba(0,0,0,0) —— 面板整块透明,白字直接压在图与亮窗上。
结构性守卫:`npm run check:grammar` 的 **R20**(任意值 alpha 必须落在 scale 内)。
影像退役后这条仍在:面板一旦改回半透明,叠在任何未来底图上都会重现同一个坑。 */}
<div
className={cn(
'bg-transparent p-7 sm:p-9 md:p-10 lg:p-12',
// 场景在场时面板必须全透明,否则 95% 的黑块会把右下那条走廊整片盖掉,
// 只剩一条缝 —— 那就不是全幅场景了。可读性改由 scrim 承担。
!HERO_SCENE_ENABLED && 'md:bg-[#0B0A08]/95',
)}
>
<div className="bg-transparent p-7 sm:p-9 md:bg-[#0B0A08]/95 md:p-10 lg:p-12">
{/* eyebrow:只作领域定位(「企业数字化转型」),**不写成立时间与共创阶段**。
2026-11-24 裁定:首屏不强调初创身份 —— 那两项已由
`EARLY_ACCESS` / `foundedFull` 降级为「在需要的地方如实呈现」,
@@ -222,13 +214,11 @@ function HomeHero({ heroData }: { heroData?: Row | null }) {
</div>
{/* 双 V 滚动提示 —— 保时捷 `.c-collageOverlay__scroller`(col 5/-1)的转译。
两种形态:E 案占右栏 9–12(填补空洞);场景在场时退到右下角(让位)。
两种形态:E 案占右栏 9–12(填补留白);场景在场时退到右下角(让位)。
两态都在移动/md 档 hidden,不参与布局(uj-11 移动首屏断言)。 */}
{HERO_SCENE_ENABLED ? (
{HERO_FIELD_ENABLED ? (
/* 场景在场时双 V **让位**:贴到版心右下角、缩到 72%、白 30%。
它原本的职责是「填补右栏空洞」,那块空洞现在由场景自己承担;
再让它居中悬浮,实测就像一块灰图标浮在机柜墙上,成了主体之外的第二焦点。
位置上仍留在版心内(`container-x` 是最近的定位祖先),不贴屏幕边。 */
它原本的职责是「填补右栏空洞」,那块空洞现在由场景自己承担。 */
<div
data-testid="hero-scroll-cue"
aria-hidden="true"
@@ -248,10 +238,10 @@ function HomeHero({ heroData }: { heroData?: Row | null }) {
</div>
{/* 场景角标:随分镜切换(U5,文案真源见 lib/constants/hero-scenes)。
{/* 场景角标:随拍次切换(文案真源见 lib/constants/hero-field-scenes)。
它是**氛围层**不是内容位:aria-hidden、只描述画面、不进证据。
flag 关时不渲染 ⇒ 默认路径的 DOM 与像素完全不变,基线零影响。 */}
{HERO_SCENE_ENABLED && <HeroSceneCaption />}
{HERO_FIELD_ENABLED && <HeroFieldCaption />}
</div>
</section>
);
@@ -0,0 +1,56 @@
'use client';
/**
* 首屏「抽象数据场」角标 —— 随拍次切换的文案层(文案真源见 `hero-field-scenes.ts`)。
*
* 为什么用 window 事件而不是 props:拍次状态活在 `hero-field.tsx` 的 rAF 里,
* 每帧都 `setState` 会以 60fps 重渲染整个首屏;这里只在**切拍那一刻**收到一次事件,
* 文案跟着拍次换,其余时间组件不动。
*
* 为什么 `aria-hidden`:这段文字每 13 秒变一次,进读屏只会制造噪音;它描述的内容
* (噪声 / 增长 / 判断)在正文行业段里有正式表述,不需要靠氛围层承载信息。
*
* 降级:事件收不到(场景未挂载 / reduced-motion 定格)时就显示结论拍的文案,
* 与定格画面一致 —— 不会出现「画面是结论帧、角标写着 01 噪声」的错位。
*/
import { useEffect, useState } from 'react';
import {
HERO_FIELD_BEAT_BY_ID,
HERO_FIELD_BEAT_EVENT,
HERO_FIELD_BEAT_IDS,
HERO_FIELD_LAST_BEAT_ID,
type HeroFieldBeatId,
} from '@/lib/constants/hero-field-scenes';
export function HeroFieldCaption() {
// SSR / 首帧:第一拍。reduced-motion 下场景定格在结论帧,
// 因此挂载后按偏好把初始拍同步为结论拍(避免「画面与文字错位」)。
const [beat, setBeat] = useState<HeroFieldBeatId>(HERO_FIELD_BEAT_IDS[0]);
useEffect(() => {
const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
if (reduced) setBeat(HERO_FIELD_LAST_BEAT_ID);
const onBeat = (event: Event) => {
const id = (event as CustomEvent<{ id?: HeroFieldBeatId }>).detail?.id;
// 只接受登记过的 id:拼错或旧事件不会把角标置空
if (id && id in HERO_FIELD_BEAT_BY_ID) setBeat(id);
};
window.addEventListener(HERO_FIELD_BEAT_EVENT, onBeat);
return () => window.removeEventListener(HERO_FIELD_BEAT_EVENT, onBeat);
}, []);
const current = HERO_FIELD_BEAT_BY_ID[beat];
return (
<div
aria-hidden="true"
data-testid="hero-field-caption"
className="absolute bottom-6 left-0 hidden items-center gap-3 lg:flex"
>
<span aria-hidden="true" className="h-px w-6 shrink-0 bg-white/30" />
<span className="text-[13px] font-medium tracking-[0.08em] text-white/70">{current.label}</span>
<span className="text-[13px] text-white/50">{current.detail}</span>
</div>
);
}
Loaded 100 of 108 files, more files were not shown because too many files have changed in this diff. Show more