"use client"; import { useEffect, useMemo, useRef, useState } from "react"; import { useFrame, useLoader, useThree } from "@react-three/fiber"; 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 * production bundle (chunk 4d3f3b68dbbde33a.js). * * Both models share one refractive-glass shader: a screen-space scene-texture * refraction (FBO of layers 1..9 rendered at half resolution) + Beer-Lambert * tint gradient along local Y + specular + directional fresnel. * * Params (light theme defaults from the cloned controls): * refractPower .72 | chromaticAberration .14 | loop 3 (RGB path) * shininess 120 | diffuseness .1 | fresnelPower 1 | fresnelStrength .24 * brightness .78 | contrast .9 | saturation 1.2 | specularStrength 1.2 * tint A #009dff / B #ffffff, tintMix 1, thicknessMaxAlpha .92, minAlpha 1 */ const VERT = /* glsl */ ` varying vec3 worldNormal; varying vec3 eyeVector; varying float modelLocalY; void main() { vec4 worldPos = modelMatrix * vec4(position, 1.0); vec4 mvPosition = viewMatrix * worldPos; gl_Position = projectionMatrix * mvPosition; worldNormal = normalize(modelMatrix * vec4(normal, 0.0)).xyz; eyeVector = normalize(worldPos.xyz - cameraPosition); modelLocalY = position.y; } `; const FRAG = /* glsl */ ` uniform float uIorR; uniform float uIorY; uniform float uIorG; uniform float uIorC; uniform float uIorB; uniform float uIorP; uniform float uSaturation; uniform float uChromaticAberration; uniform float uRefractPower; uniform float uFresnelPower; uniform float uShininess; uniform float uDiffuseness; uniform vec3 uLight; uniform float uBrightness; uniform float uContrast; uniform float uGamma; uniform float uSpecularStrength; uniform float uFresnelStrength; uniform vec3 uFresnelSideDir; uniform vec4 uTintColorA; uniform vec4 uTintColorB; uniform vec2 uTintLocalYRange; uniform float uTintEnabled; uniform float uTintMix; uniform float uTintThicknessMinAlpha; uniform float uTintThicknessMaxAlpha; uniform vec2 uScreenResolutionPx; uniform sampler2D uTexture; uniform float uSceneRefractionEnabled; uniform float uRgbRefraction; uniform float uDark; varying vec3 worldNormal; varying vec3 eyeVector; varying float modelLocalY; float random(vec2 p) { return fract(sin(dot(p.xy, vec2(12.9898, 78.233))) * 43758.5453); } vec3 sat(vec3 rgb, float adjustment) { const vec3 W = vec3(0.2125, 0.7154, 0.0721); vec3 intensity = vec3(dot(rgb, W)); return mix(intensity, rgb, adjustment); } float fresnel(vec3 eyeDir, vec3 normal, float power) { float f = abs(dot(eyeDir, normal)); return pow(1.0 - f, power); } float specular(vec3 light, vec3 normal, vec3 eyeDir, float shininess, float diffuseness) { vec3 lightVector = normalize(-light); vec3 halfVector = normalize(eyeDir + lightVector); float NdotL = dot(normal, lightVector); float NdotH = abs(dot(normal, halfVector)); float kDiffuse = max(0.0, NdotL); float kSpecular = pow(NdotH, shininess); return kSpecular + kDiffuse * diffuseness; } uniform int uLoop; void main() { vec2 uv = gl_FragCoord.xy / uScreenResolutionPx.xy; vec3 normal = normalize(worldNormal); vec3 eyeDir = normalize(eyeVector); vec3 color; if (uSceneRefractionEnabled > 0.5) { color = vec3(0.0); float noise = random(uv) * 0.025; if (uRgbRefraction > 0.5) { vec3 refractVecR = refract(eyeDir, normal, (1.0 / uIorR)); vec3 refractVecG = refract(eyeDir, normal, (1.0 / uIorG)); vec3 refractVecB = refract(eyeDir, normal, (1.0 / uIorB)); for (int i = 0; i < uLoop; i++) { float slide = float(i) / float(uLoop) * 0.1 + noise; float offset = (uRefractPower + slide) * uChromaticAberration; color.r += texture2D(uTexture, uv + refractVecR.xy * offset).r; color.g += texture2D(uTexture, uv + refractVecG.xy * offset).g; color.b += texture2D(uTexture, uv + refractVecB.xy * offset).b; } } else { vec3 refractVecR = refract(eyeDir, normal, (1.0 / uIorR)); vec3 refractVecY = refract(eyeDir, normal, (1.0 / uIorY)); vec3 refractVecG = refract(eyeDir, normal, (1.0 / uIorG)); vec3 refractVecC = refract(eyeDir, normal, (1.0 / uIorC)); vec3 refractVecB = refract(eyeDir, normal, (1.0 / uIorB)); vec3 refractVecP = refract(eyeDir, normal, (1.0 / uIorP)); for (int i = 0; i < uLoop; i++) { float slide = float(i) / float(uLoop) * 0.1 + noise; float offsetR = (uRefractPower + slide * 1.0) * uChromaticAberration; float offsetY = (uRefractPower + slide * 1.0) * uChromaticAberration; float offsetG = (uRefractPower + slide * 2.0) * uChromaticAberration; float offsetC = (uRefractPower + slide * 2.5) * uChromaticAberration; float offsetB = (uRefractPower + slide * 3.0) * uChromaticAberration; float offsetP = (uRefractPower + slide * 1.0) * uChromaticAberration; float r = texture2D(uTexture, uv + refractVecR.xy * offsetR).x * 0.5; vec3 ySample = texture2D(uTexture, uv + refractVecY.xy * offsetY).xyz; float y = (ySample.x * 2.0 + ySample.y * 2.0 - ySample.z) / 6.0; float g = texture2D(uTexture, uv + refractVecG.xy * offsetG).y * 0.5; vec3 cSample = texture2D(uTexture, uv + refractVecC.xy * offsetC).xyz; float c = (cSample.y * 2.0 + cSample.z * 2.0 - cSample.x) / 6.0; float b = texture2D(uTexture, uv + refractVecB.xy * offsetB).z * 0.5; vec3 pSample = texture2D(uTexture, uv + refractVecP.xy * offsetP).xyz; float p = (pSample.z * 2.0 + pSample.x * 2.0 - pSample.y) / 6.0; float R = r + (2.0 * p + 2.0 * y - c) / 3.0; float G = g + (2.0 * y + 2.0 * c - p) / 3.0; float B = b + (2.0 * c + 2.0 * p - y) / 3.0; color.r += R; color.g += G; color.b += B; } } color /= float(uLoop); } else { color = texture2D(uTexture, uv).rgb; } color = sat(color, uSaturation); color *= uBrightness; color = (color - 0.5) * uContrast + 0.5; float invGamma = 1.0 / max(uGamma, 0.0001); color = pow(max(color, 0.0), vec3(invGamma)); float mode = clamp(uDark, 0.0, 1.0); // --- Beer-Lambert --- float localYMin = uTintLocalYRange.x; float localYMax = uTintLocalYRange.y; float localYDenominator = max(localYMax - localYMin, 1e-5); float tintGradientFactor = clamp((modelLocalY - localYMin) / localYDenominator, 0.0, 1.0); vec4 tintColorGradient = mix(uTintColorB, uTintColorA, tintGradientFactor); float ndotv = abs(dot(normal, eyeDir)); float thicknessMask = clamp(1.0 - ndotv, 0.0, 1.0); float tintAlpha = clamp(tintColorGradient.a, 0.0, 1.0); float minAlpha = clamp(uTintThicknessMinAlpha, 0.0, 1.0); float maxAlpha = clamp(uTintThicknessMaxAlpha, 0.0, 1.0); tintAlpha *= mix(maxAlpha, minAlpha, thicknessMask); float tintK_beer = clamp(uTintEnabled, 0.0, 1.0) * tintAlpha; vec3 tintColorClamped = clamp(tintColorGradient.rgb, 0.001, 1.0); float thickness = clamp(uTintMix, 0.01, 3.0); vec3 transmittance = pow(tintColorClamped, vec3(thickness)); vec3 beerColor = mix(color, color * transmittance, tintK_beer); // --- Hard Light --- float tintK_hard = clamp(uTintEnabled, 0.0, 1.0) * clamp(uTintMix, 0.0, 1.0) * tintAlpha; vec3 baseClamped = clamp(color, 0.0, 1.0); vec3 blendClamped = clamp(tintColorGradient.rgb, 0.0, 1.0); // Hard Light blend: 2*blend*base where base < 0.5, screen elsewhere vec3 hard = mix( 2.0 * blendClamped * baseClamped, 1.0 - 2.0 * (1.0 - blendClamped) * (1.0 - baseClamped), step(0.5, baseClamped) ); vec3 hardColor = mix(color, hard, tintK_hard); color = mix(beerColor, hardColor, mode); float specularLight = specular(uLight, normal, eyeDir, uShininess, uDiffuseness); color += specularLight * uSpecularStrength; float f = fresnel(eyeDir, normal, uFresnelPower); float sideDot = dot(normal, normalize(uFresnelSideDir)); float sideMask = smoothstep(-0.5, 0.5, sideDot); color.rgb += f * sideMask * vec3(uFresnelStrength); gl_FragColor = vec4(color, 1.0); #include #include } `; // Light-theme control defaults (cloned controls, light branch) const LIGHT_PARAMS = { refractPower: 0.72, chromaticAberration: 0.14, shininess: 120, diffuseness: 0.1, fresnelPower: 1, fresnelStrength: 0.24, brightness: 0.78, contrast: 0.9, gamma: 1, saturation: 1.2, specularStrength: 1.2, loop: 3, tintMix: 1, tintColorA: "#009dff", tintColorB: "#ffffff", tintThicknessMinAlpha: 1, tintThicknessMaxAlpha: 0.92, fresnelSideDir: [-1, 1, -1] as [number, number, number], lightZ: 0.5, }; // Default uniforms from the bundle's uniform factory const IOR = { R: 1.15, Y: 1.16, G: 1.18, C: 1.22, B: 1.22, P: 1.22 }; function hexToVec4(hex: string, alpha = 1): THREE.Vector4 { const c = new THREE.Color(hex); return new THREE.Vector4(c.r, c.g, c.b, alpha); } type GlassModelProps = { url: string; position?: [number, number, number]; beforeRotation?: [number, number, number]; rotation?: [number, number, number]; afterRotation?: [number, number, number]; rotationAxisTilt?: [number, number, number]; scale?: number; tintColors?: [string, string] | [string, string, string, string]; tintEnabled?: boolean; scrollSyncFactor?: number; floating?: boolean; isMobile?: boolean; /** * Document-space geometry of the section the model belongs to. * The banner sits at the top of the page and is h-dvh tall, so the defaults * (top 0, height = viewport height) match the original "banner" section. */ sectionTopDocY?: number; sectionHeightPx?: number; }; function useFloatOffset(enabled: boolean) { const t = useRef(0); useFrame((state, delta) => { t.current += delta; }); return useMemo( () => (time: number) => enabled ? 0.18 * Math.sin(1.2 * time) + 0.06 * Math.sin(0.6 * time) : 0, [enabled] ); } /** * 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. */ export 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], beforeRotation, rotation = [0, 0, 0], afterRotation, rotationAxisTilt = [0, 0, 0], scale = 1, tintColors, tintEnabled = false, scrollSyncFactor = 0.72, floating = true, isMobile = false, sectionTopDocY = 0, sectionHeightPx, }: GlassModelProps) { const gltf = useLoader(GLTFLoader, url); const groupRef = useRef(null!); const spinRef = useRef(null!); const materialRef = useRef(null!); const meshLayerRef = useRef(null!); const scene = useThree((s) => s.scene); const gl = useThree((s) => s.gl); const size = useThree((s) => s.size); const camera = useThree((s) => s.camera); // Merge all mesh geometries into one, centered (same as original cb/cd) const mergedGeometry = useMemo(() => { gltf.scene.updateMatrixWorld(true); const geometries: THREE.BufferGeometry[] = []; gltf.scene.traverse((obj) => { if ((obj as THREE.Mesh).isMesh && (obj as THREE.Mesh).geometry) { const geo = (obj as THREE.Mesh).geometry.clone(); geo.applyMatrix4((obj as THREE.Mesh).matrixWorld); geometries.push(geo); } }); if (geometries.length === 0) return null; let merged: THREE.BufferGeometry | null = null; try { merged = mergeGeometries(geometries, false); } catch { merged = null; } if (!merged && geometries.length >= 1) merged = geometries[0]; if (!merged) return null; merged.computeBoundingBox(); const bb = merged.boundingBox!; const cx = (bb.min.x + bb.max.x) / 2; const cy = (bb.min.y + bb.max.y) / 2; const cz = (bb.min.z + bb.max.z) / 2; if (Math.abs(cx) + Math.abs(cy) + Math.abs(cz) >= 1e-8) { merged.translate(-cx, -cy, -cz); merged.computeBoundingSphere(); } return merged; }, [gltf]); // Glass renders ONLY on layer 10: the FBO refraction pass forces the camera // mask to layer 0, so the glass mesh is excluded from its own refraction // texture (an object with layer 0 kept enabled would pass the mask test and // draw into the FBO it samples — a GL feedback loop, GL_INVALID_OPERATION // every frame). The main camera enables layer 10 below, so glass stays // visible in the normal pass. Matches the original GlassSystem. useEffect(() => { const mesh = meshLayerRef.current; if (!mesh) return; mesh.layers.set(10); camera.layers.enable(10); }, [mergedGeometry, camera]); const tintYRange = useMemo<[number, number]>(() => { if (!mergedGeometry) return [0, 1]; if (!mergedGeometry.boundingBox) mergedGeometry.computeBoundingBox(); const bb = mergedGeometry.boundingBox!; return Math.abs(bb.max.y - bb.min.y) < 1e-6 ? [bb.min.y, bb.min.y + 1] : [bb.min.y, bb.max.y]; }, [mergedGeometry]); // Scene-texture FBO: render layer 0 (background + stickers) at half res. // Same as the original GlassSystem: one shared pass, camera mask forced to // layer 0 so glass meshes (layer 10) are excluded from their own refraction. const fbo = useMemo(() => { const dpr = gl.getPixelRatio(); const w = Math.max(2, Math.floor((size.width * dpr) / 2)); const h = Math.max(2, Math.floor((size.height * dpr) / 2)); const target = new THREE.WebGLRenderTarget(w, h, { stencilBuffer: false, depthBuffer: true, samples: 0, }); return target; }, [gl, size.width, size.height]); useEffect(() => { return () => { fbo.dispose(); }; }, [fbo]); const uniforms = useMemo( () => ({ uIorR: { value: IOR.R }, uIorY: { value: IOR.Y }, uIorG: { value: IOR.G }, uIorC: { value: IOR.C }, uIorB: { value: IOR.B }, uIorP: { value: IOR.P }, uRefractPower: { value: LIGHT_PARAMS.refractPower }, uChromaticAberration: { value: LIGHT_PARAMS.chromaticAberration }, uSaturation: { value: LIGHT_PARAMS.saturation }, uShininess: { value: LIGHT_PARAMS.shininess }, uDiffuseness: { value: LIGHT_PARAMS.diffuseness }, uFresnelPower: { value: LIGHT_PARAMS.fresnelPower }, uBrightness: { value: LIGHT_PARAMS.brightness }, uContrast: { value: LIGHT_PARAMS.contrast }, uGamma: { value: LIGHT_PARAMS.gamma }, uSpecularStrength: { value: LIGHT_PARAMS.specularStrength }, uFresnelStrength: { value: LIGHT_PARAMS.fresnelStrength }, uFresnelSideDir: { value: new THREE.Vector3(...LIGHT_PARAMS.fresnelSideDir), }, uTintColorA: { value: hexToVec4(tintColors ? tintColors[0] : LIGHT_PARAMS.tintColorA), }, uTintColorB: { value: hexToVec4(tintColors ? tintColors[1] : LIGHT_PARAMS.tintColorB), }, uTintLocalYRange: { value: new THREE.Vector2(0, 1) }, uTintEnabled: { value: tintEnabled ? 1 : 0 }, uTintMix: { value: LIGHT_PARAMS.tintMix }, uTintThicknessMinAlpha: { value: LIGHT_PARAMS.tintThicknessMinAlpha }, uTintThicknessMaxAlpha: { value: LIGHT_PARAMS.tintThicknessMaxAlpha }, uDark: { value: 0 }, uLoop: { value: LIGHT_PARAMS.loop }, uSceneRefractionEnabled: { value: 1 }, uRgbRefraction: { value: 1 }, uLight: { value: new THREE.Vector3(4, 9, LIGHT_PARAMS.lightZ) }, uScreenResolutionPx: { value: new THREE.Vector2(1, 1) }, uTexture: { value: fbo.texture }, }), [tintColors, tintEnabled, fbo] ); useEffect(() => { uniforms.uTintLocalYRange.value.set(tintYRange[0], tintYRange[1]); }, [tintYRange, uniforms]); useEffect(() => { const drawingBufferSize = gl.getDrawingBufferSize(new THREE.Vector2()); uniforms.uScreenResolutionPx.value.set( drawingBufferSize.x, drawingBufferSize.y ); }, [gl, size, uniforms]); // 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 // INSIDE the spin group). const negatedTilt = useMemo<[number, number, number]>( () => [-rotationAxisTilt[0], -rotationAxisTilt[1], -rotationAxisTilt[2]], [rotationAxisTilt] ); const rad = (v: number) => THREE.MathUtils.degToRad(v); const before = beforeRotation ?? rotation; useFrame((state, rawDelta) => { const delta = Math.min(rawDelta, 0.1); // Render the scene (layer 0 mask) into the FBO for refraction. // Stickers/background live on layer 0; glass models render on layer 0+10 // and are excluded by the layer-0 mask (no self-refraction). Original: // `camera.layers.mask = 1; render; restore`. const prevTarget = gl.getRenderTarget(); const prevAutoClear = gl.autoClear; const prevMask = camera.layers.mask; gl.setRenderTarget(fbo); gl.clear(); camera.layers.set(0); gl.render(scene, camera); camera.layers.mask = prevMask; gl.setRenderTarget(prevTarget); gl.autoClear = prevAutoClear; const g = groupRef.current; const spin = spinRef.current; if (!g) return; // --- Section-anchored scroll state (banner: top 0, h-dvh) --- const vh = Math.max(1, state.size.height); const sectionH = Math.max(1, sectionHeightPx ?? vh); const scrollTop = Math.max(0, scrollBus.current); // Original X(): hide the model once its section leaves the viewport. const deltaTop = sectionTopDocY - scrollTop; g.visible = deltaTop + sectionH > 0 && deltaTop < vh; // Original position sync: // worldY = (0.5 - anchorDocY/vh) * viewportWorldH // + (scrollTop/vh) * viewportWorldH * scrollSyncFactor // where anchorDocY = section top + half height. For the banner at page // top this reduces to (scrollTop/vh) * worldH * factor — i.e. the model // tracks the first viewport of scrolling, NOT whole-page progress. const viewportWorldHeight = state.viewport.getCurrentViewport( camera, new THREE.Vector3(0, 0, position[2]) ).height; const anchorDocY = sectionTopDocY + sectionH / 2; const syncWorldY = (0.5 - anchorDocY / vh) * viewportWorldHeight + (scrollTop / vh) * viewportWorldHeight * scrollSyncFactor; const float = getFloat(state.clock.getElapsedTime()); g.position.y = syncWorldY + position[1] + float; g.position.x = position[0]; g.position.z = position[2]; // --- Scroll-driven rotation targets (original Z()) --- // i = (scrollTop + vh - sectionTop) / vh // entry = clamp(i, 0, 1) after = clamp(i - 1, 0, 1) // At page top entry=1 / after=0, so nothing animates until the user // scrolls; `after` then ramps over the first viewport height. let entry = 1; let after = afterRotation ? 1 : 0; if (vh > 0) { const i = (scrollTop + vh - sectionTopDocY) / vh; entry = THREE.MathUtils.clamp(i, 0, 1); after = THREE.MathUtils.clamp(i - 1, 0, 1); } let tx = THREE.MathUtils.lerp(rad(before[0]), rad(rotation[0]), entry); let ty = THREE.MathUtils.lerp(rad(before[1]), rad(rotation[1]), entry); let tz = THREE.MathUtils.lerp(rad(before[2]), rad(rotation[2]), entry); if (afterRotation) { tx = THREE.MathUtils.lerp(tx, rad(afterRotation[0]), after); ty = THREE.MathUtils.lerp(ty, rad(afterRotation[1]), after); tz = THREE.MathUtils.lerp(tz, rad(afterRotation[2]), after); } if (spin) { spin.rotation.x = THREE.MathUtils.damp(spin.rotation.x, tx, 6, delta); 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; return ( {/* rotationAxisTilt group ... then counter-tilt INSIDE the spin group: tilt * spin * (-tilt) keeps the model upright at rest while the spin happens around the tilted axis — exactly the original hierarchy. */} ); } export function HelloModel({ isMobile = false }: { isMobile?: boolean }) { return ( ); } export function CursorStar({ isMobile = false }: { isMobile?: boolean }) { return ( ); } /** * #contact footer model (original cp call: model/cnt.gltf, scale 19, * beforeRotation [-180,0,0], scrollSyncFactor 1 — the cp default — and * light-theme tingColor m[0]/m[1] = #FFFFFF/#009dff). Anchored to the * footer section's document geometry, measured live so it tracks layout. */ export function FooterModel() { const [geom, setGeom] = useState({ top: 0, height: 0 }); useEffect(() => { const measure = () => { const el = document.getElementById("contact"); if (el) setGeom({ top: el.offsetTop, height: el.offsetHeight }); }; measure(); window.addEventListener("resize", measure); document.fonts?.ready?.then(measure).catch(() => {}); const t = window.setTimeout(measure, 500); return () => { window.removeEventListener("resize", measure); window.clearTimeout(t); }; }, []); return ( ); }