feat: 移植原版背景/点阵遮罩/入场幕布,修复贴纸淡出与 cursor 颜色
- BackgroundFX: 1:1 移植原版 sz 多通道程序化背景(vignette→swirl→sine→shatter→bokeh→output,30% 分辨率 ping-pong,指针跟随、进度门控跳帧) - DotOverlay: 移植原版 s1 滚动点阵遮罩(renderOrder 10,uOpacity=sT(sP))——贴纸随滚动溶入页面底色的原版机制 - LoadingCurtain+LoadingOverlay: 移植原版入场流程(径向圆洞幕布 + MaskedDots 点阵化后处理 + 居中进度条,字体/重资产 5:5 计时轴) - sP 修正: f2 无 footer 时取 1(原版语义),相机 lerp(24,32,sP) 拉远恢复;视差 y 系数修正为 0.6 - 相机: ready 门控 intro dolly(lerp(A+8,A,customCubic),1.2s)+ 鼠标视差(lag .18/leave .05) - GlassModels: cursor 贴色修正为亮色主题 #009dff/#009dff;新增指针跟随高光控制器 ca() - 刷新回顶: scrollRestoration=manual + pageshow(bfcache) 双 rAF 重置 + lenis immediate - 新增 lib/pointer.ts、lib/loadingBus.ts、lib/customCubic.ts;loadingBus 打点: 模型/贴纸/about 图
This commit is contained in:
@@ -0,0 +1,644 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useMemo, useRef } from "react";
|
||||
import { useFrame, useThree } from "@react-three/fiber";
|
||||
import {
|
||||
Color,
|
||||
DataTexture,
|
||||
Mesh,
|
||||
NoBlending,
|
||||
OrthographicCamera,
|
||||
PlaneGeometry,
|
||||
RGBAFormat,
|
||||
RepeatWrapping,
|
||||
Scene,
|
||||
ShaderMaterial,
|
||||
Vector2,
|
||||
Vector3,
|
||||
WebGLRenderTarget,
|
||||
} from "three";
|
||||
import { usePointer } from "@/lib/pointer";
|
||||
import { scrollBus } from "@/lib/scrollBus";
|
||||
|
||||
/**
|
||||
* Animated background — 1:1 port of the original `sz` + `sV` + `s$`
|
||||
* (chunk 4d3f3b68dbbde33a.js): a chain of fullscreen passes over two
|
||||
* ping-pong RTs at 30% resolution, composited by an output pass:
|
||||
*
|
||||
* vignette (radial color falloff, mouse-centered) →
|
||||
* swirl (radius .25) → sine (wave displacement) →
|
||||
* shatter (Voronoi cell offsets) → bokeh (32-tap golden-angle blur) →
|
||||
* output (base = bg, blend = inTex + output*0.35, mix .65) → screen
|
||||
*
|
||||
* Light-theme colors (sk/sO/sG): bg #ffead6, vignette #6196ff, output
|
||||
* #acffb9; mix {outputMix:.65, edgeIntensity:-.16}. Mouse smoothing .1 /
|
||||
* leave .05; mobile pins uPos/uMousePos to (.5,-.1). Progress-gated:
|
||||
* freezes when the page is fully scrolled (sP >= .98), frame-skip 1/2/4.
|
||||
*/
|
||||
|
||||
const BG_COLOR = "#ffead6";
|
||||
const VIGNETTE_COLOR = "#6196ff";
|
||||
const OUTPUT_COLOR = "#acffb9";
|
||||
const OUTPUT_MIX = 0.65;
|
||||
const MOUSE_POS = new Vector2(0.5, -0.1);
|
||||
const CENTER = new Vector2(0.5, 0.5);
|
||||
const clamp01 = (v: number) => Math.min(1, Math.max(0, v));
|
||||
|
||||
const COMMON_VERT = `precision mediump float;
|
||||
precision mediump int;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
vUv = uv;
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
|
||||
}`;
|
||||
|
||||
const CLIP_VERT = `precision mediump float;
|
||||
precision mediump int;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
vUv = uv;
|
||||
// Render in clip-space to fill the screen, ignoring camera transforms
|
||||
gl_Position = vec4(position, 1.0);
|
||||
}`;
|
||||
|
||||
const VIGNETTE_FRAG = `precision mediump float;
|
||||
precision mediump int;
|
||||
varying vec2 vUv;
|
||||
uniform float uRadius;
|
||||
uniform float uFalloff;
|
||||
uniform float uMix;
|
||||
uniform float uDisplace;
|
||||
uniform float uSkew;
|
||||
uniform float uAngle;
|
||||
uniform vec3 uVignetteColor;
|
||||
uniform vec2 uPos; // 动态中心(跟随指针,如原始实现)
|
||||
uniform vec2 uResolution;
|
||||
uniform vec3 uClearColor;
|
||||
// 边缘明暗强度:[-1,1],负值加深暗角,正值提亮边缘
|
||||
uniform float uEdgeIntensity;
|
||||
|
||||
mat2 rot(float a) {
|
||||
return mat2(cos(a),-sin(a),sin(a),cos(a));
|
||||
}
|
||||
void main() {
|
||||
vec2 uv = vUv;
|
||||
vec4 color = vec4(vec3(1.), 0.);
|
||||
float luma = dot(color.rgb, vec3(0.299, 0.587, 0.114));
|
||||
float displacement = (luma - 0.5) * uDisplace * 0.5;
|
||||
vec2 aspectRatio = vec2(uResolution.x/uResolution.y, 1.0);
|
||||
vec2 skew = vec2(uSkew, 1.0 - uSkew);
|
||||
float halfRadius = uRadius * 0.5;
|
||||
float innerEdge = halfRadius - uFalloff * halfRadius * 0.5;
|
||||
float outerEdge = halfRadius + uFalloff * halfRadius * 0.5;
|
||||
// 使用动态指针位置作为暗角中心(原始方案)
|
||||
vec2 pos = uPos;
|
||||
vec2 scaledUV = uv * aspectRatio * rot(uAngle * 6.28318530718) * skew;
|
||||
vec2 scaledPos = pos * aspectRatio * rot(uAngle * 6.28318530718) * skew;
|
||||
float radius = distance(scaledUV, scaledPos);
|
||||
float falloff = smoothstep(innerEdge + displacement, outerEdge + displacement, radius);
|
||||
// 原始实现不额外乘 uMix(保留 uniform 以兼容但不使用)
|
||||
|
||||
// 根据 uEdgeIntensity 调整边缘亮暗:
|
||||
// uEdgeIntensity > 0 推向 0(提亮边缘),< 0 推向 1(加深暗角)
|
||||
float brighten = max(uEdgeIntensity, 0.0);
|
||||
float darken = max(-uEdgeIntensity, 0.0);
|
||||
falloff = mix(falloff, 0.0, brighten);
|
||||
falloff = mix(falloff, 1.0, darken);
|
||||
|
||||
vec3 mixed = mix(uClearColor, uVignetteColor, falloff);
|
||||
gl_FragColor = vec4(mixed, falloff);
|
||||
}`;
|
||||
|
||||
const SWIRL_FRAG = `precision mediump float;
|
||||
precision mediump int;
|
||||
varying vec2 vUv;
|
||||
uniform vec2 uResolution;
|
||||
uniform sampler2D tInput;
|
||||
uniform float uRadius;
|
||||
uniform float uAngle;
|
||||
uniform float uPhase;
|
||||
uniform float uTime;
|
||||
uniform float uMix;
|
||||
uniform vec2 uPos;
|
||||
|
||||
void main() {
|
||||
vec2 uv = vUv;
|
||||
float angle = uAngle * 10.;
|
||||
vec2 originalUV = uv;
|
||||
vec2 pos = uPos;
|
||||
uv -= pos;
|
||||
vec2 R = vec2(uv.x * uResolution.x / uResolution.y, uv.y);
|
||||
float distanceToCenter = length(R);
|
||||
if (distanceToCenter <= uRadius) {
|
||||
float rot = atan(R.y, R.x) + angle * smoothstep(uRadius, 0., distanceToCenter);
|
||||
uv = vec2(cos(rot + uTime / 20. + uPhase * 6.28318530718), sin(rot + uTime / 20. + uPhase * 6.28318530718));
|
||||
uv = distanceToCenter * uv + pos;
|
||||
}
|
||||
float t = smoothstep(0., uRadius, distanceToCenter);
|
||||
vec2 mixedUV = mix(uv, originalUV, t);
|
||||
gl_FragColor = texture2D(tInput, mix(vUv, mixedUV, uMix));
|
||||
}`;
|
||||
|
||||
const SINE_FRAG = `precision mediump float;
|
||||
precision mediump int;
|
||||
varying vec2 vUv;
|
||||
uniform sampler2D tInput;
|
||||
uniform float uMixRadius;
|
||||
uniform vec2 uPos;
|
||||
uniform float uFrequency;
|
||||
uniform float uAmplitude;
|
||||
uniform float uRotation;
|
||||
uniform float uTime;
|
||||
uniform vec2 uResolution;
|
||||
uniform vec2 uMousePos;
|
||||
uniform float uTrackMouse;
|
||||
|
||||
void main() {
|
||||
vec2 uv = vUv;
|
||||
vec2 waveCoord = vUv.xy * 2.0 - 1.0;
|
||||
float time = uTime * 0.25;
|
||||
float frequency = 20.0 * uFrequency;
|
||||
float amp = uAmplitude * 0.2;
|
||||
float waveX = sin((waveCoord.y + uPos.y) * frequency + (time)) * amp;
|
||||
float waveY = sin((waveCoord.x - uPos.x) * frequency + (time)) * amp;
|
||||
waveCoord.xy += vec2(mix(waveX, 0., uRotation), mix(0., waveY, uRotation));
|
||||
vec2 finalUV = waveCoord * 0.5 + 0.5;
|
||||
float aspectRatio = uResolution.x/uResolution.y;
|
||||
vec2 mPos = uPos + mix(vec2(0.), (uMousePos-0.5), uTrackMouse);
|
||||
float dist = (max(0.,1.-distance(uv * vec2(aspectRatio, 1.), mPos * vec2(aspectRatio, 1.)) * 4. * (1. - uMixRadius)));
|
||||
uv = mix(uv, finalUV, dist);
|
||||
gl_FragColor = texture2D(tInput, uv);
|
||||
}`;
|
||||
|
||||
const SHATTER_FRAG = `precision mediump float;
|
||||
precision mediump int;
|
||||
varying vec2 vUv;
|
||||
uniform sampler2D tInput;
|
||||
uniform float uAmount;
|
||||
uniform float uSpread;
|
||||
uniform float uAngle;
|
||||
uniform float uTime;
|
||||
uniform float uSkew;
|
||||
uniform float uCellScale;
|
||||
uniform vec2 uPos;
|
||||
uniform vec2 uResolution;
|
||||
uniform float uMixRadius;
|
||||
uniform int uMixRadiusInvert;
|
||||
uniform int uEasing;
|
||||
uniform vec2 uMousePos;
|
||||
uniform float uTrackMouse;
|
||||
uniform float uRoundness;
|
||||
|
||||
vec2 random2( vec2 p ) {
|
||||
return fract(sin(vec2(dot(p,vec2(127.1,311.7)),dot(p,vec2(269.5,183.3))))*43758.5453);
|
||||
}
|
||||
mat2 rot(float a) { return mat2(cos(a),-sin(a),sin(a),cos(a)); }
|
||||
|
||||
float ease(int mode, float t){
|
||||
if(mode==1){ return 1.0 - (1.0 - t)*(1.0 - t); }
|
||||
if(mode==2){ return t < 0.5 ? 4.0*t*t*t : 1.0 - pow(-2.0*t + 2.0, 3.0)/2.0; }
|
||||
return t;
|
||||
}
|
||||
|
||||
void main(){
|
||||
vec2 uv = vUv;
|
||||
float aspectRatio = uResolution.x / uResolution.y;
|
||||
vec2 skew = mix(vec2(1.0), vec2(1.0, 0.0), uSkew);
|
||||
vec2 st = (uv - uPos) * vec2(aspectRatio, 1.0) * uCellScale * uAmount;
|
||||
st = st * rot(uAngle * 2.0 * 3.14159265359) * skew;
|
||||
vec2 i_st = floor(st);
|
||||
vec2 f_st = fract(st);
|
||||
|
||||
float m_dist = 15.0;
|
||||
float m_dist2 = 15.0;
|
||||
vec2 m_point = vec2(0.0);
|
||||
vec2 diffBest = vec2(0.0);
|
||||
for(int j=-1;j<=1;j++){
|
||||
for(int i=-1;i<=1;i++){
|
||||
vec2 neighbor = vec2(float(i), float(j));
|
||||
vec2 point = random2(i_st + neighbor);
|
||||
point = 0.5 + 0.5 * sin(5.0 + uTime * 0.2 + 6.2831 * point);
|
||||
vec2 diff = neighbor + point - f_st;
|
||||
float dist = length(diff);
|
||||
if(dist < m_dist){
|
||||
m_dist2 = m_dist;
|
||||
m_dist = dist;
|
||||
m_point = point;
|
||||
diffBest = diff;
|
||||
} else if (dist < m_dist2) {
|
||||
m_dist2 = dist;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
vec2 offset = (m_point * 0.2 * uSpread * 2.0) - (uSpread * 0.2);
|
||||
// soften offsets near cell edges to get rounder pieces
|
||||
// Use F2-F1 (second nearest minus nearest) to detect corners and soften further
|
||||
float cornerSoft = smoothstep(0.0, max(0.0001, uRoundness) * 2.0, m_dist2 - m_dist);
|
||||
float edgeSoft = smoothstep(0.0, max(0.0001, uRoundness), m_dist) * cornerSoft;
|
||||
offset *= edgeSoft;
|
||||
|
||||
vec2 mPos = uPos + mix(vec2(0.0), (uMousePos - 0.5), uTrackMouse);
|
||||
vec2 pos = mix(uPos, mPos, floor(uMixRadius));
|
||||
|
||||
float rawDist = max(0.0, 1.0 - distance(uv * vec2(aspectRatio,1.0), mPos * vec2(aspectRatio,1.0)) * 4.0 * (1.0 - uMixRadius));
|
||||
if(uMixRadiusInvert == 1){ rawDist = 1.0 - rawDist; }
|
||||
float dist = ease(uEasing, rawDist);
|
||||
|
||||
vec4 color = texture2D(tInput, uv + offset * dist);
|
||||
gl_FragColor = color;
|
||||
}`;
|
||||
|
||||
const BOKEH_FRAG = `precision mediump float;
|
||||
precision mediump int;
|
||||
varying vec2 vUv;
|
||||
uniform sampler2D tInput;
|
||||
uniform sampler2D tBlueNoise;
|
||||
uniform float uAmount;
|
||||
uniform float uTilt;
|
||||
uniform float uTime;
|
||||
uniform vec2 uPos;
|
||||
uniform vec2 uResolution;
|
||||
uniform vec2 uBlueNoiseResolution;
|
||||
uniform vec2 uMousePos;
|
||||
uniform float uTrackMouse;
|
||||
|
||||
#define PI 3.14159265
|
||||
#define PI2 6.28318530718
|
||||
// 优化:降低采样迭代次数 (原 50.0 -> 24.0) 以大幅提升性能
|
||||
#define ITERATIONS 32.0
|
||||
#define GOLDEN_ANGLE 2.39996323
|
||||
|
||||
vec2 Sample(in float theta, inout float r) {
|
||||
r += 1.0 / r;
|
||||
return (r - 1.0) * vec2(cos(theta), sin(theta));
|
||||
}
|
||||
|
||||
float getBlueNoiseOffset(vec2 st) {
|
||||
vec2 texSize = uBlueNoiseResolution;
|
||||
vec2 uv = fract(st * (uResolution/texSize) * vec2(texSize.x/texSize.y, 1.0));
|
||||
vec4 blueNoise = texture2D(tBlueNoise, uv);
|
||||
return mod((blueNoise.r - 0.5) * PI2, PI2);
|
||||
}
|
||||
|
||||
vec4 Bokeh(sampler2D tex, vec2 uv, float blurRadius) {
|
||||
vec3 accumulatedColor = vec3(0.0);
|
||||
vec3 accumulatedWeights = vec3(0.0);
|
||||
float accumulatedAlpha = 0.0;
|
||||
float aspectRatio = uResolution.x / uResolution.y;
|
||||
vec2 basePixelSize = vec2(1.0 / aspectRatio, 1.0) * 0.04 * 0.075;
|
||||
float r = 1.0;
|
||||
float noiseOffset = (getBlueNoiseOffset(uv) - 0.5) * 0.01;
|
||||
float noiseAngle = noiseOffset * PI2;
|
||||
mat2 rotationMatrix = mat2(
|
||||
cos(noiseAngle), -sin(noiseAngle),
|
||||
sin(noiseAngle), cos(noiseAngle)
|
||||
);
|
||||
for (float j = 0.0; j < GOLDEN_ANGLE * ITERATIONS; j += GOLDEN_ANGLE) {
|
||||
vec2 offset = Sample(j, r) * basePixelSize * blurRadius;
|
||||
float jitterAmount = 0.05 * (sin(j * 0.1) * 0.5 + 0.5);
|
||||
offset *= 1.0 + jitterAmount * sin(j * 0.7 + noiseOffset);
|
||||
vec2 sampleOffset = rotationMatrix * offset;
|
||||
vec4 colorSample = texture2D(tex, uv + sampleOffset);
|
||||
// Render targets are in Three.js working space (linear) by default.
|
||||
vec3 linearSample = colorSample.rgb;
|
||||
vec3 bokehWeight = vec3(5.0) + pow(linearSample, vec3(9.0)) * 150.0;
|
||||
accumulatedAlpha += colorSample.a;
|
||||
accumulatedColor += linearSample * bokehWeight;
|
||||
accumulatedWeights += bokehWeight;
|
||||
}
|
||||
vec3 linearOut = accumulatedColor / accumulatedWeights;
|
||||
return vec4(linearOut, accumulatedAlpha / ITERATIONS);
|
||||
}
|
||||
|
||||
void main() {
|
||||
vec2 uv = vUv;
|
||||
if(uAmount == 0.0) { gl_FragColor = vec4(0.0); return; }
|
||||
vec2 pos = uPos + mix(vec2(0.0), (uMousePos - 0.5), uTrackMouse);
|
||||
float dis = distance(uv, pos) * 1000.0;
|
||||
float tilt = mix(1.0 - dis * 0.001, dis * 0.001, uTilt);
|
||||
float blurRadius = uAmount * tilt;
|
||||
gl_FragColor = Bokeh(tInput, uv, blurRadius);
|
||||
}`;
|
||||
|
||||
const OUTPUT_FRAG = `precision mediump float;
|
||||
precision mediump int;
|
||||
varying vec2 vUv;
|
||||
uniform sampler2D tInput;
|
||||
uniform vec3 uBgColor;
|
||||
uniform vec3 uOutputColor;
|
||||
uniform int uLoaded;
|
||||
// 可调输出混合权重(0.0~1.0),用于替代固定 0.6
|
||||
uniform float uOutputMix;
|
||||
// 方案A:更接近 before.js 的合成逻辑 (base * mix(1, blend, 0.26))
|
||||
|
||||
vec3 overlay(vec3 base, vec3 blend){
|
||||
return mix(2.0 * base * blend, 1.0 - 2.0 * (1.0 - base) * (1.0 - blend), step(0.5, base));
|
||||
}
|
||||
|
||||
void main(){
|
||||
if(uLoaded!=1){
|
||||
gl_FragColor = vec4(197./255.,136./255.,122./255.,1.);
|
||||
return;
|
||||
}
|
||||
|
||||
// uBgColor/uOutputColor are provided in Three.js working space (linear).
|
||||
vec3 bgTex = vec3(1.0); // 无背景贴图时近似常量
|
||||
vec3 base = mix(uBgColor, overlay(uBgColor, bgTex), 0.61);
|
||||
|
||||
vec4 inTex = texture2D(tInput, vUv);
|
||||
// 作为 tint 加色,不依赖 alpha,保证 OUTPUT_COLOR 可见
|
||||
vec3 tint = uOutputColor * 0.35;
|
||||
vec3 blend = clamp(inTex.rgb + tint, 0.0, 1.0);
|
||||
vec3 finalColor = base * mix(vec3(1.0), blend, clamp(uOutputMix, 0.0, 1.0));
|
||||
|
||||
gl_FragColor = vec4(finalColor, 1.0);
|
||||
|
||||
#include <colorspace_fragment>
|
||||
}`;
|
||||
|
||||
function makeNoiseTexture(size = 128): { texture: DataTexture; resolution: Vector2 } {
|
||||
const data = new Uint8ClampedArray(size * size * 4);
|
||||
for (let i = 0; i < data.length; i += 4) {
|
||||
const v = Math.floor(255 * Math.random());
|
||||
data[i] = v;
|
||||
data[i + 1] = v;
|
||||
data[i + 2] = v;
|
||||
data[i + 3] = 255;
|
||||
}
|
||||
const texture = new DataTexture(data, size, size, RGBAFormat);
|
||||
texture.needsUpdate = true;
|
||||
texture.wrapS = RepeatWrapping;
|
||||
texture.wrapT = RepeatWrapping;
|
||||
return { texture, resolution: new Vector2(size, size) };
|
||||
}
|
||||
|
||||
const toVec3 = (hex: string) => {
|
||||
const c = new Color(hex);
|
||||
return new Vector3(c.r, c.g, c.b);
|
||||
};
|
||||
|
||||
/** Frame skip by scroll progress (original sF): 1 / 2 / 4. */
|
||||
function frameSkip(progress: number): number {
|
||||
const p = clamp01(progress > 1 ? progress / 100 : progress);
|
||||
return p > 0.75 ? 4 : p > 0.5 ? 2 : 1;
|
||||
}
|
||||
|
||||
export function BackgroundFX() {
|
||||
const gl = useThree((s) => s.gl);
|
||||
const size = useThree((s) => s.size);
|
||||
const { uv: pointerUv, insideRef } = usePointer();
|
||||
const isMobile = size.width < 1024;
|
||||
|
||||
const resolutionScale = 0.3;
|
||||
const smoothing = 0.1;
|
||||
const leaveSmoothing = 0.05;
|
||||
|
||||
const noise = useMemo(() => makeNoiseTexture(128), []);
|
||||
useEffect(() => () => noise.texture.dispose(), [noise]);
|
||||
|
||||
// Shared uniform objects across all passes (original o / l / a vectors).
|
||||
const shared = useMemo(
|
||||
() => ({
|
||||
resolution: new Vector2(1, 1),
|
||||
time: { value: 0 },
|
||||
pos: new Vector2(0.5, 0.5),
|
||||
}),
|
||||
[]
|
||||
);
|
||||
|
||||
const materials = useMemo(() => {
|
||||
const mk = (frag: string, extra: Record<string, { value: unknown }> = {}) =>
|
||||
new ShaderMaterial({
|
||||
vertexShader: COMMON_VERT,
|
||||
fragmentShader: frag,
|
||||
uniforms: {
|
||||
tInput: { value: null },
|
||||
uResolution: { value: shared.resolution },
|
||||
uTime: shared.time,
|
||||
uPos: { value: shared.pos },
|
||||
uMousePos: { value: new Vector2(0.5, 0.5) },
|
||||
uTrackMouse: { value: 1 },
|
||||
...extra,
|
||||
},
|
||||
transparent: false,
|
||||
blending: NoBlending,
|
||||
depthTest: false,
|
||||
depthWrite: false,
|
||||
toneMapped: false,
|
||||
});
|
||||
|
||||
const vignette = mk(VIGNETTE_FRAG, {
|
||||
uRadius: { value: 0.354 },
|
||||
uFalloff: { value: 1 },
|
||||
uMix: { value: 1 },
|
||||
uDisplace: { value: 0 },
|
||||
uSkew: { value: 0.54 },
|
||||
uAngle: { value: 0 },
|
||||
uEdgeIntensity: { value: -0.16 },
|
||||
uVignetteColor: { value: toVec3(VIGNETTE_COLOR) },
|
||||
uColorAlpha: { value: 1 },
|
||||
uClearColor: { value: toVec3(BG_COLOR) },
|
||||
});
|
||||
const swirl = mk(SWIRL_FRAG, {
|
||||
uRadius: { value: 0.25 },
|
||||
uAngle: { value: 0.1 },
|
||||
uPhase: { value: 0 },
|
||||
uMix: { value: 0.5 },
|
||||
uPinch: { value: 0 },
|
||||
});
|
||||
const sine = mk(SINE_FRAG, {
|
||||
uMixRadius: { value: 1 },
|
||||
uFrequency: { value: 0.35 },
|
||||
uAmplitude: { value: 1.18 },
|
||||
uRotation: { value: 0 },
|
||||
});
|
||||
const shatter = mk(SHATTER_FRAG, {
|
||||
uAmount: { value: 1 },
|
||||
uSpread: { value: 0.9 },
|
||||
uAngle: { value: -45 / 360 },
|
||||
uSkew: { value: 0.9 },
|
||||
uCellScale: { value: 16 },
|
||||
uMixRadius: { value: 1 },
|
||||
uMixRadiusInvert: { value: 0 },
|
||||
uEasing: { value: 1 },
|
||||
uTrackMouse: { value: 0 },
|
||||
uPos: { value: new Vector2(0.5, 0.5) },
|
||||
uRoundness: { value: 0.02 },
|
||||
});
|
||||
const bokeh = mk(BOKEH_FRAG, {
|
||||
tBlueNoise: { value: noise.texture },
|
||||
uBlueNoiseResolution: { value: noise.resolution.clone() },
|
||||
uAmount: { value: 3.125 * 0.754 },
|
||||
uTilt: { value: 0.5 },
|
||||
uPos: { value: new Vector2(0.5, 0.5) },
|
||||
uTrackMouse: { value: 0 },
|
||||
});
|
||||
const output = mk(OUTPUT_FRAG, {
|
||||
uBgColor: { value: toVec3(BG_COLOR) },
|
||||
uOutputColor: { value: toVec3(OUTPUT_COLOR) },
|
||||
uLoaded: { value: 1 },
|
||||
uOutputMix: { value: OUTPUT_MIX },
|
||||
});
|
||||
output.vertexShader = CLIP_VERT;
|
||||
output.depthTest = false;
|
||||
output.depthWrite = false;
|
||||
output.toneMapped = false;
|
||||
output.transparent = false;
|
||||
output.blending = NoBlending;
|
||||
|
||||
const prePasses = [
|
||||
{ name: "vignette", material: vignette },
|
||||
{ name: "swirl", material: swirl },
|
||||
{ name: "sine", material: sine },
|
||||
{ name: "shatter", material: shatter },
|
||||
{ name: "bokeh", material: bokeh },
|
||||
];
|
||||
return {
|
||||
prePasses,
|
||||
outputMaterial: output,
|
||||
vignetteMaterial: vignette,
|
||||
shatterMaterial: shatter,
|
||||
mouseConsumers: prePasses.filter((p) => p.name !== "shatter"),
|
||||
};
|
||||
}, [noise, shared]);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
materials.prePasses.forEach((p) => p.material.dispose());
|
||||
materials.outputMaterial.dispose();
|
||||
},
|
||||
[materials]
|
||||
);
|
||||
|
||||
// Ping-pong RTs at 30% resolution + clear color (original resize effect;
|
||||
// the original does not restore the renderer clear color afterwards).
|
||||
const rtsRef = useRef({
|
||||
read: new WebGLRenderTarget(1, 1, { depthBuffer: false }),
|
||||
write: new WebGLRenderTarget(1, 1, { depthBuffer: false }),
|
||||
});
|
||||
const frameRef = useRef(0);
|
||||
useEffect(() => {
|
||||
const w = Math.max(1, Math.floor(size.width * resolutionScale));
|
||||
const h = Math.max(1, Math.floor(size.height * resolutionScale));
|
||||
shared.resolution.set(w, h);
|
||||
rtsRef.current.read.dispose();
|
||||
rtsRef.current.write.dispose();
|
||||
rtsRef.current = {
|
||||
read: new WebGLRenderTarget(w, h, { depthBuffer: false }),
|
||||
write: new WebGLRenderTarget(w, h, { depthBuffer: false }),
|
||||
};
|
||||
gl.setClearColor(new Color(BG_COLOR), 1);
|
||||
gl.setRenderTarget(rtsRef.current.read);
|
||||
gl.clear();
|
||||
gl.setRenderTarget(null);
|
||||
frameRef.current = 0;
|
||||
materials.outputMaterial.uniforms.tInput.value = rtsRef.current.read.texture;
|
||||
}, [gl, size.width, size.height, materials, shared]);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
rtsRef.current.read.dispose();
|
||||
rtsRef.current.write.dispose();
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const bgColor = useMemo(() => toVec3(BG_COLOR), []);
|
||||
const vignetteColor = useMemo(() => toVec3(VIGNETTE_COLOR), []);
|
||||
const outputColor = useMemo(() => toVec3(OUTPUT_COLOR), []);
|
||||
|
||||
// Internal ortho scene for pre-passes (original v/A + first-pass mesh).
|
||||
const preScene = useMemo(() => new Scene(), []);
|
||||
const preCamera = useMemo(() => new OrthographicCamera(-1, 1, 1, -1, 0, 1), []);
|
||||
const preMeshRef = useRef<Mesh | null>(null);
|
||||
useEffect(() => {
|
||||
const geo = new PlaneGeometry(2, 2);
|
||||
const mesh = new Mesh(geo, materials.prePasses[0]?.material);
|
||||
preScene.add(mesh);
|
||||
preMeshRef.current = mesh;
|
||||
return () => {
|
||||
preScene.remove(mesh);
|
||||
geo.dispose();
|
||||
};
|
||||
}, [materials, preScene]);
|
||||
|
||||
// uTrackMouse = +!isMobile for every pre-pass (original effect).
|
||||
useEffect(() => {
|
||||
const flag = isMobile ? 0 : 1;
|
||||
for (const p of materials.prePasses) {
|
||||
const tm = p.material.uniforms.uTrackMouse;
|
||||
if (tm) tm.value = flag;
|
||||
}
|
||||
}, [isMobile, materials]);
|
||||
|
||||
// Mouse tracking + per-frame chain (original sz useFrame).
|
||||
const smoothed = useRef(new Vector2(0.5, 0.5));
|
||||
const target = useRef(new Vector2(0.5, 0.5));
|
||||
|
||||
useFrame((state) => {
|
||||
const rts = rtsRef.current;
|
||||
const mesh = preMeshRef.current;
|
||||
if (!rts || !mesh) return;
|
||||
|
||||
shared.time.value = state.clock.getElapsedTime();
|
||||
|
||||
if (isMobile) {
|
||||
// Pin to (.5, -.1) like the original mobile branch.
|
||||
shared.pos.copy(MOUSE_POS);
|
||||
for (const p of materials.mouseConsumers) {
|
||||
const mm = p.material.uniforms.uMousePos;
|
||||
if (mm) (mm.value as Vector2).copy(MOUSE_POS);
|
||||
}
|
||||
(materials.shatterMaterial.uniforms.uPos.value as Vector2).copy(MOUSE_POS);
|
||||
} else {
|
||||
if (insideRef.current) target.current.set(clamp01(pointerUv.x), clamp01(pointerUv.y));
|
||||
else target.current.copy(CENTER);
|
||||
smoothed.current.lerp(target.current, insideRef.current ? smoothing : leaveSmoothing);
|
||||
shared.pos.copy(smoothed.current);
|
||||
for (const p of materials.mouseConsumers) {
|
||||
const mm = p.material.uniforms.uMousePos;
|
||||
if (mm) (mm.value as Vector2).copy(smoothed.current);
|
||||
}
|
||||
(materials.shatterMaterial.uniforms.uPos.value as Vector2).copy(CENTER);
|
||||
}
|
||||
|
||||
// Theme color smoothing (light-only: instant convergence to constants).
|
||||
materials.vignetteMaterial.uniforms.uVignetteColor.value.copy(vignetteColor);
|
||||
materials.vignetteMaterial.uniforms.uClearColor.value.copy(bgColor);
|
||||
materials.outputMaterial.uniforms.uBgColor.value.copy(bgColor);
|
||||
materials.outputMaterial.uniforms.uOutputColor.value.copy(outputColor);
|
||||
|
||||
const progress = clamp01(scrollBus.sP);
|
||||
if (progress >= 0.98) return;
|
||||
|
||||
if (frameRef.current++ % Math.max(frameSkip(progress), 2) === 0) {
|
||||
for (const pass of materials.prePasses) {
|
||||
const tInput = pass.material.uniforms.tInput;
|
||||
if (tInput) tInput.value = rts.read.texture;
|
||||
mesh.material = pass.material;
|
||||
gl.setRenderTarget(rts.write);
|
||||
gl.render(preScene, preCamera);
|
||||
gl.setRenderTarget(null);
|
||||
const t = rts.read;
|
||||
rts.read = rts.write;
|
||||
rts.write = t;
|
||||
}
|
||||
materials.outputMaterial.uniforms.tInput.value = rts.read.texture;
|
||||
}
|
||||
}, -2);
|
||||
|
||||
// Output fullscreen quad at renderOrder -10 (original s$).
|
||||
return (
|
||||
<mesh frustumCulled={false} renderOrder={-10}>
|
||||
<planeGeometry args={[2, 2]} />
|
||||
<primitive object={materials.outputMaterial} attach="material" />
|
||||
</mesh>
|
||||
);
|
||||
}
|
||||
|
||||
export default BackgroundFX;
|
||||
@@ -0,0 +1,124 @@
|
||||
"use client";
|
||||
|
||||
import { useLayoutEffect, useMemo, useRef } from "react";
|
||||
import { useFrame, useThree } from "@react-three/fiber";
|
||||
import { Color, Vector2 } from "three";
|
||||
import { scrollBus } from "@/lib/scrollBus";
|
||||
|
||||
/**
|
||||
* Scroll dot-overlay — 1:1 port of the original `s1` (chunk
|
||||
* 4d3f3b68dbbde33a.js): a fullscreen transparent mesh at renderOrder 10
|
||||
* whose opacity equals sT(sP) (the banner/footer camera progress). The
|
||||
* page-background-colored dot grid (4px cells, radius .9 × opacity)
|
||||
* melts the WebGL scene (stickers, glass, gradient bg) into the page
|
||||
* background as you scroll past the hero — that IS the "stickers fade
|
||||
* out on scroll" behavior of the original site. Near the footer sP → 0
|
||||
* and the overlay opens again.
|
||||
*
|
||||
* Light-theme colors (c_): dark "#0F1111", light "#FBFAF4".
|
||||
*/
|
||||
|
||||
const OVERLAY_COLORS = ["#0F1111", "#FBFAF4"] as const;
|
||||
const OVERLAY_PIXEL_SIZE = 4;
|
||||
const OVERLAY_RADIUS_SCALE = 0.9;
|
||||
|
||||
const clamp01 = (e: number) => Math.min(1, Math.max(0, e));
|
||||
|
||||
/** Original sT: normalize (values > 1 are treated as percentages). */
|
||||
function sT(e?: number): number {
|
||||
return e === undefined ? 0 : clamp01(e > 1 ? e / 100 : e);
|
||||
}
|
||||
|
||||
export function DotOverlay() {
|
||||
// Light-only theme (original: resolvedTheme from useThemeMode).
|
||||
const isDark = false;
|
||||
const size = useThree((s) => s.size);
|
||||
const materialRef = useRef<any>(null);
|
||||
|
||||
const uniforms = useMemo(
|
||||
() => ({
|
||||
uColor: { value: new Color() },
|
||||
uOpacity: { value: 1 },
|
||||
uPixelSize: { value: OVERLAY_PIXEL_SIZE },
|
||||
uRadiusScale: { value: OVERLAY_RADIUS_SCALE },
|
||||
uResolution: { value: new Vector2(1, 1) },
|
||||
}),
|
||||
[]
|
||||
);
|
||||
|
||||
// Theme color: light theme picks the second entry (original e[1]).
|
||||
useLayoutEffect(() => {
|
||||
const [dark, light] = OVERLAY_COLORS;
|
||||
materialRef.current?.uniforms.uColor.value.set(isDark ? dark : light);
|
||||
}, [isDark]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
materialRef.current?.uniforms.uResolution.value.set(
|
||||
Math.max(1, size.width),
|
||||
Math.max(1, size.height)
|
||||
);
|
||||
}, [size.width, size.height]);
|
||||
|
||||
useFrame(() => {
|
||||
const e = sT(scrollBus.sP);
|
||||
if (materialRef.current) {
|
||||
materialRef.current.uniforms.uOpacity.value = e;
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<mesh renderOrder={10} frustumCulled={false}>
|
||||
<planeGeometry args={[2, 2]} />
|
||||
<shaderMaterial
|
||||
ref={materialRef}
|
||||
transparent
|
||||
depthTest={false}
|
||||
depthWrite={false}
|
||||
toneMapped={false}
|
||||
uniforms={uniforms}
|
||||
vertexShader={`
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
vUv = uv;
|
||||
gl_Position = vec4(position.xy, 0.0, 1.0);
|
||||
}
|
||||
`}
|
||||
fragmentShader={`
|
||||
precision highp float;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
uniform vec3 uColor;
|
||||
uniform float uOpacity;
|
||||
uniform float uPixelSize;
|
||||
uniform float uRadiusScale;
|
||||
uniform vec2 uResolution;
|
||||
|
||||
void main() {
|
||||
float a = clamp(uOpacity, 0.0, 1.0);
|
||||
|
||||
vec2 normalizedPixelSize = vec2(
|
||||
uPixelSize / max(uResolution.x, 1.0),
|
||||
uPixelSize / max(uResolution.y, 1.0)
|
||||
);
|
||||
|
||||
vec2 safePixelSize = max(normalizedPixelSize, vec2(1e-6));
|
||||
vec2 cellUV = fract(vUv / safePixelSize);
|
||||
|
||||
// 与 route_transition 点阵一致:透明度直接映射圆半径。
|
||||
float radius = uRadiusScale * a;
|
||||
float distanceFromCenter = distance(cellUV, vec2(0.5));
|
||||
float aa = fwidth(distanceFromCenter) * 1.5;
|
||||
float circleMask = smoothstep(radius, radius - aa, distanceFromCenter);
|
||||
|
||||
gl_FragColor = vec4(uColor, circleMask);
|
||||
#include <colorspace_fragment>
|
||||
}
|
||||
`}
|
||||
/>
|
||||
</mesh>
|
||||
);
|
||||
}
|
||||
|
||||
export default DotOverlay;
|
||||
@@ -6,6 +6,8 @@ import * as THREE from "three";
|
||||
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
|
||||
import { mergeGeometries } from "three/examples/jsm/utils/BufferGeometryUtils.js";
|
||||
import { scrollBus } from "@/lib/scrollBus";
|
||||
import { usePointer } from "@/lib/pointer";
|
||||
import { loadingBus } from "@/lib/loadingBus";
|
||||
|
||||
/**
|
||||
* Glass models for the hero section, reverse-engineered 1:1 from the
|
||||
@@ -299,6 +301,51 @@ function useFloatOffset(enabled: boolean) {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Specular light controller — 1:1 port of the original `ca()`: a light that
|
||||
* orbits at radius hypot(4, 9) in the XY plane, its azimuth following the
|
||||
* pointer (raycast onto the z=0 plane) with exponential damping (6/s), and
|
||||
* falling back to the initial azimuth when the pointer leaves.
|
||||
*/
|
||||
function useLightController() {
|
||||
return useMemo(() => {
|
||||
const initialAzimuth = Math.atan2(9, 4);
|
||||
const radius = Math.hypot(4, 9);
|
||||
let azimuth = initialAzimuth;
|
||||
let current = initialAzimuth;
|
||||
const raycaster = new THREE.Raycaster();
|
||||
const ndc = new THREE.Vector2();
|
||||
const plane = new THREE.Plane(new THREE.Vector3(0, 0, 1), 0);
|
||||
const hit = new THREE.Vector3();
|
||||
return {
|
||||
update({
|
||||
uv,
|
||||
inside,
|
||||
camera,
|
||||
delta,
|
||||
}: {
|
||||
uv: { x: number; y: number };
|
||||
inside: boolean;
|
||||
camera: THREE.Camera;
|
||||
delta: number;
|
||||
}) {
|
||||
ndc.set(2 * uv.x - 1, 2 * uv.y - 1);
|
||||
raycaster.setFromCamera(ndc, camera);
|
||||
const intersected = raycaster.ray.intersectPlane(plane, hit) !== null;
|
||||
const tx = -hit.x;
|
||||
const ty = -hit.y;
|
||||
if (inside && intersected && tx * tx + ty * ty > 1e-6) {
|
||||
azimuth = Math.atan2(ty, tx);
|
||||
}
|
||||
const target = inside ? azimuth : initialAzimuth;
|
||||
const diff = Math.atan2(Math.sin(target - current), Math.cos(target - current));
|
||||
current += diff * (1 - Math.exp(-6 * delta));
|
||||
return { x: radius * Math.cos(current), y: radius * Math.sin(current) };
|
||||
},
|
||||
};
|
||||
}, []);
|
||||
}
|
||||
|
||||
function GlassModel({
|
||||
url,
|
||||
position = [0, 0, 0],
|
||||
@@ -452,6 +499,15 @@ function GlassModel({
|
||||
// Float bob: desktop only in the original (floatingMotion && !isMobileWidth)
|
||||
const floatEnabled = floating && !isMobile;
|
||||
const getFloat = useFloatOffset(floatEnabled);
|
||||
const lightController = useLightController();
|
||||
const { uv: pointerUv, insideRef: pointerInsideRef } = usePointer();
|
||||
|
||||
// Heavy-asset readiness for the entrance (original onReady → load progress).
|
||||
useEffect(() => {
|
||||
if (mergedGeometry) {
|
||||
loadingBus.mark(`model:${url.split("/").pop()}`);
|
||||
}
|
||||
}, [mergedGeometry, url]);
|
||||
|
||||
// Counter tilt: cancels rotationAxisTilt so the model's static orientation
|
||||
// is upright; the tilt only skews the spin axis (original nests -tilt
|
||||
@@ -540,6 +596,19 @@ function GlassModel({
|
||||
spin.rotation.y = THREE.MathUtils.damp(spin.rotation.y, ty, 6, delta);
|
||||
spin.rotation.z = THREE.MathUtils.damp(spin.rotation.z, tz, 6, delta);
|
||||
}
|
||||
|
||||
// Pointer-following specular light (original ca() + uLight.set(x, y, lightZ))
|
||||
const light = lightController.update({
|
||||
uv: pointerUv,
|
||||
inside: pointerInsideRef.current && !isMobile,
|
||||
camera,
|
||||
delta,
|
||||
});
|
||||
materialRef.current?.uniforms.uLight.value.set(
|
||||
light.x,
|
||||
light.y,
|
||||
LIGHT_PARAMS.lightZ
|
||||
);
|
||||
}, -2);
|
||||
|
||||
if (!mergedGeometry) return null;
|
||||
@@ -599,7 +668,9 @@ export function CursorStar({ isMobile = false }: { isMobile?: boolean }) {
|
||||
afterRotation={[0, 720, 0]}
|
||||
rotation={[0, 0, 0]}
|
||||
scale={0.1}
|
||||
tintColors={["#009dff", "#64c3ff"]}
|
||||
// Original tingColor light theme: tint A and B are BOTH #009dff
|
||||
// (m[0]/m[1]); #64c3ff (m[2]/m[3]) is the dark-theme value.
|
||||
tintColors={["#009dff", "#009dff"]}
|
||||
tintEnabled
|
||||
isMobile={isMobile}
|
||||
scrollSyncFactor={0.72}
|
||||
|
||||
@@ -1,28 +1,31 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useMemo, useRef } from "react";
|
||||
import { Canvas, useFrame, useThree } from "@react-three/fiber";
|
||||
import { Canvas } from "@react-three/fiber";
|
||||
import { PerspectiveCamera } from "@react-three/drei";
|
||||
import * as THREE from "three";
|
||||
|
||||
import { StickerDrop, StickerCamera } from "@/components/canvas/StickerDrop";
|
||||
import { HelloModel, CursorStar } from "@/components/canvas/GlassModels";
|
||||
import ImageLayers from "@/components/canvas/ImageLayers";
|
||||
import BackgroundFX from "@/components/canvas/BackgroundFX";
|
||||
import DotOverlay from "@/components/canvas/DotOverlay";
|
||||
import { useAppReady } from "@/components/dom/LoadingOverlay";
|
||||
import { useIsMobile } from "@/lib/useIsMobile";
|
||||
|
||||
/**
|
||||
* Hero canvas: falling stickers + glass hello/cursor models.
|
||||
* Hero canvas: animated background + falling stickers + glass models +
|
||||
* DOM-tracked image layers.
|
||||
*
|
||||
* The glass shader refracts a scene texture rendered into an FBO with a
|
||||
* layer-0 camera mask (stickers/background), matching the original
|
||||
* "glass hosting section" FBO. Glass meshes enable layer 10 so they are
|
||||
* excluded from their own refraction pass.
|
||||
* Models animate only from scroll (entry/after targets, damp 6) — no
|
||||
* time-based motion besides the desktop float bob.
|
||||
* - BackgroundFX renders the original sz multi-pass gradient at
|
||||
* renderOrder -10; the glass FBO pass (layer-0 mask) captures it, which
|
||||
* is what tints the glass models blue.
|
||||
* - Stickers live on layer 0; glass models on layer 0+10 (10 excluded from
|
||||
* the FBO pass — no self-refraction).
|
||||
* - Models animate only from scroll (entry/after targets, damp 6); the
|
||||
* camera intro dolly starts once `ready` (loading gate).
|
||||
*/
|
||||
|
||||
export function HeroScene() {
|
||||
const isMobile = useIsMobile();
|
||||
const ready = useAppReady();
|
||||
|
||||
return (
|
||||
// z-30 keeps it above the BackgroundGrid (z-20) to prevent mix-blend-difference from making it gray
|
||||
@@ -31,11 +34,20 @@ export function HeroScene() {
|
||||
dpr={[1, 2]}
|
||||
gl={{ alpha: true, antialias: true }}
|
||||
>
|
||||
{/* Camera rig: horizontal FOV 60/38 + scroll-driven distance lerp(24, 32).
|
||||
StickerCamera drives fov/aspect/z every frame; PerspectiveCamera is the
|
||||
makeDefault camera it mutates. */}
|
||||
<PerspectiveCamera makeDefault position={[0, 0, 24]} near={0.1} far={200} />
|
||||
<StickerCamera />
|
||||
{/* Camera rig: horizontal FOV 60/38, distance lerp(24, 32, sP),
|
||||
intro dolly z+8 → A (customCubic, 1.2s, ready-gated), mouse
|
||||
parallax (desktop). */}
|
||||
<PerspectiveCamera makeDefault position={[0, 0, 32]} near={0.1} far={200} />
|
||||
<StickerCamera ready={ready} />
|
||||
|
||||
{/* Animated background (vignette/swirl/sine/shatter/bokeh → output) */}
|
||||
<BackgroundFX />
|
||||
|
||||
{/* Scroll dot-overlay (original s1): page-bg-colored 4px dot grid
|
||||
whose opacity = sT(sP) — melts the WebGL scene into the page
|
||||
background after ~0.75 viewport of scroll (this is the original
|
||||
"stickers fade out on scroll" behavior); reopens near footer. */}
|
||||
<DotOverlay />
|
||||
|
||||
{/* Falling stickers: 1:1 re-implementation of the original particle system.
|
||||
Live on layer 0 — visible to the main camera and captured by the
|
||||
|
||||
@@ -6,6 +6,7 @@ import * as THREE from "three";
|
||||
import { scrollBus } from "@/lib/scrollBus";
|
||||
import { useIsMobile } from "@/lib/useIsMobile";
|
||||
import { imageLayerTargets } from "@/lib/imageLayers";
|
||||
import { loadingBus } from "@/lib/loadingBus";
|
||||
|
||||
/**
|
||||
* DOM-tracked WebGL image layers — 1:1 port of the original `cE`/`cw`
|
||||
@@ -380,7 +381,8 @@ function ImageLayer({ def }: { def: ImageLayerDef }) {
|
||||
material.uniforms.uHoverRevealProgress.value = 0;
|
||||
hoverProgressRef.current = 0;
|
||||
hoverEnabledRef.current = !!hover || !hasHover;
|
||||
}, [base, hover, gl, isMobile, hasHover, material]);
|
||||
loadingBus.mark(`img:${def.key}`);
|
||||
}, [base, hover, gl, isMobile, hasHover, material, def.key]);
|
||||
|
||||
const geometry = useMemo(() => new THREE.PlaneGeometry(2, 2), []);
|
||||
useEffect(() => () => geometry.dispose(), [geometry]);
|
||||
|
||||
@@ -0,0 +1,445 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useMemo, useRef } from "react";
|
||||
import { useLayoutEffect } from "react";
|
||||
import { Canvas, useFrame, useThree } from "@react-three/fiber";
|
||||
import { Color, MathUtils, UnsignedByteType } from "three";
|
||||
import { Effect, BlendFunction } from "postprocessing";
|
||||
import { EffectComposer } from "@react-three/postprocessing";
|
||||
import { customCubic } from "@/lib/customCubic";
|
||||
|
||||
/**
|
||||
* Entry/route transition curtain — 1:1 port of the original fullscreen
|
||||
* transition canvas (chunk 3c6cc5b2fcccdee5.js, module 34841):
|
||||
*
|
||||
* - `s`: a separate fixed fullscreen canvas (demand frameloop, alpha,
|
||||
* premultiplied, no depth/stencil) holding only the mask material.
|
||||
* - `p`: radial-hole mask mesh (renderOrder 2000, clip-space quad):
|
||||
* alpha 0 inside the hole (content visible), 1 outside; the hole
|
||||
* radius animates from the `max(aspect,1/aspect)` diagonal to 0
|
||||
* (closed) or back up (open) with customCubic; the last 8% of progress
|
||||
* fills the pinhole (fillMix).
|
||||
* - `g`/`w`: MaskedDotsEffect post-processing (pixelSize 16 × dpr,
|
||||
* radius 0.8 × mask alpha, BlendFunction.SRC) rasterizing the mask
|
||||
* into the overlay-colored dot grid.
|
||||
*
|
||||
* Light theme overlay color (f): dark "#191b1b", light "#efede7".
|
||||
*/
|
||||
|
||||
const CURTAIN_COLORS = ["#191b1b", "#efede7"] as const;
|
||||
|
||||
const MASK_VERT = `varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
vUv = position.xy * 0.5 + 0.5;
|
||||
gl_Position = vec4(position.xy, 0.0, 1.0);
|
||||
}
|
||||
`;
|
||||
|
||||
const MASK_FRAG = `precision highp float;
|
||||
|
||||
uniform vec3 uColor;
|
||||
uniform float uFeather;
|
||||
uniform float uAspect;
|
||||
uniform float uHoleRadius;
|
||||
uniform float uProgress;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
void main() {
|
||||
vec2 p = vUv * 2.0 - 1.0;
|
||||
if (uAspect > 1.0) {
|
||||
p.x *= uAspect;
|
||||
} else {
|
||||
p.y /= max(uAspect, 0.0001);
|
||||
}
|
||||
|
||||
float d = length(p);
|
||||
|
||||
float edge = max(uFeather, uHoleRadius * 0.12);
|
||||
|
||||
// 洞内为 0,洞外为 1。
|
||||
float alphaHole = smoothstep(uHoleRadius, uHoleRadius + edge, d);
|
||||
|
||||
// 只在动画结束前一小段把“针孔”补满,让洞像是彻底消失。
|
||||
float fillMix = smoothstep(0.92, 1.0, uProgress);
|
||||
float alpha = mix(alphaHole, 1.0, fillMix);
|
||||
// 预乘 alpha,避免透明像素携带 rgb 导致后期采样出现黑边/暗圈。
|
||||
gl_FragColor = vec4(uColor * alpha, alpha);
|
||||
#include <colorspace_fragment>
|
||||
}
|
||||
`;
|
||||
|
||||
const DOTS_FRAG = `uniform float pixelSize;
|
||||
|
||||
uniform float uFeather;
|
||||
uniform float uAspect;
|
||||
uniform float uHoleRadius;
|
||||
uniform float uProgress;
|
||||
uniform vec3 uOverlayColor;
|
||||
|
||||
void dotsMainImage(const in vec4 inputColor, const in vec2 uv, out vec4 outputColor) {
|
||||
vec2 normalizedPixelSize = pixelSize / resolution;
|
||||
// 用传入的 inputColor.a 驱动圆点大小:越不透明圆点越大,越透明圆点越小。
|
||||
float a = clamp(inputColor.a, 0.0, 1.0);
|
||||
|
||||
vec2 cellUV = fract(uv / normalizedPixelSize);
|
||||
|
||||
// 透明度 -> 圆点半径:a=1 时覆盖整个 cell,避免蒙版填充区漏出底图。
|
||||
// sqrt(2)/2 是单位正方形中心到角的距离。
|
||||
float radius = 0.8 * a;
|
||||
vec2 circleCenter = vec2(0.5, 0.5);
|
||||
|
||||
float distanceFromCenter = distance(cellUV, circleCenter);
|
||||
float aa = fwidth(distanceFromCenter) * 1.5;
|
||||
float circleMask = smoothstep(radius, radius - aa, distanceFromCenter);
|
||||
|
||||
// 输出为 mask:rgb/alpha 都是 circleMask,供后期用来替换 opacity。
|
||||
outputColor = vec4(vec3(circleMask), circleMask);
|
||||
}
|
||||
|
||||
float radialMaskAlpha(vec2 uv) {
|
||||
vec2 p = uv * 2.0 - 1.0;
|
||||
if (uAspect > 1.0) {
|
||||
p.x *= uAspect;
|
||||
} else {
|
||||
p.y /= max(uAspect, 0.0001);
|
||||
}
|
||||
|
||||
float d = length(p);
|
||||
float edge = max(uFeather, uHoleRadius * 0.12);
|
||||
|
||||
// 洞内为 0,洞外为 1。
|
||||
float alphaHole = smoothstep(uHoleRadius, uHoleRadius + edge, d);
|
||||
|
||||
// 与 radial_mask.frag.glsl 保持一致:末段补满针孔。
|
||||
float fillMix = smoothstep(0.92, 1.0, uProgress);
|
||||
return mix(alphaHole, 1.0, fillMix);
|
||||
}
|
||||
|
||||
void mainImage(const in vec4 inputColor, const in vec2 uv, out vec4 outputColor) {
|
||||
// 用蒙版 alpha 直接驱动点阵大小(0=最小,1=最大),不再只处理过渡带。
|
||||
// 为了让点阵在一个 cell 内保持一致:用 cell 中心点的 alpha 驱动圆点大小。
|
||||
vec2 normalizedPixelSize = pixelSize / resolution;
|
||||
vec2 cellId = floor(uv / normalizedPixelSize);
|
||||
vec2 uvCellCenter = (cellId + vec2(0.5)) * normalizedPixelSize;
|
||||
float cellAlpha = clamp(radialMaskAlpha(uvCellCenter), 0.0, 1.0);
|
||||
|
||||
vec4 dotOut;
|
||||
dotsMainImage(vec4(0.0, 0.0, 0.0, cellAlpha), uv, dotOut);
|
||||
float dotMask = clamp(dotOut.a, 0.0, 1.0);
|
||||
|
||||
float finalAlpha = dotMask;
|
||||
|
||||
// 直接输出 overlay 颜色(预乘 alpha),避免颜色混合导致点边黑描边。
|
||||
vec3 outRgb = uOverlayColor * finalAlpha;
|
||||
outputColor = vec4(outRgb, finalAlpha);
|
||||
}
|
||||
`;
|
||||
|
||||
class MaskedDotsEffect extends Effect {
|
||||
pixelSize: number;
|
||||
feather: number;
|
||||
aspect: number;
|
||||
holeRadius: number;
|
||||
progress: number;
|
||||
overlayColor: Color;
|
||||
private _uPixelSize: { value: number };
|
||||
private _uFeather: { value: number };
|
||||
private _uAspect: { value: number };
|
||||
private _uHoleRadius: { value: number };
|
||||
private _uProgress: { value: number };
|
||||
private _uOverlayColor: { value: Color };
|
||||
private _dirty = true;
|
||||
|
||||
constructor({
|
||||
pixelSize = 32,
|
||||
feather = 0.5,
|
||||
aspect = 1,
|
||||
holeRadius = 2,
|
||||
progress = 0,
|
||||
overlayColor = new Color(1, 1, 1),
|
||||
} = {}) {
|
||||
const uniforms = new Map<string, { value: any }>([
|
||||
["pixelSize", { value: pixelSize }],
|
||||
["uFeather", { value: feather }],
|
||||
["uAspect", { value: aspect }],
|
||||
["uHoleRadius", { value: holeRadius }],
|
||||
["uProgress", { value: progress }],
|
||||
["uOverlayColor", { value: overlayColor.clone() }],
|
||||
]);
|
||||
super("MaskedDotsEffect", DOTS_FRAG, {
|
||||
uniforms: uniforms as unknown as Map<string, import("three").Uniform<any>>,
|
||||
blendFunction: BlendFunction.SRC,
|
||||
});
|
||||
this.pixelSize = pixelSize;
|
||||
this.feather = feather;
|
||||
this.aspect = aspect;
|
||||
this.holeRadius = holeRadius;
|
||||
this.progress = progress;
|
||||
this.overlayColor = overlayColor.clone();
|
||||
this._uPixelSize = uniforms.get("pixelSize")!;
|
||||
this._uFeather = uniforms.get("uFeather")!;
|
||||
this._uAspect = uniforms.get("uAspect")!;
|
||||
this._uHoleRadius = uniforms.get("uHoleRadius")!;
|
||||
this._uProgress = uniforms.get("uProgress")!;
|
||||
this._uOverlayColor = uniforms.get("uOverlayColor")!;
|
||||
}
|
||||
|
||||
setParams(e: {
|
||||
pixelSize?: number;
|
||||
feather?: number;
|
||||
aspect?: number;
|
||||
holeRadius?: number;
|
||||
progress?: number;
|
||||
overlayColor?: Color;
|
||||
}) {
|
||||
let dirty = false;
|
||||
if (typeof e.pixelSize === "number" && e.pixelSize !== this.pixelSize) {
|
||||
this.pixelSize = e.pixelSize;
|
||||
dirty = true;
|
||||
}
|
||||
if (typeof e.feather === "number" && e.feather !== this.feather) {
|
||||
this.feather = e.feather;
|
||||
dirty = true;
|
||||
}
|
||||
if (typeof e.aspect === "number" && e.aspect !== this.aspect) {
|
||||
this.aspect = e.aspect;
|
||||
dirty = true;
|
||||
}
|
||||
if (typeof e.holeRadius === "number" && e.holeRadius !== this.holeRadius) {
|
||||
this.holeRadius = e.holeRadius;
|
||||
dirty = true;
|
||||
}
|
||||
if (typeof e.progress === "number" && e.progress !== this.progress) {
|
||||
this.progress = e.progress;
|
||||
dirty = true;
|
||||
}
|
||||
if (e.overlayColor && !this.overlayColor.equals(e.overlayColor)) {
|
||||
this.overlayColor.copy(e.overlayColor);
|
||||
dirty = true;
|
||||
}
|
||||
if (dirty) this._dirty = true;
|
||||
}
|
||||
|
||||
update() {
|
||||
if (this._dirty) {
|
||||
this._dirty = false;
|
||||
this._uPixelSize.value = this.pixelSize;
|
||||
this._uFeather.value = this.feather;
|
||||
this._uAspect.value = this.aspect;
|
||||
this._uHoleRadius.value = this.holeRadius;
|
||||
this._uProgress.value = this.progress;
|
||||
this._uOverlayColor.value.copy(this.overlayColor);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function RadialHoleMask({
|
||||
open,
|
||||
duration,
|
||||
initialProgress,
|
||||
resetKey,
|
||||
onComplete,
|
||||
materialRef,
|
||||
}: {
|
||||
open: boolean;
|
||||
duration: number;
|
||||
initialProgress?: number;
|
||||
resetKey: string;
|
||||
onComplete?: (open: boolean) => void;
|
||||
materialRef: React.MutableRefObject<any>;
|
||||
}) {
|
||||
const { size } = useThree();
|
||||
const invalidate = useThree((s) => s.invalidate);
|
||||
|
||||
// Light theme picks f[1] (#efede7).
|
||||
const color = CURTAIN_COLORS[1];
|
||||
|
||||
const uniforms = useMemo(
|
||||
() => ({
|
||||
uColor: { value: new Color() },
|
||||
uFeather: { value: 0.8 },
|
||||
uAspect: { value: 1 },
|
||||
uHoleRadius: { value: 2 },
|
||||
uProgress: { value: 0 },
|
||||
}),
|
||||
[]
|
||||
);
|
||||
|
||||
// b: sqrt(max(aspect, 1/aspect)^2 + 1) — the closed-hole diagonal norm.
|
||||
const bMax = useMemo(() => {
|
||||
const aspect = size.width / Math.max(1, size.height);
|
||||
const t = Math.max(aspect, 1 / aspect);
|
||||
return Math.sqrt(t * t + 1);
|
||||
}, [size.width, size.height]);
|
||||
|
||||
useEffect(() => {
|
||||
invalidate();
|
||||
}, [color, invalidate]);
|
||||
|
||||
useEffect(() => {
|
||||
if (materialRef.current) {
|
||||
const aspect = size.width / Math.max(1, size.height);
|
||||
materialRef.current.uniforms.uAspect.value = aspect;
|
||||
}
|
||||
}, [size.width, size.height, materialRef]);
|
||||
|
||||
const progressRef = useRef(0);
|
||||
const startTimeRef = useRef<number | null>(null);
|
||||
const fromRef = useRef(0);
|
||||
const toRef = useRef(0);
|
||||
const completedRef = useRef(false);
|
||||
const initializedRef = useRef(false);
|
||||
|
||||
// initialProgress: cover fully closed on mount (entry:wait → 1).
|
||||
useLayoutEffect(() => {
|
||||
if (initializedRef.current || typeof initialProgress !== "number") return;
|
||||
initializedRef.current = true;
|
||||
const e = MathUtils.clamp(initialProgress, 0, 1);
|
||||
progressRef.current = e;
|
||||
fromRef.current = e;
|
||||
const holeRadius = MathUtils.lerp(bMax, 0, e);
|
||||
if (materialRef.current) {
|
||||
materialRef.current.uniforms.uHoleRadius.value = holeRadius;
|
||||
materialRef.current.uniforms.uProgress.value = e;
|
||||
}
|
||||
invalidate();
|
||||
}, [initialProgress, bMax, materialRef, invalidate]);
|
||||
|
||||
// Reset the animation whenever open/resetKey changes.
|
||||
useLayoutEffect(() => {
|
||||
fromRef.current = progressRef.current;
|
||||
toRef.current = +!!open;
|
||||
startTimeRef.current = null;
|
||||
completedRef.current = false;
|
||||
invalidate();
|
||||
}, [open, resetKey, invalidate]);
|
||||
|
||||
useFrame((state) => {
|
||||
const elapsed = state.clock.getElapsedTime();
|
||||
if (startTimeRef.current === null) startTimeRef.current = elapsed;
|
||||
const l = elapsed - startTimeRef.current;
|
||||
const t01 = MathUtils.clamp(l / Math.max(1e-6, duration), 0, 1);
|
||||
const eased = customCubic(t01);
|
||||
progressRef.current = MathUtils.lerp(fromRef.current, toRef.current, eased);
|
||||
const holeRadius = MathUtils.lerp(bMax, 0, progressRef.current);
|
||||
if (materialRef.current) {
|
||||
materialRef.current.uniforms.uHoleRadius.value = holeRadius;
|
||||
materialRef.current.uniforms.uProgress.value = progressRef.current;
|
||||
materialRef.current.uniforms.uColor.value.set(color);
|
||||
}
|
||||
if (!completedRef.current && t01 >= 1 - 1e-6) {
|
||||
completedRef.current = true;
|
||||
onComplete?.(open);
|
||||
}
|
||||
if (!completedRef.current && t01 < 1 - 1e-6) state.invalidate();
|
||||
});
|
||||
|
||||
return (
|
||||
<mesh renderOrder={2000} frustumCulled={false}>
|
||||
<planeGeometry args={[2, 2]} />
|
||||
<shaderMaterial
|
||||
ref={materialRef}
|
||||
transparent
|
||||
premultipliedAlpha
|
||||
depthTest={false}
|
||||
depthWrite={false}
|
||||
toneMapped={false}
|
||||
uniforms={uniforms}
|
||||
vertexShader={MASK_VERT}
|
||||
fragmentShader={MASK_FRAG}
|
||||
/>
|
||||
</mesh>
|
||||
);
|
||||
}
|
||||
|
||||
function DotsPost({ materialRef }: { materialRef: React.MutableRefObject<any> }) {
|
||||
const effect = useMemo(
|
||||
() =>
|
||||
new MaskedDotsEffect({
|
||||
pixelSize: 32,
|
||||
feather: 0.5,
|
||||
aspect: 1,
|
||||
holeRadius: 2,
|
||||
progress: 0,
|
||||
overlayColor: new Color(1, 1, 1),
|
||||
}),
|
||||
[]
|
||||
);
|
||||
const dpr = useThree((s) => s.viewport.dpr);
|
||||
useEffect(() => () => effect.dispose(), [effect]);
|
||||
|
||||
useFrame(() => {
|
||||
const t = materialRef.current;
|
||||
if (t) {
|
||||
effect.setParams({
|
||||
pixelSize: 16 * dpr,
|
||||
feather: t.uniforms.uFeather.value,
|
||||
aspect: t.uniforms.uAspect.value,
|
||||
holeRadius: t.uniforms.uHoleRadius.value,
|
||||
progress: t.uniforms.uProgress.value,
|
||||
overlayColor: t.uniforms.uColor.value,
|
||||
});
|
||||
}
|
||||
}, 1);
|
||||
|
||||
return (
|
||||
<EffectComposer
|
||||
multisampling={0}
|
||||
autoClear
|
||||
renderPriority={999}
|
||||
frameBufferType={UnsignedByteType}
|
||||
>
|
||||
<primitive object={effect} />
|
||||
</EffectComposer>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fullscreen transition canvas — port of the original `s` wrapper:
|
||||
* demand frameloop, alpha, premultiplied, depth/stencil off.
|
||||
*/
|
||||
export function LoadingCurtain({
|
||||
open,
|
||||
duration = 0.8,
|
||||
initialProgress,
|
||||
resetKey,
|
||||
onComplete,
|
||||
}: {
|
||||
open: boolean;
|
||||
duration?: number;
|
||||
initialProgress?: number;
|
||||
resetKey: string;
|
||||
onComplete?: (open: boolean) => void;
|
||||
}) {
|
||||
const materialRef = useRef<any>(null);
|
||||
return (
|
||||
<Canvas
|
||||
dpr={[1, 2]}
|
||||
frameloop="demand"
|
||||
gl={{
|
||||
alpha: true,
|
||||
antialias: false,
|
||||
premultipliedAlpha: true,
|
||||
depth: false,
|
||||
stencil: false,
|
||||
powerPreference: "high-performance",
|
||||
preserveDrawingBuffer: false,
|
||||
}}
|
||||
className="fixed inset-0 z-[60] pointer-events-none"
|
||||
>
|
||||
<RadialHoleMask
|
||||
open={open}
|
||||
duration={duration}
|
||||
initialProgress={initialProgress}
|
||||
resetKey={resetKey}
|
||||
onComplete={onComplete}
|
||||
materialRef={materialRef}
|
||||
/>
|
||||
<DotsPost materialRef={materialRef} />
|
||||
</Canvas>
|
||||
);
|
||||
}
|
||||
|
||||
export default LoadingCurtain;
|
||||
@@ -1,10 +1,14 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useEffect, useMemo, useRef } from "react";
|
||||
import { useFrame, useThree } from "@react-three/fiber";
|
||||
import * as THREE from "three";
|
||||
import { StickerLayer } from "@/components/webgl/StickerLayer";
|
||||
import { scrollBus } from "@/lib/scrollBus";
|
||||
import { loadingBus } from "@/lib/loadingBus";
|
||||
import { usePointer } from "@/lib/pointer";
|
||||
import { useIsMobile } from "@/lib/useIsMobile";
|
||||
import { customCubic } from "@/lib/customCubic";
|
||||
|
||||
const STICKER_IMAGES = Array.from(
|
||||
{ length: 12 },
|
||||
@@ -27,11 +31,15 @@ export function StickerDrop() {
|
||||
const camera = useThree((s) => s.camera);
|
||||
const gl = useThree((s) => s.gl);
|
||||
const layerRef = useRef<StickerLayer | null>(null);
|
||||
const isMobile = useIsMobile();
|
||||
|
||||
useEffect(() => {
|
||||
const layer = new StickerLayer(scene);
|
||||
layerRef.current = layer;
|
||||
layer.load(STICKER_IMAGES).catch(() => {});
|
||||
layer
|
||||
.load(STICKER_IMAGES)
|
||||
.then(() => loadingBus.mark("stickers"))
|
||||
.catch(() => {});
|
||||
return () => {
|
||||
layer.dispose();
|
||||
layerRef.current = null;
|
||||
@@ -39,6 +47,7 @@ export function StickerDrop() {
|
||||
}, [scene]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isMobile) return; // original: pointer bursts are desktop-only
|
||||
const raycaster = new THREE.Raycaster();
|
||||
const ndc = new THREE.Vector2();
|
||||
const plane = new THREE.Plane(new THREE.Vector3(0, 0, 1), 0);
|
||||
@@ -110,7 +119,7 @@ export function StickerDrop() {
|
||||
window.removeEventListener("pointerup", onPointerUp, true);
|
||||
window.removeEventListener("pointercancel", onPointerCancel, true);
|
||||
};
|
||||
}, [camera, gl]);
|
||||
}, [camera, gl, isMobile]);
|
||||
|
||||
useFrame((_, delta) => {
|
||||
layerRef.current?.update(delta);
|
||||
@@ -120,24 +129,78 @@ export function StickerDrop() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Camera rig matching the original: horizontal FOV 60° (desktop) / 38°
|
||||
* (mobile) converted to vertical FOV per aspect, and camera distance
|
||||
* lerp(24, 32) driven by page scroll progress.
|
||||
* Camera rig matching the original cK:
|
||||
* - horizontal FOV 60° (desktop) / 38° (mobile) converted to vertical FOV
|
||||
* - distance A = lerp(24, 32, sP); position.z = lerp(A + 8, A,
|
||||
* customCubic(introT)) where introT ramps 0→1 over 1.2s once `ready`
|
||||
* (the entrance dolly from z+8)
|
||||
* - mouse parallax (desktop, ready only): offset = ((.5-uv)*2) * (1.4, .84),
|
||||
* rotated around the base position by lookAt(gyro*-.12), lerp lag .18
|
||||
* (.05 when the pointer leaves)
|
||||
* - sP is the original camera progress (banner/footer geometry), updated
|
||||
* from scrollBus.sP written by the page's scroll-geometry effect
|
||||
*/
|
||||
export function StickerCamera() {
|
||||
export function StickerCamera({ ready }: { ready: boolean }) {
|
||||
const camera = useThree((s) => s.camera) as THREE.PerspectiveCamera;
|
||||
const size = useThree((s) => s.size);
|
||||
const { uv, insideRef } = usePointer();
|
||||
const isMobile = useIsMobile();
|
||||
|
||||
useFrame(() => {
|
||||
const baseRef = useRef<THREE.Vector2 | null>(null);
|
||||
const posLagRef = useRef(new THREE.Vector3());
|
||||
const rotLagRef = useRef(new THREE.Vector3());
|
||||
const introRef = useRef(0);
|
||||
const distanceRef = useRef(24);
|
||||
const parallaxVec = useMemo(() => new THREE.Vector3(), []);
|
||||
|
||||
useFrame((_state, rawDelta) => {
|
||||
const delta = Math.min(rawDelta, 0.1);
|
||||
const aspect = size.width / Math.max(1, size.height);
|
||||
const horizontalFov = size.width >= 1024 ? 60 : 38;
|
||||
const verticalFov =
|
||||
2 * Math.atan(Math.tan(THREE.MathUtils.degToRad(horizontalFov) / 2) / aspect);
|
||||
camera.fov = THREE.MathUtils.radToDeg(verticalFov);
|
||||
camera.aspect = aspect;
|
||||
const progress = THREE.MathUtils.clamp(scrollBus.progress, 0, 1);
|
||||
camera.position.z = THREE.MathUtils.lerp(24, 32, progress);
|
||||
camera.updateProjectionMatrix();
|
||||
if (
|
||||
Math.abs(camera.fov - THREE.MathUtils.radToDeg(verticalFov)) > 1e-4 ||
|
||||
Math.abs(camera.aspect - aspect) > 1e-6
|
||||
) {
|
||||
camera.fov = THREE.MathUtils.radToDeg(verticalFov);
|
||||
camera.aspect = aspect;
|
||||
camera.updateProjectionMatrix();
|
||||
}
|
||||
|
||||
const progress = THREE.MathUtils.clamp(scrollBus.sP, 0, 1);
|
||||
const distance = THREE.MathUtils.lerp(24, 32, progress);
|
||||
distanceRef.current = distance;
|
||||
|
||||
if (!baseRef.current) {
|
||||
baseRef.current = new THREE.Vector2(camera.position.x, camera.position.y);
|
||||
}
|
||||
introRef.current = ready
|
||||
? Math.min(introRef.current + delta / 1.2, 1)
|
||||
: 0;
|
||||
camera.position.z = THREE.MathUtils.lerp(
|
||||
distance + 8,
|
||||
distance,
|
||||
customCubic(introRef.current)
|
||||
);
|
||||
|
||||
if (!isMobile) {
|
||||
const px = (0.5 - uv.x) * 2;
|
||||
const py = (0.5 - uv.y) * 2;
|
||||
const offset = posLagRef.current;
|
||||
const rot = rotLagRef.current;
|
||||
offset.lerp(parallaxVec.set(px * 1.4, py * 0.84, 0), insideRef.current ? 0.18 : 0.05);
|
||||
rot.lerp(parallaxVec.set(-offset.x * 0.12, -offset.y * 0.12, 0), insideRef.current ? 0.18 : 0.05);
|
||||
camera.position.x = baseRef.current.x + offset.x;
|
||||
camera.position.y = baseRef.current.y + offset.y;
|
||||
camera.lookAt(rot);
|
||||
} else {
|
||||
posLagRef.current.lerp(parallaxVec.set(0, 0, 0), 0.18);
|
||||
rotLagRef.current.lerp(parallaxVec.set(0, 0, 0), 0.18);
|
||||
camera.position.x = baseRef.current.x;
|
||||
camera.position.y = baseRef.current.y;
|
||||
camera.lookAt(0, 0, 0);
|
||||
}
|
||||
});
|
||||
|
||||
return null;
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
useEffect,
|
||||
useState,
|
||||
useSyncExternalStore,
|
||||
} from "react";
|
||||
import { loadingBus } from "@/lib/loadingBus";
|
||||
import LoadingCurtain from "@/components/canvas/LoadingCurtain";
|
||||
|
||||
/** Stable server snapshot (must be cached — a fresh object would loop). */
|
||||
const SERVER_SNAPSHOT = { progress: 0, ready: false };
|
||||
|
||||
function useHeavyLoad() {
|
||||
return useSyncExternalStore(
|
||||
loadingBus.subscribe,
|
||||
loadingBus.getSnapshot,
|
||||
() => SERVER_SNAPSHOT
|
||||
);
|
||||
}
|
||||
|
||||
function useFontsReady() {
|
||||
const [fontsReady, setFontsReady] = useState(false);
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
const fonts = (document as any).fonts;
|
||||
if (!fonts) {
|
||||
setFontsReady(true);
|
||||
return;
|
||||
}
|
||||
fonts.ready.then(() => {
|
||||
if (!cancelled) setFontsReady(true);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
return fontsReady;
|
||||
}
|
||||
|
||||
const clamp = (v: number, min: number, max: number) =>
|
||||
Math.min(max, Math.max(min, v));
|
||||
|
||||
/**
|
||||
* Heavy-asset readiness for the camera intro dolly (original cV's `p`:
|
||||
* models + image layers ready — fonts are NOT part of this gate).
|
||||
*/
|
||||
export function useAppReady(): boolean {
|
||||
const heavy = useHeavyLoad();
|
||||
|
||||
// Safety valve: a stalled asset must never soft-lock the page.
|
||||
useEffect(() => {
|
||||
const safety = window.setTimeout(() => loadingBus.forceReady(), 6000);
|
||||
return () => window.clearTimeout(safety);
|
||||
}, []);
|
||||
|
||||
return heavy.ready;
|
||||
}
|
||||
|
||||
/**
|
||||
* Entry loading flow — port of the original route-transition controller
|
||||
* (module 34841) for the entry case on "/":
|
||||
*
|
||||
* 1. entry:wait — curtain fully closed (initialProgress 1), centered
|
||||
* 140px bar shows 50%·fontsReady + 50%·heavyLoadProgress.
|
||||
* 2. readyToLoadHeavy && fontsReady → hold 250ms → bar fades (250ms)
|
||||
* → 250ms later the curtain opens (0.8s customCubic radial hole +
|
||||
* dot mask) — reveal phase.
|
||||
* 3. Curtain reveal completes (+0.9s grace) → idle: unmount everything.
|
||||
*/
|
||||
export function LoadingOverlay() {
|
||||
const heavy = useHeavyLoad();
|
||||
const fontsReady = useFontsReady();
|
||||
|
||||
// wait → fading → reveal → (unmount when reveal completes)
|
||||
const [phase, setPhase] = useState<"wait" | "fading" | "reveal">("wait");
|
||||
const [mounted, setMounted] = useState(true);
|
||||
|
||||
const progress = Math.round(clamp(50 * +fontsReady + heavy.progress / 2, 0, 100));
|
||||
const assetsDone = heavy.ready && fontsReady;
|
||||
|
||||
useEffect(() => {
|
||||
if (!assetsDone || phase !== "wait") return;
|
||||
// Original: 250ms hold → fade the bar → 250ms later open the curtain.
|
||||
const t1 = window.setTimeout(() => setPhase("fading"), 250);
|
||||
return () => window.clearTimeout(t1);
|
||||
}, [assetsDone, phase]);
|
||||
|
||||
useEffect(() => {
|
||||
if (phase !== "fading") return;
|
||||
const t2 = window.setTimeout(() => setPhase("reveal"), 250);
|
||||
return () => window.clearTimeout(t2);
|
||||
}, [phase]);
|
||||
|
||||
if (!mounted) return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
<LoadingCurtain
|
||||
open={phase === "reveal"}
|
||||
duration={0.8}
|
||||
initialProgress={1}
|
||||
resetKey={`entry:${phase}`}
|
||||
onComplete={(open) => {
|
||||
if (open) {
|
||||
// Reveal finished — a beat later the curtain canvas unmounts.
|
||||
window.setTimeout(() => setMounted(false), 900);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{phase !== "reveal" && (
|
||||
<ProgressBar progress={progress} fading={phase === "fading"} />
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** Centered 140px progress bar (original `b`). */
|
||||
function ProgressBar({ progress, fading }: { progress: number; fading: boolean }) {
|
||||
const clamped = clamp(progress, 0, 100);
|
||||
return (
|
||||
<div
|
||||
aria-hidden="true"
|
||||
className={`left-1/2 top-1/2 z-40 fixed flex h-4 w-[140px] -translate-x-1/2 -translate-y-1/2 items-center justify-center pointer-events-none ${
|
||||
fading ? "opacity-0" : "opacity-100"
|
||||
}`}
|
||||
style={{ transition: "opacity 250ms cubic-bezier(0.25, 1, 0.5, 1)" }}
|
||||
>
|
||||
<div className="relative h-1.5 w-full overflow-hidden rounded-full bg-l3">
|
||||
<div
|
||||
className="absolute inset-y-0 left-0 rounded-full bg-l1"
|
||||
style={{
|
||||
width: `${clamped}%`,
|
||||
transition: "width 520ms cubic-bezier(0.22, 1, 0.36, 1)",
|
||||
willChange: "width",
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default LoadingOverlay;
|
||||
@@ -4,18 +4,70 @@ import { useEffect } from 'react';
|
||||
import Lenis from 'lenis';
|
||||
import { scrollBus } from '@/lib/scrollBus';
|
||||
|
||||
const clamp01 = (v: number) => Math.min(1, Math.max(0, v));
|
||||
|
||||
/**
|
||||
* Lenis smooth scrolling + the original sP camera-progress computation
|
||||
* (banner/footer section geometry):
|
||||
* f1 = clamp((vh - bannerBottom) / max(1, vh - .25vh), 0, 1)
|
||||
* f2 = footer ? clamp(footerTop / vh, 0, 1) : 1
|
||||
* sP = f1 * f2
|
||||
* f2 measures the footer's distance ABOVE: it is 1 while the footer is
|
||||
* further than one viewport away and falls to 0 as the footer top reaches
|
||||
* the viewport top. Until the footer section exists we keep f2 at 1 —
|
||||
* matching the original's behavior for most of the page (sP → 1 after
|
||||
* ~0.75 viewport of scroll, which drives the dot-overlay fade and the
|
||||
* camera pull-back).
|
||||
*/
|
||||
export default function SmoothScroller() {
|
||||
useEffect(() => {
|
||||
// Refresh must always start at the top (original behavior: no anchor
|
||||
// → scroll to 0; also re-asserted on bfcache pageshow).
|
||||
if ('scrollRestoration' in window.history) {
|
||||
window.history.scrollRestoration = 'manual';
|
||||
}
|
||||
const resetScroll = () => {
|
||||
if (window.location.hash) return;
|
||||
window.scrollTo(0, 0);
|
||||
requestAnimationFrame(() => window.scrollTo(0, 0));
|
||||
};
|
||||
resetScroll();
|
||||
const onPageShow = (e: PageTransitionEvent) => {
|
||||
if (e.persisted) resetScroll();
|
||||
};
|
||||
window.addEventListener('pageshow', onPageShow);
|
||||
|
||||
const updateCameraProgress = () => {
|
||||
const vh = Math.max(1, window.innerHeight);
|
||||
const banner = document.querySelector('[data-section="banner"]');
|
||||
const footer = document.querySelector('[data-section="footer"]');
|
||||
if (!banner) {
|
||||
scrollBus.sP = 0;
|
||||
return;
|
||||
}
|
||||
const bannerRect = banner.getBoundingClientRect();
|
||||
const f1 = clamp01((vh - bannerRect.bottom) / Math.max(1, vh - 0.25 * vh));
|
||||
const f2 = footer
|
||||
? clamp01(footer.getBoundingClientRect().top / vh)
|
||||
: 1;
|
||||
scrollBus.sP = f1 * f2;
|
||||
};
|
||||
|
||||
const lenis = new Lenis({
|
||||
lerp: 0.1,
|
||||
smoothWheel: true,
|
||||
});
|
||||
|
||||
lenis.scrollTo(0, { immediate: true });
|
||||
|
||||
lenis.on('scroll', (e: any) => {
|
||||
scrollBus.current = e.scroll;
|
||||
scrollBus.velocity = e.velocity;
|
||||
scrollBus.progress = e.progress;
|
||||
updateCameraProgress();
|
||||
});
|
||||
window.addEventListener('resize', updateCameraProgress);
|
||||
updateCameraProgress();
|
||||
|
||||
function raf(time: number) {
|
||||
lenis.raf(time);
|
||||
@@ -25,6 +77,8 @@ export default function SmoothScroller() {
|
||||
requestAnimationFrame(raf);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('resize', updateCameraProgress);
|
||||
window.removeEventListener('pageshow', onPageShow);
|
||||
lenis.destroy();
|
||||
};
|
||||
}, []);
|
||||
|
||||
Reference in New Issue
Block a user